TenantAtlas/app/Support/Middleware/EnsureFilamentTenantSelected.php
ahmido 57f3e3934c 085-tenant-operate-hub (#104)
Summary
Implements Spec 085 “Tenant Operate Hub” semantics so central Monitoring pages are context-aware when entered from a tenant, without changing canonical URLs or implicitly mutating tenant selection. Also fixes a UX leak where tenant-scoped Inventory/Policies/Backups surfaces could appear in Admin navigation / be reachable without a selected tenant.

Why

Reduce “where am I / lost tenant context” confusion when operators jump between tenant work and central Monitoring.
Preserve deny-as-not-found security semantics and avoid tenant identity leaks.
Keep tenant-scoped data surfaces strictly tenant-scoped (not workspace-scoped).
What changed

Context-aware Monitoring:
/admin/operations shows scope label + CTAs (“Back to <tenant>”, “Show all tenants”) when tenant context is active and entitled.
/admin/operations/{run} shows deterministic back affordances + optional escape hatch (“Show all operations”) when tenant context is active and entitled.
Canonical Monitoring GET routes do not mutate tenant context.
Stale tenant context (not entitled) falls back to workspace scope without leaking tenant identity.
Tenant navigation IA:
Tenant panel sidebar provides “Monitoring” shortcuts (Runs/Alerts/Audit Log) into the central Monitoring surfaces.
Tenant-scoped Admin surfaces guard:
Inventory/Policies/Policy Versions/Backup Sets no longer show up tenantless; direct access redirects to /admin/choose-tenant when no tenant is selected.
Tests

Added/updated Pest coverage for:
Spec 085 header affordances + stale-context behavior
deny-as-not-found regressions for non-members/non-entitled users
“DB-only render” (no outbound calls) for Monitoring pages
tenant-scoped admin surfaces redirect when no tenant selected
Compatibility / Constraints

Filament v5 + Livewire v4 compliant (no v3 APIs).
Panel providers remain registered via providers.php (Laravel 11+/12).
No new assets; no changes to filament:assets deployment requirements.
No global search changes.
Manual verification

From a tenant, click “Monitoring → Runs” and confirm:
Scope label shows tenant scope
“Show all tenants” clears tenant context and returns to workspace scope
Open a run detail and confirm “Back to <tenant>” behavior + “Show all operations”.

Co-authored-by: Ahmed Darrazi <ahmeddarrazi@ebc83aaa-d947-4a08-b88e-bd72ac9645f7.fritz.box>
Co-authored-by: Ahmed Darrazi <ahmeddarrazi@MacBookPro.fritz.box>
Co-authored-by: Ahmed Darrazi <ahmeddarrazi@adsmac.fritz.box>
Reviewed-on: #104
2026-02-11 21:01:23 +00:00

229 lines
7.4 KiB
PHP

<?php
namespace App\Support\Middleware;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceMembership;
use App\Services\Auth\WorkspaceRoleCapabilityMap;
use App\Support\Auth\Capabilities;
use App\Support\Workspaces\WorkspaceContext;
use Closure;
use Filament\Facades\Filament;
use Filament\Models\Contracts\HasTenants;
use Filament\Navigation\NavigationBuilder;
use Filament\Navigation\NavigationItem;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureFilamentTenantSelected
{
/**
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
$panel = Filament::getCurrentOrDefaultPanel();
$path = '/'.ltrim($request->path(), '/');
$workspaceContext = app(WorkspaceContext::class);
$workspaceId = $workspaceContext->currentWorkspaceId($request);
$existingTenant = Filament::getTenant();
if ($existingTenant instanceof Tenant && $workspaceId !== null && (int) $existingTenant->workspace_id !== (int) $workspaceId) {
Filament::setTenant(null, true);
$existingTenant = null;
}
$user = $request->user();
if ($existingTenant instanceof Tenant && $user instanceof User && ! $user->canAccessTenant($existingTenant)) {
Filament::setTenant(null, true);
}
if ($path === '/livewire/update') {
$refererPath = parse_url((string) $request->headers->get('referer', ''), PHP_URL_PATH) ?? '';
$refererPath = '/'.ltrim((string) $refererPath, '/');
if (preg_match('#^/admin/operations/[^/]+$#', $refererPath) === 1) {
$this->configureNavigationForRequest($panel);
return $next($request);
}
}
if (preg_match('#^/admin/operations/[^/]+$#', $path) === 1) {
$this->configureNavigationForRequest($panel);
return $next($request);
}
if ($path === '/admin/operations') {
$this->configureNavigationForRequest($panel);
return $next($request);
}
$tenantParameter = null;
if ($request->route()?->hasParameter('tenant')) {
$tenantParameter = $request->route()->parameter('tenant');
} elseif (filled($request->query('tenant'))) {
$tenantParameter = $request->query('tenant');
}
if (
$tenantParameter === null
&& ! filled(Filament::getTenant())
&& $this->adminPathRequiresTenantSelection($path)
) {
return redirect()->route('filament.admin.pages.choose-tenant');
}
if ($tenantParameter !== null) {
$user = $request->user();
if ($user === null) {
return $next($request);
}
if (! $user instanceof HasTenants) {
abort(404);
}
$tenant = $tenantParameter instanceof Tenant
? $tenantParameter
: Tenant::query()->withTrashed()->where('external_id', (string) $tenantParameter)->first();
if (! $tenant instanceof Tenant) {
abort(404);
}
if ($workspaceId === null) {
abort(404);
}
if ((int) $tenant->workspace_id !== (int) $workspaceId) {
abort(404);
}
$workspace = Workspace::query()->whereKey($workspaceId)->first();
if (! $workspace instanceof Workspace) {
abort(404);
}
if (! $user instanceof User || ! $workspaceContext->isMember($user, $workspace)) {
abort(404);
}
if (! $user->canAccessTenant($tenant)) {
abort(404);
}
Filament::setTenant($tenant, true);
app(WorkspaceContext::class)->rememberLastTenantId((int) $workspaceId, (int) $tenant->getKey(), $request);
$this->configureNavigationForRequest($panel);
return $next($request);
}
if (
str_starts_with($path, '/admin/w/')
|| str_starts_with($path, '/admin/workspaces')
|| str_starts_with($path, '/admin/operations')
|| in_array($path, ['/admin/choose-workspace', '/admin/choose-tenant', '/admin/no-access', '/admin/alerts', '/admin/audit-log', '/admin/onboarding'], true)
) {
$this->configureNavigationForRequest($panel);
return $next($request);
}
if (filled(Filament::getTenant())) {
$this->configureNavigationForRequest($panel);
return $next($request);
}
if (! $user instanceof User) {
$this->configureNavigationForRequest($panel);
return $next($request);
}
$this->configureNavigationForRequest($panel);
return $next($request);
}
private function configureNavigationForRequest(\Filament\Panel $panel): void
{
if (! $panel->hasTenancy()) {
return;
}
if (filled(Filament::getTenant())) {
$panel->navigation(true);
return;
}
$panel->navigation(function (): NavigationBuilder {
return app(NavigationBuilder::class)
->item(
NavigationItem::make('Manage workspaces')
->url(fn (): string => route('filament.admin.resources.workspaces.index'))
->icon('heroicon-o-squares-2x2')
->group('Settings')
->sort(10)
->visible(function (): bool {
$user = auth()->user();
if (! $user instanceof User) {
return false;
}
$roles = WorkspaceRoleCapabilityMap::rolesWithCapability(Capabilities::WORKSPACE_MEMBERSHIP_MANAGE);
return WorkspaceMembership::query()
->where('user_id', (int) $user->getKey())
->whereIn('role', $roles)
->exists();
}),
)
->item(
NavigationItem::make('Operations')
->url(fn (): string => route('admin.operations.index'))
->icon('heroicon-o-queue-list')
->group('Monitoring')
->sort(10),
)
->item(
NavigationItem::make('Alerts')
->url(fn (): string => '/admin/alerts')
->icon('heroicon-o-bell-alert')
->group('Monitoring')
->sort(20),
)
->item(
NavigationItem::make('Audit Log')
->url(fn (): string => '/admin/audit-log')
->icon('heroicon-o-clipboard-document-list')
->group('Monitoring')
->sort(30),
);
});
}
private function adminPathRequiresTenantSelection(string $path): bool
{
if (! str_starts_with($path, '/admin/')) {
return false;
}
return preg_match('#^/admin/(inventory|policies|policy-versions|backup-sets)(/|$)#', $path) === 1;
}
}