Merge pull request #5414 from connortechnology/fix/ghsa-6pfc-api-error-body

fix: keep SQL exception text and credentials out of API 5xx bodies (GHSA-6pfc-r2pp-g9rm)
This commit is contained in:
Isaac Connor authored and GitHub committed 2026-11-01 17:06:33 -05:00
commit 150c12e5c6
7 files changed
+326 -4

No files matched your search

+102
View File
@@ -0,0 +1,102 @@
<?php
// Tests what the API returns in error bodies:
// ZmExceptionRenderer::_getErrorData() - with debug 0, a 5xx body must not
// carry the exception's own message
// (PDO text, SQL), and data.url must
// not carry credentials
//
// The Cake and Crud base classes are stubbed, so this runs from a source
// checkout: php tests/php/test_api_error_body.php
class App {
public static function uses($class, $package) {}
}
class Configure {
public static $values = array('debug' => 0);
public static function read($key) {
return isset(self::$values[$key]) ? self::$values[$key] : null;
}
}
function __d($domain, $msg) { return $msg; }
// ZmErrorHandler::redact() cleans data.url; its base class is not exercised.
class ErrorHandler {}
// What Crud's renderer returns for a 500 with debug 0: Cake's generic message,
// the HTML-escaped URL, and the raw exception.
class CrudExceptionRenderer {
public $controller;
public $data = array();
protected function _getErrorData() {
return $this->data;
}
}
class StubResponse {
public $code;
public function statusCode() { return $this->code; }
}
require_once __DIR__.'/../../web/api/app/Lib/Error/ZmErrorHandler.php';
require_once __DIR__.'/../../web/api/app/Lib/Error/ZmExceptionRenderer.php';
class TestRenderer extends ZmExceptionRenderer {
public function __construct($code, $data) {
$this->controller = new stdClass();
$this->controller->response = new StubResponse();
$this->controller->response->code = $code;
$this->data = $data;
}
public function errorData() { return $this->_getErrorData(); }
}
$failures = 0;
$passes = 0;
function check($name, $got, $expected) {
global $failures, $passes;
if ($got === $expected) {
$passes++;
echo "ok - $name\n";
} else {
$failures++;
echo "not ok - $name (got ".var_export($got, true)." expected ".var_export($expected, true).")\n";
}
}
// ---- the error body ----
$pdo = array(
'name' => 'An Internal Error Has Occurred.',
'message' => 'An Internal Error Has Occurred.',
'url' => '/zm/api/monitors/index/Nope:1.json?p=%2Fx&amp;token=eyJ0.eyJp.sig',
'exception' => array(
'class' => 'PDOException',
'code' => '42S22',
'message' => "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Nope' in 'WHERE'",
),
);
$data = (new TestRenderer(500, $pdo))->errorData();
check('500 with debug 0: exception message is generic',
$data['exception']['message'], 'An Internal Error Has Occurred.');
check('500 keeps the exception class and code',
array($data['exception']['class'], $data['exception']['code']), array('PDOException', '42S22'));
check('500 body url has no token',
$data['url'], '/zm/api/monitors/index/Nope:1.json?p=%2Fx&amp;token=[redacted]');
$notFound = array(
'url' => '/zm/api/monitors/view/9.json',
'exception' => array('class' => 'NotFoundException', 'code' => 404, 'message' => 'Invalid monitor'),
);
$data = (new TestRenderer(404, $notFound))->errorData();
check('4xx keeps its message', $data['exception']['message'], 'Invalid monitor');
Configure::$values['debug'] = 2;
$data = (new TestRenderer(500, $pdo))->errorData();
check('500 with debug on keeps the message', $data['exception']['message'], $pdo['exception']['message']);
echo "\n$passes passed, $failures failed\n";
exit($failures ? 1 : 0);
?>
@@ -0,0 +1,102 @@
<?php
// Tests FilterComponent::qualifyFields(), which MonitorsController::index()
// runs on its named parameters before buildFilter():
// - a bare Monitors column is written Monitor.Field, so Id and Name are no
// longer ambiguous with the joined tables
// - a bare column of exactly one joined table (Status, CaptureFPS from
// Monitor_Status) is left bare, as before; one that two joined tables
// have (MonitorId) is a 400
// - Model.Field must be a column of the queried or a joined model
// - GroupId is left bare for the controller's Groups_Monitors join
// - anything else is a 400 naming the field, instead of reaching MySQL as
// an unknown column (a 500 that carried the SQL error)
//
// Cake's Component is stubbed, so this runs from a source checkout:
// php tests/php/test_api_monitor_filter_fields.php
class App {
public static function uses($class, $package) {}
}
class Component {}
class BadRequestException extends Exception {}
require_once __DIR__.'/../../web/api/app/Controller/Component/FilterComponent.php';
$failures = 0;
$passes = 0;
function check($name, $got, $expected) {
global $failures, $passes;
if ($got === $expected) {
$passes++;
echo "ok - $name\n";
} else {
$failures++;
echo "not ok - $name (got ".var_export($got, true)." expected ".var_export($expected, true).")\n";
}
}
// What a 400 says, or the conditions buildFilter() makes.
function run($named) {
$f = new FilterComponent();
$fields = array(
'Monitor' => array('Id', 'Name', 'Type', 'Enabled', 'Deleted', 'Capturing', 'ServerId'),
'Monitor_Status' => array('MonitorId', 'Status', 'CaptureFPS', 'AnalysisFPS'),
'Event_Summary' => array('MonitorId', 'TotalEvents'),
'Manufacturer' => array('Id', 'Name'),
);
try {
return $f->buildFilter($f->qualifyFields($named, $fields, array('GroupId')));
} catch (BadRequestException $e) {
return '400 '.$e->getMessage();
}
}
check('bare column is qualified',
run(array('Name' => 'hikvision-1')), array('Monitor.Name' => 'hikvision-1'));
check('operator is kept',
run(array('Id >' => '0')), array('Monitor.Id >' => '0'));
check('LIKE is kept',
run(array('Name LIKE' => 'hik')), array('Monitor.Name LIKE' => '%hik%'));
check('IN is kept',
run(array('Id IN' => '1,2')), array(array('Monitor.Id IN' => array('1', '2'))));
check('Monitor.Field is accepted',
run(array('Monitor.Deleted' => '0')), array('Monitor.Deleted' => '0'));
check('column case follows the schema',
run(array('enabled' => '1')), array('Monitor.Enabled' => '1'));
check('a joined model column is accepted',
run(array('Manufacturer.Name' => 'Acme')), array('Manufacturer.Name' => 'Acme'));
check('GroupId stays bare',
run(array('GroupId' => '3')), array('GroupId' => '3'));
check('paging parameters are skipped as before',
run(array('Deleted' => '0', 'limit' => '5', 'page' => '2')), array('Monitor.Deleted' => '0'));
check('bare column of one joined table is left bare',
run(array('Status' => 'Connected')), array('Status' => 'Connected'));
check('bare joined column with an operator',
run(array('CaptureFPS >' => '0')), array('CaptureFPS >' => '0'));
check('bare joined column case follows the schema',
run(array('analysisfps <' => '5')), array('AnalysisFPS <' => '5'));
check('bare joined column next to a Monitors column',
run(array('Status' => 'Connected', 'Deleted' => '0')), array('Status' => 'Connected', 'Monitor.Deleted' => '0'));
check('bare column of two joined tables is a 400',
run(array('MonitorId' => '1')), '400 Ambiguous filter field: MonitorId');
check('a joined model column can still be qualified',
run(array('Manufacturer.Id' => '1')), array('Manufacturer.Id' => '1'));
check('unknown column is a 400',
run(array('NoSuchField' => '1')), '400 Unknown filter field: NoSuchField');
check('unknown model is a 400',
run(array('Event.Id' => '1')), '400 Unknown filter field: Event.Id');
check('column of the wrong model is a 400',
run(array('Manufacturer.Type' => '1')), '400 Unknown filter field: Manufacturer.Type');
check('groupid in another case is not the join',
run(array('groupid' => '1')), '400 Unknown filter field: groupid');
check('operator allow list still applies',
run(array('Id OR' => '1')), '400 Invalid operator: OR');
check('invalid characters still rejected',
run(array(';Id' => '1')), '400 Invalid argument before `:`: ;Id');
check('no named params',
(new FilterComponent())->qualifyFields(array(), array('Monitor' => array('Id'))), array());
echo "\n$passes passed, $failures failed\n";
exit($failures ? 1 : 0);
?>
+5
View File
@@ -56,6 +56,11 @@ class AppController extends Controller {
// for role and deny API access in future
// Also checking to do this only if ZM_OPT_USE_AUTH is on
public function beforeFilter() {
// Crud's ApiListener registers its exception renderer for API requests when
// the component starts; use ours, which keeps internals out of 5xx bodies.
if ( Configure::read('Exception.renderer') == 'Crud.CrudExceptionRenderer' ) {
Configure::write('Exception.renderer', 'ZmExceptionRenderer');
}
if ( ! ZM_OPT_USE_API ) {
throw new UnauthorizedException(__('API Disabled'));
return;
@@ -72,6 +72,80 @@ class FilterComponent extends Component {
'direction'
);
// Check the fields of named parameters against the tables a find() reads,
// and write each one so MySQL finds exactly one column.
//
// $fields maps a model alias to its column names, the queried model first.
// A bare field that is a column of the queried model is written Model.Field,
// so a name that is also a column of a joined table (Id, Name) is not
// ambiguous. Otherwise it must be a column of exactly one joined model
// (Status, CaptureFPS from Monitor_Status) and is left bare, which MySQL
// resolves to that table; buildFilter() does not accept an alias with an
// underscore such as Monitor_Status. A field written Model.Field must be a
// column of one of the models in $fields. Names in $unqualified are left as
// they are for the caller to resolve (GroupId; matched exactly, as the
// caller looks for it). Column names match without regard to case, as in
// MySQL, and are written as the schema spells them.
//
// A field no model has, or a bare field two joined models have and the
// queried model does not, is a 400 naming the field. It used to reach MySQL
// as an unknown or ambiguous column and come back as a 500 carrying the SQL
// error. Parameters buildFilter() skips or rejects are passed through to it.
public function qualifyFields($namedParams, $fields, $unqualified = array()) {
if (!$namedParams) {
return $namedParams;
}
reset($fields);
$model = key($fields);
$scoped = array();
foreach ($namedParams as $attribute => $value) {
$lhs = trim($attribute);
$matches = NULL;
if (in_array($lhs, $this->paramsToFilterOut)
or preg_match('/^(?P<field>[a-z0-9\.]+)(?P<rest>.*)$/is', $lhs, $matches) !== 1) {
$scoped[$attribute] = $value;
continue;
}
$field = $matches['field'];
$dot = strrpos($field, '.');
if ($dot === false) {
if (in_array($field, $unqualified, true)) {
$scoped[$attribute] = $value;
continue;
}
$alias = false;
$column = $field;
} else {
$alias = substr($field, 0, $dot);
$column = substr($field, $dot + 1);
}
$found = array();
foreach ($fields as $name => $columns) {
if ($alias !== false and strcasecmp($name, $alias)) {
continue;
}
foreach ($columns as $c) {
if (!strcasecmp($c, $column)) {
$found[] = ($alias === false and $name != $model) ? $c : $name.'.'.$c;
break;
}
}
if ($alias === false and $name == $model and count($found)) {
break;
}
}
if (!count($found)) {
throw new BadRequestException('Unknown filter field: ' . $field);
}
if (count($found) > 1) {
throw new BadRequestException('Ambiguous filter field: ' . $field);
}
$found = $found[0];
$scoped[$found.$matches['rest']] = $value;
}
return $scoped;
}
// Build a CakePHP find() condition based on the named parameters
// that are passed in.
//
+3 -3
View File
@@ -447,12 +447,12 @@ class EventsController extends AppController {
// Transform params into conditions
if ( preg_match('/^\s?interval\s?/i', $value) ) {
if (preg_match('/^[a-z0-9]+$/i', $param_name) !== 1) {
throw new Exception('Invalid field name: ' . $param_name);
throw new BadRequestException('Invalid field name: ' . $param_name);
}
$matches = NULL;
$value = preg_replace('/^\s?interval\s?/i', '', $value);
if (preg_match('/^(?P<expr>[ \-.:0-9]+)\s+(?P<unit>[_a-z]+)$/i', trim($value), $matches) !== 1) {
throw new Exception('Invalid interval: ' . $value);
throw new BadRequestException('Invalid interval: ' . $value);
}
$expr = trim($matches['expr']);
$unit = trim($matches['unit']);
@@ -486,7 +486,7 @@ class EventsController extends AppController {
// https://dev.mysql.com/doc/refman/5.5/en/expressions.html#temporal-intervals
// Examples: `'1-1' YEAR_MONTH`, `'-1 10' DAY_HOUR`, `'1.999999' SECOND_MICROSECOND`
if (preg_match('/^(?P<expr>[ \-.:0-9]+)\s+(?P<unit>[_a-z]+)$/i', trim($interval), $matches) !== 1) {
throw new Exception('Invalid interval: ' . $interval);
throw new BadRequestException('Invalid interval: ' . $interval);
}
$expr = trim($matches['expr']);
$unit = trim($matches['unit']);
+10 -1
View File
@@ -33,7 +33,16 @@ class MonitorsController extends AppController {
if ($this->request->params['named']) {
$this->FilterComponent = $this->Components->load('Filter');
$conditions = $this->FilterComponent->buildFilter($this->request->params['named']);
// The columns of Monitors and of the tables find() joins at recursive 0
// (hasOne, belongsTo), plus GroupId, served by the Groups_Monitors join
// below. Anything else would reach MySQL as an unknown column and come
// back as a 500.
$fields = array('Monitor' => array_keys($this->Monitor->schema()));
foreach (array_merge(array_keys($this->Monitor->hasOne), array_keys($this->Monitor->belongsTo)) as $alias) {
$fields[$alias] = array_keys($this->Monitor->{$alias}->schema());
}
$named = $this->FilterComponent->qualifyFields($this->request->params['named'], $fields, array('GroupId'));
$conditions = $this->FilterComponent->buildFilter($named);
} else {
$conditions = array();
}
@@ -0,0 +1,30 @@
<?php
App::uses('CrudExceptionRenderer', 'Crud.Error');
App::uses('ZmErrorHandler', 'Error');
/**
* Crud's API exception renderer, without internals in 5xx bodies.
*
* Crud adds data.exception.message from the raw exception even when Cake has
* replaced the message with a generic one (debug 0), so a PDOException put the
* SQL error and its fragment of the query in the response. It also echoes the
* request URL, credentials included, in data.url.
*/
class ZmExceptionRenderer extends CrudExceptionRenderer {
/**
* {@inheritDoc}
*/
protected function _getErrorData() {
$data = parent::_getErrorData();
if (isset($data['url'])) {
$data['url'] = ZmErrorHandler::redact($data['url']);
}
if (!Configure::read('debug') && isset($data['exception'])
&& $this->controller->response->statusCode() >= 500) {
$data['exception']['message'] = __d('cake', 'An Internal Error Has Occurred.');
}
return $data;
}
}