diff --git a/tests/php/test_api_error_body.php b/tests/php/test_api_error_body.php new file mode 100644 index 0000000000..521f5cf7bd --- /dev/null +++ b/tests/php/test_api_error_body.php @@ -0,0 +1,102 @@ + 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&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&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); +?> diff --git a/tests/php/test_api_monitor_filter_fields.php b/tests/php/test_api_monitor_filter_fields.php new file mode 100644 index 0000000000..d455fa7535 --- /dev/null +++ b/tests/php/test_api_monitor_filter_fields.php @@ -0,0 +1,102 @@ + 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); +?> diff --git a/web/api/app/Controller/AppController.php b/web/api/app/Controller/AppController.php index b092f330e7..2f87c39d4d 100644 --- a/web/api/app/Controller/AppController.php +++ b/web/api/app/Controller/AppController.php @@ -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; diff --git a/web/api/app/Controller/Component/FilterComponent.php b/web/api/app/Controller/Component/FilterComponent.php index ba8a9bc56d..2addcee846 100644 --- a/web/api/app/Controller/Component/FilterComponent.php +++ b/web/api/app/Controller/Component/FilterComponent.php @@ -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[a-z0-9\.]+)(?P.*)$/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. // diff --git a/web/api/app/Controller/EventsController.php b/web/api/app/Controller/EventsController.php index 1162930567..9023aa902b 100644 --- a/web/api/app/Controller/EventsController.php +++ b/web/api/app/Controller/EventsController.php @@ -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[ \-.:0-9]+)\s+(?P[_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[ \-.:0-9]+)\s+(?P[_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']); diff --git a/web/api/app/Controller/MonitorsController.php b/web/api/app/Controller/MonitorsController.php index ef242cefe7..8c2dbd6065 100644 --- a/web/api/app/Controller/MonitorsController.php +++ b/web/api/app/Controller/MonitorsController.php @@ -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(); } diff --git a/web/api/app/Lib/Error/ZmExceptionRenderer.php b/web/api/app/Lib/Error/ZmExceptionRenderer.php new file mode 100644 index 0000000000..53dc6e08fd --- /dev/null +++ b/web/api/app/Lib/Error/ZmExceptionRenderer.php @@ -0,0 +1,30 @@ +controller->response->statusCode() >= 500) { + $data['exception']['message'] = __d('cake', 'An Internal Error Has Occurred.'); + } + return $data; + } + +}