From fd2a7f7dedd43a8d32935e12abd149c2ba8fa759 Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Sat, 24 Oct 2026 09:14:10 +0200 Subject: [PATCH 1/2] =?UTF-8?q?Dienste=20wirklich=20anschlie=C3=9Fen:=20ze?= =?UTF-8?q?ntrale=20Steuerung=20statt=20folgenloser=20Schalter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Die Schalter aus Phase 3 schrieben nur in eine Tabelle, die niemand las. Ein gesperrter Portal-Abgleich lief trotzdem weiter. Das ist behoben. `App\Tenancy\TenantFeatures` ist die eine Stelle, die beantwortet, ob ein Mandant einen Dienst hat. Sie wird an allen Wegen abgefragt, die zum Dienst führen: - `RolePolicy::allows()` – damit greift die Mandanten-Ebene in *jeder* Richtlinie des Admins. Die Rolle sagt, was ein Benutzer darf; der Dienst sagt, was der Mandant überhaupt hat. Keine Rolle wiegt einen gesperrten Dienst auf. - `Channel::importsOccupations()` – Import und Scheduler. - Der öffentliche iCal-Feed antwortet mit 404. - `ProcessPortalMail` und `channels:fetch-mail` für den Postfach-Schnellweg. `TenantServiceKey::isWired()` trennt Gebautes von Geplantem. Nur verdrahtete Dienste erscheinen als Schalter; die drei KI-Dienste stehen als Hinweis da, bis die Anwendung sie abfragt. Eigene API-Schlüssel sind aus dem Betreiber- Formular verschwunden – sie gehören in den Admin des Mandanten, wenn es soweit ist (A16). Neu im Betreiber-Bereich: Seite „System" mit den Grenzen, die für alle Mandanten gelten (aus der .env, bewusst nicht änderbar), der Mandantenliste und dem Zugriffsprotokoll. Bisher war dort nur die Mandantenliste. Die Migration schaltet jedem vorhandenen Mandanten die Portal-Dienste frei, damit der Umbau laufenden Betrieb nicht stillschweigend stoppt. 240 Feature-Tests grün, davon fünf neue in `TenantServiceGateTest`. Co-Authored-By: Claude Opus 5 --- app/Actions/ProcessPortalMail.php | 7 ++ app/Console/Commands/FetchPortalMail.php | 3 + app/Enums/TenantServiceKey.php | 60 ++++++++- .../Operator/Concerns/EditsTenantServices.php | 22 ++-- .../Operator/Pages/SystemOverview.php | 116 ++++++++++++++++++ app/Filament/Operator/TenantResource.php | 29 +++-- app/Http/Controllers/ChannelController.php | 2 + app/Models/Channel.php | 13 +- app/Policies/RolePolicy.php | 12 +- .../Filament/OperatorPanelProvider.php | 2 + app/Tenancy/TenantFeatures.php | 105 ++++++++++++++++ ..._default_services_for_existing_tenants.php | 35 ++++++ .../operator/system-overview.blade.php | 86 +++++++++++++ tests/Feature/TenantServiceGateTest.php | 115 +++++++++++++++++ tests/Feature/TenantSettingsTest.php | 46 ++++--- 15 files changed, 598 insertions(+), 55 deletions(-) create mode 100644 app/Filament/Operator/Pages/SystemOverview.php create mode 100644 app/Tenancy/TenantFeatures.php create mode 100644 database/migrations/2026_10_24_080000_unlock_default_services_for_existing_tenants.php create mode 100644 resources/views/filament/operator/system-overview.blade.php create mode 100644 tests/Feature/TenantServiceGateTest.php diff --git a/app/Actions/ProcessPortalMail.php b/app/Actions/ProcessPortalMail.php index ec604e0..7a2412a 100644 --- a/app/Actions/ProcessPortalMail.php +++ b/app/Actions/ProcessPortalMail.php @@ -8,12 +8,14 @@ use App\Channels\Mail\PortalMailParser; use App\Enums\PortalEmailStatus; use App\Enums\PortalEmailType; +use App\Enums\TenantServiceKey; use App\Mail\ChannelConflict; use App\Mail\PortalMailNotification; use App\Models\BlockedPeriod; use App\Models\Channel; use App\Models\PortalEmail; use App\Support\Settings; +use App\Tenancy\TenantFeatures; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Mail; @@ -40,6 +42,11 @@ public function handle(PortalMail $mail): ?PortalEmail return null; } + // The fast path is a service of its own: a landlord without it keeps the mail unprocessed. + if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) { + return null; + } + $parsed = $this->parser->parse($mail->subject, $mail->text); $conflicts = []; diff --git a/app/Console/Commands/FetchPortalMail.php b/app/Console/Commands/FetchPortalMail.php index 90c1b4e..221b3bb 100644 --- a/app/Console/Commands/FetchPortalMail.php +++ b/app/Console/Commands/FetchPortalMail.php @@ -5,7 +5,9 @@ use App\Actions\ProcessPortalMail; use App\Channels\ChannelSyncException; use App\Channels\Mail\MailboxReader; +use App\Enums\TenantServiceKey; use App\Models\Channel; +use App\Tenancy\TenantFeatures; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; @@ -26,6 +28,7 @@ public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMa } $senders = Channel::query()->active()->get() + ->filter(fn (Channel $channel): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) ->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel)) ->unique() ->values() diff --git a/app/Enums/TenantServiceKey.php b/app/Enums/TenantServiceKey.php index 405d774..1c7473f 100644 --- a/app/Enums/TenantServiceKey.php +++ b/app/Enums/TenantServiceKey.php @@ -3,7 +3,9 @@ namespace App\Enums; /** - * Services the operator can switch on per landlord. The AI services have no function behind them yet. + * Services the operator unlocks per landlord. `isWired()` says whether the application really asks before + * it acts – a service that nothing asks for must not be offered as a switch, because switching it would + * promise something that does not happen. */ enum TenantServiceKey: string { @@ -17,10 +19,58 @@ public function label(): string { return match ($this) { self::PortalSync => 'Portal-Abgleich (iCal)', - self::PortalMail => 'Portal-Postfach', - self::AiOffers => 'KI: Angebote', - self::AiMarketing => 'KI: Marketing', - self::AiGuestMail => 'KI: Gästepost', + self::PortalMail => 'Portal-Postfach (Schnellweg)', + self::AiOffers => 'KI: Angebotsentwürfe', + self::AiMarketing => 'KI: Vermarktungsassistent', + self::AiGuestMail => 'KI: Gästekommunikation', }; } + + public function description(): string + { + return match ($this) { + self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.', + self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.', + self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.', + }; + } + + /** + * Whether the application asks this switch before it acts. Only wired services are offered for switching. + */ + public function isWired(): bool + { + return match ($this) { + self::PortalSync, self::PortalMail => true, + self::AiOffers, self::AiMarketing, self::AiGuestMail => false, + }; + } + + /** + * What applies to a landlord the operator has not decided about yet. The portal services were part of + * the product before there were landlords, so switching tenancy on must not silently stop them. + */ + public function enabledByDefault(): bool + { + return $this->isWired(); + } + + /** + * Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one. + */ + public function usesApiKey(): bool + { + return match ($this) { + self::AiOffers, self::AiMarketing, self::AiGuestMail => true, + self::PortalSync, self::PortalMail => false, + }; + } + + /** + * @return list + */ + public static function wired(): array + { + return array_values(array_filter(self::cases(), fn (self $service): bool => $service->isWired())); + } } diff --git a/app/Filament/Operator/Concerns/EditsTenantServices.php b/app/Filament/Operator/Concerns/EditsTenantServices.php index 0049300..0024c04 100644 --- a/app/Filament/Operator/Concerns/EditsTenantServices.php +++ b/app/Filament/Operator/Concerns/EditsTenantServices.php @@ -4,11 +4,12 @@ use App\Enums\TenantServiceKey; use App\Models\Tenant; -use App\Models\TenantService; +use App\Tenancy\TenantFeatures; /** * The service switches of the tenant form. They live in their own table, so the form state is read and - * written separately from the landlord's own columns. + * written separately from the landlord's own columns. Only wired services are written – a switch for a + * service nothing asks about would promise something that does not happen. */ trait EditsTenantServices { @@ -24,10 +25,11 @@ protected function mutateFormDataBeforeFill(array $data): array return $data; // creating: there is nothing to read yet } - $data['services'] = $tenant->services - ->mapWithKeys(fn (TenantService $service): array => [$service->service => [ - 'is_enabled' => $service->is_enabled, - 'api_key' => $service->api_key, + $stored = $tenant->services->keyBy('service'); + + $data['services'] = collect(TenantServiceKey::wired()) + ->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [ + 'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(), ]]) ->all(); @@ -83,18 +85,16 @@ private function saveServices(): void return; } - foreach (TenantServiceKey::cases() as $service) { + foreach (TenantServiceKey::wired() as $service) { $state = $this->services[$service->value] ?? []; $tenant->services()->updateOrCreate( ['service' => $service->value], - [ - 'is_enabled' => (bool) ($state['is_enabled'] ?? false), - 'api_key' => filled($state['api_key'] ?? null) ? $state['api_key'] : null, - ], + ['is_enabled' => (bool) ($state['is_enabled'] ?? false)], ); } $tenant->unsetRelation('services'); + app(TenantFeatures::class)->forget($tenant); } } diff --git a/app/Filament/Operator/Pages/SystemOverview.php b/app/Filament/Operator/Pages/SystemOverview.php new file mode 100644 index 0000000..83edcca --- /dev/null +++ b/app/Filament/Operator/Pages/SystemOverview.php @@ -0,0 +1,116 @@ + + */ + public function limits(): array + { + $config = app(TenantConfig::class); + + $rows = [ + ['Gästedaten löschen nach', 'fewo.guest_retention_years', 'Jahre', 'Ein Mandant kann kürzer löschen, nicht länger aufbewahren.'], + ['Nicht gebuchte Anfragen löschen nach', 'fewo.retention.inquiry_months', 'Monate', ''], + ['Portal-Mail-Auszug löschen nach', 'fewo.retention.portal_email_excerpt_days', 'Tage', ''], + ['Herkunftsangaben löschen nach', 'fewo.retention.attribution_months', 'Monate', ''], + ['Bot-Schutz: Mindestzeit im Formular', 'fewo.spam.min_seconds', 'Sekunden', 'Ein Mandant kann länger warten lassen, nicht kürzer.'], + ['Bot-Schutz: Anfragen je IP und Stunde', 'fewo.spam.per_ip_per_hour', '', ''], + ['Bot-Schutz: Anfragen je E-Mail und Tag', 'fewo.spam.per_email_per_day', '', ''], + ['Bot-Schutz: offene Anfragen je E-Mail', 'fewo.spam.open_requests_per_email', '', ''], + ['Bot-Schutz: Links im Text', 'fewo.spam.max_links', '', ''], + ]; + + return array_map(fn (array $row): array => [ + 'label' => $row[0], + 'value' => trim($config->baselineValue($row[1]).' '.$row[2]), + 'note' => $row[3], + ], $rows); + } + + /** + * Values that belong to the whole installation and to no landlord. + * + * @return list + */ + public function global(): array + { + $redirect = config('fewo.mail_redirect_to'); + + return [ + [ + 'label' => 'Anfragen aller Websites zusammen', + 'value' => config('fewo.spam.total_per_hour').' je Stunde', + 'note' => 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.', + ], + [ + 'label' => 'Harte Mail-Umleitung', + 'value' => filled($redirect) ? (string) $redirect : 'nicht gesetzt', + 'note' => filled($redirect) + ? 'FEWO_MAIL_REDIRECT_TO: jede E-Mail dieses Servers geht hierhin, auch bei scharf geschalteten Mandanten.' + : 'Ohne Umleitung entscheidet die Betriebsart des jeweiligen Mandanten.', + ], + [ + 'label' => 'Versandweg', + 'value' => (string) config('mail.default'), + 'note' => 'SMTP-Zugang und Datenbank sind Infrastruktur und liegen in der .env des Servers.', + ], + [ + 'label' => 'Datenbank-Sicherungen', + 'value' => config('fewo.backup.keep').' Stück', + 'note' => 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.', + ], + ]; + } + + /** + * @return Collection + */ + public function tenants(): Collection + { + return Tenant::query()->withCount(['services' => fn ($query) => $query->where('is_enabled', true)])->orderBy('name')->get(); + } + + public function wiredServiceCount(): int + { + return count(TenantServiceKey::wired()); + } + + /** + * @return Collection + */ + public function accessLog(): Collection + { + return TenantAccessLog::query()->with(['tenant', 'user'])->latest('created_at')->limit(20)->get(); + } +} diff --git a/app/Filament/Operator/TenantResource.php b/app/Filament/Operator/TenantResource.php index 319f15a..015ba8b 100644 --- a/app/Filament/Operator/TenantResource.php +++ b/app/Filament/Operator/TenantResource.php @@ -14,13 +14,14 @@ use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Resources\Resource; -use Filament\Schemas\Components\Fieldset; use Filament\Schemas\Components\Section; +use Filament\Schemas\Components\Text; use Filament\Schemas\Schema; use Filament\Support\Icons\Heroicon; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Columns\ToggleColumn; use Filament\Tables\Table; +use Illuminate\Database\Eloquent\Builder; class TenantResource extends Resource { @@ -55,18 +56,17 @@ public static function form(Schema $schema): Schema ->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.') ->default(true), Section::make('Dienste') - ->description('Welche Dienste dieser Mandant nutzen darf. Ein eigener Schlüssel ist freiwillig; bleibt er leer, gilt später der Schlüssel des Betreibers.') + ->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.') ->columnSpanFull() - ->schema(array_map(fn (TenantServiceKey $service): Fieldset => Fieldset::make($service->label()) - ->columns(2) - ->schema([ - Toggle::make('services.'.$service->value.'.is_enabled')->label('Freigeschaltet'), - TextInput::make('services.'.$service->value.'.api_key') - ->label('Eigener API-Schlüssel') - ->password() - ->revealable() - ->maxLength(255), - ]), TenantServiceKey::cases())), + ->schema([ + ...array_map(fn (TenantServiceKey $service): Toggle => Toggle::make('services.'.$service->value.'.is_enabled') + ->label($service->label()) + ->helperText($service->description()), TenantServiceKey::wired()), + Text::make('Noch nicht gebaut und deshalb nicht schaltbar: '.implode(', ', array_map( + fn (TenantServiceKey $service): string => $service->label(), + array_values(array_filter(TenantServiceKey::cases(), fn (TenantServiceKey $service): bool => ! $service->isWired())), + )).'. Diese Dienste erscheinen hier, sobald die Anwendung sie wirklich abfragt; eigene API-Schlüssel gehören dann in den Admin des Mandanten.'), + ]), ]); } @@ -76,7 +76,10 @@ public static function table(Table $table): Table ->columns([ TextColumn::make('name')->label('Name')->searchable(), TextColumn::make('slug')->label('Kurzname'), - TextColumn::make('services_count')->label('Dienste')->counts(['services' => fn ($query) => $query->where('is_enabled', true)]), + TextColumn::make('services_count') + ->label('Dienste frei') + ->counts(['services' => fn (Builder $query): Builder => $query->where('is_enabled', true)]) + ->suffix(' von '.count(TenantServiceKey::wired())), ToggleColumn::make('is_active')->label('Aktiv'), ]) ->recordActions([ diff --git a/app/Http/Controllers/ChannelController.php b/app/Http/Controllers/ChannelController.php index 2f2e75d..c0ebca1 100644 --- a/app/Http/Controllers/ChannelController.php +++ b/app/Http/Controllers/ChannelController.php @@ -27,6 +27,8 @@ public function feed(string $token, ICalFeed $feed): Response { $channel = Channel::query()->where('export_token', $token)->where('is_active', true)->firstOrFail(); + abort_unless($channel->servesItsLandlord(), 404); + return response($feed->build($channel), 200, [ 'Content-Type' => 'text/calendar; charset=utf-8', 'Content-Disposition' => 'inline; filename="belegung.ics"', diff --git a/app/Models/Channel.php b/app/Models/Channel.php index 6ed0969..00884dd 100644 --- a/app/Models/Channel.php +++ b/app/Models/Channel.php @@ -4,7 +4,9 @@ use App\Channels\ChannelRegistry; use App\Channels\Contracts\ChannelConnector; +use App\Enums\TenantServiceKey; use App\Models\Concerns\BelongsToTenant; +use App\Tenancy\TenantFeatures; use Database\Factories\ChannelFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Hidden; @@ -100,7 +102,16 @@ public function connector(): ChannelConnector public function importsOccupations(): bool { - return $this->is_active && $this->connector()->canImport($this); + return $this->is_active && $this->servesItsLandlord() && $this->connector()->canImport($this); + } + + /** + * Whether the landlord this channel belongs to has the portal synchronisation unlocked at all. + * Asked here, so that neither an import nor the export feed can run around the switch. + */ + public function servesItsLandlord(): bool + { + return app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $this->tenant); } public function exportUrl(): string diff --git a/app/Policies/RolePolicy.php b/app/Policies/RolePolicy.php index 7ec5d30..d665952 100644 --- a/app/Policies/RolePolicy.php +++ b/app/Policies/RolePolicy.php @@ -4,6 +4,7 @@ use App\Enums\Permission; use App\Models\User; +use App\Tenancy\TenantFeatures; /** * Grants every ability that the current membership includes. The operator counts as administrator @@ -48,8 +49,17 @@ public function reorder(User $user): bool return $this->allows($user); } + /** + * Both questions, in one place: the role says what this user may do, TenantFeatures says what the + * landlord has unlocked at all. An administrator of a landlord without the portal services does not + * reach the portal screens either – no role grants what the landlord does not have. + */ protected function allows(User $user): bool { - return (bool) $user->currentRole()?->grants($this->permission()); + if (! $user->currentRole()?->grants($this->permission())) { + return false; + } + + return app(TenantFeatures::class)->permits($this->permission()); } } diff --git a/app/Providers/Filament/OperatorPanelProvider.php b/app/Providers/Filament/OperatorPanelProvider.php index a11e12d..2934b72 100644 --- a/app/Providers/Filament/OperatorPanelProvider.php +++ b/app/Providers/Filament/OperatorPanelProvider.php @@ -2,6 +2,7 @@ namespace App\Providers\Filament; +use App\Filament\Operator\Pages\SystemOverview; use App\Http\Middleware\ResolveTheme; use Filament\Auth\MultiFactor\App\AppAuthentication; use Filament\Http\Middleware\Authenticate; @@ -40,6 +41,7 @@ public function panel(Panel $panel): Panel ->discoverResources(in: app_path('Filament/Operator'), for: 'App\Filament\Operator') ->pages([ Dashboard::class, + SystemOverview::class, ]) ->widgets([ AccountWidget::class, diff --git a/app/Tenancy/TenantFeatures.php b/app/Tenancy/TenantFeatures.php new file mode 100644 index 0000000..2db5f26 --- /dev/null +++ b/app/Tenancy/TenantFeatures.php @@ -0,0 +1,105 @@ +> + */ + private const REQUIRES_ANY = [ + Permission::Channels->value => [TenantServiceKey::PortalSync, TenantServiceKey::PortalMail], + ]; + + /** + * Unlocked services per landlord id, for the length of one request. + * + * @var array> + */ + private array $cache = []; + + /** + * Whether the landlord may use the service. Without a landlord (console before a context is chosen, + * boot) the default of the service applies, which keeps a single-landlord installation unchanged. + */ + public function enabled(TenantServiceKey $service, ?Tenant $tenant = null): bool + { + $tenant ??= app(TenantContext::class)->get(); + + if ($tenant === null) { + return $service->enabledByDefault(); + } + + return $this->forTenant($tenant)[$service->value] ?? $service->enabledByDefault(); + } + + /** + * Whether the landlord has what a permission needs. A permission that depends on no service is always + * granted here – the role still decides separately. + */ + public function permits(Permission $permission, ?Tenant $tenant = null): bool + { + $required = self::REQUIRES_ANY[$permission->value] ?? []; + + if ($required === []) { + return true; + } + + foreach ($required as $service) { + if ($this->enabled($service, $tenant)) { + return true; + } + } + + return false; + } + + /** + * Forgets what was read, so a switch takes effect without a new request. + */ + public function forget(?Tenant $tenant = null): void + { + if ($tenant === null) { + $this->cache = []; + + return; + } + + unset($this->cache[$tenant->id]); + } + + /** + * @return array + */ + private function forTenant(Tenant $tenant): array + { + if (! array_key_exists($tenant->id, $this->cache)) { + try { + $this->cache[$tenant->id] = TenantService::query() + ->where('tenant_id', $tenant->id) + ->pluck('is_enabled', 'service') + ->map(fn (mixed $enabled): bool => (bool) $enabled) + ->all(); + } catch (Throwable) { + return []; // before the migrations ran; the defaults apply + } + } + + return $this->cache[$tenant->id]; + } +} diff --git a/database/migrations/2026_10_24_080000_unlock_default_services_for_existing_tenants.php b/database/migrations/2026_10_24_080000_unlock_default_services_for_existing_tenants.php new file mode 100644 index 0000000..1406eab --- /dev/null +++ b/database/migrations/2026_10_24_080000_unlock_default_services_for_existing_tenants.php @@ -0,0 +1,35 @@ +pluck('id') as $tenantId) { + foreach (TenantServiceKey::wired() as $service) { + DB::table('tenant_services')->updateOrInsert( + ['tenant_id' => $tenantId, 'service' => $service->value], + ['is_enabled' => $service->enabledByDefault(), 'updated_at' => $now, 'created_at' => $now], + ); + } + } + } + + public function down(): void + { + DB::table('tenant_services')->whereIn('service', array_map( + fn (TenantServiceKey $service): string => $service->value, + TenantServiceKey::wired(), + ))->delete(); + } +}; diff --git a/resources/views/filament/operator/system-overview.blade.php b/resources/views/filament/operator/system-overview.blade.php new file mode 100644 index 0000000..700e802 --- /dev/null +++ b/resources/views/filament/operator/system-overview.blade.php @@ -0,0 +1,86 @@ + + + Mandanten + Wer auf diesem Server liegt und was freigeschaltet ist. + +
+ + + + + + + + + + + @foreach ($this->tenants() as $tenant) + + + + + + + @endforeach + +
NameKurznameZustandDienste frei
{{ $tenant->name }}{{ $tenant->slug }} + + {{ $tenant->is_active ? 'aktiv' : 'gesperrt' }} + + {{ $tenant->services_count }} von {{ $this->wiredServiceCount() }}
+
+
+ + + Grenzen für alle Mandanten + + Aus der .env dieses Servers. Ein Mandant kann sie in seinem Admin verschärfen, aber nicht + überschreiten. Änderungen hier wären Änderungen an der Infrastruktur und gehören deshalb auf den Server, + nicht in eine Oberfläche, die ein Mandant erreichen könnte. + + +
+ @foreach ($this->limits() as $row) +
+
{{ $row['label'] }}
+
{{ $row['value'] }}
+
{{ $row['note'] }}
+
+ @endforeach +
+
+ + + Gilt für den ganzen Server + +
+ @foreach ($this->global() as $row) +
+
{{ $row['label'] }}
+
{{ $row['value'] }}
+
{{ $row['note'] }}
+
+ @endforeach +
+
+ + + Zugriffe des Betreibers + Wer wann den Admin eines Mandanten geöffnet hat. Support-Zugriff bleibt sichtbar. + + @if ($this->accessLog()->isEmpty()) +

Noch kein Zugriff aufgezeichnet.

+ @else +
    + @foreach ($this->accessLog() as $entry) +
  • + {{ $entry->created_at?->format('d.m.Y H:i') }} + {{ $entry->user?->name ?? 'Unbekannt' }} + öffnete + {{ $entry->tenant?->name ?? 'gelöschter Mandant' }} +
  • + @endforeach +
+ @endif +
+
diff --git a/tests/Feature/TenantServiceGateTest.php b/tests/Feature/TenantServiceGateTest.php new file mode 100644 index 0000000..7da4d7d --- /dev/null +++ b/tests/Feature/TenantServiceGateTest.php @@ -0,0 +1,115 @@ +create(); + app(TenantContext::class)->set($tenant); + $channel = Channel::factory()->create(); + + $this->assertTrue($channel->importsOccupations()); + $this->get(route('channels.feed', ['token' => $channel->export_token]))->assertOk(); + + $this->lock($tenant, TenantServiceKey::PortalSync); + + $this->assertFalse($channel->fresh()->importsOccupations()); + $this->get(route('channels.feed', ['token' => $channel->export_token]))->assertNotFound(); + } + + public function test_the_sync_command_skips_a_landlord_without_the_service(): void + { + $allowed = Tenant::factory()->create(['name' => 'Mit Dienst']); + $locked = Tenant::factory()->create(['name' => 'Ohne Dienst']); + + app(TenantContext::class)->set($allowed); + $allowedChannel = Channel::factory()->create(); + + app(TenantContext::class)->set($locked); + $lockedChannel = Channel::factory()->create(); + $this->lock($locked, TenantServiceKey::PortalSync); + + app(TenantContext::class)->forget(); + + $this->assertTrue($allowedChannel->fresh()->importsOccupations()); + $this->assertFalse($lockedChannel->fresh()->importsOccupations()); + } + + public function test_a_locked_service_closes_the_admin_screens_whatever_the_role_says(): void + { + $tenant = Tenant::factory()->create(); + app(TenantContext::class)->set($tenant); + + $admin = User::factory()->role(UserRole::Admin)->create(); + $this->actingAs($admin); + + $this->assertTrue(Gate::forUser($admin)->allows('viewAny', ChannelTask::class)); + + $this->lock($tenant, TenantServiceKey::PortalSync); + $this->lock($tenant, TenantServiceKey::PortalMail); + + $this->assertFalse(Gate::forUser($admin)->allows('viewAny', ChannelTask::class)); + $this->assertFalse(Gate::forUser($admin)->allows('viewAny', PortalEmail::class)); + + // The role itself is untouched – the landlord simply does not have the service. + $this->assertTrue(Gate::forUser($admin)->allows('viewAny', Booking::class)); + } + + public function test_the_mailbox_fast_path_stays_open_while_only_the_sync_is_locked(): void + { + $tenant = Tenant::factory()->create(); + app(TenantContext::class)->set($tenant); + + $admin = User::factory()->role(UserRole::Admin)->create(); + + $this->lock($tenant, TenantServiceKey::PortalSync); + + $this->assertTrue(Gate::forUser($admin)->allows('viewAny', PortalEmail::class)); + } + + public function test_the_system_page_shows_the_limits_and_stays_closed_for_a_landlords_administrator(): void + { + $tenant = Tenant::factory()->create(['name' => 'Beispiel GbR']); + app(TenantContext::class)->set($tenant); + config(['fewo.spam.total_per_hour' => 30, 'fewo.guest_retention_years' => 10]); + + $admin = User::factory()->role(UserRole::Admin)->create(); + $this->actingAs($admin)->get('/betreiber/system')->assertForbidden(); + + $admin->forceFill(['is_operator' => true])->saveQuietly(); + + $this->actingAs($admin)->get('/betreiber/system') + ->assertOk() + ->assertSee('Beispiel GbR') + ->assertSee('30 je Stunde') + ->assertSee('10 Jahre'); + } + + private function lock(Tenant $tenant, TenantServiceKey $service): void + { + $tenant->services()->updateOrCreate(['service' => $service->value], ['is_enabled' => false]); + app(TenantFeatures::class)->forget($tenant); + } +} diff --git a/tests/Feature/TenantSettingsTest.php b/tests/Feature/TenantSettingsTest.php index df472e2..d52647e 100644 --- a/tests/Feature/TenantSettingsTest.php +++ b/tests/Feature/TenantSettingsTest.php @@ -10,9 +10,9 @@ use App\Support\Settings; use App\Tenancy\TenantConfig; use App\Tenancy\TenantContext; +use App\Tenancy\TenantFeatures; use Filament\Facades\Filament; use Illuminate\Foundation\Testing\RefreshDatabase; -use Illuminate\Support\Facades\DB; use Livewire\Livewire; use Tests\TestCase; @@ -76,29 +76,27 @@ public function test_without_a_landlord_the_configuration_of_the_installation_ap $this->assertNull(Settings::tenant()); } - public function test_the_operator_switches_services_per_landlord_and_an_empty_key_is_allowed(): void + public function test_only_services_the_application_really_asks_about_are_offered(): void { - $tenant = Tenant::factory()->create(); + $this->assertSame( + [TenantServiceKey::PortalSync, TenantServiceKey::PortalMail], + TenantServiceKey::wired(), + ); - $tenant->services()->create(['service' => TenantServiceKey::PortalSync->value, 'is_enabled' => true, 'api_key' => null]); - $tenant->services()->create(['service' => TenantServiceKey::AiOffers->value, 'is_enabled' => true, 'api_key' => 'sk-beispiel']); - - $sync = $tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole(); - $ai = $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->sole(); - - $this->assertTrue($sync->is_enabled); - $this->assertNull($sync->api_key); - $this->assertSame('sk-beispiel', $ai->api_key); - $this->assertSame(0, Tenant::factory()->create()->services()->count()); + foreach (TenantServiceKey::cases() as $service) { + if (! $service->isWired()) { + $this->assertFalse($service->enabledByDefault(), $service->value.' darf nicht vorgegeben an sein, solange nichts danach fragt.'); + } + } } - public function test_an_own_service_key_is_stored_encrypted(): void + public function test_a_landlord_without_a_decision_keeps_the_portal_services(): void { $tenant = Tenant::factory()->create(); - $service = $tenant->services()->create(['service' => TenantServiceKey::AiMarketing->value, 'is_enabled' => true, 'api_key' => 'sk-geheim']); - $this->assertNotSame('sk-geheim', DB::table('tenant_services')->where('id', $service->id)->value('api_key')); - $this->assertSame('sk-geheim', $service->fresh()->api_key); + $this->assertSame(0, $tenant->services()->count()); + $this->assertTrue(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $tenant)); + $this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::AiOffers, $tenant)); } public function test_the_operator_switches_a_service_on_the_tenant_form(): void @@ -112,17 +110,17 @@ public function test_the_operator_switches_a_service_on_the_tenant_form(): void Livewire::test(EditTenant::class, ['record' => $tenant->getRouteKey()]) ->fillForm([ - 'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => true, - 'services.'.TenantServiceKey::AiOffers->value.'.is_enabled' => true, - 'services.'.TenantServiceKey::AiOffers->value.'.api_key' => 'sk-beispiel', + 'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => false, + 'services.'.TenantServiceKey::PortalMail->value.'.is_enabled' => true, ]) ->call('save') ->assertHasNoErrors(); - $this->assertTrue($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->is_enabled); - $this->assertNull($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->api_key); - $this->assertSame('sk-beispiel', $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->sole()->api_key); - $this->assertFalse($tenant->services()->where('service', TenantServiceKey::AiGuestMail->value)->sole()->is_enabled); + $this->assertFalse($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->is_enabled); + $this->assertTrue($tenant->services()->where('service', TenantServiceKey::PortalMail->value)->sole()->is_enabled); + $this->assertSame(0, $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->count()); + + $this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $tenant)); } /** From 2e3f2ca9384bda695f370eded3986db655b3321c Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Sat, 24 Oct 2026 09:25:22 +0200 Subject: [PATCH 2/2] Mehrere Adressen je Website, damit ein zweiter Mandant niemanden abschaltet MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bisher schrieb das Feld „Domain" genau einen Host nach `site_domains` und löschte den vorherigen. Solange es einen Mandanten gibt, fällt das nicht auf: jede Adresse liefert die Standard-Website. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse 404 – und „www.beispiel.de" ist eine eigene Adresse. stommer.info hätte einen zweiten Mandanten nicht überlebt. Das Formular hat jetzt „Hauptadresse" (steht in Gästelinks) und „Weitere Adressen". Eingaben werden normalisiert, „https://WWW.Beispiel.de/" wird zu „www.beispiel.de". Eine Adresse, die schon zu einer anderen Website gehört, wird abgelehnt. Ohne diese Sperre könnte ein Mandant die Besucher eines anderen auf seine eigene Seite ziehen, indem er dessen Adresse einträgt. 242 Feature-Tests grün. Co-Authored-By: Claude Opus 5 --- .claude/settings.local.json | 7 + .../Sites/Concerns/EditsSiteHosts.php | 136 ++++++++++++++++++ .../Resources/Sites/Pages/CreateSite.php | 6 + .../Resources/Sites/Pages/EditSite.php | 6 + .../Resources/Sites/Schemas/SiteForm.php | 11 +- .../Resources/Sites/Tables/SitesTable.php | 3 +- app/Models/SiteDomain.php | 13 ++ tests/Feature/WebsiteTenancyTest.php | 57 ++++++++ 8 files changed, 236 insertions(+), 3 deletions(-) create mode 100644 .claude/settings.local.json create mode 100644 app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..6708181 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,7 @@ +{ + "permissions": { + "allow": [ + "Bash(git merge *)" + ] + } +} diff --git a/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php b/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php new file mode 100644 index 0000000..ddb9099 --- /dev/null +++ b/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php @@ -0,0 +1,136 @@ + $data + * @return array + */ + protected function mutateFormDataBeforeFill(array $data): array + { + $site = $this->record; + + if (! $site instanceof Site) { + return $data; + } + + $primary = SiteDomain::normalise($site->domain); + + $data['extra_hosts'] = $site->domains() + ->pluck('host') + ->reject(fn (string $host): bool => $host === $primary) + ->values() + ->all(); + + return $data; + } + + /** + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeCreate(array $data): array + { + return $this->withoutHosts($data); + } + + /** + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeSave(array $data): array + { + return $this->withoutHosts($data); + } + + protected function afterCreate(): void + { + $this->saveHosts(); + } + + protected function afterSave(): void + { + $this->saveHosts(); + } + + /** + * @param array $data + * @return array + */ + private function withoutHosts(array $data): array + { + $hosts = is_array($data['extra_hosts'] ?? null) ? $data['extra_hosts'] : []; + + $this->extraHosts = array_values(array_filter(array_map( + fn (mixed $host): string => SiteDomain::normalise(is_string($host) ? $host : null), + $hosts, + ))); + + $this->refuseForeignHosts(); + + unset($data['extra_hosts']); + + return $data; + } + + /** + * A hostname that already answers for another website must not be taken over – otherwise one landlord + * could pull another landlord's visitors onto their own site just by typing that address here. + */ + private function refuseForeignHosts(): void + { + $site = $this->record; + + $taken = SiteDomain::query() + ->whereIn('host', $this->extraHosts) + ->when($site instanceof Site, fn ($query) => $query->where('site_id', '!=', $site->id)) + ->pluck('host'); + + if ($taken->isNotEmpty()) { + throw ValidationException::withMessages([ + 'data.extra_hosts' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '), + ]); + } + } + + private function saveHosts(): void + { + $site = $this->record; + + if (! $site instanceof Site) { + return; + } + + $primary = SiteDomain::normalise($site->domain); + + $wanted = collect($this->extraHosts) + ->filter() + ->when(filled($primary), fn ($hosts) => $hosts->push($primary)) + ->unique() + ->values(); + + $site->domains()->whereNotIn('host', $wanted->all())->delete(); + + foreach ($wanted as $host) { + // Never take a host away from another website: that would hand one landlord's visitors to another. + $owner = SiteDomain::query()->where('host', $host)->value('site_id'); + + if ($owner !== null && $owner !== $site->id) { + continue; + } + + SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]); + } + } +} diff --git a/app/Filament/Resources/Sites/Pages/CreateSite.php b/app/Filament/Resources/Sites/Pages/CreateSite.php index e98951a..4fd9dab 100644 --- a/app/Filament/Resources/Sites/Pages/CreateSite.php +++ b/app/Filament/Resources/Sites/Pages/CreateSite.php @@ -2,10 +2,16 @@ namespace App\Filament\Resources\Sites\Pages; +use App\Filament\Resources\Sites\Concerns\EditsSiteHosts; use App\Filament\Resources\Sites\SiteResource; use Filament\Resources\Pages\CreateRecord; class CreateSite extends CreateRecord { + use EditsSiteHosts; + protected static string $resource = SiteResource::class; + + /** @var list */ + public array $extraHosts = []; } diff --git a/app/Filament/Resources/Sites/Pages/EditSite.php b/app/Filament/Resources/Sites/Pages/EditSite.php index 21ed400..947fe92 100644 --- a/app/Filament/Resources/Sites/Pages/EditSite.php +++ b/app/Filament/Resources/Sites/Pages/EditSite.php @@ -2,14 +2,20 @@ namespace App\Filament\Resources\Sites\Pages; +use App\Filament\Resources\Sites\Concerns\EditsSiteHosts; use App\Filament\Resources\Sites\SiteResource; use Filament\Actions\DeleteAction; use Filament\Resources\Pages\EditRecord; class EditSite extends EditRecord { + use EditsSiteHosts; + protected static string $resource = SiteResource::class; + /** @var list */ + public array $extraHosts = []; + protected function getHeaderActions(): array { return [ diff --git a/app/Filament/Resources/Sites/Schemas/SiteForm.php b/app/Filament/Resources/Sites/Schemas/SiteForm.php index 563fe96..710fb95 100644 --- a/app/Filament/Resources/Sites/Schemas/SiteForm.php +++ b/app/Filament/Resources/Sites/Schemas/SiteForm.php @@ -7,6 +7,7 @@ use App\Themes\ThemeRegistry; use Filament\Actions\Action; use Filament\Forms\Components\Select; +use Filament\Forms\Components\TagsInput; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Schemas\Components\Section; @@ -26,11 +27,17 @@ public static function configure(Schema $schema): Schema ->schema([ TextInput::make('name')->label('Name')->required()->maxLength(120), TextInput::make('domain') - ->label('Domain') + ->label('Hauptadresse') ->placeholder('www.fewo-stommer.de') - ->helperText('Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Domain.') + ->helperText('Steht in Links an Gäste. Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Adresse, alles andere bekommt 404.') ->unique(ignoreRecord: true) ->maxLength(190), + TagsInput::make('extra_hosts') + ->label('Weitere Adressen') + ->placeholder('stommer.info') + ->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Alle hier eingetragenen liefern dieselbe Website. Enter nach jeder Adresse.') + ->nestedRecursiveRules(['string', 'max:190']) + ->columnSpanFull(), Select::make('theme') ->label('Theme') ->options(fn (): array => app(ThemeRegistry::class)->options()) diff --git a/app/Filament/Resources/Sites/Tables/SitesTable.php b/app/Filament/Resources/Sites/Tables/SitesTable.php index 71714f9..da0e572 100644 --- a/app/Filament/Resources/Sites/Tables/SitesTable.php +++ b/app/Filament/Resources/Sites/Tables/SitesTable.php @@ -15,7 +15,8 @@ public static function configure(Table $table): Table return $table ->columns([ TextColumn::make('name')->label('Website')->weight('medium'), - TextColumn::make('domain')->label('Domain')->placeholder('alle übrigen Adressen'), + TextColumn::make('domain')->label('Hauptadresse')->placeholder('alle übrigen Adressen'), + TextColumn::make('domains.host')->label('Antwortet auf')->badge()->placeholder('jede Adresse'), TextColumn::make('theme')->label('Theme')->formatStateUsing(fn (string $state): string => app(ThemeRegistry::class)->get($state)->name), TextColumn::make('properties_count')->label('Wohnungen')->counts('properties'), IconColumn::make('is_default')->label('Standard')->boolean(), diff --git a/app/Models/SiteDomain.php b/app/Models/SiteDomain.php index 7f07e86..2e466b9 100644 --- a/app/Models/SiteDomain.php +++ b/app/Models/SiteDomain.php @@ -12,6 +12,19 @@ #[Fillable(['site_id', 'host'])] class SiteDomain extends Model { + /** + * Turns what someone typed into a bare hostname: "https://WWW.Example.de/" becomes "www.example.de". + * Returns an empty string when nothing usable is left, so callers can skip it. + */ + public static function normalise(?string $value): string + { + $host = mb_strtolower(trim((string) $value)); + $host = (string) preg_replace('~^[a-z]+://~', '', $host); + $host = (string) preg_replace('~[/?#].*$~', '', $host); + + return trim($host, '.'); + } + /** * @return BelongsTo */ diff --git a/tests/Feature/WebsiteTenancyTest.php b/tests/Feature/WebsiteTenancyTest.php index 8389579..1751068 100644 --- a/tests/Feature/WebsiteTenancyTest.php +++ b/tests/Feature/WebsiteTenancyTest.php @@ -3,12 +3,18 @@ namespace Tests\Feature; use App\Actions\SendOffer; +use App\Enums\UserRole; +use App\Filament\Resources\Sites\Pages\EditSite; use App\Models\Booking; use App\Models\Page; use App\Models\Property; use App\Models\Site; use App\Models\Tenant; +use App\Models\User; +use App\Tenancy\TenantContext; use Illuminate\Foundation\Testing\RefreshDatabase; +use Livewire\Features\SupportTesting\Testable; +use Livewire\Livewire; use Tests\TestCase; class WebsiteTenancyTest extends TestCase @@ -40,6 +46,42 @@ public function test_a_second_landlord_is_reached_only_on_their_own_address(): v $this->get('http://unbekannt.test/')->assertNotFound(); } + /** + * The trap that would take a live site down: as long as there is one landlord every address works, so + * nobody notices that no host is entered. The second landlord turns every unentered address into a 404 – + * including "www", which is a host of its own. + */ + public function test_a_website_answers_on_every_address_entered_for_it(): void + { + $site = $this->website('Nordhaus', 'nordhaus.test'); + $this->website('Südheim', 'suedheim.test'); + + $this->get('http://www.nordhaus.test/')->assertNotFound(); + + $this->editHosts($site, ['www.nordhaus.test', 'https://ALT.nordhaus.test/'])->assertHasNoFormErrors(); + + $this->get('http://nordhaus.test/')->assertOk()->assertSee('Nordhaus'); + $this->get('http://www.nordhaus.test/')->assertOk()->assertSee('Nordhaus'); + $this->get('http://alt.nordhaus.test/')->assertOk()->assertSee('Nordhaus'); + $this->get('http://unbekannt.test/')->assertNotFound(); + + $this->assertSame( + ['alt.nordhaus.test', 'nordhaus.test', 'www.nordhaus.test'], + $site->domains()->orderBy('host')->pluck('host')->all(), + ); + } + + public function test_a_host_of_another_website_cannot_be_taken_over(): void + { + $nord = $this->website('Nordhaus', 'nordhaus.test'); + $sued = $this->website('Südheim', 'suedheim.test'); + + $this->editHosts($nord, ['suedheim.test'])->assertHasFormErrors(); + + $this->get('http://suedheim.test/')->assertOk()->assertSee('Südheim')->assertDontSee('Nordhaus'); + $this->assertSame([$sued->id], $sued->domains()->pluck('site_id')->all()); + } + public function test_the_offer_link_uses_the_website_address(): void { $site = $this->website('Nordhaus', 'nordhaus.test'); @@ -55,6 +97,21 @@ public function test_the_offer_link_uses_the_website_address(): void $this->assertStringContainsString('signature=', $url); } + /** + * Enters the further addresses through the real admin form, so the form's own defences are under test. + * + * @param list $hosts + */ + private function editHosts(Site $site, array $hosts): Testable + { + app(TenantContext::class)->set($site->tenant); + $this->actingAs(User::factory()->role(UserRole::Admin)->create()); + + return Livewire::test(EditSite::class, ['record' => $site->getRouteKey()]) + ->fillForm(['extra_hosts' => $hosts]) + ->call('save'); + } + private function website(string $name, ?string $domain = null): Site { $tenant = Tenant::factory()->create();