Skip to content

Commit 3839263

Browse files
committed
feat(model): add encrypted JSON casts
- Add encrypted-json and encrypted-json-array cast types - Reuse existing JSON and encrypted cast handling - Cover nullable values, invalid payloads, DataConverter, and Entity usage - Update Model and Entity docs Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 0d4f36d commit 3839263

6 files changed

Lines changed: 238 additions & 53 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\DataCaster\Cast;
15+
16+
use SensitiveParameter;
17+
use stdClass;
18+
19+
/**
20+
* Class EncryptedJsonCast
21+
*
22+
* (PHP) [array|stdClass --> encrypted JSON string] --> (DB driver) --> (DB column) string
23+
* [ <-- decrypted JSON string] <-- (DB driver) <-- (DB column) encrypted JSON string
24+
*/
25+
class EncryptedJsonCast extends BaseCast
26+
{
27+
/**
28+
* @return array<array-key, mixed>|stdClass|null
29+
*/
30+
public static function get(
31+
#[SensitiveParameter]
32+
mixed $value,
33+
array $params = [],
34+
?object $helper = null,
35+
): array|stdClass|null {
36+
if ($value === null) {
37+
return null;
38+
}
39+
40+
$json = EncryptedCast::get($value, $params, $helper);
41+
42+
return JsonCast::get($json, $params, $helper);
43+
}
44+
45+
public static function set(
46+
#[SensitiveParameter]
47+
mixed $value,
48+
array $params = [],
49+
?object $helper = null,
50+
): ?string {
51+
if ($value === null) {
52+
return null;
53+
}
54+
55+
$json = JsonCast::set($value, $params, $helper);
56+
57+
return EncryptedCast::set($json, $params, $helper);
58+
}
59+
}

‎system/DataCaster/DataCaster.php‎

Lines changed: 24 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use CodeIgniter\DataCaster\Cast\CSVCast;
2020
use CodeIgniter\DataCaster\Cast\DatetimeCast;
2121
use CodeIgniter\DataCaster\Cast\EncryptedCast;
22+
use CodeIgniter\DataCaster\Cast\EncryptedJsonCast;
2223
use CodeIgniter\DataCaster\Cast\EnumCast;
2324
use CodeIgniter\DataCaster\Cast\FloatCast;
2425
use CodeIgniter\DataCaster\Cast\IntBoolCast;
@@ -51,21 +52,22 @@ final class DataCaster
5152
* @var cast_handlers [type => classname]
5253
*/
5354
private array $castHandlers = [
54-
'array' => ArrayCast::class,
55-
'bool' => BooleanCast::class,
56-
'boolean' => BooleanCast::class,
57-
'csv' => CSVCast::class,
58-
'datetime' => DatetimeCast::class,
59-
'encrypted' => EncryptedCast::class,
60-
'enum' => EnumCast::class,
61-
'double' => FloatCast::class,
62-
'float' => FloatCast::class,
63-
'int' => IntegerCast::class,
64-
'integer' => IntegerCast::class,
65-
'int-bool' => IntBoolCast::class,
66-
'json' => JsonCast::class,
67-
'timestamp' => TimestampCast::class,
68-
'uri' => URICast::class,
55+
'array' => ArrayCast::class,
56+
'bool' => BooleanCast::class,
57+
'boolean' => BooleanCast::class,
58+
'csv' => CSVCast::class,
59+
'datetime' => DatetimeCast::class,
60+
'encrypted' => EncryptedCast::class,
61+
'encrypted-json' => EncryptedJsonCast::class,
62+
'enum' => EnumCast::class,
63+
'double' => FloatCast::class,
64+
'float' => FloatCast::class,
65+
'int' => IntegerCast::class,
66+
'integer' => IntegerCast::class,
67+
'int-bool' => IntBoolCast::class,
68+
'json' => JsonCast::class,
69+
'timestamp' => TimestampCast::class,
70+
'uri' => URICast::class,
6971
];
7072

7173
/**
@@ -159,9 +161,13 @@ public function castAs(mixed $value, string $field, string $method = 'get'): mix
159161
}
160162
}
161163

162-
// In order not to create a separate handler for the
163-
// json-array type, we transform the required one.
164-
$type = ($type === 'json-array') ? 'json[array]' : $type;
164+
// In order not to create separate handlers for these
165+
// array variants, we transform the required ones.
166+
$type = match ($type) {
167+
'json-array' => 'json[array]',
168+
'encrypted-json-array' => 'encrypted-json[array]',
169+
default => $type,
170+
};
165171

166172
$params = [];
167173

‎tests/system/DataCaster/EncryptedCastTest.php‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
use Config\Services;
2424
use PHPUnit\Framework\Attributes\Group;
2525
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
26+
use stdClass;
2627

2728
/**
2829
* @internal
@@ -109,6 +110,73 @@ public function testEncryptedCastCanDecryptPreviousKeyValues(): void
109110
$this->assertSame('old-secret', $dataCaster->castAs($oldEncryptedValue, 'secret'));
110111
}
111112

113+
public function testEncryptedJsonCastConvertsObjectToAndFromEncryptedJson(): void
114+
{
115+
$dataCaster = new DataCaster(types: ['settings' => 'encrypted-json']);
116+
117+
$encrypted = $dataCaster->castAs((object) ['notifications' => true, 'theme' => 'dark'], 'settings', 'set');
118+
119+
$this->assertIsString($encrypted);
120+
$this->assertNotSame('{"notifications":true,"theme":"dark"}', $encrypted);
121+
$this->assertNotFalse(base64_decode($encrypted, true));
122+
123+
$settings = $dataCaster->castAs($encrypted, 'settings');
124+
125+
$this->assertInstanceOf(stdClass::class, $settings);
126+
$this->assertTrue($settings->notifications);
127+
$this->assertSame('dark', $settings->theme);
128+
}
129+
130+
public function testEncryptedJsonArrayCastConvertsArrayToAndFromEncryptedJson(): void
131+
{
132+
$dataCaster = new DataCaster(types: ['settings' => 'encrypted-json-array']);
133+
134+
$encrypted = $dataCaster->castAs(['notifications' => true, 'theme' => 'dark'], 'settings', 'set');
135+
136+
$this->assertIsString($encrypted);
137+
$this->assertNotSame('{"notifications":true,"theme":"dark"}', $encrypted);
138+
$this->assertSame(
139+
['notifications' => true, 'theme' => 'dark'],
140+
$dataCaster->castAs($encrypted, 'settings'),
141+
);
142+
}
143+
144+
public function testEncryptedJsonCastsSupportNullableValues(): void
145+
{
146+
$dataCaster = new DataCaster(types: [
147+
'settings' => '?encrypted-json',
148+
'arraySettings' => '?encrypted-json-array',
149+
]);
150+
151+
$this->assertNull($dataCaster->castAs(null, 'settings', 'set'));
152+
$this->assertNull($dataCaster->castAs(null, 'settings'));
153+
$this->assertNull($dataCaster->castAs(null, 'arraySettings', 'set'));
154+
$this->assertNull($dataCaster->castAs(null, 'arraySettings'));
155+
}
156+
157+
public function testEncryptedJsonCastRejectsMalformedEncryptedPayload(): void
158+
{
159+
$this->expectException(CastException::class);
160+
$this->expectExceptionMessage('Type casting "encrypted" expects a valid encrypted value.');
161+
162+
$dataCaster = new DataCaster(types: ['settings' => 'encrypted-json']);
163+
164+
$dataCaster->castAs('@@not-base64@@', 'settings');
165+
}
166+
167+
public function testEncryptedJsonCastRejectsDecryptedMalformedJson(): void
168+
{
169+
$this->expectException(CastException::class);
170+
$this->expectExceptionMessage('Syntax error, malformed JSON.');
171+
172+
$encryptedCast = new DataCaster(types: ['settings' => 'encrypted']);
173+
$encrypted = $encryptedCast->castAs('not-json', 'settings', 'set');
174+
175+
$dataCaster = new DataCaster(types: ['settings' => 'encrypted-json']);
176+
177+
$dataCaster->castAs($encrypted, 'settings');
178+
}
179+
112180
public function testDataConverterConvertsEncryptedFieldToAndFromDataSource(): void
113181
{
114182
$converter = new DataConverter(['secret' => 'encrypted']);
@@ -120,6 +188,21 @@ public function testDataConverterConvertsEncryptedFieldToAndFromDataSource(): vo
120188
$this->assertSame(['secret' => 'plain-secret'], $converter->fromDataSource($dataSourceData));
121189
}
122190

191+
public function testDataConverterConvertsEncryptedJsonArrayFieldToAndFromDataSource(): void
192+
{
193+
$converter = new DataConverter(['settings' => 'encrypted-json-array']);
194+
195+
$dataSourceData = $converter->toDataSource([
196+
'settings' => ['notifications' => true, 'theme' => 'dark'],
197+
]);
198+
199+
$this->assertIsString($dataSourceData['settings']);
200+
$this->assertSame(
201+
['settings' => ['notifications' => true, 'theme' => 'dark']],
202+
$converter->fromDataSource($dataSourceData),
203+
);
204+
}
205+
123206
public function testEntityStoresEncryptedRawValueAndReturnsPlaintext(): void
124207
{
125208
$entity = new class () extends Entity {
@@ -138,6 +221,27 @@ public function testEntityStoresEncryptedRawValueAndReturnsPlaintext(): void
138221
$this->assertSame(['secret' => 'plain-secret'], $entity->toArray());
139222
}
140223

224+
public function testEntityStoresEncryptedJsonRawValueAndReturnsPlainValue(): void
225+
{
226+
$entity = new class () extends Entity {
227+
protected $casts = [
228+
'settings' => 'encrypted-json-array',
229+
];
230+
};
231+
232+
$entity->settings = ['notifications' => true, 'theme' => 'dark'];
233+
234+
$raw = $entity->toRawArray();
235+
236+
$this->assertIsString($raw['settings']);
237+
$this->assertNotSame('{"notifications":true,"theme":"dark"}', $raw['settings']);
238+
$this->assertSame(['notifications' => true, 'theme' => 'dark'], $entity->settings);
239+
$this->assertSame(
240+
['settings' => ['notifications' => true, 'theme' => 'dark']],
241+
$entity->toArray(),
242+
);
243+
}
244+
141245
/**
142246
* @param list<string> $previousKeys
143247
*/

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -274,7 +274,7 @@ Model
274274
=====
275275

276276
- Added new ``chunkRows()`` method to ``CodeIgniter\Model`` for processing large datasets in smaller chunks.
277-
- Added ``encrypted`` casting for Entity properties and Model fields using the Encryption service. See :ref:`model-field-casting-encrypted`.
277+
- Added ``encrypted``, ``encrypted-json`` and ``encrypted-json-array`` casting for Entity properties and Model fields using the Encryption service. See :ref:`model-field-casting-encrypted`.
278278
- Added new ``firstOrInsert()`` method to ``CodeIgniter\Model`` that finds the first row matching the given attributes or inserts a new one. See :ref:`model-first-or-insert`.
279279
- Added ``$insertOnlyFields`` and ``setInsertOnlyFields()`` to ``CodeIgniter\Model`` to remove configured fields from Model update operations while allowing them during inserts. See :ref:`model-insert-only-fields`.
280280
- Added ``$throwOnDisallowedFields`` and ``throwOnDisallowedFields()`` to ``CodeIgniter\Model`` to throw a ``DataException`` when write data contains fields that would otherwise be discarded by ``$allowedFields``. See :ref:`model-throw-on-disallowed-fields`.
@@ -300,8 +300,8 @@ Helpers and Functions
300300
object rows (including ``Entity``) in :php:func:`dot_array_search()`,
301301
:php:func:`dot_array_has()`, :php:func:`dot_array_only()`,
302302
:php:func:`dot_array_except()`, and :php:func:`array_group_by()`.
303-
:php:func:`dot_array_only()` and :php:func:`dot_array_except()` still return arrays. If the source itself is an object,
304-
it is read as an array-like value. Object values inside the source are kept unchanged when selected as a whole or left untouched.
303+
:php:func:`dot_array_only()` and :php:func:`dot_array_except()` still return arrays. If the source itself is an object,
304+
it is read as an array-like value. Object values inside the source are kept unchanged when selected as a whole or left untouched.
305305
Partial object paths are returned as arrays.
306306

307307
HTTP

‎user_guide_src/source/models/entities.rst‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,12 +256,12 @@ Scalar Type Casting
256256
-------------------
257257

258258
Properties can be cast to any of the following data types:
259-
**integer**, **float**, **double**, **string**, **boolean**, **object**, **array**, **datetime**, **timestamp**, **uri**, **int-bool**, **enum** and **encrypted**.
259+
**integer**, **float**, **double**, **string**, **boolean**, **object**, **array**, **datetime**, **timestamp**, **uri**, **int-bool**, **enum**, **encrypted**, **encrypted-json** and **encrypted-json-array**.
260260
Add a question mark at the beginning of type to mark property as nullable, i.e., **?string**, **?integer**.
261261

262262
.. note:: **int-bool** can be used since v4.3.0.
263263
.. note:: **enum** can be used since v4.7.0.
264-
.. note:: **encrypted** can be used since v4.8.0.
264+
.. note:: **encrypted**, **encrypted-json** and **encrypted-json-array** can be used since v4.8.0.
265265
.. note:: Since v4.8.0, you can also pass parameters to **float** and **double** types to specify the number of decimal places and rounding mode, i.e., **float[2,even]**.
266266

267267
For example, if you had a User entity with an ``is_banned`` property, you can cast it as a boolean:
@@ -349,6 +349,12 @@ for nullable values.
349349

350350
.. literalinclude:: entities/029.php
351351

352+
The ``encrypted-json`` and ``encrypted-json-array`` types JSON encode values
353+
before encryption and JSON decode them after decryption. The ``encrypted-json``
354+
type returns ``stdClass`` values, while ``encrypted-json-array`` returns arrays.
355+
Use ``?encrypted-json`` and ``?encrypted-json-array`` for nullable values. These
356+
values are still stored as encrypted text, not as queryable database JSON.
357+
352358
Encrypted values are stored as Base64-encoded ciphertext. Use a ``TEXT`` column
353359
or a sufficiently large string column because the stored value is longer than
354360
the plain text value. Avoid narrow columns like ``VARCHAR(255)`` unless you have

‎user_guide_src/source/models/model.rst‎

Lines changed: 40 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -399,35 +399,39 @@ Data Types
399399
The following types are provided by default. Add a question mark at the beginning
400400
of type to mark the field as nullable, i.e., ``?int``, ``?datetime``.
401401

402-
+---------------+----------------+---------------------------+
403-
| Type | PHP Value Type | DB Column Type |
404-
+===============+================+===========================+
405-
|``int`` | int | int type |
406-
+---------------+----------------+---------------------------+
407-
|``float`` | float | float (numeric) type |
408-
+---------------+----------------+---------------------------+
409-
|``bool`` | bool | bool/int/string type |
410-
+---------------+----------------+---------------------------+
411-
|``int-bool`` | bool | int type (1 or 0) |
412-
+---------------+----------------+---------------------------+
413-
|``array`` | array | string type (serialized) |
414-
+---------------+----------------+---------------------------+
415-
|``csv`` | array | string type (CSV) |
416-
+---------------+----------------+---------------------------+
417-
|``json`` | stdClass | json/string type |
418-
+---------------+----------------+---------------------------+
419-
|``json-array`` | array | json/string type |
420-
+---------------+----------------+---------------------------+
421-
|``datetime`` | Time | datetime type |
422-
+---------------+----------------+---------------------------+
423-
|``timestamp`` | Time | int type (UNIX timestamp) |
424-
+---------------+----------------+---------------------------+
425-
|``uri`` | URI | string type |
426-
+---------------+----------------+---------------------------+
427-
|``enum`` | Enum | string/int type |
428-
+---------------+----------------+---------------------------+
429-
|``encrypted`` | string | string/text type |
430-
+---------------+----------------+---------------------------+
402+
+--------------------------+----------------+---------------------------+
403+
| Type | PHP Value Type | DB Column Type |
404+
+==========================+================+===========================+
405+
|``int`` | int | int type |
406+
+--------------------------+----------------+---------------------------+
407+
|``float`` | float | float (numeric) type |
408+
+--------------------------+----------------+---------------------------+
409+
|``bool`` | bool | bool/int/string type |
410+
+--------------------------+----------------+---------------------------+
411+
|``int-bool`` | bool | int type (1 or 0) |
412+
+--------------------------+----------------+---------------------------+
413+
|``array`` | array | string type (serialized) |
414+
+--------------------------+----------------+---------------------------+
415+
|``csv`` | array | string type (CSV) |
416+
+--------------------------+----------------+---------------------------+
417+
|``json`` | stdClass | json/string type |
418+
+--------------------------+----------------+---------------------------+
419+
|``json-array`` | array | json/string type |
420+
+--------------------------+----------------+---------------------------+
421+
|``datetime`` | Time | datetime type |
422+
+--------------------------+----------------+---------------------------+
423+
|``timestamp`` | Time | int type (UNIX timestamp) |
424+
+--------------------------+----------------+---------------------------+
425+
|``uri`` | URI | string type |
426+
+--------------------------+----------------+---------------------------+
427+
|``enum`` | Enum | string/int type |
428+
+--------------------------+----------------+---------------------------+
429+
|``encrypted`` | string | string/text type |
430+
+--------------------------+----------------+---------------------------+
431+
|``encrypted-json`` | stdClass | string/text type |
432+
+--------------------------+----------------+---------------------------+
433+
|``encrypted-json-array`` | array | string/text type |
434+
+--------------------------+----------------+---------------------------+
431435

432436
float
433437
-----
@@ -505,7 +509,13 @@ encryption key before using it. The configured key is required for both writing
505509
new values and reading stored values back. The ``encrypted`` type accepts string
506510
values. Use ``?encrypted`` for nullable values.
507511

508-
.. literalinclude:: model/069.php
512+
.. literalinclude:: model/070.php
513+
514+
The ``encrypted-json`` and ``encrypted-json-array`` types JSON encode values
515+
before encryption and JSON decode them after decryption. The ``encrypted-json``
516+
type returns ``stdClass`` values, while ``encrypted-json-array`` returns arrays.
517+
Use ``?encrypted-json`` and ``?encrypted-json-array`` for nullable values. These
518+
values are still stored as encrypted text, not as queryable database JSON.
509519

510520
Encrypted values are stored as Base64-encoded ciphertext. Use a ``TEXT`` column
511521
or a sufficiently large string column because the stored value is longer than

0 commit comments

Comments
 (0)