Files

200 lines
8.1 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\User;
use App\Process\ChannelProcessConfiguration;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Str;
use RuntimeException;
/**
* The process tester seen from the landlord's request (docs/Prozessarchitektur/Architektur/04 §3.2): checks that the
* isolation can be established on this server, prepares a run (read-only snapshot, run directory), starts the run in a
* process of its own – which knows neither the real database nor any real service – waits for its report, stores the
* report and removes the run's directory. The landlord's request never switches into sandbox mode itself.
*/
final class ProcessSandbox
{
/** At most this many runs at the same time on the server (one per landlord). */
public const SLOTS = 3;
public const TIMEOUT_SECONDS = 30;
/**
* What keeps the tester from running safely here (empty = it may run). Checked in the request that would start it.
*
* @return list<string>
*/
public static function requirements(): array
{
$missing = [];
if (! extension_loaded('pdo_sqlite')) {
$missing[] = 'Die PHP-Erweiterung pdo_sqlite fehlt (eigene Testdatenbank je Lauf).';
}
if (! is_file(storage_path('app/sandbox/template.sqlite'))) {
$missing[] = 'Die Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).';
}
$disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
if (! function_exists('proc_open') || in_array('proc_open', $disabled, true)) {
$missing[] = 'Eigene Prozesse lassen sich nicht starten (proc_open gesperrt) – ohne eigenen Prozess ist keine sichere Trennung möglich.';
}
if (str_contains(str_replace(DIRECTORY_SEPARATOR, '/', self::php()), '/') && ! is_file(self::php())) {
$missing[] = 'Das PHP-Programm für den Testlauf wurde nicht gefunden.';
}
return $missing;
}
/**
* Plays a scenario with the (possibly unsaved) draft of a channel's process and returns the stored report.
*
* @param array<string, mixed> $draft
* @param array<string, mixed> $inputs
*/
public function run(Channel $channel, IntakeKind $intake, array $draft, string $scenario, array $inputs, int $steps, User $user): ProcessTestRun
{
if (($missing = self::requirements()) !== []) {
throw new RuntimeException('Der Prozess-Tester ist auf diesem Server gesperrt: '.implode(' ', $missing));
}
if (ScenarioCatalogue::find($scenario) === null) {
throw new RuntimeException('Unbekanntes Szenario.');
}
if (($problems = app(ChannelProcessConfiguration::class)->problems($channel, $intake, $draft, sandbox: true)) !== []) {
throw new RuntimeException('Die Konfiguration ist nicht zulässig: '.implode(' ', $problems));
}
self::prune();
$locks = $this->slot($channel->tenant_id);
$run = (string) Str::uuid();
$directory = SandboxBootstrapper::directory($run);
try {
File::ensureDirectoryExists($directory.'/files', 0700);
$input = [
'snapshot' => SandboxSnapshot::build($channel, $intake, $draft),
'scenario' => $scenario,
'inputs' => $inputs,
'steps' => $steps,
'start' => now()->startOfMinute()->toIso8601String(),
];
File::put($directory.'/input.json', (string) json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
$result = Process::path(base_path())
->timeout(self::TIMEOUT_SECONDS)
->env([SandboxBootstrapper::ENV => $run, ...self::childEnvironment(), ...(app()->environment('testing') ? (array) config('fewo.sandbox.test_environment', []) : [])])
->run([self::php(), 'artisan', 'process:sandbox-run', $run, '--no-interaction']);
$report = is_file($directory.'/report.json') ? (array) json_decode((string) File::get($directory.'/report.json'), true) : [];
if ($report === []) {
$report = ['aborted' => 'Der Testlauf hat keinen Bericht geliefert'.($result->successful() ? '.' : ': '.mb_substr(trim($result->errorOutput() ?: $result->output()), 0, 300)), 'timeline' => [], 'violations' => []];
}
return ProcessTestRun::query()->create([
'tenant_id' => $channel->tenant_id,
'channel_id' => $channel->id,
'user_id' => $user->id,
'intake' => $intake->value,
'scenario' => $scenario,
'configuration' => $draft,
'inputs' => $inputs,
'steps' => $steps,
'report' => $report,
'outcome' => filled($report['aborted'] ?? null) ? ProcessTestRun::ABORTED : ProcessTestRun::COMPLETED,
'release' => self::release(),
]);
} finally {
File::deleteDirectory($directory);
foreach ($locks as $lock) {
flock($lock, LOCK_UN);
fclose($lock);
}
}
}
/**
* Removes directories of runs that ended abnormally (older than an hour).
*/
public static function prune(): void
{
foreach (glob(storage_path('app/sandbox/runs/*'), GLOB_ONLYDIR) ?: [] as $directory) {
if (filemtime($directory) < time() - 3600) {
File::deleteDirectory($directory);
}
}
}
/**
* The release the report belongs to.
*/
public static function release(): ?string
{
// Releases on Strato live in releases/<timestamp>-<commit> (pipeline-manager, scripts/deploy.sh).
$release = basename(base_path());
return preg_match('/^\d{14}-[0-9a-f]{7,40}$/', $release) === 1 ? $release : null;
}
/**
* The PHP command line program for the run (Strato: php-cli next to the web PHP).
*/
public static function php(): string
{
$configured = (string) config('fewo.sandbox.php', '');
if ($configured !== '') {
return $configured;
}
return PHP_SAPI === 'cli' ? PHP_BINARY : (is_file('/opt/RZphp84/bin/php-cli') ? '/opt/RZphp84/bin/php-cli' : 'php');
}
/**
* Environment of the run's process: what Laravel needs to boot – never database, mail or service credentials (the
* run's configuration replaces them anyway, this keeps them out of its environment, too).
*
* @return array<string, string|false>
*/
private static function childEnvironment(): array
{
$blank = [];
foreach (array_keys(getenv()) as $key) {
if (preg_match('/^(DB_|MAIL_|REDIS_|AWS_|MAILBOX_|FEWO_MAILBOX|OPENAI|ANTHROPIC|OPENROUTER|N8N_|PIPELINE_)/', (string) $key) === 1) {
$blank[$key] = false;
}
}
return $blank;
}
/**
* One run per landlord and at most SLOTS on the server, as file locks (they end with the process).
*
* @return list<resource> the held locks (landlord, slot)
*/
private function slot(int $tenant): array
{
$directory = storage_path('app/sandbox/slots');
File::ensureDirectoryExists($directory, 0700);
$tenantLock = fopen($directory.'/tenant-'.$tenant.'.lock', 'c');
if ($tenantLock === false || ! flock($tenantLock, LOCK_EX | LOCK_NB)) {
throw new RuntimeException('Für diesen Vermieter läuft bereits ein Test. Bitte einen Moment warten.');
}
for ($index = 1; $index <= self::SLOTS; $index++) {
$slot = fopen($directory.'/slot-'.$index.'.lock', 'c');
if ($slot !== false && flock($slot, LOCK_EX | LOCK_NB)) {
return [$tenantLock, $slot];
}
if ($slot !== false) {
fclose($slot);
}
}
fclose($tenantLock);
throw new RuntimeException('Der Prozess-Tester ist gerade belegt. Bitte gleich noch einmal versuchen.');
}
}