Files
FOSSBilling/tests/Support/ToApiArrayAuditor.php
T
Adam Daley 5ecfeb335e Harden templates and API responses against missing data (#3730)
* Guard Activity index template against missing client/staff nested data

The activity log API at Activity/Api/Admin.php:38-49 only injects a
nested 'client' or 'staff' key when the corresponding *_id is set
(via isset() which returns false for null). System events and
client-only events therefore have no 'client' key, while staff-only
events have no 'client' key.

Under strict_variables, '{% if event.client %}' (line 191) throws
"Key 'client' ... does not exist" for any event without a client.

Switch the conditional to event.client_id / event.staff_id (always
present as SQL columns) and add '|default("")' to the nested
event.client.email / event.client.name / event.staff.email / event.staff.name
accesses so deleted-but-referenced records render gracefully.

* Guard Security iplookup template against empty country/asn data

When the GeoIP or ASN lookup fails (IncompleteRecord from MaxMind), the
Service catches and substitutes [] for the missing data. Under
strict_variables, the empty mapping at record.asn / record.country
causes line 48 to throw "sequence/mapping is empty".

Twig's |default filter on a GetAttrExpression compiles to a safe
is-defined check, so it correctly falls through to the placeholder
when the underlying array is empty or the key is missing.

Verified:
- /admin/security/iplookup?ip=192.168.1.1 (private IP, empty asn)
  renders the row with 'Unknown' ASN cells.
- /admin/security/iplookup?ip=8.8.8.8 still renders
  '15169' / 'GOOGLE' / 'United States'.

* Initialize notes/rel arrays in Support toApiArray so templates render without errors

Two related issues surfaced under strict_variables on the admin support
ticket page:

1. toApiArray only set $data['notes'] inside the foreach loop over
   ticket notes. Tickets without any notes therefore had no 'notes' key
   and 'ticket.notes|length' in mod_support_ticket.html.twig:42 threw
   'Key "notes" does not exist'.

2. _getRelDetails returned [] (empty array) when a ticket has no
   related entity. mod_support_ticket.html.twig sets {% set task =
   ticket.rel %} and then accesses task.task, task.type, task.status
   etc. on the next lines. Any access into an empty mapping throws
   under strict_variables.

Fixes:
- Service::toApiArray: always initialize $data['notes'] = [] for admin
  identity so the key is present even when empty.
- Service::_getRelDetails: always return the base structure with all
  fields (id, type, task, new_value, status) set to null when there
  is no related entity. Skip the DB lookups for the non-rel case.

Template hardening (defense-in-depth, in case other code paths return
a different shape):
- mod_support_ticket.html.twig:42: 'ticket.notes|length' -> 'is defined and
  ticket.notes|length'.
- mod_support_ticket.html.twig:222: 'ticket.notes' -> 'ticket.notes|default([])'.
- mod_support_tickets.html.twig:238: same is defined guard.

Verified on dev:
- /admin/support/ticket/1 renders without errors.
- API now returns rel as {id: null, type: null, ...} and notes: [] for
  tickets without related data.
- 1777 local tests pass, PHPStan clean.

* Harden tests and add Twig/ToApi linters

* Remove redundant setAccessible calls in tests

* Update cspell.json word list

* Add UrlAwarePermissiveContainer & trim errors

* Add geoip stub and fix ParserFactory usage

* Enforce and apply parentheses for new expressions
2026-06-06 18:32:19 +01:00

253 lines
7.9 KiB
PHP

<?php
/**
* Copyright 2022-2026 FOSSBilling
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
declare(strict_types=1);
namespace Tests\Support;
use PhpParser\Node;
use PhpParser\Node\Expr\ArrayDimFetch;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\NodeFinder;
use PhpParser\ParserFactory;
use Symfony\Component\Finder\Finder;
/**
* Walks every `function toApiArray` under `src/modules` and reports fields
* that are assigned to `$data['xxx']` only inside conditional blocks. The
* toApiArray method is the canonical bridge between a service-layer model
* and the JSON returned to the API; if a template reads a key that is only
* set inside an `if ($identity instanceof \Model_Admin)` branch, the
* template raises `Key "xxx" does not exist` under strict_variables, or
* returns a silent empty value under permissive rendering, when the
* response is consumed by a non-admin caller.
*
* Findings shape:
* <code>
* [
* 'modules/Foo/Service.php' => [
* 'top' => ['config', 'total', ...], // assigned unconditionally
* 'conditional' => [
* 'plugin' => ['if/else', 'if/else'], // never assigned at the top
* ],
* ],
* ]
* </code>
*/
final class ToApiArrayAuditor
{
private readonly \PhpParser\Parser $parser;
private readonly NodeFinder $nodeFinder;
public function __construct(private readonly string $srcDir)
{
// Parenthesise the `new` so the chained `->createForHostVersion()`
// call parses on PHP 8.3 as well as 8.4+. Without the parentheses,
// PHP 8.3 sees `new ParserFactory()->...` as a syntax error: the
// ability to omit them is a PHP 8.4 language change
// (https://wiki.php.net/rfc/new_without_parentheses).
$factory = new ParserFactory();
$this->parser = $factory->createForHostVersion();
$this->nodeFinder = new NodeFinder();
}
/**
* @return array<string, array{top: list<string>, conditional: array<string, list<string>>}>
*/
public function audit(): array
{
$findings = [];
$finder = new Finder();
$finder->files()->in($this->srcDir . '/modules')->name('*.php');
foreach ($finder as $file) {
$code = (string) $file->getContents();
try {
$ast = $this->parser->parse($code);
} catch (\Throwable) {
continue;
}
if ($ast === null) {
continue;
}
$methods = $this->nodeFinder->findInstanceOf($ast, ClassMethod::class);
foreach ($methods as $method) {
if ($method->name->toString() !== 'toApiArray') {
continue;
}
if ($method->stmts === null) {
continue;
}
$relPath = str_replace($this->srcDir . '/', '', $file->getPathName());
$fields = $this->auditMethodBody($method->stmts);
$top = [];
$conditional = [];
foreach ($fields as $name => $locations) {
$hasTop = false;
$conditionalLocs = [];
foreach ($locations as $loc) {
if ($loc === 'top') {
$hasTop = true;
} else {
$conditionalLocs[] = $loc;
}
}
if ($hasTop) {
$top[] = $name;
} elseif (!empty($conditionalLocs)) {
$conditional[$name] = $conditionalLocs;
}
}
if (!empty($conditional)) {
$findings[$relPath] = [
'top' => $top,
'conditional' => $conditional,
];
}
}
}
ksort($findings);
return $findings;
}
/**
* Walk a list of statements and return a map of `$data['xxx']` field
* names to the set of places they are assigned.
*
* @param Node\Stmt[] $stmts
*
* @return array<string, list<string>>
*/
private function auditMethodBody(array $stmts): array
{
$result = [];
foreach ($stmts as $stmt) {
$this->collectAssignments($stmt, $result, 'top');
}
return $result;
}
/**
* @param array<string, list<string>> $result
*/
private function collectAssignments(Node $node, array &$result, string $where): void
{
if ($node instanceof Node\Stmt\If_) {
$childWhere = 'if';
if ($node->elseifs !== null && count($node->elseifs) > 0) {
$childWhere = 'if (with elseifs)';
}
if ($node->else !== null) {
$childWhere = 'if/else';
}
foreach ($node->stmts as $child) {
$this->collectAssignments($child, $result, $childWhere);
}
foreach ($node->elseifs as $elseif) {
foreach ($elseif->stmts as $child) {
$this->collectAssignments($child, $result, $childWhere);
}
}
if ($node->else !== null) {
foreach ($node->else->stmts as $child) {
$this->collectAssignments($child, $result, $childWhere);
}
}
return;
}
if ($node instanceof Node\Stmt\For_ || $node instanceof Node\Stmt\Foreach_ || $node instanceof Node\Stmt\While_ || $node instanceof Node\Stmt\Do_) {
$childWhere = 'loop';
foreach ($node->stmts as $child) {
$this->collectAssignments($child, $result, $childWhere);
}
return;
}
if ($node instanceof Node\Stmt\Switch_) {
foreach ($node->cases as $case) {
foreach ($case->stmts as $child) {
$this->collectAssignments($child, $result, 'switch');
}
}
return;
}
if ($node instanceof Node\Stmt\TryCatch) {
$this->collectAssignments($node->try, $result, $where);
foreach ($node->catches as $catch) {
$this->collectAssignments($catch, $result, $where);
}
if ($node->finally !== null) {
$this->collectAssignments($node->finally, $result, $where);
}
return;
}
if ($node instanceof Node\Stmt\Block) {
foreach ($node->stmts as $child) {
$this->collectAssignments($child, $result, $where);
}
return;
}
if ($node instanceof Node\Stmt\Expression) {
$this->collectAssignments($node->expr, $result, $where);
return;
}
if ($node instanceof Assign) {
$field = $this->extractDataFieldName($node->var);
if ($field !== null) {
$result[$field][] = $where;
}
}
}
/**
* Extract the field name from a `$data['xxx']` or `$data['xxx'][]` access
* chain, or null if the chain doesn't terminate at a string-keyed
* `$data` access.
*/
private function extractDataFieldName(Node $node): ?string
{
if ($node instanceof ArrayDimFetch) {
if ($node->dim instanceof Node\Scalar\String_) {
$inner = $node->var;
if ($inner instanceof Variable && $inner->name === 'data') {
return $node->dim->value;
}
}
// Recurse in case of chained access like $data['x']['y'].
return $this->extractDataFieldName($node->var);
}
return null;
}
}