fix(security): block ORDER BY SQL injection via orderByField (GHSA-cp8p) (#670)

v3 port. orderByField/orderBy were passed straight into Eloquent's orderBy()
in every model's scopeWhereOrder (and Invoice::scopeApplyFilters), allowing
arbitrary SQL in the ORDER BY clause.

Adds App\Support\SafeOrderBy::apply() (plain/table-qualified column identifier
only, asc/desc clamp) and routes all 10 model sort sinks through it. Aliased
sorts (e.g. estimates by customers.name) stay valid.

Adds unit tests for injection rejection, plain + aliased columns, direction clamp.
This commit is contained in:
Darko Gjorgjijoski
2026-06-12 11:02:15 +02:00
committed by GitHub
parent e56b6b4fe5
commit ca6dd57bf9
12 changed files with 85 additions and 11 deletions

View File

@@ -0,0 +1,32 @@
<?php
use App\Support\SafeOrderBy;
use Illuminate\Support\Facades\DB;
test('rejects sql expressions in the order-by field', function () {
$sql = strtolower(
SafeOrderBy::apply(DB::table('invoices'), '(CASE WHEN (SELECT 1)=1 THEN id ELSE total END)', 'asc')->toSql()
);
expect($sql)->toContain('order by')
->and($sql)->not->toContain('case')
->and($sql)->not->toContain('select 1');
});
test('allows a plain column', function () {
$sql = strtolower(SafeOrderBy::apply(DB::table('invoices'), 'invoice_date', 'asc')->toSql());
expect($sql)->toContain('order by')->and($sql)->toContain('invoice_date');
});
test('allows a table-qualified column so joined/aliased sorts keep working', function () {
$sql = strtolower(SafeOrderBy::apply(DB::table('estimates'), 'customers.name', 'asc')->toSql());
expect($sql)->toContain('customers')->and($sql)->toContain('name');
});
test('clamps the direction to asc/desc', function () {
$sql = strtolower(SafeOrderBy::apply(DB::table('invoices'), 'id', 'asc); drop table users; --')->toSql());
expect($sql)->toContain('order by')->and($sql)->not->toContain('drop table');
});