Testbetrieb: eine Schranke fuer jede ausgehende E-Mail
Deploy FeWo mit PipelineManager / deploy (push) Failing after 3m10s

EnforceMailTestMode prueft jede Mail unmittelbar vor dem Versand (MessageSending,
jeder Mailer): im Testbetrieb gehen An/Cc/Bcc nur an die Testadresse, ohne
Testadresse wird nichts versendet; der Modus wird je Mail frisch gelesen.
Ersetzt alwaysTo am Standard-Mailer. Tests inkl. Pruefung, dass kein Code am
Mailer vorbei versendet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-01 21:03:24 +01:00
1 parent ac9d20b812
commit 0c10880e4f
6 files changed
+248 -9

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@ # Ferienwohnung Stommer
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The one gate is `App\Listeners\EnforceMailTestMode` (MessageSending, every mailer; no test address in test mode = nothing is sent) – never send mail around Laravel's mailer (no direct transports, `mail()`, own SMTP; `MailTestModeGateTest` checks this). Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
+2
View File
@@ -25,6 +25,8 @@ public function handle(): int
$this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address'));
if (filled($redirect)) {
$this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}.");
} elseif (! Settings::isLive()) {
$this->warn('Testbetrieb ohne Testadresse: Es wird keine E-Mail versendet. Testempfänger unter System › Betrieb eintragen.');
}
if ($mailer === 'log') {
$this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).');
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Listeners;
use App\Models\Tenant;
use App\Support\Settings;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
/**
* The one gate every outgoing e-mail passes – whichever mailer, mailable or notification sent it (Laravel fires
* MessageSending for every message right before the transport). In test operation it replaces every recipient (To, Cc,
* Bcc) by the test recipient; when no test recipient can be determined, the mail is not sent at all. Only a landlord
* switched live (and no server override) lets mails reach their real recipients.
*
* The operating mode is read fresh from the database for every mail, so a switch in the admin applies at once, also in
* long-running processes. Without any landlord the installation counts as being in test operation.
*/
class EnforceMailTestMode
{
public const ORIGINAL_RECIPIENTS_HEADER = 'X-Fewo-Testbetrieb-Original';
/**
* @return false|null false stops the mail; null lets it go on
*/
public function handle(MessageSending $event): ?bool
{
$message = $event->message;
$tenant = Settings::tenant();
$tenant = $tenant instanceof Tenant ? ($tenant->fresh() ?? $tenant) : null;
$override = config('fewo.mail_redirect_to');
if (blank($override) && $tenant?->isLive()) {
return null;
}
$redirect = Settings::mailRedirectFor($tenant);
if (blank($redirect) || filter_var($redirect, FILTER_VALIDATE_EMAIL) === false) {
// Test operation without anybody to redirect to: never fall through to the real recipients.
Log::warning('E-Mail im Testbetrieb nicht versendet: keine Testadresse eingerichtet.', ['subject' => $message instanceof Email ? $message->getSubject() : null, 'tenant' => $tenant?->id]);
return false;
}
if (! $message instanceof Email) {
Log::warning('E-Mail im Testbetrieb nicht versendet: unbekannter Nachrichtentyp.', ['type' => $message::class]);
return false;
}
$original = collect([...$message->getTo(), ...$message->getCc(), ...$message->getBcc()])
->map(fn (Address $address): string => $address->getAddress())->unique()->implode(', ');
$headers = $message->getHeaders();
$headers->remove('Cc');
$headers->remove('Bcc');
$headers->remove(self::ORIGINAL_RECIPIENTS_HEADER);
$message->to($redirect);
if ($original !== '') {
$headers->addTextHeader(self::ORIGINAL_RECIPIENTS_HEADER, mb_substr($original, 0, 900));
}
return null;
}
}
+3 -7
View File
@@ -2,8 +2,8 @@
namespace App\Tenancy;
use App\Listeners\EnforceMailTestMode;
use App\Models\Tenant;
use App\Support\Settings;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Mail;
use Throwable;
@@ -146,7 +146,8 @@ public function apply(?Tenant $tenant): void
}
/**
* The mailer sends everything to one address while the landlord is in test mode.
* Rebuilds the mailers so that they use the sender of the current landlord. Where mails go in test operation is
* decided for every single mail by the one gate {@see EnforceMailTestMode}, not here.
*/
public function applyMailRouting(?Tenant $tenant): void
{
@@ -157,11 +158,6 @@ public function applyMailRouting(?Tenant $tenant): void
}
$manager->purge();
$redirect = Settings::mailRedirectFor($tenant);
if (filled($redirect)) {
$manager->alwaysTo($redirect);
}
}
/**
+1 -1
View File
@@ -74,7 +74,7 @@ ## 5. Konfiguration auf dem Server (`shared/.env`)
## 5a. E-Mail: Testbetrieb und scharf schalten
- **Betriebsart** in der Verwaltung: **System › Betrieb** (nur Administratoren). Jede Installation beginnt im **Testbetrieb**: alle E-Mails (an Gäste, Vermieterin, Benachrichtigungen) gehen ausschließlich an die dort eingetragene **Testadresse** (ohne Eintrag: `FEWO_NOTIFICATION_EMAIL`), egal was auf der Webseite eingetragen wurde. Ein gelber Hinweis oben in der Verwaltung zeigt das an. Erst „Scharf geschaltet“ liefert an die echten Empfänger.
- **Betriebsart** in der Verwaltung: **System › Betrieb** (nur Administratoren). Jede Installation beginnt im **Testbetrieb**: alle E-Mails (an Gäste, Vermieterin, Benachrichtigungen) gehen ausschließlich an die dort eingetragene **Testadresse** (ohne Eintrag: `FEWO_NOTIFICATION_EMAIL`), egal was auf der Webseite eingetragen wurde. Ein gelber Hinweis oben in der Verwaltung zeigt das an. Erst „Scharf geschaltet“ liefert an die echten Empfänger. Technisch prüft **eine einzige Schranke** jede ausgehende Mail unmittelbar vor dem Versand (`App\Listeners\EnforceMailTestMode`, Ereignis `MessageSending`, für jeden Mailer): Im Testbetrieb ersetzt sie An/Cc/Bcc durch die Testadresse (Original im Kopf `X-Fewo-Testbetrieb-Original`); **ohne jede Testadresse wird gar nichts versendet** (Warnung im Log). Der Modus wird für jede Mail frisch aus der Datenbank gelesen.
- **Adressen der internen Kommunikation** ebenfalls unter System › Betrieb: *Benachrichtigungen an* (mehrere Adressen: neue Anfragen, Angebotsantworten, Fristabläufe, Bewertungen, Portal-Mails/-Aufgaben, Kopie der Zahlungserinnerungen), *Kontakt- und Antwortadresse* (Webseite, Mietvertrag, Antwortadresse der Gäste-Mails), *Absendername/-adresse* (muss zum SMTP-Postfach `MAIL_USERNAME` passen – das Formular warnt). Ohne Eintrag gelten `FEWO_NOTIFICATION_EMAIL`, `FEWO_OWNER_EMAIL`, `MAIL_FROM_*` aus `shared/.env`.
- `FEWO_MAIL_REDIRECT_TO` in `shared/.env` ist eine **harte Überschreibung** für Testserver (gilt auch bei „scharf“); normalerweise leer lassen.
- **Versandweg:** Standard `MAIL_MAILER=log` – dann wird gar nichts zugestellt (auch nicht im Protokoll gespeichert). Für echten Versand in `shared/.env` `MAIL_MAILER=smtp` und `MAIL_PASSWORD=<Passwort des Postfachs info@fewo-stommer.de>` (nur selbst eintragen; Absender und SMTP-Anmeldung: `info@fewo-stommer.de`, Antwortadresse und Benachrichtigungen weiter `FEWO_OWNER_EMAIL`/`FEWO_NOTIFICATION_EMAIL` = fewo@stommer.de), dann `bash scripts/deploy.sh staging artisan optimize`.
+174
View File
@@ -0,0 +1,174 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Actions\SendOffer;
use App\Listeners\EnforceMailTestMode;
use App\Models\Property;
use App\Models\Tenant;
use App\Pricing\StayRequest;
use App\Support\Settings;
use App\Tenancy\TenantConfig;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Mail\MailManager;
use Illuminate\Mail\SentMessage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\Finder\Finder;
use Tests\TestCase;
/**
* The test operation is one gate for every outgoing e-mail ({@see EnforceMailTestMode}): whichever mailer or mailable
* sends, in test operation nothing reaches a real recipient – and without a test address nothing is sent at all.
*/
class MailTestModeGateTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
config(['fewo.mail_redirect_to' => null, 'mail.default' => 'array']);
}
public function test_the_gate_is_registered_for_every_outgoing_message(): void
{
$listeners = json_encode(app('events')->getRawListeners()[MessageSending::class] ?? []);
$this->assertStringContainsString(addslashes(EnforceMailTestMode::class), (string) $listeners);
}
public function test_in_test_operation_to_cc_and_bcc_all_go_to_the_test_recipient_only(): void
{
$this->landlord(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => 'test@example.com']);
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->cc('vermieterin@example.com')->bcc('archiv@example.com')->subject('Angebot'));
$sent = $this->sent();
$this->assertCount(1, $sent);
$this->assertSame(['test@example.com'], $this->recipients($sent[0]));
$this->assertStringContainsString('gast@example.com', $sent[0]->getOriginalMessage()->getHeaders()->get(EnforceMailTestMode::ORIGINAL_RECIPIENTS_HEADER)?->getBodyAsString());
}
public function test_any_mailer_is_gated_not_only_the_default_one(): void
{
$this->landlord(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => 'test@example.com']);
config(['mail.default' => 'log']);
app(MailManager::class)->mailer('array')->raw('Hallo', fn ($message) => $message->to('gast@example.com')->subject('Direkt'));
$this->assertSame(['test@example.com'], $this->recipients($this->sent()[0]));
}
public function test_test_operation_without_any_address_sends_nothing_instead_of_the_real_recipient(): void
{
config(['fewo.notification_email' => null]);
$this->landlord(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => null, 'notification_emails' => null]);
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->subject('Angebot'));
$this->assertSame([], $this->sent());
}
public function test_a_mode_switched_in_the_database_applies_to_the_next_mail_at_once(): void
{
$tenant = $this->landlord(['operating_mode' => Settings::MODE_LIVE, 'test_recipient' => 'test@example.com']);
// Switched back to test operation elsewhere (another process); this process was not told.
DB::table('tenants')->where('id', $tenant->id)->update(['operating_mode' => Settings::MODE_TEST]);
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->subject('Angebot'));
$this->assertSame(['test@example.com'], $this->recipients($this->sent()[0]));
}
public function test_only_a_landlord_switched_live_reaches_real_recipients_and_the_server_override_always_wins(): void
{
$this->landlord(['operating_mode' => Settings::MODE_LIVE]);
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->subject('Angebot'));
$this->assertSame(['gast@example.com'], $this->recipients($this->sent()[0]));
config(['fewo.mail_redirect_to' => 'server@example.com']);
Mail::raw('Hallo', fn ($message) => $message->to('gast@example.com')->cc('x@example.com')->subject('Angebot'));
$this->assertSame(['server@example.com'], $this->recipients($this->sent()[1]));
}
public function test_real_guest_mails_of_the_booking_process_go_to_the_test_recipient(): void
{
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed(PropertySeeder::class);
Storage::fake('local');
$property = Property::sole();
$property->tenant->update(['operating_mode' => Settings::MODE_TEST, 'test_recipient' => 'test@example.com']);
app(TenantContext::class)->set($property->tenant->fresh());
$booking = app(CreateReservation::class)->handle($property, new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@gast.example']);
app(SendOffer::class)->handle($booking);
$sent = $this->sent();
$this->assertNotEmpty($sent);
foreach ($sent as $message) {
$this->assertSame(['test@example.com'], $this->recipients($message));
}
}
/**
* Nothing in the application may send around the gate: no direct transports, no PHP mail(), no own SMTP.
*/
public function test_no_code_sends_mail_around_the_gate(): void
{
$forbidden = [
'/(?<![\w>:])mail\s*\(/' => 'PHP mail()',
'/Symfony\\\\Component\\\\Mailer\\\\(Transport|Mailer)\b/' => 'Symfony-Transport direkt',
'/getSymfonyTransport\s*\(/' => 'Transport direkt',
'/fsockopen|stream_socket_client/' => 'eigene Socket-Verbindung',
'/PHPMailer|SwiftMailer|Swift_/' => 'fremde Mail-Bibliothek',
'/sendmail/' => 'sendmail',
];
$violations = [];
foreach ((new Finder)->files()->in([app_path(), base_path('routes'), base_path('config')])->name('*.php') as $file) {
foreach ($forbidden as $pattern => $what) {
if (preg_match($pattern, $file->getContents()) === 1 && ! str_ends_with($file->getRealPath(), 'config'.DIRECTORY_SEPARATOR.'mail.php')) {
$violations[] = $file->getRelativePathname().': '.$what;
}
}
}
$this->assertSame([], $violations);
}
/**
* @return list<SentMessage|\Symfony\Component\Mailer\SentMessage>
*/
private function sent(): array
{
return array_values(iterator_to_array(app(MailManager::class)->mailer('array')->getSymfonyTransport()->messages()));
}
/**
* @return list<string>
*/
private function recipients(object $sent): array
{
return array_map(fn ($address) => $address->getAddress(), $sent->getEnvelope()->getRecipients());
}
/**
* @param array<string, mixed> $attributes
*/
private function landlord(array $attributes = []): Tenant
{
$tenant = Tenant::factory()->create($attributes);
app(TenantContext::class)->set($tenant);
app(TenantConfig::class)->refresh();
return $tenant;
}
}