feat: песочницу можно отключать для каждого инструмента

- FileSandbox: флаг restricted (по умолчанию true) и фабрика unrestricted()
- свободный режим разрешает абсолютные пути и '..'; корень остаётся базой
  для относительных путей
- isRestricted() для проверки режима
- каждый инструмент получает свой экземпляр песочницы, поэтому политика
  задаётся для каждого инструмента отдельно
- 93 теста
This commit is contained in:
rsgrinko committed 2026-11-12 19:13:26 +03:00
1 parent 72883fbc53
commit 48e59c0bb7
3 files changed
+159 -55

No files matched your search

+28 -4
View File
@@ -208,6 +208,29 @@ $tools = (new ToolRegistry())->add(
файлы и файлы больше 1 МБ; файлы и файлы больше 1 МБ;
- большие файлы читаются через `offset` и `limit` в строках. - большие файлы читаются через `offset` и `limit` в строках.
### Песочница: включить и выключить
По умолчанию всё ограничено корнем. Ограничение снимается осознанно — и
**отдельно для каждого инструмента**, потому что каждый получает свой экземпляр:
```php
$root = __DIR__ . '/data';
$tools = (new ToolRegistry())->add(
new ReadFileTool(FileSandbox::unrestricted()), // читать где угодно
new WriteFileTool(new FileSandbox($root)), // писать только в data
);
```
- `new FileSandbox($root)` — только внутри корня (по умолчанию);
- `FileSandbox::unrestricted($root)` — абсолютные пути и `..` разрешены,
корень нужен только как база для относительных путей;
- `$sandbox->isRestricted()` — проверить текущий режим.
Свободный режим — это фактически файловый `run_command`: модель сможет
прочитать `~/.ssh/id_rsa` или перезаписать системный файл. Включайте, только
если процесс и так ограничен контейнером или отдельным пользователем.
Запись — единственная деструктивная операция среди файловых инструментов. Запись — единственная деструктивная операция среди файловых инструментов.
Перед регистрацией `write_file`/`replace_in_file` стоит подумать о Перед регистрацией `write_file`/`replace_in_file` стоит подумать о
`toolApproval`: хук может спросить человека или запретить запись вне нужных `toolApproval`: хук может спросить человека или запретить запись вне нужных
@@ -450,11 +473,12 @@ curl http://10.10.10.77:8080/v1/models
php tests/run.php php tests/run.php
``` ```
88 проверок: калькулятор, время, реестр, обрезка результатов, весь цикл агента, 93 проверки: калькулятор, время, реестр, обрезка результатов, весь цикл агента,
настройки (tool_choice, подтверждение вызовов, история), finish, файлы настройки (tool_choice, подтверждение вызовов, история), finish, файлы
(чтение, запись, замена, поиск, побег из песочницы), CSV, единицы, даты, (чтение, запись, замена, поиск, побег из песочницы, свободный режим), CSV,
uuid/хеши, сборка HTTP-запроса (методы, тело, заголовки, Basic/Bearer), единицы, даты, uuid/хеши, сборка HTTP-запроса (методы, тело, заголовки,
защита от SSRF, run_command (код выхода, таймаут, allowlist, обрезка) Basic/Bearer), защита от SSRF, run_command (код выхода, таймаут, allowlist,
обрезка)
(успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель (успех, ошибка инструмента, лимит раундов, история). Сеть не нужна — модель
подменяется `FakeClient` из `tests/run.php`. подменяется `FakeClient` из `tests/run.php`.
+58
View File
@@ -1225,6 +1225,64 @@ test('json_query: битый JSON', function (): void {
assertContains('Некорректный JSON', $result); assertContains('Некорректный JSON', $result);
}); });
// ---------------------------------------------------------------------------
// Песочница: ограниченный и свободный режимы
// ---------------------------------------------------------------------------
test('sandbox: по умолчанию ограничена', function (): void {
$dir = testDir();
assertTrue((new FileSandbox($dir))->isRestricted());
assertTrue(!FileSandbox::unrestricted($dir)->isRestricted());
});
test('sandbox: свободный режим читает вне корня', function (): void {
$dir = testDir();
$outside = str_replace('\\', '/', dirname($dir) . '/outside.txt');
file_put_contents($outside, 'снаружи');
$result = (new ReadFileTool(FileSandbox::unrestricted($dir)))->handle(['path' => $outside]);
assertContains('снаружи', $result);
});
test('sandbox: свободный режим пишет вне корня', function (): void {
$dir = testDir();
$outside = str_replace('\\', '/', dirname($dir) . '/written.txt');
$result = (new WriteFileTool(FileSandbox::unrestricted($dir)))->handle([
'path' => $outside,
'content' => 'записано',
]);
assertContains('Создан', $result);
assertSame('записано', file_get_contents($outside));
});
test('sandbox: политика задаётся для каждого инструмента отдельно', function (): void {
$dir = testDir();
$outside = str_replace('\\', '/', dirname($dir) . '/mixed.txt');
file_put_contents($outside, 'данные');
// Читать можно везде...
$read = new ReadFileTool(FileSandbox::unrestricted($dir));
assertContains('данные', $read->handle(['path' => $outside]));
// ...а писать — только в корень.
$write = new WriteFileTool(new FileSandbox($dir));
assertContains('запрещены', $write->handle(['path' => $outside, 'content' => 'x']));
});
test('sandbox: ограниченный режим по-прежнему блокирует выход', function (): void {
$dir = testDir();
$outside = dirname($dir) . '/blocked.txt';
file_put_contents($outside, 'секрет');
$result = (new ReadFileTool(new FileSandbox($dir)))->handle(['path' => '../blocked.txt']);
assertContains('не должен содержать', $result);
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// run_command: оболочка // run_command: оболочка
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+73 -51
View File
@@ -5,17 +5,28 @@ declare(strict_types=1);
namespace AiSdk\Tools; namespace AiSdk\Tools;
/** /**
* Ограничитель файловых инструментов: любой путь обязан лежать внутри корня. * Ограничитель файловых инструментов.
* *
* Чтение проверяется через realpath, запись — через realpath каталога: * По умолчанию любой путь обязан лежать внутри корня: чтение проверяется через
* иначе «..» и симлинки уводили бы за пределы корня. * realpath, запись — через realpath каталога. Иначе «..» и симлинки уводили бы
* за пределы корня.
*
* Ограничение можно снять — осознанно и точечно:
*
* new ReadFileTool(FileSandbox::unrestricted()); // читать везде
* new WriteFileTool(new FileSandbox(__DIR__ . '/data')); // писать только в data
*
* Каждый инструмент получает свой экземпляр, поэтому политика задаётся
* для каждого инструмента отдельно.
*/ */
final class FileSandbox final class FileSandbox
{ {
private string $root; private string $root;
public function __construct(string $root) public function __construct(
{ string $root,
private readonly bool $restricted = true,
) {
$resolved = realpath($root); $resolved = realpath($root);
if ($resolved === false || !is_dir($resolved)) { if ($resolved === false || !is_dir($resolved)) {
@@ -25,33 +36,48 @@ final class FileSandbox
$this->root = rtrim($resolved, DIRECTORY_SEPARATOR); $this->root = rtrim($resolved, DIRECTORY_SEPARATOR);
} }
/**
* Песочница без ограничений: абсолютные пути и «..» разрешены.
* Корень нужен только как база для относительных путей.
*/
public static function unrestricted(string $root = ''): self
{
$base = $root !== '' ? $root : (string) getcwd();
return new self($base, false);
}
public function root(): string public function root(): string
{ {
return $this->root; return $this->root;
} }
public function isRestricted(): bool
{
return $this->restricted;
}
/** /**
* Абсолютный путь к существующему файлу или каталогу. * Абсолютный путь к существующему файлу или каталогу.
* *
* @throws \RuntimeException если путь вне корня или не найден * @throws \RuntimeException если путь вне корня (в ограниченном режиме) или не найден
*/ */
public function resolve(string $path): string public function resolve(string $path): string
{ {
$relative = $this->normalize($path); $target = $this->absolutePath($path);
$real = realpath($target);
if ($relative === '') {
return $this->root;
}
$real = realpath($this->root . DIRECTORY_SEPARATOR . $relative);
if ($real === false) { if ($real === false) {
throw new \RuntimeException( $hint = $this->restricted
'Путь не найден: ' . $path . '. Нужен путь к файлу относительно корня, например src/app.php.' ? ' Нужен путь к файлу относительно корня, например src/app.php.'
); : '';
throw new \RuntimeException('Путь не найден: ' . $path . '.' . $hint);
} }
$this->assertInside($real); if ($this->restricted) {
$this->assertInside($real);
}
return $real; return $real;
} }
@@ -64,41 +90,30 @@ final class FileSandbox
*/ */
public function resolveForWrite(string $path, bool $createDirs = false): string public function resolveForWrite(string $path, bool $createDirs = false): string
{ {
$relative = $this->normalize($path); $target = $this->absolutePath($path);
$directory = dirname($target);
if ($relative === '') { $name = basename($target);
throw new \RuntimeException('Не указан путь к файлу.');
}
$directory = dirname($relative);
$name = basename($relative);
if ($name === '' || $name === '.' || $name === '..') { if ($name === '' || $name === '.' || $name === '..') {
throw new \RuntimeException('Некорректное имя файла.'); throw new \RuntimeException('Некорректное имя файла.');
} }
$directoryPath = $directory === '.' || $directory === '' if (!is_dir($directory)) {
? $this->root
: $this->root . DIRECTORY_SEPARATOR . $directory;
if (!is_dir($directoryPath)) {
if (!$createDirs) { if (!$createDirs) {
throw new \RuntimeException('Каталог не существует: ' . $directory); throw new \RuntimeException('Каталог не существует: ' . $directory);
} }
if (!@mkdir($directoryPath, 0777, true) && !is_dir($directoryPath)) { if (!@mkdir($directory, 0777, true) && !is_dir($directory)) {
throw new \RuntimeException('Не удалось создать каталог: ' . $directory); throw new \RuntimeException('Не удалось создать каталог: ' . $directory);
} }
} }
$realDirectory = realpath($directoryPath); $realDirectory = realpath($directory) ?: $directory;
if ($realDirectory === false) { if ($this->restricted) {
throw new \RuntimeException('Каталог недоступен: ' . $directory); $this->assertInside($realDirectory);
} }
$this->assertInside($realDirectory);
return $realDirectory . DIRECTORY_SEPARATOR . $name; return $realDirectory . DIRECTORY_SEPARATOR . $name;
} }
@@ -138,7 +153,7 @@ final class FileSandbox
} }
/** /**
* Путь для показа пользователю (относительно корня). * Путь для показа пользователю (относительно корня, если внутри него).
*/ */
public function relative(string $absolute): string public function relative(string $absolute): string
{ {
@@ -146,41 +161,48 @@ final class FileSandbox
return '.'; return '.';
} }
$prefix = $this->root . DIRECTORY_SEPARATOR; if (!$this->startsWithRoot($absolute)) {
return $absolute;
if ($this->startsWithRoot($absolute)) {
return str_replace(DIRECTORY_SEPARATOR, '/', substr($absolute, strlen($prefix)));
} }
return $absolute; return str_replace(
DIRECTORY_SEPARATOR,
'/',
substr($absolute, strlen($this->root . DIRECTORY_SEPARATOR))
);
} }
/** /**
* Относительный путь без «..», абсолютных путей и нулевых байтов. * Привести путь к абсолютному. В ограниченном режиме абсолютные пути
* и «..» запрещены; в свободном — разрешены.
*/ */
private function normalize(string $path): string private function absolutePath(string $path): string
{ {
$path = trim(str_replace('\\', '/', $path)); $path = trim(str_replace('\\', '/', $path));
if ($path === '' || $path === '.') { if ($path === '' || $path === '.') {
return ''; return $this->root;
} }
if (str_contains($path, "\0")) { if (str_contains($path, "\0")) {
throw new \RuntimeException('Некорректный путь.'); throw new \RuntimeException('Некорректный путь.');
} }
if (str_starts_with($path, '/') || preg_match('/^[A-Za-z]:[\\\\\/]/', $path) === 1) { $absolute = str_starts_with($path, '/') || preg_match('/^[A-Za-z]:\//', $path) === 1;
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
if ($absolute) {
if ($this->restricted) {
throw new \RuntimeException('Абсолютные пути запрещены: указывайте путь относительно корня.');
}
return rtrim($path, '/');
} }
$path = preg_replace('#/+#', '/', $path) ?? $path; if ($this->restricted && preg_match('#(^|/)\.\.(/|$)#', $path) === 1) {
if (preg_match('#(^|/)\.\.(/|$)#', $path) === 1) {
throw new \RuntimeException('Путь не должен содержать "..".'); throw new \RuntimeException('Путь не должен содержать "..".');
} }
return trim($path, '/'); return $this->root . DIRECTORY_SEPARATOR . $path;
} }
private function assertInside(string $real): void private function assertInside(string $real): void