From 8ec5c62bbfe1a603586ddc2f05caf9d6b29524ca Mon Sep 17 00:00:00 2001 From: David Badura Date: Tue, 19 Mar 2024 15:52:02 +0100 Subject: [PATCH] add event payload cryptographer for personal data --- baseline.xml | 57 +++- deptrac.yaml | 8 + docs/mkdocs.yml | 1 + docs/pages/personal_data.md | 243 ++++++++++++++++ phpstan-baseline.neon | 25 ++ src/Attribute/DataSubjectId.php | 12 + src/Attribute/PersonalData.php | 16 + src/Cryptography/Cipher/Cipher.php | 14 + src/Cryptography/Cipher/CipherKey.php | 20 ++ src/Cryptography/Cipher/CipherKeyFactory.php | 11 + .../Cipher/CreateCipherKeyFailed.php | 15 + src/Cryptography/Cipher/DecryptionFailed.php | 15 + src/Cryptography/Cipher/EncryptionFailed.php | 15 + .../Cipher/MethodNotSupported.php | 17 ++ src/Cryptography/Cipher/OpensslCipher.php | 67 +++++ .../Cipher/OpensslCipherKeyFactory.php | 59 ++++ .../DefaultEventPayloadCryptographer.php | 145 +++++++++ .../EventPayloadCryptographer.php | 24 ++ src/Cryptography/MissingSubjectId.php | 15 + src/Cryptography/Store/CipherKeyNotExists.php | 17 ++ src/Cryptography/Store/CipherKeyStore.php | 17 ++ .../Store/DoctrineCipherKeyStore.php | 105 +++++++ .../Store/InMemoryCipherKeyStore.php | 33 +++ src/Cryptography/UnsupportedSubjectId.php | 18 ++ .../Event/AttributeEventMetadataFactory.php | 88 ++++++ .../Event/DataSubjectIdIsPersonalData.php | 24 ++ src/Metadata/Event/EventMetadata.php | 3 + src/Metadata/Event/MissingDataSubjectId.php | 20 ++ src/Metadata/Event/MultipleDataSubjectId.php | 23 ++ src/Metadata/Event/PropertyMetadata.php | 16 + src/Serializer/CryptographicHydrator.php | 40 +++ src/Serializer/DefaultEventSerializer.php | 16 +- .../Events/EmailChanged.php | 24 ++ .../Events/ProfileCreated.php | 5 + .../{Aggregate => }/Profile.php | 27 +- tests/Benchmark/PersonalDataBench.php | 128 ++++++++ tests/Benchmark/SimpleSetupBench.php | 2 +- tests/Benchmark/SnapshotsBench.php | 2 +- tests/Benchmark/SplitStreamBench.php | 2 +- tests/Benchmark/SubscriptionEngineBench.php | 2 +- tests/Benchmark/blackfire.php | 2 +- .../PersonalData/Events/NameChanged.php | 24 ++ .../Events/PersonalDataRemoved.php | 12 + .../PersonalData/Events/ProfileCreated.php | 24 ++ .../PersonalData/PersonalDataTest.php | 188 ++++++++++++ .../Processor/DeletePersonalDataProcessor.php | 29 ++ tests/Integration/PersonalData/Profile.php | 68 +++++ tests/Integration/PersonalData/ProfileId.php | 25 ++ .../Cipher/CreateCipherKeyFailedTest.php | 19 ++ .../Cipher/DecryptionFailedTest.php | 19 ++ .../Cipher/EncryptionFailedTest.php | 19 ++ .../Cipher/OpensslCipherKeyFactoryTest.php | 33 +++ .../Cryptography/Cipher/OpensslCipherTest.php | 78 +++++ .../DefaultEventPayloadCryptographerTest.php | 274 ++++++++++++++++++ .../Cryptography/MissingSubjectIdTest.php | 19 ++ .../Store/CipherKeyNotExistsTest.php | 19 ++ .../Store/InMemoryCipherKeyStoreTest.php | 76 +++++ .../Cryptography/UnsupportedSubjectIdTest.php | 19 ++ tests/Unit/Fixture/EmailChanged.php | 21 ++ .../AttributeEventMetadataFactoryTest.php | 114 ++++++++ .../Serializer/CryptographicHydratorTest.php | 74 +++++ 61 files changed, 2533 insertions(+), 14 deletions(-) create mode 100644 docs/pages/personal_data.md create mode 100644 src/Attribute/DataSubjectId.php create mode 100644 src/Attribute/PersonalData.php create mode 100644 src/Cryptography/Cipher/Cipher.php create mode 100644 src/Cryptography/Cipher/CipherKey.php create mode 100644 src/Cryptography/Cipher/CipherKeyFactory.php create mode 100644 src/Cryptography/Cipher/CreateCipherKeyFailed.php create mode 100644 src/Cryptography/Cipher/DecryptionFailed.php create mode 100644 src/Cryptography/Cipher/EncryptionFailed.php create mode 100644 src/Cryptography/Cipher/MethodNotSupported.php create mode 100644 src/Cryptography/Cipher/OpensslCipher.php create mode 100644 src/Cryptography/Cipher/OpensslCipherKeyFactory.php create mode 100644 src/Cryptography/DefaultEventPayloadCryptographer.php create mode 100644 src/Cryptography/EventPayloadCryptographer.php create mode 100644 src/Cryptography/MissingSubjectId.php create mode 100644 src/Cryptography/Store/CipherKeyNotExists.php create mode 100644 src/Cryptography/Store/CipherKeyStore.php create mode 100644 src/Cryptography/Store/DoctrineCipherKeyStore.php create mode 100644 src/Cryptography/Store/InMemoryCipherKeyStore.php create mode 100644 src/Cryptography/UnsupportedSubjectId.php create mode 100644 src/Metadata/Event/DataSubjectIdIsPersonalData.php create mode 100644 src/Metadata/Event/MissingDataSubjectId.php create mode 100644 src/Metadata/Event/MultipleDataSubjectId.php create mode 100644 src/Metadata/Event/PropertyMetadata.php create mode 100644 src/Serializer/CryptographicHydrator.php create mode 100644 tests/Benchmark/BasicImplementation/Events/EmailChanged.php rename tests/Benchmark/BasicImplementation/{Aggregate => }/Profile.php (73%) create mode 100644 tests/Benchmark/PersonalDataBench.php create mode 100644 tests/Integration/PersonalData/Events/NameChanged.php create mode 100644 tests/Integration/PersonalData/Events/PersonalDataRemoved.php create mode 100644 tests/Integration/PersonalData/Events/ProfileCreated.php create mode 100644 tests/Integration/PersonalData/PersonalDataTest.php create mode 100644 tests/Integration/PersonalData/Processor/DeletePersonalDataProcessor.php create mode 100644 tests/Integration/PersonalData/Profile.php create mode 100644 tests/Integration/PersonalData/ProfileId.php create mode 100644 tests/Unit/Cryptography/Cipher/CreateCipherKeyFailedTest.php create mode 100644 tests/Unit/Cryptography/Cipher/DecryptionFailedTest.php create mode 100644 tests/Unit/Cryptography/Cipher/EncryptionFailedTest.php create mode 100644 tests/Unit/Cryptography/Cipher/OpensslCipherKeyFactoryTest.php create mode 100644 tests/Unit/Cryptography/Cipher/OpensslCipherTest.php create mode 100644 tests/Unit/Cryptography/DefaultEventPayloadCryptographerTest.php create mode 100644 tests/Unit/Cryptography/MissingSubjectIdTest.php create mode 100644 tests/Unit/Cryptography/Store/CipherKeyNotExistsTest.php create mode 100644 tests/Unit/Cryptography/Store/InMemoryCipherKeyStoreTest.php create mode 100644 tests/Unit/Cryptography/UnsupportedSubjectIdTest.php create mode 100644 tests/Unit/Fixture/EmailChanged.php create mode 100644 tests/Unit/Serializer/CryptographicHydratorTest.php diff --git a/baseline.xml b/baseline.xml index 617141b91..bc73302a6 100644 --- a/baseline.xml +++ b/baseline.xml @@ -1,5 +1,5 @@ - + @@ -15,6 +15,34 @@ + + + ivLength)]]> + keyLength)]]> + + + + + + ]]> + + + + + fieldName]]]> + + + fieldName]]]> + fieldName]]]> + fieldName]]]> + + + + + + + + getName()]]> @@ -88,12 +116,21 @@ - + + + + + + + + + + @@ -145,6 +182,17 @@ + + + + + + + + + + + @@ -164,6 +212,11 @@ + + + + + diff --git a/deptrac.yaml b/deptrac.yaml index 5798c3dc6..40872af5b 100644 --- a/deptrac.yaml +++ b/deptrac.yaml @@ -21,6 +21,10 @@ deptrac: collectors: - type: directory value: src/Console/.* + - name: Cryptography + collectors: + - type: directory + value: src/Cryptography/.* - name: Debug collectors: - type: directory @@ -108,6 +112,9 @@ deptrac: - Serializer - Store - Subscription + Cryptography: + - MetadataEvent + - Schema Debug: - Attribute - Message @@ -159,6 +166,7 @@ deptrac: Schema: Serializer: - Aggregate + - Cryptography - MetadataEvent Snapshot: - Aggregate diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index ebe9a619a..66ba1427a 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -88,6 +88,7 @@ nav: - Aggregate ID: aggregate_id.md - Normalizer: normalizer.md - Snapshots: snapshots.md + - Personal Data: personal_data.md - Upcasting: upcasting.md - Outbox: outbox.md - Pipeline: pipeline.md diff --git a/docs/pages/personal_data.md b/docs/pages/personal_data.md new file mode 100644 index 000000000..5531307fd --- /dev/null +++ b/docs/pages/personal_data.md @@ -0,0 +1,243 @@ +# Personal Data (GDPR) + +According to GDPR, personal data must be able to be deleted upon request. +But here we have the problem that our events are immutable and we cannot easily manipulate the event store. + +The first solution is not to save the personal data in the Event Store at all +and use something different for this, for example a separate table or an ORM. + +The other option the library offers is crypto shredding. +In this process, the personal data is encrypted with a key that is assigned to a subject (person). +When saving and reading the events, this key is then used to convert the data. +This key with the subject is saved in a database. + +As soon as a request for data deletion comes, +you can simply delete the key and the personal data can no longer be decrypted. + +## Configuration + +Encrypting and decrypting is handled by the library. +You just have to configure the events accordingly. + +### PersonalData + +First of all, we have to mark the fields that contain personal data. + +```php +use Patchlevel\EventSourcing\Attribute\PersonalData; + +final class EmailChanged +{ + public function __construct( + #[PersonalData] + public readonly string|null $email + ) { + } +} +``` + +If the information could not be decrypted, then a fallback value is inserted. +The default fallback value is `null`. +You can change this by setting the `fallback` parameter. +In this case `unknown` is added: + +```php +use Patchlevel\EventSourcing\Attribute\PersonalData; + +final class EmailChanged +{ + public function __construct( + #[PersonalData(fallback: 'unknown')] + public readonly string|null $email + ) { + } +} +``` + +!!! danger + + You have to deal with this case in your business logic such as aggregates and subscriptions. + +!!! warning + + You need to define a subject ID to use the personal data attribute. + +!!! note + + The normalized data is encrypted. This means that this happens after the 'extract' or before the 'hydrate'. + +### DataSubjectId + +In order for the correct key to be used, a subject ID must be defined. +Without Subject Id, no personal data can be encrypted or decrypted. + +```php +use Patchlevel\EventSourcing\Attribute\PersonalData; +use Patchlevel\EventSourcing\Attribute\DataSubjectId; + +final class EmailChanged +{ + public function __construct( + #[DataSubjectId] + public readonly string $personId, + #[PersonalData(fallback: 'unknown')] + public readonly string|null $email + ) { + } +} +``` + +!!! warning + + A subject ID can not be a personal data. + +## Setup + +In order for the system to work, a few things have to be done. + +!!! tip + + You can use named constructor `DefaultEventPayloadCryptographer::createWithOpenssl` to skip some necessary setups. + +### Cipher Key Factory + +We need a factory to generate keys. We provide an openssl implementation by default. + + +```php +use Patchlevel\EventSourcing\Cryptography\Cipher\OpensslCipherKeyFactory; + +$cipherKeyFactory = new OpensslCipherKeyFactory(); +$cipherKey = $cipherKeyFactory(); +``` + +You can change the algorithm by passing it as a parameter. + +```php +use Patchlevel\EventSourcing\Cryptography\Cipher\OpensslCipherKeyFactory; + +$cipherKeyFactory = new OpensslCipherKeyFactory('aes256'); +$cipherKey = $cipherKeyFactory(); +``` + +!!! tip + + With `OpensslCipherKeyFactory::supportedMethods()` you can get a list of all available algorithms. + +### Cipher Key Store + +The keys must be stored somewhere. For this we provide a doctrine implementation. + +```php +use Patchlevel\EventSourcing\Cryptography\Cipher\CipherKey; +use Patchlevel\EventSourcing\Cryptography\Store\DoctrineCipherKeyStore; + +$cipherKeyStore = new DoctrineCipherKeyStore($dbalConnection); + +$cipherKeyStore->store('personId', $cipherKey); +$cipherKey = $cipherKeyStore->get('personId'); +$cipherKeyStore->remove('personId'); +``` + +To use the `DoctrineCipherKeyStore` you need to register this service in Doctrine Schema Director. +Then the table will be added automatically. + +```php +$schemaDirector = new DoctrineSchemaDirector( + $dbalConnection, + new ChainDoctrineSchemaConfigurator([ + $store, + $cipherKeyStore, + ]), +); +``` + +### Cipher + +The encryption and decryption is handled by the `Cipher`. +We offer an openssl implementation by default. + +```php + +use Patchlevel\EventSourcing\Cryptography\Cipher\OpensslCipher; + +$cipher = new OpensslCipher(); + +$encrypted = $cipher->encrypt($cipherKey, $value); +$value = $cipher->decrypt($cipherKey, $encrypted); +``` + +!!! note + + If the encryption or decryption fails, an exception `EncryptionFailed` or `DecryptionFailed` is thrown. + +### Event Payload Cryptographer + +Now we have to put the whole thing together in an Event Payload Cryptographer. + +```php +use Patchlevel\EventSourcing\Cryptography\DefaultEventPayloadCryptographer; + +$cryptographer = new DefaultEventPayloadCryptographer( + $eventMetadataFactory, + $cipherKeyStore, + $cipherKeyFactory, + $cipher, +); +``` + +You can also use the shortcut with openssl. + +```php +use Patchlevel\EventSourcing\Cryptography\DefaultEventPayloadCryptographer; + +$cryptographer = DefaultEventPayloadCryptographer::createWithOpenssl( + $eventMetadataFactory, + $cipherKeyStore, +); +``` + +### Integration + +The last step is to integrate the cryptographer into the event store. + +```php +use Patchlevel\EventSourcing\Serializer\DefaultEventSerializer; + +DefaultEventSerializer::createFromPaths( + [__DIR__ . '/Events'], + cryptographer: $cryptographer +); +``` + +!!! success + + Now you can save and read events with personal data. + +## Remove personal data + +To remove personal data, you can either remove the key manually or do it with a processor. + +```php +use Patchlevel\EventSourcing\Attribute\Processor; +use Patchlevel\EventSourcing\Attribute\Subscribe; +use Patchlevel\EventSourcing\Cryptography\Store\CipherKeyStore; +use Patchlevel\EventSourcing\Message\Message; + +#[Processor('delete_personal_data')] +final class DeletePersonalDataProcessor +{ + public function __construct( + private readonly CipherKeyStore $cipherKeyStore, + ) { + } + + #[Subscribe(UserHasRequestedDeletion::class)] + public function handleUserHasRequestedDeletion(Message $message): void + { + $event = $message->event(); + + $this->cipherKeyStore->remove($event->personId); + } +} +``` diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index e97903bba..3cec5d190 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -5,6 +5,31 @@ parameters: count: 1 path: src/Console/DoctrineHelper.php + - + message: "#^Parameter \\#1 \\$key of class Patchlevel\\\\EventSourcing\\\\Cryptography\\\\Cipher\\\\CipherKey constructor expects non\\-empty\\-string, string given\\.$#" + count: 1 + path: src/Cryptography/Cipher/OpensslCipherKeyFactory.php + + - + message: "#^Parameter \\#3 \\$iv of class Patchlevel\\\\EventSourcing\\\\Cryptography\\\\Cipher\\\\CipherKey constructor expects non\\-empty\\-string, string given\\.$#" + count: 1 + path: src/Cryptography/Cipher/OpensslCipherKeyFactory.php + + - + message: "#^Parameter \\#2 \\$data of method Patchlevel\\\\EventSourcing\\\\Cryptography\\\\Cipher\\\\Cipher\\:\\:decrypt\\(\\) expects string, mixed given\\.$#" + count: 1 + path: src/Cryptography/DefaultEventPayloadCryptographer.php + + - + message: "#^Parameter \\#1 \\$key of class Patchlevel\\\\EventSourcing\\\\Cryptography\\\\Cipher\\\\CipherKey constructor expects non\\-empty\\-string, string given\\.$#" + count: 1 + path: src/Cryptography/Store/DoctrineCipherKeyStore.php + + - + message: "#^Parameter \\#3 \\$iv of class Patchlevel\\\\EventSourcing\\\\Cryptography\\\\Cipher\\\\CipherKey constructor expects non\\-empty\\-string, string given\\.$#" + count: 1 + path: src/Cryptography/Store/DoctrineCipherKeyStore.php + - message: "#^Parameter \\#2 \\$data of method Patchlevel\\\\Hydrator\\\\Hydrator\\:\\:hydrate\\(\\) expects array\\, mixed given\\.$#" count: 1 diff --git a/src/Attribute/DataSubjectId.php b/src/Attribute/DataSubjectId.php new file mode 100644 index 000000000..e41005217 --- /dev/null +++ b/src/Attribute/DataSubjectId.php @@ -0,0 +1,12 @@ +dataEncode($data), + $key->method, + $key->key, + 0, + $key->iv, + ); + + if ($encryptedData === false) { + throw new EncryptionFailed(); + } + + return base64_encode($encryptedData); + } + + public function decrypt(CipherKey $key, string $data): mixed + { + $data = @openssl_decrypt( + base64_decode($data), + $key->method, + $key->key, + 0, + $key->iv, + ); + + if ($data === false) { + throw new DecryptionFailed(); + } + + try { + return $this->dataDecode($data); + } catch (JsonException) { + throw new DecryptionFailed(); + } + } + + private function dataEncode(mixed $data): string + { + return json_encode($data, JSON_THROW_ON_ERROR); + } + + private function dataDecode(string $data): mixed + { + return json_decode($data, true, 512, JSON_THROW_ON_ERROR); + } +} diff --git a/src/Cryptography/Cipher/OpensslCipherKeyFactory.php b/src/Cryptography/Cipher/OpensslCipherKeyFactory.php new file mode 100644 index 000000000..8f189cf7f --- /dev/null +++ b/src/Cryptography/Cipher/OpensslCipherKeyFactory.php @@ -0,0 +1,59 @@ +method)) { + throw new MethodNotSupported($this->method); + } + + $keyLength = @openssl_cipher_key_length($this->method); + $ivLength = @openssl_cipher_iv_length($this->method); + + if ($keyLength === false || $ivLength === false) { + throw new MethodNotSupported($this->method); + } + + $this->keyLength = $keyLength; + $this->ivLength = $ivLength; + } + + public function __invoke(): CipherKey + { + return new CipherKey( + openssl_random_pseudo_bytes($this->keyLength), + $this->method, + openssl_random_pseudo_bytes($this->ivLength), + ); + } + + /** @return list */ + public static function supportedMethods(): array + { + return openssl_get_cipher_methods(true); + } + + public static function methodSupported(string $method): bool + { + return in_array($method, self::supportedMethods(), true); + } +} diff --git a/src/Cryptography/DefaultEventPayloadCryptographer.php b/src/Cryptography/DefaultEventPayloadCryptographer.php new file mode 100644 index 000000000..6f20ad7ab --- /dev/null +++ b/src/Cryptography/DefaultEventPayloadCryptographer.php @@ -0,0 +1,145 @@ + $data + * + * @return array + */ + public function encrypt(string $class, array $data): array + { + $subjectId = $this->subjectId($class, $data); + + if ($subjectId === null) { + return $data; + } + + try { + $cipherKey = $this->cipherKeyStore->get($subjectId); + } catch (CipherKeyNotExists) { + $cipherKey = ($this->cipherKeyFactory)(); + $this->cipherKeyStore->store($subjectId, $cipherKey); + } + + $metadata = $this->eventMetadataFactory->metadata($class); + + foreach ($metadata->propertyMetadata as $propertyMetadata) { + if (!$propertyMetadata->isPersonalData) { + continue; + } + + $data[$propertyMetadata->fieldName] = $this->cipher->encrypt( + $cipherKey, + $data[$propertyMetadata->fieldName], + ); + } + + return $data; + } + + /** + * @param class-string $class + * @param array $data + * + * @return array + */ + public function decrypt(string $class, array $data): array + { + $subjectId = $this->subjectId($class, $data); + + if ($subjectId === null) { + return $data; + } + + try { + $cipherKey = $this->cipherKeyStore->get($subjectId); + } catch (CipherKeyNotExists) { + $cipherKey = null; + } + + $metadata = $this->eventMetadataFactory->metadata($class); + + foreach ($metadata->propertyMetadata as $propertyMetadata) { + if (!$propertyMetadata->isPersonalData) { + continue; + } + + if (!$cipherKey) { + $data[$propertyMetadata->fieldName] = $propertyMetadata->personalDataFallback; + continue; + } + + try { + $data[$propertyMetadata->fieldName] = $this->cipher->decrypt( + $cipherKey, + $data[$propertyMetadata->fieldName], + ); + } catch (DecryptionFailed) { + $data[$propertyMetadata->fieldName] = $propertyMetadata->personalDataFallback; + } + } + + return $data; + } + + /** + * @param class-string $class + * @param array $data + */ + private function subjectId(string $class, array $data): string|null + { + $metadata = $this->eventMetadataFactory->metadata($class); + + if ($metadata->dataSubjectIdField === null) { + return null; + } + + if (!array_key_exists($metadata->dataSubjectIdField, $data)) { + throw new MissingSubjectId(); + } + + $subjectId = $data[$metadata->dataSubjectIdField]; + + if (!is_string($subjectId)) { + throw new UnsupportedSubjectId($subjectId); + } + + return $subjectId; + } + + public static function createWithOpenssl(EventMetadataFactory $eventMetadataFactory, CipherKeyStore $cryptoStore): static + { + return new self( + $eventMetadataFactory, + $cryptoStore, + new OpensslCipherKeyFactory(), + new OpensslCipher(), + ); + } +} diff --git a/src/Cryptography/EventPayloadCryptographer.php b/src/Cryptography/EventPayloadCryptographer.php new file mode 100644 index 000000000..ea1aa6569 --- /dev/null +++ b/src/Cryptography/EventPayloadCryptographer.php @@ -0,0 +1,24 @@ + $data + * + * @return array + */ + public function encrypt(string $class, array $data): array; + + /** + * @param class-string $class + * @param array $data + * + * @return array + */ + public function decrypt(string $class, array $data): array; +} diff --git a/src/Cryptography/MissingSubjectId.php b/src/Cryptography/MissingSubjectId.php new file mode 100644 index 000000000..37dc7c91e --- /dev/null +++ b/src/Cryptography/MissingSubjectId.php @@ -0,0 +1,15 @@ + */ + private array $keys = []; + + public function __construct( + private readonly Connection $connection, + private readonly string $tableName = 'crypto_keys', + ) { + } + + public function get(string $id): CipherKey + { + if (array_key_exists($id, $this->keys)) { + return $this->keys[$id]; + } + + /** @var Row|false $result */ + $result = $this->connection->fetchAssociative( + "SELECT * FROM {$this->tableName} WHERE subject_id = :subject_id", + ['subject_id' => $id], + ); + + if ($result === false) { + throw new CipherKeyNotExists($id); + } + + $this->keys[$id] = new CipherKey( + base64_decode($result['crypto_key']), + $result['crypto_method'], + base64_decode($result['crypto_iv']), + ); + + return $this->keys[$id]; + } + + public function store(string $id, CipherKey $key): void + { + $this->connection->insert($this->tableName, [ + 'subject_id' => $id, + 'crypto_key' => base64_encode($key->key), + 'crypto_method' => $key->method, + 'crypto_iv' => base64_encode($key->iv), + ]); + + $this->keys[$id] = $key; + } + + public function remove(string $id): void + { + $this->connection->delete($this->tableName, ['subject_id' => $id]); + + unset($this->keys[$id]); + } + + public function configureSchema(Schema $schema, Connection $connection): void + { + if ($connection !== $this->connection) { + return; + } + + $table = $schema->createTable($this->tableName); + $table->addColumn('subject_id', 'string') + ->setNotnull(true) + ->setLength(255); + $table->addColumn('crypto_key', 'string') + ->setNotnull(true) + ->setLength(255); + $table->addColumn('crypto_method', 'string') + ->setNotnull(true) + ->setLength(255); + $table->addColumn('crypto_iv', 'string') + ->setNotnull(true) + ->setLength(255); + $table->setPrimaryKey(['subject_id']); + } + + public function clear(): void + { + $this->keys = []; + } +} diff --git a/src/Cryptography/Store/InMemoryCipherKeyStore.php b/src/Cryptography/Store/InMemoryCipherKeyStore.php new file mode 100644 index 000000000..7bf8c5f3e --- /dev/null +++ b/src/Cryptography/Store/InMemoryCipherKeyStore.php @@ -0,0 +1,33 @@ + */ + private array $keys = []; + + public function get(string $id): CipherKey + { + return $this->keys[$id] ?? throw new CipherKeyNotExists($id); + } + + public function store(string $id, CipherKey $key): void + { + $this->keys[$id] = $key; + } + + public function remove(string $id): void + { + unset($this->keys[$id]); + } + + public function clear(): void + { + $this->keys = []; + } +} diff --git a/src/Cryptography/UnsupportedSubjectId.php b/src/Cryptography/UnsupportedSubjectId.php new file mode 100644 index 000000000..bd3da12c7 --- /dev/null +++ b/src/Cryptography/UnsupportedSubjectId.php @@ -0,0 +1,18 @@ +subjectIdField($reflectionClass); + + foreach ($reflectionClass->getProperties() as $reflectionProperty) { + $propertyMetadata = $this->propertyMetadata($reflectionProperty); + + if ($propertyMetadata->isPersonalData) { + if ($subjectId === $propertyMetadata->fieldName) { + throw new DataSubjectIdIsPersonalData($event, $propertyMetadata->fieldName); + } + + $hasPersonalData = true; + } + + $propertyMetadataList[$reflectionProperty->getName()] = $propertyMetadata; + } + + if ($hasPersonalData && $subjectId === null) { + throw new MissingDataSubjectId($event); + } + $eventAttribute = $attributeReflectionList[0]->newInstance(); $this->eventMetadata[$event] = new EventMetadata( $eventAttribute->name, $this->splitStream($reflectionClass), + $subjectId, + $propertyMetadataList, ); return $this->eventMetadata[$event]; @@ -45,4 +74,63 @@ private function splitStream(ReflectionClass $reflectionClass): bool { return count($reflectionClass->getAttributes(SplitStream::class)) !== 0; } + + private function propertyMetadata(ReflectionProperty $reflectionProperty): PropertyMetadata + { + $attributeReflectionList = $reflectionProperty->getAttributes(PersonalData::class); + + if (!$attributeReflectionList) { + return new PropertyMetadata( + $reflectionProperty->getName(), + $this->fieldName($reflectionProperty), + ); + } + + $attribute = $attributeReflectionList[0]->newInstance(); + + return new PropertyMetadata( + $reflectionProperty->getName(), + $this->fieldName($reflectionProperty), + true, + $attribute->fallback, + ); + } + + private function subjectIdField(ReflectionClass $reflectionClass): string|null + { + $property = null; + + foreach ($reflectionClass->getProperties() as $reflectionProperty) { + $attributeReflectionList = $reflectionProperty->getAttributes(DataSubjectId::class); + + if (!$attributeReflectionList) { + continue; + } + + if ($property !== null) { + throw new MultipleDataSubjectId($property->getName(), $reflectionProperty->getName()); + } + + $property = $reflectionProperty; + } + + if ($property === null) { + return null; + } + + return $this->fieldName($property); + } + + private function fieldName(ReflectionProperty $reflectionProperty): string + { + $attributeReflectionList = $reflectionProperty->getAttributes(NormalizedName::class); + + if (!$attributeReflectionList) { + return $reflectionProperty->getName(); + } + + $attribute = $attributeReflectionList[0]->newInstance(); + + return $attribute->name(); + } } diff --git a/src/Metadata/Event/DataSubjectIdIsPersonalData.php b/src/Metadata/Event/DataSubjectIdIsPersonalData.php new file mode 100644 index 000000000..9ff1b2957 --- /dev/null +++ b/src/Metadata/Event/DataSubjectIdIsPersonalData.php @@ -0,0 +1,24 @@ + */ + public readonly array $propertyMetadata = [], ) { } } diff --git a/src/Metadata/Event/MissingDataSubjectId.php b/src/Metadata/Event/MissingDataSubjectId.php new file mode 100644 index 000000000..d9b7051b8 --- /dev/null +++ b/src/Metadata/Event/MissingDataSubjectId.php @@ -0,0 +1,20 @@ + $class + * @param array $data + * + * @return T + * + * @template T of object + */ + public function hydrate(string $class, array $data): object + { + $data = $this->cryptographer->decrypt($class, $data); + + return $this->hydrator->hydrate($class, $data); + } + + /** @return array */ + public function extract(object $object): array + { + $data = $this->hydrator->extract($object); + + return $this->cryptographer->encrypt($object::class, $data); + } +} diff --git a/src/Serializer/DefaultEventSerializer.php b/src/Serializer/DefaultEventSerializer.php index a1d3f2a4c..e3e0fdbc8 100644 --- a/src/Serializer/DefaultEventSerializer.php +++ b/src/Serializer/DefaultEventSerializer.php @@ -4,6 +4,7 @@ namespace Patchlevel\EventSourcing\Serializer; +use Patchlevel\EventSourcing\Cryptography\EventPayloadCryptographer; use Patchlevel\EventSourcing\Metadata\Event\AttributeEventRegistryFactory; use Patchlevel\EventSourcing\Metadata\Event\EventRegistry; use Patchlevel\EventSourcing\Serializer\Encoder\Encoder; @@ -53,11 +54,20 @@ public function deserialize(SerializedEvent $data, array $options = []): object } /** @param list $paths */ - public static function createFromPaths(array $paths, Upcaster|null $upcaster = null): static - { + public static function createFromPaths( + array $paths, + Upcaster|null $upcaster = null, + EventPayloadCryptographer|null $cryptographer = null, + ): static { + $hydrator = new MetadataHydrator(); + + if ($cryptographer) { + $hydrator = new CryptographicHydrator($hydrator, $cryptographer); + } + return new self( (new AttributeEventRegistryFactory())->create($paths), - new MetadataHydrator(), + $hydrator, new JsonEncoder(), $upcaster, ); diff --git a/tests/Benchmark/BasicImplementation/Events/EmailChanged.php b/tests/Benchmark/BasicImplementation/Events/EmailChanged.php new file mode 100644 index 000000000..d0f642cf8 --- /dev/null +++ b/tests/Benchmark/BasicImplementation/Events/EmailChanged.php @@ -0,0 +1,24 @@ +recordThat(new ProfileCreated($id, $name)); + $self->recordThat(new ProfileCreated($id, $name, $email)); return $self; } @@ -37,6 +38,11 @@ public function changeName(string $name): void $this->recordThat(new NameChanged($name)); } + public function changeEmail(string $email): void + { + $this->recordThat(new EmailChanged($this->id, $email)); + } + public function reborn(): void { $this->recordThat(new Reborn( @@ -50,6 +56,7 @@ protected function applyProfileCreated(ProfileCreated $event): void { $this->id = $event->profileId; $this->name = $event->name; + $this->email = $event->email; } #[Apply] @@ -58,15 +65,27 @@ protected function applyNameChanged(NameChanged $event): void $this->name = $event->name; } + #[Apply] + protected function applyEmailChanged(EmailChanged $event): void + { + $this->email = $event->email; + } + #[Apply] protected function applyReborn(Reborn $event): void { $this->id = $event->profileId; $this->name = $event->name; + $this->email = null; } public function name(): string { return $this->name; } + + public function email(): string|null + { + return $this->email; + } } diff --git a/tests/Benchmark/PersonalDataBench.php b/tests/Benchmark/PersonalDataBench.php new file mode 100644 index 000000000..390dac4cf --- /dev/null +++ b/tests/Benchmark/PersonalDataBench.php @@ -0,0 +1,128 @@ +bus = DefaultEventBus::create(); + + $this->store = new DoctrineDbalStore( + $connection, + DefaultEventSerializer::createFromPaths( + [__DIR__ . '/BasicImplementation/Events'], + cryptographer: $cryptographer, + ), + DefaultHeadersSerializer::createFromPaths([ + __DIR__ . '/../../src', + __DIR__ . '/BasicImplementation/Events', + ]), + 'eventstore', + ); + + $this->repository = new DefaultRepository($this->store, $this->bus, Profile::metadata()); + + $schemaDirector = new DoctrineSchemaDirector( + $connection, + new ChainDoctrineSchemaConfigurator([ + $this->store, + $cipherKeyStore, + ]), + ); + + $schemaDirector->create(); + + $this->id = ProfileId::v7(); + + $profile = Profile::create($this->id, 'Peter', 'info@patchlevel.de'); + + for ($i = 0; $i < 10_000; $i++) { + $profile->changeEmail('info@patchlevel.de'); + } + + $this->repository->save($profile); + } + + #[Bench\Revs(10)] + public function benchLoad10000Events(): void + { + $this->repository->load($this->id); + } + + #[Bench\Revs(10)] + public function benchSave1Event(): void + { + $profile = Profile::create(ProfileId::v7(), 'Peter', 'info@patchlevel.de'); + $this->repository->save($profile); + } + + #[Bench\Revs(10)] + public function benchSave10000Events(): void + { + $profile = Profile::create(ProfileId::v7(), 'Peter', 'info@patchlevel.de'); + + for ($i = 1; $i < 10_000; $i++) { + $profile->changeEmail('info@patchlevel.de'); + } + + $this->repository->save($profile); + } + + #[Bench\Revs(1)] + public function benchSave10000Aggregates(): void + { + for ($i = 1; $i < 10_000; $i++) { + $profile = Profile::create(ProfileId::v7(), 'Peter', 'info@patchlevel.de'); + $this->repository->save($profile); + } + } + + #[Bench\Revs(10)] + public function benchSave10000AggregatesTransaction(): void + { + $this->store->transactional(function (): void { + for ($i = 1; $i < 10_000; $i++) { + $profile = Profile::create(ProfileId::v7(), 'Peter', 'info@patchlevel.de'); + $this->repository->save($profile); + } + }); + } +} diff --git a/tests/Benchmark/SimpleSetupBench.php b/tests/Benchmark/SimpleSetupBench.php index e6a13c7f5..e6af30560 100644 --- a/tests/Benchmark/SimpleSetupBench.php +++ b/tests/Benchmark/SimpleSetupBench.php @@ -14,7 +14,7 @@ use Patchlevel\EventSourcing\Serializer\DefaultEventSerializer; use Patchlevel\EventSourcing\Store\DoctrineDbalStore; use Patchlevel\EventSourcing\Store\Store; -use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Aggregate\Profile; +use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Profile; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\ProfileId; use Patchlevel\EventSourcing\Tests\DbalManager; use PhpBench\Attributes as Bench; diff --git a/tests/Benchmark/SnapshotsBench.php b/tests/Benchmark/SnapshotsBench.php index a8c898b31..135d36750 100644 --- a/tests/Benchmark/SnapshotsBench.php +++ b/tests/Benchmark/SnapshotsBench.php @@ -17,7 +17,7 @@ use Patchlevel\EventSourcing\Snapshot\SnapshotStore; use Patchlevel\EventSourcing\Store\DoctrineDbalStore; use Patchlevel\EventSourcing\Store\Store; -use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Aggregate\Profile; +use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Profile; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\ProfileId; use Patchlevel\EventSourcing\Tests\DbalManager; use PhpBench\Attributes as Bench; diff --git a/tests/Benchmark/SplitStreamBench.php b/tests/Benchmark/SplitStreamBench.php index c0b1ced5f..c319fd198 100644 --- a/tests/Benchmark/SplitStreamBench.php +++ b/tests/Benchmark/SplitStreamBench.php @@ -16,7 +16,7 @@ use Patchlevel\EventSourcing\Serializer\DefaultEventSerializer; use Patchlevel\EventSourcing\Store\DoctrineDbalStore; use Patchlevel\EventSourcing\Store\Store; -use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Aggregate\Profile; +use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Profile; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\ProfileId; use Patchlevel\EventSourcing\Tests\DbalManager; use PhpBench\Attributes as Bench; diff --git a/tests/Benchmark/SubscriptionEngineBench.php b/tests/Benchmark/SubscriptionEngineBench.php index c30a0567d..cb494de1e 100644 --- a/tests/Benchmark/SubscriptionEngineBench.php +++ b/tests/Benchmark/SubscriptionEngineBench.php @@ -19,8 +19,8 @@ use Patchlevel\EventSourcing\Subscription\Engine\SubscriptionEngine; use Patchlevel\EventSourcing\Subscription\Store\DoctrineSubscriptionStore; use Patchlevel\EventSourcing\Subscription\Subscriber\MetadataSubscriberAccessorRepository; -use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Aggregate\Profile; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Processor\SendEmailProcessor; +use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Profile; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\ProfileId; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Projection\ProfileProjector; use Patchlevel\EventSourcing\Tests\DbalManager; diff --git a/tests/Benchmark/blackfire.php b/tests/Benchmark/blackfire.php index aa785c9dc..347aa6f8e 100644 --- a/tests/Benchmark/blackfire.php +++ b/tests/Benchmark/blackfire.php @@ -10,7 +10,7 @@ use Patchlevel\EventSourcing\Schema\DoctrineSchemaDirector; use Patchlevel\EventSourcing\Serializer\DefaultEventSerializer; use Patchlevel\EventSourcing\Store\DoctrineDbalStore; -use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Aggregate\Profile; +use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\Profile; use Patchlevel\EventSourcing\Tests\Benchmark\BasicImplementation\ProfileId; require_once __DIR__ . '/../../vendor/autoload.php'; diff --git a/tests/Integration/PersonalData/Events/NameChanged.php b/tests/Integration/PersonalData/Events/NameChanged.php new file mode 100644 index 000000000..741515412 --- /dev/null +++ b/tests/Integration/PersonalData/Events/NameChanged.php @@ -0,0 +1,24 @@ +connection = DbalManager::createConnection(); + } + + public function tearDown(): void + { + $this->connection->close(); + } + + public function testSuccessful(): void + { + $cipherKeyStore = new DoctrineCipherKeyStore($this->connection); + + $cryptographer = DefaultEventPayloadCryptographer::createWithOpenssl( + new AttributeEventMetadataFactory(), + $cipherKeyStore, + ); + + $store = new DoctrineDbalStore( + $this->connection, + DefaultEventSerializer::createFromPaths([__DIR__ . '/Events'], cryptographer: $cryptographer), + DefaultHeadersSerializer::createFromPaths([ + __DIR__ . '/../../../src', + __DIR__, + ]), + 'eventstore', + ); + + $eventBus = DefaultEventBus::create(); + + $manager = new DefaultRepositoryManager( + new AggregateRootRegistry(['profile' => Profile::class]), + $store, + $eventBus, + ); + + $repository = $manager->get(Profile::class); + + $schemaDirector = new DoctrineSchemaDirector( + $this->connection, + new ChainDoctrineSchemaConfigurator([ + $store, + $cipherKeyStore, + ]), + ); + + $schemaDirector->create(); + + $profileId = ProfileId::fromString('1'); + $profile = Profile::create($profileId, 'John'); + + $repository->save($profile); + + $profile = $repository->load($profileId); + + self::assertInstanceOf(Profile::class, $profile); + self::assertEquals($profileId, $profile->aggregateRootId()); + self::assertSame(1, $profile->playhead()); + self::assertSame('John', $profile->name()); + + $result = $this->connection->fetchAllAssociative('SELECT * FROM eventstore'); + + self::assertCount(1, $result); + self::assertArrayHasKey(0, $result); + + $row = $result[0]; + + self::assertStringNotContainsString('John', $row['payload']); + } + + public function testRemoveKey(): void + { + $cipherKeyStore = new DoctrineCipherKeyStore($this->connection); + + $cryptographer = DefaultEventPayloadCryptographer::createWithOpenssl( + new AttributeEventMetadataFactory(), + $cipherKeyStore, + ); + + $subscriptionStore = new DoctrineSubscriptionStore( + $this->connection, + ); + + $store = new DoctrineDbalStore( + $this->connection, + DefaultEventSerializer::createFromPaths([__DIR__ . '/Events'], cryptographer: $cryptographer), + DefaultHeadersSerializer::createFromPaths([ + __DIR__ . '/../../../src', + __DIR__, + ]), + 'eventstore', + ); + + $eventBus = DefaultEventBus::create(); + + $manager = new DefaultRepositoryManager( + new AggregateRootRegistry(['profile' => Profile::class]), + $store, + $eventBus, + ); + + $repository = $manager->get(Profile::class); + + $schemaDirector = new DoctrineSchemaDirector( + $this->connection, + new ChainDoctrineSchemaConfigurator([ + $store, + $cipherKeyStore, + $subscriptionStore, + ]), + ); + + $schemaDirector->create(); + + $engine = new DefaultSubscriptionEngine( + $store, + $subscriptionStore, + new MetadataSubscriberAccessorRepository([new DeletePersonalDataProcessor($cipherKeyStore)]), + ); + + $engine->setup(skipBooting: true); + + $profileId = ProfileId::fromString('1'); + $profile = Profile::create($profileId, 'John'); + + $repository->save($profile); + $engine->run(); + + $profile = $repository->load($profileId); + + self::assertInstanceOf(Profile::class, $profile); + self::assertEquals($profileId, $profile->aggregateRootId()); + self::assertSame(1, $profile->playhead()); + self::assertSame('John', $profile->name()); + + $profile->removePersonalData(); + $repository->save($profile); + $engine->run(); + + $profile = $repository->load($profileId); + + self::assertInstanceOf(Profile::class, $profile); + self::assertEquals($profileId, $profile->aggregateRootId()); + self::assertSame(2, $profile->playhead()); + self::assertSame('unknown', $profile->name()); + + $profile->changeName('hallo'); + $repository->save($profile); + + $profile = $repository->load($profileId); + + self::assertInstanceOf(Profile::class, $profile); + self::assertEquals($profileId, $profile->aggregateRootId()); + self::assertSame(3, $profile->playhead()); + self::assertSame('hallo', $profile->name()); + } +} diff --git a/tests/Integration/PersonalData/Processor/DeletePersonalDataProcessor.php b/tests/Integration/PersonalData/Processor/DeletePersonalDataProcessor.php new file mode 100644 index 000000000..6b661a5c1 --- /dev/null +++ b/tests/Integration/PersonalData/Processor/DeletePersonalDataProcessor.php @@ -0,0 +1,29 @@ +header(AggregateHeader::class)->aggregateId; + + $this->cipherKeyStore->remove($aggregateId); + } +} diff --git a/tests/Integration/PersonalData/Profile.php b/tests/Integration/PersonalData/Profile.php new file mode 100644 index 000000000..f3d8905b5 --- /dev/null +++ b/tests/Integration/PersonalData/Profile.php @@ -0,0 +1,68 @@ +recordThat(new ProfileCreated($id, $name)); + + return $self; + } + + public function removePersonalData(): void + { + $this->recordThat(new PersonalDataRemoved()); + } + + public function changeName(string $name): void + { + $this->recordThat(new NameChanged($this->id, $name)); + } + + #[Apply(ProfileCreated::class)] + protected function applyProfileCreated(ProfileCreated $event): void + { + $this->id = $event->profileId; + $this->name = $event->name; + } + + #[Apply(PersonalDataRemoved::class)] + protected function applyPersonalDataRemoved(): void + { + $this->name = 'unknown'; + } + + #[Apply(NameChanged::class)] + protected function applyNameChanged(NameChanged $event): void + { + $this->name = $event->name; + } + + public function name(): string + { + return $this->name; + } +} diff --git a/tests/Integration/PersonalData/ProfileId.php b/tests/Integration/PersonalData/ProfileId.php new file mode 100644 index 000000000..6b2f1f6ff --- /dev/null +++ b/tests/Integration/PersonalData/ProfileId.php @@ -0,0 +1,25 @@ +id; + } +} diff --git a/tests/Unit/Cryptography/Cipher/CreateCipherKeyFailedTest.php b/tests/Unit/Cryptography/Cipher/CreateCipherKeyFailedTest.php new file mode 100644 index 000000000..8096db340 --- /dev/null +++ b/tests/Unit/Cryptography/Cipher/CreateCipherKeyFailedTest.php @@ -0,0 +1,19 @@ +getMessage()); + } +} diff --git a/tests/Unit/Cryptography/Cipher/DecryptionFailedTest.php b/tests/Unit/Cryptography/Cipher/DecryptionFailedTest.php new file mode 100644 index 000000000..a3af5c794 --- /dev/null +++ b/tests/Unit/Cryptography/Cipher/DecryptionFailedTest.php @@ -0,0 +1,19 @@ +getMessage()); + } +} diff --git a/tests/Unit/Cryptography/Cipher/EncryptionFailedTest.php b/tests/Unit/Cryptography/Cipher/EncryptionFailedTest.php new file mode 100644 index 000000000..6dbd10ab3 --- /dev/null +++ b/tests/Unit/Cryptography/Cipher/EncryptionFailedTest.php @@ -0,0 +1,19 @@ +getMessage()); + } +} diff --git a/tests/Unit/Cryptography/Cipher/OpensslCipherKeyFactoryTest.php b/tests/Unit/Cryptography/Cipher/OpensslCipherKeyFactoryTest.php new file mode 100644 index 000000000..449c9374a --- /dev/null +++ b/tests/Unit/Cryptography/Cipher/OpensslCipherKeyFactoryTest.php @@ -0,0 +1,33 @@ +assertSame(16, strlen($cipherKey->key)); + $this->assertSame('aes128', $cipherKey->method); + $this->assertSame(16, strlen($cipherKey->iv)); + } + + public function testMethodNotSupported(): void + { + $this->expectException(MethodNotSupported::class); + + $cipherKeyFactory = new OpensslCipherKeyFactory(method: 'foo'); + $cipherKeyFactory(); + } +} diff --git a/tests/Unit/Cryptography/Cipher/OpensslCipherTest.php b/tests/Unit/Cryptography/Cipher/OpensslCipherTest.php new file mode 100644 index 000000000..ca3346cf3 --- /dev/null +++ b/tests/Unit/Cryptography/Cipher/OpensslCipherTest.php @@ -0,0 +1,78 @@ +encrypt($this->createKey(), $value); + + self::assertEquals($encryptedString, $return); + } + + public function testEncryptFailed(): void + { + $this->expectException(EncryptionFailed::class); + + $cipher = new OpensslCipher(); + $cipher->encrypt(new CipherKey( + 'key', + 'bar', + 'abcdefg123456789', + ), ''); + } + + #[DataProvider('dataProvider')] + public function testDecrypt(mixed $value, string $encryptedString): void + { + $cipher = new OpensslCipher(); + $return = $cipher->decrypt($this->createKey(), $encryptedString); + + self::assertEquals($value, $return); + } + + public function testDecryptFailed(): void + { + $this->expectException(DecryptionFailed::class); + + $cipher = new OpensslCipher(); + $cipher->decrypt($this->createKey('foo'), 'emNpWDlMWFBnRStpZk9YZktrUStRQT09'); + } + + public static function dataProvider(): Generator + { + yield 'empty' => ['', 'emNpWDlMWFBnRStpZk9YZktrUStRQT09']; + yield 'string' => ['foo bar baz', 'YUlYRnJZMEd1RkFycjNrQitETHhqQT09']; + yield 'integer' => [42, 'M1FHSnlnbWNlZFJiV2xwdzZIZUhDdz09']; + yield 'float' => [0.5, 'N2tOWGNia3lrdUJ1ancrMFA4OEY0Zz09']; + yield 'null' => [null, 'OUE1T081cXdpNmFMc1FIMGsrME5vdz09']; + yield 'true' => [true, 'NCtWMDE4WnV5NEtCamVVdkIxZjRrdz09']; + yield 'false' => [false, 'czh5NUYxWXhQOWhSbGVwWG5ETFdVQT09']; + yield 'array' => [['foo' => 'bar'], 'cHo2QlhxSnNFZG1kUEhRZ3pjcFJrUT09']; + yield 'long text' => ['Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'eDNCalYzSS9LbkZIcGdKNWVmUFQwTTI0YXhhSnNmdUxXeXhGUGFwMWZkTmx1ZnNwNzBUa29NcUFxUzRFV3V2WWNlUmt6YWhTSlRzVXpqd3RLZkpzUWFWYVRCR1pvbkt3TUE4UzZmaDVQcTYzMzJoWVBRRzllbHhhNjYrenNWbzFDZ2lnVm1PRFhvamozZEVmcXFYVTZGQ1dIWEgzcE1mU2w2SWlRQ2o2WFdNPQ==']; + } + + /** @param non-empty-string $key */ + private function createKey(string $key = 'key'): CipherKey + { + return new CipherKey( + $key, + 'aes128', + 'abcdefg123456789', + ); + } +} diff --git a/tests/Unit/Cryptography/DefaultEventPayloadCryptographerTest.php b/tests/Unit/Cryptography/DefaultEventPayloadCryptographerTest.php new file mode 100644 index 000000000..a739c4e37 --- /dev/null +++ b/tests/Unit/Cryptography/DefaultEventPayloadCryptographerTest.php @@ -0,0 +1,274 @@ +prophesize(CipherKeyStore::class); + $cipherKeyStore->get(Argument::any())->shouldNotBeCalled(); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipher = $this->prophesize(Cipher::class); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $payload = ['id' => 'foo', 'email' => 'info@patchlevel.de']; + + $result = $cryptographer->encrypt(ProfileVisited::class, ['id' => 'foo', 'email' => 'info@patchlevel.de']); + + self::assertSame($payload, $result); + } + + public function testEncryptWithMissingKey(): void + { + $cipherKey = new CipherKey( + 'foo', + 'bar', + 'baz', + ); + + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyStore->get('foo')->willThrow(new CipherKeyNotExists('foo')); + $cipherKeyStore->store('foo', $cipherKey)->shouldBeCalled(); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipherKeyFactory->__invoke()->willReturn($cipherKey)->shouldBeCalledOnce(); + + $cipher = $this->prophesize(Cipher::class); + $cipher + ->encrypt($cipherKey, 'info@patchlevel.de') + ->willReturn('encrypted') + ->shouldBeCalledOnce(); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $result = $cryptographer->encrypt(EmailChanged::class, ['id' => 'foo', 'email' => 'info@patchlevel.de']); + + self::assertEquals(['id' => 'foo', 'email' => 'encrypted'], $result); + } + + public function testEncryptWithExistingKey(): void + { + $cipherKey = new CipherKey( + 'foo', + 'bar', + 'baz', + ); + + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyStore->get('foo')->willReturn($cipherKey); + $cipherKeyStore->store('foo', Argument::type(CipherKey::class))->shouldNotBeCalled(); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipherKeyFactory->__invoke()->shouldNotBeCalled(); + + $cipher = $this->prophesize(Cipher::class); + $cipher + ->encrypt($cipherKey, 'info@patchlevel.de') + ->willReturn('encrypted') + ->shouldBeCalledOnce(); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $result = $cryptographer->encrypt(EmailChanged::class, ['id' => 'foo', 'email' => 'info@patchlevel.de']); + + self::assertEquals(['id' => 'foo', 'email' => 'encrypted'], $result); + } + + public function testSkipDecrypt(): void + { + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyStore->get(Argument::any())->shouldNotBeCalled(); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipher = $this->prophesize(Cipher::class); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $payload = ['id' => 'foo', 'email' => 'info@patchlevel.de']; + + $result = $cryptographer->decrypt(ProfileVisited::class, ['id' => 'foo', 'email' => 'info@patchlevel.de']); + + self::assertSame($payload, $result); + } + + public function testDecryptWithMissingKey(): void + { + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyStore->get('foo')->willThrow(new CipherKeyNotExists('foo')); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipherKeyFactory->__invoke()->shouldNotBeCalled(); + + $cipher = $this->prophesize(Cipher::class); + $cipher->decrypt()->shouldNotBeCalled(); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $result = $cryptographer->decrypt(EmailChanged::class, ['id' => 'foo', 'email' => 'encrypted']); + + self::assertEquals(['id' => 'foo', 'email' => 'fallback'], $result); + } + + public function testDecryptWithInvalidKey(): void + { + $cipherKey = new CipherKey( + 'foo', + 'bar', + 'baz', + ); + + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyStore->get('foo')->willReturn($cipherKey); + $cipherKeyStore->store('foo', Argument::type(CipherKey::class))->shouldNotBeCalled(); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipherKeyFactory->__invoke()->shouldNotBeCalled(); + + $cipher = $this->prophesize(Cipher::class); + $cipher + ->decrypt($cipherKey, 'encrypted') + ->willThrow(new DecryptionFailed()) + ->shouldBeCalledOnce(); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $result = $cryptographer->decrypt(EmailChanged::class, ['id' => 'foo', 'email' => 'encrypted']); + + self::assertEquals(['id' => 'foo', 'email' => 'fallback'], $result); + } + + public function testDecryptWithExistingKey(): void + { + $cipherKey = new CipherKey( + 'foo', + 'bar', + 'baz', + ); + + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyStore->get('foo')->willReturn($cipherKey); + $cipherKeyStore->store('foo', Argument::type(CipherKey::class))->shouldNotBeCalled(); + + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipherKeyFactory->__invoke()->shouldNotBeCalled(); + + $cipher = $this->prophesize(Cipher::class); + $cipher + ->decrypt($cipherKey, 'encrypted') + ->willReturn('info@patchlevel.de') + ->shouldBeCalledOnce(); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $result = $cryptographer->decrypt(EmailChanged::class, ['id' => 'foo', 'email' => 'encrypted']); + + self::assertEquals(['id' => 'foo', 'email' => 'info@patchlevel.de'], $result); + } + + public function testUnsupportedSubjectId(): void + { + $this->expectException(UnsupportedSubjectId::class); + + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipher = $this->prophesize(Cipher::class); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $cryptographer->decrypt(EmailChanged::class, ['id' => null, 'email' => 'encrypted']); + } + + public function testMissingSubjectId(): void + { + $this->expectException(MissingSubjectId::class); + + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + $cipherKeyFactory = $this->prophesize(CipherKeyFactory::class); + $cipher = $this->prophesize(Cipher::class); + + $cryptographer = new DefaultEventPayloadCryptographer( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + $cipherKeyFactory->reveal(), + $cipher->reveal(), + ); + + $cryptographer->decrypt(EmailChanged::class, ['email' => 'encrypted']); + } + + public function testCreateWithOpenssl(): void + { + $cipherKeyStore = $this->prophesize(CipherKeyStore::class); + + $cryptographer = DefaultEventPayloadCryptographer::createWithOpenssl( + new AttributeEventMetadataFactory(), + $cipherKeyStore->reveal(), + ); + + self::assertInstanceOf(DefaultEventPayloadCryptographer::class, $cryptographer); + } +} diff --git a/tests/Unit/Cryptography/MissingSubjectIdTest.php b/tests/Unit/Cryptography/MissingSubjectIdTest.php new file mode 100644 index 000000000..90b6c0b6e --- /dev/null +++ b/tests/Unit/Cryptography/MissingSubjectIdTest.php @@ -0,0 +1,19 @@ +getMessage()); + } +} diff --git a/tests/Unit/Cryptography/Store/CipherKeyNotExistsTest.php b/tests/Unit/Cryptography/Store/CipherKeyNotExistsTest.php new file mode 100644 index 000000000..c7c1d112f --- /dev/null +++ b/tests/Unit/Cryptography/Store/CipherKeyNotExistsTest.php @@ -0,0 +1,19 @@ +getMessage()); + } +} diff --git a/tests/Unit/Cryptography/Store/InMemoryCipherKeyStoreTest.php b/tests/Unit/Cryptography/Store/InMemoryCipherKeyStoreTest.php new file mode 100644 index 000000000..d4ee6ec22 --- /dev/null +++ b/tests/Unit/Cryptography/Store/InMemoryCipherKeyStoreTest.php @@ -0,0 +1,76 @@ +store('foo', $key); + + self::assertSame($key, $store->get('foo')); + } + + public function testLoadFailed(): void + { + $this->expectException(CipherKeyNotExists::class); + + $store = new InMemoryCipherKeyStore(); + $store->get('foo'); + } + + public function testRemove(): void + { + $key = new CipherKey( + 'foo', + 'bar', + 'baz', + ); + + $store = new InMemoryCipherKeyStore(); + $store->store('foo', $key); + + self::assertSame($key, $store->get('foo')); + + $store->remove('foo'); + + $this->expectException(CipherKeyNotExists::class); + + $store->get('foo'); + } + + public function testClear(): void + { + $key = new CipherKey( + 'foo', + 'bar', + 'baz', + ); + + $store = new InMemoryCipherKeyStore(); + $store->store('foo', $key); + + self::assertSame($key, $store->get('foo')); + + $store->clear(); + + $this->expectException(CipherKeyNotExists::class); + + $store->get('foo'); + } +} diff --git a/tests/Unit/Cryptography/UnsupportedSubjectIdTest.php b/tests/Unit/Cryptography/UnsupportedSubjectIdTest.php new file mode 100644 index 000000000..036660ec9 --- /dev/null +++ b/tests/Unit/Cryptography/UnsupportedSubjectIdTest.php @@ -0,0 +1,19 @@ +getMessage()); + } +} diff --git a/tests/Unit/Fixture/EmailChanged.php b/tests/Unit/Fixture/EmailChanged.php new file mode 100644 index 000000000..60bcbfc41 --- /dev/null +++ b/tests/Unit/Fixture/EmailChanged.php @@ -0,0 +1,21 @@ +metadata($event::class); self::assertSame('profile_created', $metadata->name); + self::assertSame(false, $metadata->splitStream); + self::assertSame(null, $metadata->dataSubjectIdField); + self::assertEmpty($metadata->propertyMetadata); + } + + public function testSplitStream(): void + { + $event = new #[Event('profile_created')] + #[SplitStream] + class { + }; + + $metadataFactory = new AttributeEventMetadataFactory(); + $metadata = $metadataFactory->metadata($event::class); + + self::assertSame('profile_created', $metadata->name); + self::assertSame(true, $metadata->splitStream); + self::assertSame(null, $metadata->dataSubjectIdField); + self::assertEmpty($metadata->propertyMetadata); + } + + public function testPersonalData(): void + { + $event = new #[Event('profile_created')] + class ('id', 'name') { + public function __construct( + #[DataSubjectId] + #[NormalizedName('_id')] + public string $id, + #[PersonalData('fallback')] + #[NormalizedName('_name')] + public string $name, + ) { + } + }; + + $metadataFactory = new AttributeEventMetadataFactory(); + $metadata = $metadataFactory->metadata($event::class); + + self::assertSame('profile_created', $metadata->name); + self::assertSame(false, $metadata->splitStream); + self::assertSame('_id', $metadata->dataSubjectIdField); + self::assertCount(2, $metadata->propertyMetadata); + + self::assertSame('id', $metadata->propertyMetadata['id']->propertyName); + self::assertSame(false, $metadata->propertyMetadata['id']->isPersonalData); + self::assertSame('_id', $metadata->propertyMetadata['id']->fieldName); + self::assertSame(null, $metadata->propertyMetadata['id']->personalDataFallback); + + self::assertSame('name', $metadata->propertyMetadata['name']->propertyName); + self::assertSame(true, $metadata->propertyMetadata['name']->isPersonalData); + self::assertSame('_name', $metadata->propertyMetadata['name']->fieldName); + self::assertSame('fallback', $metadata->propertyMetadata['name']->personalDataFallback); + } + + public function testMissingDataSubjectId(): void + { + $event = new #[Event('profile_created')] + class ('name') { + public function __construct( + #[PersonalData] + public string $name, + ) { + } + }; + + $this->expectException(MissingDataSubjectId::class); + + $metadataFactory = new AttributeEventMetadataFactory(); + $metadataFactory->metadata($event::class); + } + + public function testDataSubjectIdIsPersonalData(): void + { + $event = new #[Event('profile_created')] + class ('name') { + public function __construct( + #[DataSubjectId] + #[PersonalData] + public string $name, + ) { + } + }; + + $this->expectException(DataSubjectIdIsPersonalData::class); + + $metadataFactory = new AttributeEventMetadataFactory(); + $metadataFactory->metadata($event::class); + } + + public function testMultipleDataSubjectId(): void + { + $event = new #[Event('profile_created')] + class ('id', 'name') { + public function __construct( + #[DataSubjectId] + public string $id, + #[DataSubjectId] + public string $name, + ) { + } + }; + + $this->expectException(MultipleDataSubjectId::class); + + $metadataFactory = new AttributeEventMetadataFactory(); + $metadataFactory->metadata($event::class); } } diff --git a/tests/Unit/Serializer/CryptographicHydratorTest.php b/tests/Unit/Serializer/CryptographicHydratorTest.php new file mode 100644 index 000000000..b6431318e --- /dev/null +++ b/tests/Unit/Serializer/CryptographicHydratorTest.php @@ -0,0 +1,74 @@ + 'bar']; + $encryptedPayload = ['foo' => 'encrypted']; + + $parentHydrator = $this->prophesize(Hydrator::class); + $parentHydrator + ->hydrate(stdClass::class, $payload) + ->willReturn($object) + ->shouldBeCalledOnce(); + + $cryptographer = $this->prophesize(EventPayloadCryptographer::class); + $cryptographer + ->decrypt(stdClass::class, $encryptedPayload) + ->willReturn($payload) + ->shouldBeCalledOnce(); + + $hydrator = new CryptographicHydrator( + $parentHydrator->reveal(), + $cryptographer->reveal(), + ); + + $return = $hydrator->hydrate(stdClass::class, $encryptedPayload); + + self::assertSame($object, $return); + } + + public function testExtract(): void + { + $object = new stdClass(); + $payload = ['foo' => 'bar']; + $encryptedPayload = ['foo' => 'encrypted']; + + $parentHydrator = $this->prophesize(Hydrator::class); + $parentHydrator + ->extract($object) + ->willReturn($payload) + ->shouldBeCalledOnce(); + + $cryptographer = $this->prophesize(EventPayloadCryptographer::class); + $cryptographer + ->encrypt(stdClass::class, $payload) + ->willReturn($encryptedPayload) + ->shouldBeCalledOnce(); + + $hydrator = new CryptographicHydrator( + $parentHydrator->reveal(), + $cryptographer->reveal(), + ); + + $return = $hydrator->extract($object); + + self::assertSame($encryptedPayload, $return); + } +}