Files
clinicpro/tests/Shared/TenantLookupInventoryTest.php
T
hamedandClaude Opus 5 d2f4b5c428 fix(tenant): check the environment wherever a uuid comes from the request
Phase 7 was scoped to guard aggregate children, which the Doctrine filter cannot
reach. Measuring first — as the plan required — moved the target: all 22 children
and their 20 repositories were already sound. Every list query anchors on its
root, and ServiceItemRepository even joins service_sections and filters on the
pair by hand. A repository-level guard would have found nothing.

The real exposure was one layer up. Where a uuid arrives from a request body or
query string, the entity it names is loaded by uuid alone, and the filter is no
help: aggregate children have no tenant column, and a panel user who never chose
an environment is not filtered at all. Three leaks, each proven by removing the
fix and watching the new tests go red:

- GET /api/v1/appointment-service-slots accepted service_item_uuids from any
  environment. Existence, bookable state and duration leaked through the error
  messages and the returned slots. The booking path in the same controller had
  guarded this since it was written; the slot path never did.
- POST /api/v1/my/appointment attached service_section_uuid, service_item_uuid,
  staff_uuid and the service list without any check, and persisted them onto the
  appointment. A write, not just a read.
- PatientService did the same in all three of its loops — pricing, session
  create, session update — so another environment's service price entered the
  invoice and its SessionService row was stored, staff included.

TenantOwnershipChecker is the single place that answers "does this belong to the
current environment?". It reads getEntityType()/getEntityId(), so ServiceItem now
delegates that pair to its section: an aggregate child exposing the tenant it
inherits. An entity that exposes no pair throws rather than returning false —
silence here builds an always-closed guard, which is its own bug.

TenantLookupInventoryTest keeps a per-file count of these lookups. It earned its
place immediately: the first run found more sites than the manual grep had, and
reviewing them turned up the third PatientService loop. StaffController looked
unguarded until read properly — ownsStaff sits two lines below the null check.

One assertion was wrong before it was right: the create-path test read
`$session['services'] ?? []`, which passes vacuously. It now counts the stored
rows through the repository, and fails without the fix.

Tests: 879 passing. PHPStan unchanged at its 17 pre-existing errors.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 13:39:59 +03:30

107 lines
5.0 KiB
PHP

<?php
namespace App\Tests\Shared;
use PHPUnit\Framework\TestCase;
/**
* فهرستِ بازبینی‌شدهٔ جست‌وجوهای «uuid از درخواست → موجودیت محیط‌دار».
*
* سه نشتی این فاز همگی همین شکل را داشتند و هیچ‌کدام در repository نبودند؛ در
* کنترلر و سرویس بودند، جایی که uuid از بدنه/کوئری می‌آید و کسی محیط را نمی‌سنجد.
* پس گارد هم باید همان‌جا باشد، نه روی DQLهای repository.
*
* قاعده: عدد هر فایل = تعداد findByUuid روی repositoryهای محیط‌دار در آن فایل، که
* همگی بازبینی شده‌اند. اگر عدد عوض شود یعنی جست‌وجوی تازه‌ای اضافه شده و باید
* ثابت شود محیطش بررسی می‌شود — با ownsRecord/ownsSection/ownedItem،
* TenantOwnershipChecker، یا لنگرزدن به ریشه‌ای که خودش بررسی شده.
*
* @see \App\Shared\Tenant\TenantOwnershipChecker
* @see docs/architecture/tenancy.md
*/
class TenantLookupInventoryTest extends TestCase
{
/** repositoryهایی که موجودیت محیط‌دار یا فرزند aggregate برمی‌گردانند. */
private const TENANT_REPOSITORY_VARIABLES = [
'itemRepo', 'serviceItemRepo', 'sectionRepo', 'staffRepo',
'noteRepo', 'attachmentRepo', 'callRepo', 'messageRepo', 'medicalRepo',
'sessionRepo', 'sessionPaymentRepo', 'recordRepo',
'tenantInsuranceRepo', 'tenantTagRepo', 'packageRepo', 'ruleRepo',
];
/**
* فایل => تعداد جست‌وجوی بازبینی‌شده.
*
* @var array<string, int>
*/
private const REVIEWED = [
// assertServicesMatchContext در هر سه مسیر (اسلات سرویسی، ثبت، و خودِ گارد)
'src/Appointment/Controller/AppointmentController.php' => 3,
// TenantOwnershipChecker روی بخش/سرویس/پرسنل و فهرست سرویس‌ها
'src/Appointment/Controller/MyAppointmentsController.php' => 1,
// ownsSession / getEntityType روی صورتحساب، پرونده و مطالبه
'src/Billing/Controller/BillingController.php' => 3,
// ownsSection ×۹ و مقایسهٔ مستقیم جفت ×۳ (پکیج، کالا، پرسنل)
'src/ClinicService/Controller/ClinicServiceController.php' => 10,
'src/Discount/Controller/DiscountController.php' => 1,
// قرارداد بیمه با جفت، و سرویس با getSection()->getEntityType()
'src/Insurance/Controller/InsuranceController.php' => 5,
// ownedItem() / ownedPackage()
'src/Inventory/Controller/InventoryController.php' => 2,
'src/Inventory/Service/InventoryService.php' => 1,
// ownsRecord ×۳۳ و دو پرداختِ لنگرخورده به مراجعهٔ بررسی‌شده
'src/Patient/Controller/PatientController.php' => 35,
// TenantOwnershipChecker در هر سه حلقه (قیمت‌گذاری، ساخت، ویرایش) + کالا
'src/Patient/Service/PatientService.php' => 5,
// ownsStaff()
'src/Staff/Controller/StaffController.php' => 2,
];
private function projectDir(): string
{
return dirname(__DIR__, 2);
}
/** @return array<string, int> */
private function countLookups(): array
{
$pattern = '/->(' . implode('|', self::TENANT_REPOSITORY_VARIABLES) . ')->findByUuid\(/';
$counts = [];
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->projectDir() . '/src', \FilesystemIterator::SKIP_DOTS),
);
foreach ($files as $file) {
if ($file->getExtension() !== 'php') {
continue;
}
$found = preg_match_all($pattern, (string) file_get_contents($file->getPathname()));
if ($found > 0) {
$relative = str_replace($this->projectDir() . '/', '', $file->getPathname());
$counts[$relative] = $found;
}
}
ksort($counts);
return $counts;
}
public function testNoUnreviewedTenantLookupExists(): void
{
$actual = $this->countLookups();
$expected = self::REVIEWED;
ksort($expected);
self::assertSame($expected, $actual, <<<'MSG'
جست‌وجوی «uuid از درخواست موجودیت محیط‌دار» تغییر کرده.
برای هر مورد تازه ثابت کن محیطش بررسی می‌شود (ownsRecord/ownsSection/
ownedItem، TenantOwnershipChecker، یا لنگر به ریشهٔ بررسی‌شده) و بعد عدد
همان فایل را در REVIEWED به‌روز کن. اگر عدد کم شده، فقط عدد را کم کن.
MSG);
}
}