Files
InvoiceShelf/tests/Unit/AiToolRegistryTest.php
Darko Gjorgjijoski ac2a8ca939 fix(security): gate AI tools by user ability and block admin-URL SSRF
The AI chat assistant scoped tool queries by company but ignored the
per-user Bouncer abilities the rest of the app enforces, so any `use ai`
holder could read customers, invoices, payments, and company financials
their role couldn't otherwise see. Each AiTool now declares a required
ability (entity-aligned); the registry hides unauthorized tools from the
model and refuses to execute them as a backstop.

Separately, admin/owner-supplied URLs were fetched server-side with no
guard against private/reserved targets (SSRF): the AI base URL, the
CurrencyConverter "DEDICATED" exchange-rate URL, and S3/Spaces file-disk
endpoints. A shared PrivateNetworkGuard now backs a PublicHttpUrl
validation rule (save-time) and runtime guards in each driver.

- AiTool::requiredAbility() + mapping across all 12 tools
- AiToolRegistry filters schemas() by ability and re-checks in execute()
- PrivateNetworkGuard / BlockedUrlException / PublicHttpUrl rule (new)
- Rule wired into AI config (service + 3 controllers), exchange-rate,
  and file-disk endpoints; runtime guards in OpenRouterDriver,
  CurrencyConverterDriver, and FileDiskService
- Tests for ability filtering, the guard, the rule, and 422 rejections
2026-06-05 00:01:09 +02:00

98 lines
2.5 KiB
PHP

<?php
use App\Services\Ai\AiToolRegistry;
use App\Services\Ai\Tools\AiTool;
/**
* A stub tool for exercising the registry without touching any real DB tables.
*/
class FakeAiTool extends AiTool
{
public array $lastArgs = [];
public int $lastCompanyId = 0;
public int $lastUserId = 0;
public function __construct(
private readonly string $toolName = 'fake_tool',
) {}
public function name(): string
{
return $this->toolName;
}
public function description(): string
{
return 'A fake tool for tests.';
}
public function parameterSchema(): array
{
return [
'type' => 'object',
'properties' => [
'echo' => ['type' => 'string'],
],
'required' => [],
];
}
public function requiredAbility(): ?array
{
return null;
}
public function execute(array $arguments, int $companyId, int $userId): mixed
{
$this->lastArgs = $arguments;
$this->lastCompanyId = $companyId;
$this->lastUserId = $userId;
return ['echo' => $arguments['echo'] ?? null];
}
}
test('register stores a tool by its name', function () {
$registry = new AiToolRegistry;
$tool = new FakeAiTool;
$registry->register($tool);
expect($registry->get('fake_tool'))->toBe($tool);
expect($registry->all())->toHaveKey('fake_tool');
});
test('schemas returns OpenAI-format tool entries for every registered tool', function () {
$registry = new AiToolRegistry;
$registry->register(new FakeAiTool('alpha'));
$registry->register(new FakeAiTool('beta'));
$schemas = $registry->schemas(1);
expect($schemas)->toHaveCount(2);
expect($schemas[0]['type'])->toBe('function');
expect($schemas[0]['function']['name'])->toBe('alpha');
expect($schemas[1]['function']['name'])->toBe('beta');
});
test('execute injects companyId and userId into the tool and returns its result', function () {
$registry = new AiToolRegistry;
$tool = new FakeAiTool;
$registry->register($tool);
$result = $registry->execute('fake_tool', ['echo' => 'hello'], 42, 7);
expect($result)->toEqual(['echo' => 'hello']);
expect($tool->lastCompanyId)->toBe(42);
expect($tool->lastUserId)->toBe(7);
});
test('execute throws for unknown tool names', function () {
$registry = new AiToolRegistry;
expect(fn () => $registry->execute('nonexistent', [], 1, 1))
->toThrow(InvalidArgumentException::class);
});