Skip to content

Commit 451d539

Browse files
authored
fix(Database): escape table and column names in SQLSRV Forge default constraint lookups (#10736)
1 parent 772cd90 commit 451d539

3 files changed

Lines changed: 139 additions & 7 deletions

File tree

‎docs/changelogs/v4.7.7.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Release Date: Unreleased
1717
## Bugs Fixed
1818

1919
- **CORS:** Fixed a bug where `Cors::hasResponseHeaders()` matched header substrings via `str_contains()`, causing false positives when existing exposed headers shared a prefix with configured exposed headers.
20+
- **Database:** Fixed a bug where `SQLSRV\Forge::_alterTable()` interpolated table and column names without escaping in default constraint lookups.
2021
- **HTTP:** Fixed a bug where `UploadedFile::move()` and `UploadedFile::store()` on Windows could store a file under a different name than `getName()` reported, or write its contents to an NTFS alternate data stream. Filenames ending in a period or space or containing a colon are now rejected, including explicitly supplied names.
2122
- **Security:** Fixed a bug where `Security::__construct()` threw a `TypeError` when the CSRF cookie was an array, causing an HTTP 500 response for affected requests.
2223
- **Worker Mode:** Fixed a bug where every request that ended with an uncaught exception, including a `404 Page Not Found` without a 404 override, called `exit()` in the exception handler. This ended the worker script, so FrankenPHP booted a new one, and the worker loop skipped its cleanup after the request. The exception handler now returns to the worker loop.

‎system/Database/SQLSRV/Forge.php‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -195,17 +195,18 @@ protected function _alterTable(string $alterType, string $table, $processedField
195195
}
196196
}
197197

198-
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
198+
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
199+
$escapedFullTable = $this->db->escape($fullTable);
199200

200201
// Drop default constraints
201202
$fields = implode(',', $this->db->escape((array) $columnNamesToDrop));
202203

203204
$sql = <<<SQL
204205
SELECT name
205206
FROM sys.default_constraints
206-
WHERE parent_object_id = OBJECT_ID('{$fullTable}')
207+
WHERE parent_object_id = OBJECT_ID(N{$escapedFullTable})
207208
AND parent_column_id IN (
208-
SELECT column_id FROM sys.columns WHERE name IN ({$fields}) AND object_id = OBJECT_ID(N'{$fullTable}')
209+
SELECT column_id FROM sys.columns WHERE name IN ({$fields}) AND object_id = OBJECT_ID(N{$escapedFullTable})
209210
)
210211
SQL;
211212

@@ -244,8 +245,9 @@ protected function _alterTable(string $alterType, string $table, $processedField
244245
}
245246

246247
if (($field['default'] ?? '') !== '') {
247-
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
248-
$colName = $field['name']; // bare, for sys.columns lookup
248+
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
249+
$escapedFullTable = $this->db->escape($fullTable);
250+
$escapedColName = $this->db->escape($field['name']);
249251

250252
// find the existing default constraint name for this column
251253
$findSql = <<<SQL
@@ -254,8 +256,8 @@ protected function _alterTable(string $alterType, string $table, $processedField
254256
JOIN sys.columns c
255257
ON dc.parent_object_id = c.object_id
256258
AND dc.parent_column_id = c.column_id
257-
WHERE dc.parent_object_id = OBJECT_ID(N'{$fullTable}')
258-
AND c.name = N'{$colName}';
259+
WHERE dc.parent_object_id = OBJECT_ID(N{$escapedFullTable})
260+
AND c.name = N{$escapedColName};
259261
SQL;
260262

261263
$toDrop = $this->db->query($findSql)->getRowArray();
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
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\Database\Forge;
15+
16+
use CodeIgniter\Database\ResultInterface;
17+
use CodeIgniter\Database\SQLSRV\Connection;
18+
use CodeIgniter\Database\SQLSRV\Forge;
19+
use CodeIgniter\Database\SQLSRV\Result;
20+
use CodeIgniter\Test\CIUnitTestCase;
21+
use PHPUnit\Framework\Attributes\Group;
22+
23+
/**
24+
* @internal
25+
*/
26+
#[Group('Others')]
27+
final class SQLSRVForgeTest extends CIUnitTestCase
28+
{
29+
public function testModifyColumnEscapesTableNameAndColumnNameInDefaultConstraintLookup(): void
30+
{
31+
$db = new class () extends Connection {
32+
/**
33+
* @var list<string>
34+
*/
35+
public array $queries = [];
36+
37+
public function __construct()
38+
{
39+
$this->DBDriver = 'SQLSRV';
40+
$this->schema = 'dbo';
41+
$this->escapeChar = ['[', ']'];
42+
$this->connID = false;
43+
$this->pretend = true;
44+
}
45+
46+
public function initialize(): void
47+
{
48+
}
49+
50+
/**
51+
* @param array<array-key, mixed>|string|null $binds
52+
*/
53+
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = ''): ResultInterface
54+
{
55+
$this->queries[] = $sql;
56+
57+
return new class ($this->connID, $this->resultID) extends Result {
58+
public function getRowArray(int $n = 0): array
59+
{
60+
return ['constraint_name' => 'df_test'];
61+
}
62+
};
63+
}
64+
};
65+
66+
$forge = new Forge($db);
67+
68+
$forge->modifyColumn("user's", [
69+
"col'name" => [
70+
'type' => 'VARCHAR',
71+
'default' => "'default_val'",
72+
],
73+
]);
74+
75+
$this->assertNotEmpty($db->queries);
76+
$findSql = $db->queries[0];
77+
78+
$this->assertStringContainsString("OBJECT_ID(N'[dbo].[user''s]')", $findSql);
79+
$this->assertStringContainsString("c.name = N'col''name'", $findSql);
80+
}
81+
82+
public function testDropColumnEscapesTableNameInDefaultConstraintLookup(): void
83+
{
84+
$db = new class () extends Connection {
85+
/**
86+
* @var list<string>
87+
*/
88+
public array $queries = [];
89+
90+
public function __construct()
91+
{
92+
$this->DBDriver = 'SQLSRV';
93+
$this->schema = 'dbo';
94+
$this->escapeChar = ['[', ']'];
95+
$this->connID = false;
96+
$this->pretend = true;
97+
}
98+
99+
public function initialize(): void
100+
{
101+
}
102+
103+
/**
104+
* @param array<array-key, mixed>|string|null $binds
105+
*/
106+
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = ''): ResultInterface
107+
{
108+
$this->queries[] = $sql;
109+
110+
return new class ($this->connID, $this->resultID) extends Result {
111+
public function getResultArray(): array
112+
{
113+
return [];
114+
}
115+
};
116+
}
117+
};
118+
119+
$forge = new Forge($db);
120+
121+
$forge->dropColumn("user's", "col'name");
122+
123+
$this->assertCount(3, $db->queries);
124+
$dropDefaultSql = $db->queries[1];
125+
126+
$this->assertStringContainsString("parent_object_id = OBJECT_ID(N'[dbo].[user''s]')", $dropDefaultSql);
127+
$this->assertStringContainsString("object_id = OBJECT_ID(N'[dbo].[user''s]')", $dropDefaultSql);
128+
}
129+
}

0 commit comments

Comments
 (0)