Skip to content

Commit c0ef372

Browse files
authored
feat: add strict field protection for Models (#10302)
* feat(model): add strict field protection Add an opt-in Model setting that throws when write data contains fields that would otherwise be discarded by allowed field protection. - Add $strictFieldProtection and strictFieldProtection() - Throw DataException for disallowed write fields in strict mode - Preserve existing primary key and updateBatch index behavior - Cover insert, save, update, batch, validation order, and protect(false) - Document the new option and update the model generator template Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com> * test: avoid SQLSRV identity update in strict protection test Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com> * refactor: rename disallowed field exception mode Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com> * fix: restore validation state on insert batch exception Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com> --------- Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent d2c0168 commit c0ef372

9 files changed

Lines changed: 362 additions & 21 deletions

File tree

‎system/BaseModel.php‎

Lines changed: 90 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,12 @@ abstract class BaseModel
141141
*/
142142
protected $protectFields = true;
143143

144+
/**
145+
* Whether Model should throw instead of silently discarding
146+
* fields that are not in $allowedFields.
147+
*/
148+
protected bool $throwOnDisallowedFields = false;
149+
144150
/**
145151
* An array of field names that are allowed
146152
* to be set by the user in inserts/updates.
@@ -990,32 +996,31 @@ public function insertBatch(?array $set = null, ?bool $escape = null, int $batch
990996
$cleanValidationRules = $this->cleanValidationRules;
991997
$this->cleanValidationRules = false;
992998

993-
if (is_array($set)) {
994-
foreach ($set as &$row) {
995-
$row = $this->transformDataToArray($row, 'insert');
996-
997-
// Validate every row.
998-
if (! $this->skipValidation && ! $this->validate($row)) {
999-
// Restore $cleanValidationRules
1000-
$this->cleanValidationRules = $cleanValidationRules;
999+
try {
1000+
if (is_array($set)) {
1001+
foreach ($set as &$row) {
1002+
$row = $this->transformDataToArray($row, 'insert');
10011003

1002-
return false;
1003-
}
1004+
// Validate every row.
1005+
if (! $this->skipValidation && ! $this->validate($row)) {
1006+
return false;
1007+
}
10041008

1005-
// Must be called first so we don't
1006-
// strip out created_at values.
1007-
$row = $this->doProtectFieldsForInsert($row);
1009+
// Must be called first so we don't
1010+
// strip out created_at values.
1011+
$row = $this->doProtectFieldsForInsert($row);
10081012

1009-
// Set created_at and updated_at with same time
1010-
$date = $this->setDate();
1011-
$row = $this->setCreatedField($row, $date);
1012-
$row = $this->setUpdatedField($row, $date);
1013+
// Set created_at and updated_at with same time
1014+
$date = $this->setDate();
1015+
$row = $this->setCreatedField($row, $date);
1016+
$row = $this->setUpdatedField($row, $date);
1017+
}
10131018
}
1019+
} finally {
1020+
// Restore $cleanValidationRules
1021+
$this->cleanValidationRules = $cleanValidationRules;
10141022
}
10151023

1016-
// Restore $cleanValidationRules
1017-
$this->cleanValidationRules = $cleanValidationRules;
1018-
10191024
$eventData = ['data' => $set];
10201025

10211026
if ($this->tempAllowCallbacks) {
@@ -1067,7 +1072,7 @@ public function update($id = null, $row = null): bool
10671072

10681073
// Must be called first, so we don't
10691074
// strip out updated_at values.
1070-
$row = $this->doProtectFields($row);
1075+
$row = $this->doProtectFieldsForUpdate($row);
10711076

10721077
// doProtectFields() can further remove elements from
10731078
// $row, so we need to check for empty dataset again
@@ -1157,6 +1162,7 @@ public function updateBatch(?array $set = null, ?string $index = null, int $batc
11571162

11581163
// Must be called first so we don't
11591164
// strip out updated_at values.
1165+
$this->ensureNoDisallowedFields($row, $index === null ? [] : [$index]);
11601166
$row = $this->doProtectFields($row);
11611167

11621168
// Restore updateIndex value in case it was wiped out
@@ -1382,6 +1388,19 @@ public function protect(bool $protect = true)
13821388
return $this;
13831389
}
13841390

1391+
/**
1392+
* Sets whether or not disallowed fields should throw an exception
1393+
* instead of being discarded.
1394+
*
1395+
* @return $this
1396+
*/
1397+
public function throwOnDisallowedFields(bool $throw = true)
1398+
{
1399+
$this->throwOnDisallowedFields = $throw;
1400+
1401+
return $this;
1402+
}
1403+
13851404
/**
13861405
* Ensures that only the fields that are allowed to be updated are
13871406
* in the data array.
@@ -1414,6 +1433,35 @@ protected function doProtectFields(array $row): array
14141433
return $row;
14151434
}
14161435

1436+
/**
1437+
* Throws when configured to detect fields that would be discarded.
1438+
*
1439+
* @param row_array $row
1440+
* @param list<string> $ignoredFields
1441+
*
1442+
* @throws DataException
1443+
*/
1444+
protected function ensureNoDisallowedFields(array $row, array $ignoredFields = []): void
1445+
{
1446+
if (! $this->throwOnDisallowedFields || ! $this->protectFields || $this->allowedFields === []) {
1447+
return;
1448+
}
1449+
1450+
$disallowedFields = [];
1451+
1452+
foreach (array_keys($row) as $key) {
1453+
if (in_array($key, $this->allowedFields, true) || in_array($key, $ignoredFields, true)) {
1454+
continue;
1455+
}
1456+
1457+
$disallowedFields[] = $key;
1458+
}
1459+
1460+
if ($disallowedFields !== []) {
1461+
throw DataException::forDisallowedFields(static::class, $disallowedFields);
1462+
}
1463+
}
1464+
14171465
/**
14181466
* Ensures that only the fields that are allowed to be inserted are in
14191467
* the data array.
@@ -1429,6 +1477,27 @@ protected function doProtectFields(array $row): array
14291477
*/
14301478
protected function doProtectFieldsForInsert(array $row): array
14311479
{
1480+
$this->ensureNoDisallowedFields($row);
1481+
1482+
return $this->doProtectFields($row);
1483+
}
1484+
1485+
/**
1486+
* Ensures that only the fields that are allowed to be updated are in
1487+
* the data array.
1488+
*
1489+
* @used-by update() to protect against mass assignment vulnerabilities.
1490+
*
1491+
* @param row_array $row
1492+
*
1493+
* @return row_array
1494+
*
1495+
* @throws DataException
1496+
*/
1497+
protected function doProtectFieldsForUpdate(array $row): array
1498+
{
1499+
$this->ensureNoDisallowedFields($row);
1500+
14321501
return $this->doProtectFields($row);
14331502
}
14341503

‎system/Commands/Generators/Views/model.tpl.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ class {class} extends Model
1717
protected $protectFields = true;
1818
protected $allowedFields = [];
1919

20+
protected bool $throwOnDisallowedFields = false;
2021
protected bool $allowEmptyInserts = false;
2122
protected bool $updateOnlyChanged = true;
2223

‎system/Database/Exceptions/DataException.php‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,16 @@ public static function forInvalidAllowedFields(string $model)
7373
return new static(lang('Database.invalidAllowedFields', [$model]));
7474
}
7575

76+
/**
77+
* @param list<string> $fields
78+
*
79+
* @return DataException
80+
*/
81+
public static function forDisallowedFields(string $model, array $fields)
82+
{
83+
return new static(lang('Database.disallowedFields', [$model, implode(', ', $fields)]));
84+
}
85+
7686
/**
7787
* @return DataException
7888
*/

‎system/Language/en/Database.php‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
'invalidEvent' => '"{0}" is not a valid Model Event callback.',
1717
'invalidArgument' => 'You must provide a valid "{0}".',
1818
'invalidAllowedFields' => 'Allowed fields must be specified for model: "{0}"',
19+
'disallowedFields' => 'Fields are not allowed for model "{0}": {1}',
1920
'emptyDataset' => 'There is no data to {0}.',
2021
'emptyPrimaryKey' => 'There is no primary key defined when trying to make {0}.',
2122
'failGetFieldData' => 'Failed to get field data from database.',

‎system/Model.php‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,8 @@ protected function doProtectFieldsForInsert(array $row): array
767767
throw DataException::forInvalidAllowedFields(static::class);
768768
}
769769

770+
$this->ensureNoDisallowedFields($row, $this->useAutoIncrement === false ? [$this->primaryKey] : []);
771+
770772
foreach (array_keys($row) as $key) {
771773
// Do not remove the non-auto-incrementing primary key data.
772774
if ($this->useAutoIncrement === false && $key === $this->primaryKey) {
@@ -781,6 +783,13 @@ protected function doProtectFieldsForInsert(array $row): array
781783
return $row;
782784
}
783785

786+
protected function doProtectFieldsForUpdate(array $row): array
787+
{
788+
$this->ensureNoDisallowedFields($row, [$this->primaryKey]);
789+
790+
return $this->doProtectFields($row);
791+
}
792+
784793
/**
785794
* Finds the first row matching attributes or inserts a new row.
786795
*

0 commit comments

Comments
 (0)