Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,6 @@
<code><![CDATA[new ReflectionClass($data['className'])]]></code>
</InvalidPropertyAssignmentValue>
</file>
<file src="src/Metadata/PropertyMetadata.php">
<RiskyTruthyFalsyComparison>
<code><![CDATA[$this->sensitiveDataFallbackCallable]]></code>
</RiskyTruthyFalsyComparison>
</file>
<file src="src/MetadataHydrator.php">
<InvalidOperand>
<code><![CDATA[$guessers]]></code>
Expand Down Expand Up @@ -93,6 +88,11 @@
<code><![CDATA[Generator]]></code>
</MixedReturnStatement>
</file>
<file src="tests/Unit/Cryptography/CryptographyMetadataFactoryTest.php">
<MixedAssignment>
<code><![CDATA[$sensitiveDataInfo]]></code>
</MixedAssignment>
</file>
<file src="tests/Unit/Cryptography/CryptographySubscriberTest.php">
<InvalidArgument>
<code><![CDATA[$metadata]]></code>
Expand Down
84 changes: 84 additions & 0 deletions src/Cryptography/CryptographyMetadataFactory.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Cryptography;

use Patchlevel\Hydrator\Attribute\DataSubjectId;
use Patchlevel\Hydrator\Attribute\SensitiveData;
use Patchlevel\Hydrator\Metadata\ClassMetadata;
use Patchlevel\Hydrator\Metadata\MetadataFactory;
use ReflectionProperty;

use function array_key_exists;

final class CryptographyMetadataFactory implements MetadataFactory
{
public function __construct(
private readonly MetadataFactory $metadataFactory,
) {
}

public function metadata(string $class): ClassMetadata
{
$metadata = $this->metadataFactory->metadata($class);

$subjectIdMapping = [];

foreach ($metadata->properties as $property) {
$isSubjectId = false;
$attributeReflectionList = $property->reflection->getAttributes(DataSubjectId::class);

if ($attributeReflectionList) {
$subjectIdIdentifier = $attributeReflectionList[0]->newInstance()->name;

if (array_key_exists($subjectIdIdentifier, $subjectIdMapping)) {
throw new DuplicateSubjectIdIdentifier(
$metadata->className(),
$metadata->propertyForField($subjectIdMapping[$subjectIdIdentifier])->propertyName(),
$property->propertyName(),
$subjectIdIdentifier,
);
}

$subjectIdMapping[$subjectIdIdentifier] = $property->fieldName;

$isSubjectId = true;
}

$sensitiveDataInfo = $this->sensitiveDataInfo($property->reflection);

if (!$sensitiveDataInfo) {
continue;
}

if ($isSubjectId) {
throw new SubjectIdAndSensitiveDataConflict($metadata->className(), $property->propertyName());
}

$property->extras[SensitiveDataInfo::class] = $sensitiveDataInfo;
}

if ($subjectIdMapping !== []) {
$metadata->extras[SubjectIdFieldMapping::class] = new SubjectIdFieldMapping($subjectIdMapping);
}

return $metadata;
}

private function sensitiveDataInfo(ReflectionProperty $reflectionProperty): SensitiveDataInfo|null
{
$attributeReflectionList = $reflectionProperty->getAttributes(SensitiveData::class);

if ($attributeReflectionList === []) {
return null;
}

$attribute = $attributeReflectionList[0]->newInstance();

return new SensitiveDataInfo(
$attribute->subjectIdName,
$attribute->fallbackCallable !== null ? ($attribute->fallbackCallable)(...) : $attribute->fallback,
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

declare(strict_types=1);

namespace Patchlevel\Hydrator\Metadata;
namespace Patchlevel\Hydrator\Cryptography;

use Patchlevel\Hydrator\Metadata\MetadataException;
use RuntimeException;

use function sprintf;
Expand Down
18 changes: 0 additions & 18 deletions src/Cryptography/NotSensitiveData.php

This file was deleted.

14 changes: 14 additions & 0 deletions src/Cryptography/SensitiveDataInfo.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Cryptography;

final class SensitiveDataInfo
{
public function __construct(
public readonly string $subjectIdName,
public readonly mixed $fallback = null,
) {
}
}
104 changes: 65 additions & 39 deletions src/Cryptography/SensitiveDataPayloadCryptographer.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Patchlevel\Hydrator\Cryptography;

use Closure;
use Patchlevel\Hydrator\Cryptography\Cipher\Cipher;
use Patchlevel\Hydrator\Cryptography\Cipher\CipherKeyFactory;
use Patchlevel\Hydrator\Cryptography\Cipher\DecryptionFailed;
Expand All @@ -12,14 +13,15 @@
use Patchlevel\Hydrator\Cryptography\Store\CipherKeyNotExists;
use Patchlevel\Hydrator\Cryptography\Store\CipherKeyStore;
use Patchlevel\Hydrator\Metadata\ClassMetadata;
use Patchlevel\Hydrator\Metadata\PropertyMetadata;

use function array_key_exists;
use function is_int;
use function is_string;

final class SensitiveDataPayloadCryptographer implements PayloadCryptographer
{
private const ENCRYPTED_PREFIX = '!';

public function __construct(
private readonly CipherKeyStore $cipherKeyStore,
private readonly CipherKeyFactory $cipherKeyFactory,
Expand All @@ -36,12 +38,26 @@ public function __construct(
*/
public function encrypt(ClassMetadata $metadata, array $data): array
{
$mapping = $metadata->extras[SubjectIdFieldMapping::class] ?? null;

if (!$mapping instanceof SubjectIdFieldMapping) {
return $data;
}

$subjectIds = $this->getSubjectIds($metadata, $mapping, $data);

foreach ($metadata->properties as $propertyMetadata) {
if (!$propertyMetadata->isSensitiveData()) {
$sensitiveDataInfo = $propertyMetadata->extras[SensitiveDataInfo::class] ?? null;

if (!$sensitiveDataInfo instanceof SensitiveDataInfo) {
continue;
}

$subjectId = $this->subjectId($propertyMetadata, $metadata, $data);
$subjectId = $subjectIds[$sensitiveDataInfo->subjectIdName] ?? null;

if ($subjectId === null) {
throw new MissingSubjectId($metadata->className(), $sensitiveDataInfo->subjectIdName);
}

try {
$cipherKey = $this->cipherKeyStore->get($subjectId);
Expand All @@ -51,7 +67,7 @@ public function encrypt(ClassMetadata $metadata, array $data): array
}

$targetFieldName = $this->useEncryptedFieldName
? $propertyMetadata->encryptedFieldName()
? self::ENCRYPTED_PREFIX . $propertyMetadata->fieldName
: $propertyMetadata->fieldName;

$data[$targetFieldName] = $this->cipher->encrypt(
Expand All @@ -76,30 +92,44 @@ public function encrypt(ClassMetadata $metadata, array $data): array
*/
public function decrypt(ClassMetadata $metadata, array $data): array
{
$mapping = $metadata->extras[SubjectIdFieldMapping::class] ?? null;

if (!$mapping instanceof SubjectIdFieldMapping) {
return $data;
}

$subjectIds = $this->getSubjectIds($metadata, $mapping, $data);

foreach ($metadata->properties as $propertyMetadata) {
if (!$propertyMetadata->isSensitiveData()) {
$sensitiveDataInfo = $propertyMetadata->extras[SensitiveDataInfo::class] ?? null;

if (!$sensitiveDataInfo instanceof SensitiveDataInfo) {
continue;
}

$subjectId = $this->subjectId($propertyMetadata, $metadata, $data);
$subjectId = $subjectIds[$sensitiveDataInfo->subjectIdName] ?? null;

if ($subjectId === null) {
throw new MissingSubjectId($metadata->className(), $sensitiveDataInfo->subjectIdName);
}

try {
$cipherKey = $this->cipherKeyStore->get($subjectId);
} catch (CipherKeyNotExists) {
$cipherKey = null;
}

if ($this->useEncryptedFieldName && array_key_exists($propertyMetadata->encryptedFieldName(), $data)) {
$rawData = $data[$propertyMetadata->encryptedFieldName()];
unset($data[$propertyMetadata->encryptedFieldName()]);
if ($this->useEncryptedFieldName && array_key_exists(self::ENCRYPTED_PREFIX . $propertyMetadata->fieldName, $data)) {
$rawData = $data[self::ENCRYPTED_PREFIX . $propertyMetadata->fieldName];
unset($data[self::ENCRYPTED_PREFIX . $propertyMetadata->fieldName]);
} elseif (!$this->useEncryptedFieldName || $this->fallbackToFieldName) {
$rawData = $data[$propertyMetadata->fieldName];
} else {
continue;
}

if (!$cipherKey) {
$data[$propertyMetadata->fieldName] = $this->fallback($propertyMetadata, $subjectId, $rawData);
$data[$propertyMetadata->fieldName] = $this->fallback($sensitiveDataInfo, $subjectId, $rawData);
continue;
}

Expand All @@ -109,54 +139,50 @@ public function decrypt(ClassMetadata $metadata, array $data): array
$rawData,
);
} catch (DecryptionFailed) {
$data[$propertyMetadata->fieldName] = $this->fallback($propertyMetadata, $subjectId, $rawData);
$data[$propertyMetadata->fieldName] = $this->fallback($sensitiveDataInfo, $subjectId, $rawData);
}
}

return $data;
}

/** @param array<string, mixed> $data */
private function subjectId(PropertyMetadata $propertyMetadata, ClassMetadata $metadata, array $data): string
/**
* @param array<string, mixed> $data
*
* @return array<string, string>
*/
private function getSubjectIds(ClassMetadata $metadata, SubjectIdFieldMapping $mapping, array $data): array
{
if (!$propertyMetadata->isSensitiveData()) {
throw new NotSensitiveData($metadata->className(), $propertyMetadata->propertyName());
}

$sensitiveDataSubjectIdName = $propertyMetadata->sensitiveDataSubjectIdName;

if (!$metadata->hasSubjectIdIdentifier($sensitiveDataSubjectIdName)) {
throw new MissingSubjectId($metadata->className(), $propertyMetadata->propertyName());
}
$result = [];

$fieldName = $metadata->getSubjectIdFieldName($sensitiveDataSubjectIdName);
foreach ($mapping->nameToField as $name => $fieldName) {
if (!array_key_exists($fieldName, $data)) {
throw new MissingSubjectId($metadata->className(), $fieldName);
}

if (!array_key_exists($fieldName, $data)) {
throw new MissingSubjectId($metadata->className(), $fieldName);
}
$subjectId = $data[$fieldName];

$subjectId = $data[$fieldName];
if (is_int($subjectId)) {
$subjectId = (string)$subjectId;
}

if (is_int($subjectId)) {
$subjectId = (string)$subjectId;
}
if (!is_string($subjectId)) {
throw new UnsupportedSubjectId($metadata->className(), $fieldName, $subjectId);
}

if (!is_string($subjectId)) {
throw new UnsupportedSubjectId($metadata->className(), $fieldName, $subjectId);
$result[$name] = $subjectId;
}

return $subjectId;
return $result;
}

private function fallback(PropertyMetadata $propertyMetadata, string $subjectId, mixed $rawData): mixed
private function fallback(SensitiveDataInfo $sensitiveDataInfo, string $subjectId, mixed $rawData): mixed
{
$callback = $propertyMetadata->sensitiveDataFallbackCallable();

if (!$callback) {
return $propertyMetadata->sensitiveDataFallback;
if ($sensitiveDataInfo->fallback instanceof Closure) {
return ($sensitiveDataInfo->fallback)($subjectId, $rawData);
}

return $callback($subjectId, $rawData);
return $sensitiveDataInfo->fallback;
}

/** @param non-empty-string $method */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

declare(strict_types=1);

namespace Patchlevel\Hydrator\Metadata;
namespace Patchlevel\Hydrator\Cryptography;

use Patchlevel\Hydrator\Metadata\MetadataException;
use RuntimeException;

use function sprintf;
Expand Down
14 changes: 14 additions & 0 deletions src/Cryptography/SubjectIdFieldMapping.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

declare(strict_types=1);

namespace Patchlevel\Hydrator\Cryptography;

final class SubjectIdFieldMapping
{
/** @param array<string, string> $nameToField */
public function __construct(
public readonly array $nameToField,
) {
}
}
Loading
Loading