Skip to content

Commit cefe25c

Browse files
committed
fix(Model): protect fields against mass assignment in replace()
1 parent 609d458 commit cefe25c

4 files changed

Lines changed: 180 additions & 2 deletions

File tree

‎system/BaseModel.php‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1265,6 +1265,8 @@ public function onlyDeleted()
12651265
* @param bool $returnSQL `true` means SQL is returned, `false` will execute the query.
12661266
*
12671267
* @return BaseResult|false|Query|string
1268+
*
1269+
* @throws DataException
12681270
*/
12691271
public function replace(?array $row = null, bool $returnSQL = false)
12701272
{
@@ -1274,8 +1276,20 @@ public function replace(?array $row = null, bool $returnSQL = false)
12741276
}
12751277

12761278
$row = (array) $row;
1277-
$row = $this->setCreatedField($row, $this->setDate());
1278-
$row = $this->setUpdatedField($row, $this->setDate());
1279+
1280+
// Must be called first, so we don't
1281+
// strip out created_at values.
1282+
$row = $this->doProtectFieldsForReplace($row);
1283+
1284+
// doProtectFields() can further remove elements from
1285+
// $row, so we need to check for empty dataset again
1286+
if ($row === []) {
1287+
throw DataException::forEmptyDataset('replace');
1288+
}
1289+
1290+
$date = $this->setDate();
1291+
$row = $this->setCreatedField($row, $date);
1292+
$row = $this->setUpdatedField($row, $date);
12791293

12801294
return $this->doReplace($row, $returnSQL);
12811295
}
@@ -1414,6 +1428,23 @@ protected function doProtectFieldsForInsert(array $row): array
14141428
return $this->doProtectFields($row);
14151429
}
14161430

1431+
/**
1432+
* Ensures that only the fields that are allowed to be replaced are in
1433+
* the data array.
1434+
*
1435+
* @used-by replace() to protect against mass assignment vulnerabilities.
1436+
*
1437+
* @param row_array $row
1438+
*
1439+
* @return row_array
1440+
*
1441+
* @throws DataException
1442+
*/
1443+
protected function doProtectFieldsForReplace(array $row): array
1444+
{
1445+
return $this->doProtectFields($row);
1446+
}
1447+
14171448
/**
14181449
* Sets the timestamp or current timestamp if null value is passed.
14191450
*

‎system/Model.php‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,42 @@ protected function doProtectFieldsForInsert(array $row): array
695695
return $row;
696696
}
697697

698+
/**
699+
* Ensures that only the fields that are allowed to be replaced are in
700+
* the data array.
701+
*
702+
* Used by replace() to protect against mass assignment vulnerabilities.
703+
*
704+
* @param row_array $row
705+
*
706+
* @return row_array
707+
*
708+
* @throws DataException
709+
*/
710+
protected function doProtectFieldsForReplace(array $row): array
711+
{
712+
if (! $this->protectFields) {
713+
return $row;
714+
}
715+
716+
if ($this->allowedFields === []) {
717+
throw DataException::forInvalidAllowedFields(static::class);
718+
}
719+
720+
foreach (array_keys($row) as $key) {
721+
// Do not remove the primary key data.
722+
if ($this->primaryKey !== '' && $key === $this->primaryKey) {
723+
continue;
724+
}
725+
726+
if (! in_array($key, $this->allowedFields, true)) {
727+
unset($row[$key]);
728+
}
729+
}
730+
731+
return $row;
732+
}
733+
698734
public function update($id = null, $row = null): bool
699735
{
700736
if (isset($this->tempData['data'])) {

‎tests/system/Models/ReplaceModelTest.php‎

Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
namespace CodeIgniter\Models;
1515

16+
use CodeIgniter\Database\Exceptions\DataException;
1617
use PHPUnit\Framework\Attributes\Group;
1718
use Tests\Support\Models\UserModel;
1819

@@ -47,4 +48,113 @@ public function testReplaceRespectsUseTimestamps(): void
4748
$this->assertStringContainsString('created_at', (string) $sql);
4849
$this->assertStringContainsString('updated_at', (string) $sql);
4950
}
51+
52+
public function testReplaceProtectsFields(): void
53+
{
54+
$this->createModel(UserModel::class);
55+
56+
$data = [
57+
'name' => 'Amanda Holmes',
58+
'email' => 'amanda@holmes.com',
59+
'country' => 'US',
60+
'not_allowed' => 'hack',
61+
];
62+
63+
$sql = $this->model->replace($data, true);
64+
$this->assertStringNotContainsString('not_allowed', (string) $sql);
65+
$this->assertStringContainsString('email', (string) $sql);
66+
}
67+
68+
public function testReplacePreservesPrimaryKeyEvenIfNotInAllowedFields(): void
69+
{
70+
$this->createModel(UserModel::class);
71+
72+
$data = [
73+
'id' => 1,
74+
'name' => 'Amanda Holmes',
75+
'email' => 'amanda@holmes.com',
76+
'country' => 'US',
77+
'not_allowed' => 'hack',
78+
];
79+
80+
$sql = $this->model->replace($data, true);
81+
$this->assertStringContainsString('id', (string) $sql);
82+
$this->assertStringNotContainsString('not_allowed', (string) $sql);
83+
}
84+
85+
public function testReplaceWithProtectFalseAllowsAllFields(): void
86+
{
87+
$this->createModel(UserModel::class);
88+
89+
$data = [
90+
'name' => 'Amanda Holmes',
91+
'email' => 'amanda@holmes.com',
92+
'country' => 'US',
93+
'not_allowed' => 'hack',
94+
];
95+
96+
$sql = $this->model->protect(false)->replace($data, true);
97+
$this->assertStringContainsString('not_allowed', (string) $sql);
98+
}
99+
100+
public function testReplaceThrowsDataExceptionWhenNoAllowedFields(): void
101+
{
102+
$this->createModel(UserModel::class);
103+
$this->setPrivateProperty($this->model, 'allowedFields', []);
104+
105+
$this->expectException(DataException::class);
106+
$this->expectExceptionMessage('Allowed fields must be specified for model: "Tests\Support\Models\UserModel"');
107+
108+
$this->model->replace(['id' => 1, 'name' => 'Amanda']);
109+
}
110+
111+
public function testReplaceThrowsDataExceptionWhenDatasetEmpty(): void
112+
{
113+
$this->createModel(UserModel::class);
114+
115+
$this->expectException(DataException::class);
116+
$this->expectExceptionMessage('There is no data to replace.');
117+
118+
$this->model->replace([]);
119+
}
120+
121+
public function testReplaceThrowsDataExceptionWhenAllFieldsProtected(): void
122+
{
123+
$this->createModel(UserModel::class);
124+
125+
$this->expectException(DataException::class);
126+
$this->expectExceptionMessage('There is no data to replace.');
127+
128+
$this->model->replace(['not_allowed' => 'hack']);
129+
}
130+
131+
public function testReplaceLiveExecutionWithUnallowedFields(): void
132+
{
133+
$this->createModel(UserModel::class);
134+
135+
$data = [
136+
'name' => 'Amanda Holmes',
137+
'email' => 'amanda@holmes.com',
138+
'country' => 'US',
139+
];
140+
141+
$id = $this->model->insert($data);
142+
143+
$replaceData = [
144+
'id' => $id,
145+
'name' => 'Amanda Holmes',
146+
'email' => 'amanda_updated@holmes.com',
147+
'country' => 'UK',
148+
'not_allowed' => 'ignored',
149+
];
150+
151+
$result = $this->model->replace($replaceData);
152+
$this->assertNotFalse($result);
153+
154+
$this->seeInDatabase('user', [
155+
'id' => $id,
156+
'email' => 'amanda_updated@holmes.com',
157+
'country' => 'UK',
158+
]);
159+
}
50160
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ Bugs Fixed
5252
- **HTTP:** Fixed a bug where ``Negotiate`` could select a value that the request header excluded with ``q=0`` through a wildcard or a broader range. A ``q=0`` range now excludes every value it matches, such as ``text/html`` and ``text/html;charset=utf-8`` for ``text/*;q=0``, or ``en-US`` for ``en;q=0``, unless a more specific range in the header accepts the value. For example, ``Accept-Encoding: gzip;q=0, *`` no longer selects ``gzip``.
5353
- **HTTP:** Fixed stale ``$_REQUEST`` values after ``SiteURIFactory`` normalizes GET parameters, so ``Validation::withRequest()`` reads the normalized values while unrelated REQUEST entries are preserved.
5454
- **I18n:** Fixed a regression in v4.7.1 where ``Time`` and ``TimeLegacy`` lost their timezone, locale and ``__toString()`` format after ``unserialize()``, so methods such as ``difference()`` and ``getTimezoneName()`` threw an ``Error``.
55+
- **Model:** Fixed a bug where ``BaseModel::replace()`` did not protect fields against mass assignment or check for empty datasets, passing raw input data to the builder.
5556
- **Routing:** Corrected the PHPDoc callback type of ``RouteCollection::group()`` to preserve the concrete collection type, allowing callbacks typed to a ``RouteCollection`` subclass to pass static analysis.
5657
- **Security:** Fixed a bug where a valid JSON request body that is not an object (for example a JSON array) was corrupted after CSRF verification when the token was sent via the ``X-CSRF-TOKEN`` header.
5758

0 commit comments

Comments
 (0)