Files
fewo-stommer/tests/Feature/Process/ProcessTesterSecurityTest.php

193 lines
7.7 KiB
PHP

<?php
namespace Tests\Feature\Process;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Process\Tester\ProcessSandbox;
use App\Process\Tester\SandboxSnapshot;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\URL;
use PDO;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use RuntimeException;
use Tests\Support\Process\HostileProbe;
use Tests\TestCase;
/**
* Safety proof of the process tester (requirement T2, docs/Prozessarchitektur/Architektur/04 §7): a probe inside the
* tester process deliberately tries forbidden accesses. A passing happy path is no proof; these tests are. The
* "operational database" is a SQLite file of its own here; its hash before and after is compared.
*/
#[Group('sandbox')]
class ProcessTesterSecurityTest extends TestCase
{
use RefreshDatabase;
private Channel $website;
private User $user;
private string $operational;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
Settings::tenant()->update(['test_recipient' => 'vermieter@example.org', 'mailbox_password' => 'geheim']);
$this->website = Channel::websiteOf(Property::sole());
$this->user = User::factory()->create();
ProcessTesterTest::template();
$this->operational = storage_path('framework/testing/operational-'.getmypid().'.sqlite');
File::ensureDirectoryExists(dirname($this->operational));
@unlink($this->operational);
$pdo = new PDO('sqlite:'.$this->operational);
$pdo->exec('create table probe (id integer primary key, value text)');
$pdo->exec("insert into probe (value) values ('real')");
$pdo = null;
}
protected function tearDown(): void
{
@unlink($this->operational);
@unlink(base_path('sandbox-probe.txt'));
parent::tearDown();
}
/**
* @return array<string, array{string, ?string}>
*/
public static function forbidden(): array
{
return [
'N-DB1 other connection' => ['db_other_connection', 'database'],
'N-DB3 new connection to the real file' => ['db_new_connection', 'database'],
'N-DB3 sandbox redirected to the real file' => ['db_redirected_sandbox', 'database'],
'N-NET1 network without scripted answer' => ['network', 'network'],
'N-NET2 automation webhook' => ['webhook', 'network'],
'N-IMAP mailbox' => ['imap', 'imap'],
'N-MAIL other mailer' => ['mail_other_mailer', 'mail'],
'N-FILE storage outside the run' => ['file_outside', 'file'],
'N-CACHE other store' => ['cache_other_store', 'cache'],
];
}
#[DataProvider('forbidden')]
public function test_a_forbidden_access_is_recorded_aborts_the_run_and_changes_nothing(string $case, string $kind): void
{
$before = hash_file('sha256', $this->operational);
$run = $this->probe($case);
$this->assertSame(ProcessTestRun::ABORTED, $run->outcome, json_encode($run->report));
$this->assertSame($kind, $run->report['violations'][0]['kind'] ?? null, json_encode($run->report['violations']));
$this->assertSame($before, hash_file('sha256', $this->operational), 'the operational database file is unchanged');
$this->assertFileDoesNotExist(base_path('sandbox-probe.txt'));
$this->assertSame(0, Booking::query()->count());
}
/** N-DB2: the run's own database has no access to the operational tables at all. */
public function test_the_runs_database_does_not_contain_the_operational_tables(): void
{
$before = hash_file('sha256', $this->operational);
$run = $this->probe('db_operational_table');
$probe = collect($run->report['timeline'][0]['effects'] ?? [])->firstWhere('type', 'probe');
$this->assertSame('QueryException', $probe['outcome'] ?? null);
$this->assertSame($before, hash_file('sha256', $this->operational));
}
/** No credentials, no real configuration, no real cases inside the run; its key is its own. */
public function test_the_run_has_no_credentials_no_real_data_and_its_own_key(): void
{
Booking::factory()->for(Property::sole())->create();
$run = $this->probe('environment');
$probe = collect($run->report['timeline'][0]['effects'])->firstWhere('type', 'probe');
$this->assertFalse($probe['db_password_env']);
$this->assertSame(['sandbox'], $probe['connections']);
$this->assertSame(['array'], $probe['mailers']);
$this->assertNull($probe['smtp_password']);
$this->assertTrue($probe['app_key_differs']);
$this->assertSame([0, 0], [$probe['bookings'], $probe['guests']], 'no real case or guest is copied');
$snapshot = SandboxSnapshot::build($this->website, IntakeKind::Inquiry, ['model' => 'a1.offer']);
$this->assertArrayNotHasKey('bookings', $snapshot['tables']);
$this->assertNull($snapshot['tables']['tenants'][0]['mailbox_password']);
}
/** N-SIGN: a link signed inside a run is worthless in the real application. */
public function test_a_link_signed_in_a_run_is_invalid_outside(): void
{
$run = $this->probe('signed_link');
$url = collect($run->report['timeline'][0]['effects'])->firstWhere('type', 'probe')['url'];
$this->assertStringContainsString('signature=', $url);
$this->assertFalse(URL::hasValidSignature(Request::create($url)));
}
/** N-TOKEN: the run command refuses to work outside a run the tester started. */
public function test_the_run_command_refuses_outside_a_prepared_run(): void
{
$this->artisan('process:sandbox-run', ['run' => '00000000-0000-0000-0000-000000000000'])->assertFailed();
}
/** N-PAR: one run per landlord at a time. */
public function test_a_second_run_of_the_same_landlord_waits(): void
{
$directory = storage_path('app/sandbox/slots');
File::ensureDirectoryExists($directory);
$lock = fopen($directory.'/tenant-'.$this->website->tenant_id.'.lock', 'c');
flock($lock, LOCK_EX | LOCK_NB);
try {
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('läuft bereits');
$this->probe('none');
} finally {
flock($lock, LOCK_UN);
fclose($lock);
}
}
/** N-ABORT: the directory of an aborted run is removed by the next run. */
public function test_leftovers_of_aborted_runs_are_removed(): void
{
$left = storage_path('app/sandbox/runs/11111111-1111-1111-1111-111111111111');
File::ensureDirectoryExists($left);
touch($left, time() - 7200);
$this->probe('none');
$this->assertDirectoryDoesNotExist($left);
}
private function probe(string $case): ProcessTestRun
{
config(['fewo.sandbox.test_environment' => [
'FEWO_SANDBOX_PROBE' => HostileProbe::class,
'FEWO_SANDBOX_PROBE_CASE' => $case,
'FEWO_SANDBOX_PROBE_FILE' => $this->operational,
'FEWO_SANDBOX_PROBE_PARENT_KEY' => (string) config('app.key'),
'APP_ENV' => 'testing',
]]);
return app(ProcessSandbox::class)->run($this->website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', ['arrival' => '2026-11-07', 'nights' => 3], 1, $this->user);
}
}