From 1d0ca27bc8f81d20ca902f10e094f90263a2152b Mon Sep 17 00:00:00 2001 From: Abrar Ahmad Date: Thu, 3 Aug 2023 03:23:26 +0500 Subject: [PATCH] Central routes without `Route::domain()`, configurable tenant/central routes by default for domain/subdomain identification, allow accessing central routes in early identification for path & request data middleware (#3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Update url binding bootstrapper test * Fix parent::temporarySignedRoute() call * Add universal route tests for all identification types * Improve determineContextFromRequest() * Add setting `TenancyUrlGenerator::$prefixRouteNames` to true in TSP stub * Delete seemingly redundant test (making one route universal won't make all routes universal in any case) * Use collection syntax in ReregisterUniversalRoutes * Improve comments * Add domain identification MW annotation * Update condition in GloballyUsable * Set `tenancy.bootstrappers` instead of adding the bootstrappers using `tenancy.bootstrappers.x`, move test * Revert GloballyUsable condition change * Delete assigning bootstrappers to tenancy.bootstrappers.x * Exclude cache prefixing bootstrapper from the initial configuration * Fix test * Unset bypass parameter * Set static kernel identification-related properties in TestCase * Update bootstrapper name in annotation * Move unset() into a condition * Update TenancyUrlGenerator condition * Set static properties without instantiating Tenancy * Fix unsetting bypass parameter * formatting changes * add a comment * improve docblock * add docblock to TenancyUrlGenerator [ci skip] * docblock changes [ci skip] * Update TenancyUrlGenerator (rename variable, allow bypassing prefixing temporarySignedRoute name) * Improve determineContextFromRequest * Only return the new url generator instance when extending 'url' in UrlBindingBootstrapper * Check route's MW groups for the path ID MW * Remove extra imports from config * Rename MiddlewareContext to Context, add condition for skipping ID MW * Set only the needed bootstrappers in TestCase * Fix code style (php-cs-fixer) * Remove condition * Use correct return type * Fix PHPStan issue * Update comment * Check for tenant parameter instead of prefix * Update shouldBeSkipped condition for universal routes * Don't remove the 'universal' MW group after route re-registration, update test * Fix code style (php-cs-fixer) * Fix typo * Add test for mixing placement of access prevention and identification MW * Add test for mixing placement of access prevention and identification MW * Update docblock * Add setting the session and key resolvers in UrlBindingBootstrapper (required with LW file uploads) * Update stub * Update variable name in route reregistering action * Add trailing comma * Fix code style (php-cs-fixer) * Require routes using path identification to be flagged as tenant in order to be recognized as tenant routes * Add tenant flag while re-registering routes * Update determineContextFromRequest condition (wip) * Fix code style (php-cs-fixer) * Update the middleware context logic so that universal routes have to be flagged as tenant instead of just having ID MW * Update path identification condition * Fix re-registering the LW localized route (add 'tenant' MW) * Update docblock * Simplify LW route re-registration * Add comment * Update comment * Simplify determineContextFromRequest, add comment * Improve stub * Add skipRoute method + test * Fix typo * Update assets/TenancyServiceProvider.stub.php * Update src/Concerns/DealsWithEarlyIdentification.php * Fix typo Co-authored-by: Samuel Štancl * Improve comment * Update test structure * Restructure Fortify test * code style * Fix typo * Update ReregisterUniversalRoutes annotation * Only prefix route name if it wasn't already prefixed * Add todo@docs * Delete `Tenancy::$kernelAccessPreventionSkipped` and related logic * Delete test tenant cleanup * Test MW group unpacking, restructure and improve test * Test that tenancy isn't initialized after visiting a central route with the tenant parameter * Delete "in both central and tenant contexts" from test names * Test that re-registering works with controllers too * Set misc route properties during re-registering * Determine context instead of guessing, update universal route tests * Use randomly generated tenant ID instead of hardcoding `acme` * Remove setting route validators * Rename and update determine context method, add comments * Update ForgetTenantParameter annotation * Add comment * Delete comment, delete variable assignment * Update early domain identification test * Improve domain identification tests (test defaulting accurately) * Improve readability * Simplify domain early ID test * Use randomly generated tenant instead of 'acme' * Simplify request data ID test, use random tenant instead of 'acme' * Simplify defaulting domain identification test * Use RouteFacade alias for the Route facade, improve test code * Add defaulting to the request data and path ID tests * Merge path identification tenant parameter removal tests, clean up * Correct wording Co-authored-by: Samuel Štancl * Delete debugging things from UniversalRouteTest * Update annotation * Add `// Creates a matrix` * Improve comment wording * Add MiddlewareUsableWithUniversalRoutes, refactor code accordingly * Fix code style (php-cs-fixer) * Delete debugging leftovers * Delete unused import * Update universal route GloballyUsable condition * Don't implement the universal route interface in access prevention MW * Check if request host is in the central domains in domain ID MW * Test universal routes with domain identification without access prevent MW * Test that universal routes work only with identification MW implementing the universal route interface * Fix code style (php-cs-fixer) * Rename GloballyUsable to UsableWithEarlyIdentification * Fix annotation * Update requestHasTenant annotations * Update comment * Add `with()` comments * Add with() comments where missing * Rename interface, update/add comments * Rename exception, update its default message * Fix code style (php-cs-fixer) * Fix interface name * Delete redundant code from subdomain ID MW * Change domainOrSubdomain ID MW so that instead of passing the identification to other MWs, it happens in the domainOrSubdomain MW * Test domainOrSubdomain identification with universal routes * Fix code style (php-cs-fixer) * Rename universal routes interface * Fix code style (php-cs-fixer) * Try explaining forgetting the tenant parameter better * update interface name reference * uncouple example from query parameters * Update ForgetTenantParameter.php * Update ForgetTenantParameter annotation * Check both routeHasMiddleware and routeHasIdentificationMiddleware in the route MW detection test * Hardcode tenant subdomain * Delete redundant event listening code * Delete unused imports * Delete misuse of `tenancy()->getMiddlewareContext()` from conditions * Delete unused variable * Update comment * Correct request data identification test (defaulting) * Fix defaulting in path id test * Move default route context configuration in domian id test * Rename and update the tenant parameter test * Delete extra tenant parameter test * Use `tenant-domain.test` instead of `127.0.0.2` * Add `default_to_universal_routes` config key * Deal with defaulting to universal routes in the reregistering action * Update logic to make defaulting to universal routes possible * Test defaulting to universal routes * Fix code style (php-cs-fixer) * Delete extra tests * Delete "without access prevention" from datasets * Add defaulting to universal routes to datasets * Override universal flag by central/tenant flag * Add universal flag overriding test * Update "a route can be universal in both route modes" so that the name corresponds with the tested thing * Ignore the PHPStan error * Reset `InitializeTenancyByPath::$onFail` in PathIdentificationTest * Simplify expression * Use 'Tenancy (not) initialized.' in instead of `tenant()?->getTenantKey()` for better assertions * Properly test removing tenant parameter * Reset static properties in tests * Correct comments in EarlyIdentificationTest * Add comment * Add detail to annotation * Throw exception if payload isn't string or null in request data ID MW * Fix code style (php-cs-fixer) * Delete static `$kernelIdentificationSkipped` property, use `$request->attributes` instead * Use 'default_route_mode' instead of 'default_to_tenant/universal_routes' * Fix code style (php-cs-fixer) * Make path identification MW, tenantParameterName and tenantRouteNamePrefix configurable in ReregisterUniversalRoutes * Delete unused import * Add `$passTenantParameterToRoute` to TenancyUrlGenerator * Use `$passTenantParameterToRoute` in BootstrapperTest * Bypass tenant parameter passing * Improve TenancyUrlGenerator so that both ID methods work * Fix code style (php-cs-fixer) * Improve TenancyUrlGenerator readability * Add modifyBehavior() to TenancyUrlGenerator * Fix code style (php-cs-fixer) * Improve comment * Toggle route name prefixing in path/request data ID MW (route-level identification) * Fix code style (php-cs-fixer) * Add path identification MW config key, add `getTenantParameterName()` to ForgetTenantParameter * Fix code style (php-cs-fixer) * Fix modifyBehavior and routeBehaviorModificationBypassed * Add type to `$parameters` parameter * Split modifyBehavior into two methods, don't pass name and parameters by reference * Update UrlBindingBootstrapper annotation * Correct naming in tests (request data -> query string identification) * Add info to annotation * Pass arrays to the behavior modification methods instead of `mixed` * Fix default value of static property in Fortify bootstrapper * Fix code style (php-cs-fixer) * Correct annotation * Enable prefixing routes directly using path identification MW * Test re-registration of routes with path ID MW * Prefix names of routes directly using path ID MW * Fix code style (php-cs-fixer) * Add Livewire v3 integration example to TSP stub * Prefix route name only if it's not prefixed already * Rename ReregisterUniversalRoutes to ReregisterRoutesAsTenant * Fix code style (php-cs-fixer) * Improve ReregisterRoutesAsTenant * Add/update TenancyUrlGenerator docblocks * Update action name in comments/test names * Update reregister action annotation * Delete unused imports * Improve comments * Make method protected * Improve TenancyUrlGenerator code * Test bypass parameter removal * Fix comment * Update annotation * Improve shouldReregisterRoute * Fix typo, delete redundant comment * Improve skipRoute * Improve shouldBeSkipped * Add and test `$passTenantParameterToRoutes` * add a comment * Fix typo in comment * Pass array as $parameters in prepareRouteInputs * Make path_identification_middleware an array * Fix code style (php-cs-fixer) * Fix ReregisterRouteAsTenant * Move tenantParameterName and tenantRouteNamePrefix getting to PathIdentificationManager * Make PathIdentificationManager properties `Closure|null` * Fix code style (php-cs-fixer) * Fix PathIdentificationManager * Update comments * Use foreach for dataset definition * Extract repetitive inGlobalStack and routeHasMiddleware calls * Refactor PathIdentificationManager * Update TenancyUrlGenerator annotation * Add $skippedRoutes, refactor ReregisterRoutesAsTenant * Improve reregisterRoute * Update re-register action annotation * update test name * Make PathIdentificationManager methods static again, update comments * Add test comment * Update ForgetTenantParameter annotation * Improve route re-registration condition, add comment * Change "re-register" to "clone" * minor code improvements --------- Co-authored-by: lukinovec Co-authored-by: Samuel Štancl Co-authored-by: PHP CS Fixer --- assets/TenancyServiceProvider.stub.php | 59 +- assets/config.php | 31 +- src/Actions/CloneRoutesAsTenant.php | 171 ++++++ src/Actions/CreateStorageSymlinksAction.php | 8 +- src/Actions/RemoveStorageSymlinksAction.php | 10 +- .../FortifyRouteTenancyBootstrapper.php | 57 ++ src/Bootstrappers/UrlBindingBootstrapper.php | 69 +++ src/Commands/Link.php | 4 +- src/Concerns/DealsWithEarlyIdentification.php | 144 +++++ src/Concerns/DealsWithTenantSymlinks.php | 4 +- .../UsableWithEarlyIdentification.php | 118 ++++ src/Concerns/UsableWithUniversalRoutes.php | 26 + src/Context.php | 11 + ...eNotUsableWithUniversalRoutesException.php | 15 + src/Jobs/CreateStorageSymlinks.php | 2 +- src/Jobs/RemoveStorageSymlinks.php | 2 +- src/Listeners/ForgetTenantParameter.php | 36 ++ src/Middleware/InitializeTenancyByDomain.php | 20 +- .../InitializeTenancyByDomainOrSubdomain.php | 43 +- src/Middleware/InitializeTenancyByPath.php | 59 +- .../InitializeTenancyByRequestData.php | 37 +- .../InitializeTenancyBySubdomain.php | 8 + .../PreventAccessFromUnwantedDomains.php | 55 +- src/PathIdentificationManager.php | 59 ++ src/Resolvers/PathTenantResolver.php | 6 + src/RouteMode.php | 12 + src/Tenancy.php | 3 +- src/TenancyServiceProvider.php | 10 + src/TenancyUrlGenerator.php | 118 ++++ tests/ActionTest.php | 6 +- tests/BootstrapperTest.php | 139 ++++- tests/BroadcastingTest.php | 2 + tests/DatabaseUsersTest.php | 14 + tests/EarlyIdentificationTest.php | 407 +++++++++++-- tests/Etc/EarlyIdentification/Controller.php | 19 - .../ControllerWithMiddleware.php | 37 ++ .../ControllerWithRouteMiddleware.php | 44 ++ .../EarlyIdentification/Models/Comment.php | 17 + tests/Etc/EarlyIdentification/Models/Post.php | 17 + tests/Etc/EarlyIdentification/Service.php | 2 +- ...019_08_08_000001_create_comments_table.php | 29 + .../2019_08_08_000001_create_posts_table.php | 28 + tests/EventListenerTest.php | 7 + tests/MailTest.php | 1 + tests/PathIdentificationTest.php | 42 +- .../PreventAccessFromUnwantedDomainsTest.php | 235 ++++++++ tests/RequestDataIdentificationTest.php | 24 +- tests/ResourceSyncingTest.php | 2 + tests/ResourceSyncingUsingPolymorphicTest.php | 2 +- tests/RouteMiddlewareTest.php | 87 +++ tests/TenantDatabaseManagerTest.php | 6 + tests/TestCase.php | 22 +- tests/UniversalRouteTest.php | 553 +++++++++++++++--- 53 files changed, 2668 insertions(+), 271 deletions(-) create mode 100644 src/Actions/CloneRoutesAsTenant.php create mode 100644 src/Bootstrappers/Integrations/FortifyRouteTenancyBootstrapper.php create mode 100644 src/Bootstrappers/UrlBindingBootstrapper.php create mode 100644 src/Concerns/DealsWithEarlyIdentification.php create mode 100644 src/Concerns/UsableWithEarlyIdentification.php create mode 100644 src/Concerns/UsableWithUniversalRoutes.php create mode 100644 src/Context.php create mode 100644 src/Exceptions/MiddlewareNotUsableWithUniversalRoutesException.php create mode 100644 src/Listeners/ForgetTenantParameter.php create mode 100644 src/PathIdentificationManager.php create mode 100644 src/RouteMode.php create mode 100644 src/TenancyUrlGenerator.php delete mode 100644 tests/Etc/EarlyIdentification/Controller.php create mode 100644 tests/Etc/EarlyIdentification/ControllerWithMiddleware.php create mode 100644 tests/Etc/EarlyIdentification/ControllerWithRouteMiddleware.php create mode 100644 tests/Etc/EarlyIdentification/Models/Comment.php create mode 100644 tests/Etc/EarlyIdentification/Models/Post.php create mode 100644 tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_comments_table.php create mode 100644 tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_posts_table.php create mode 100644 tests/PreventAccessFromUnwantedDomainsTest.php create mode 100644 tests/RouteMiddlewareTest.php diff --git a/assets/TenancyServiceProvider.stub.php b/assets/TenancyServiceProvider.stub.php index 6c916d71..5b4afbf6 100644 --- a/assets/TenancyServiceProvider.stub.php +++ b/assets/TenancyServiceProvider.stub.php @@ -10,8 +10,12 @@ use Stancl\Tenancy\Listeners; use Stancl\Tenancy\Middleware; use Stancl\JobPipeline\JobPipeline; use Illuminate\Support\Facades\Event; -use Illuminate\Support\Facades\Route; use Illuminate\Support\ServiceProvider; +use Stancl\Tenancy\TenancyUrlGenerator; +use Illuminate\Support\Facades\Route as RouteFacade; +use Stancl\Tenancy\Actions\CloneRoutesAsTenant; +use Stancl\Tenancy\Middleware\InitializeTenancyByPath; +use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData; class TenancyServiceProvider extends ServiceProvider { @@ -145,6 +149,54 @@ class TenancyServiceProvider extends ServiceProvider $this->makeTenancyMiddlewareHighestPriority(); $this->overrideUrlInTenantContext(); + + /** + * To make Livewire v3 work with Tenancy, make the update route universal. + * + * Livewire::setUpdateRoute(function ($handle) { + * return Route::post('/livewire/update', $handle)->middleware(['web', 'universal']); + * }); + * + * If using domain identification, also make the script route universal. + * + * app(FrontendAssets::class)->setScriptRoute(function ($handle) { + * return Route::get('/livewire/livewire.js', $handle)->middleware(['universal']); + * }); + */ + + if (InitializeTenancyByRequestData::inGlobalStack()) { + TenancyUrlGenerator::$prefixRouteNames = false; + } + + if (InitializeTenancyByPath::inGlobalStack()) { + TenancyUrlGenerator::$prefixRouteNames = true; + + /** @var CloneRoutesAsTenant $reregisterRoutes */ + $reregisterRoutes = app(CloneRoutesAsTenant::class); + + /** + * You can provide a closure for re-registering a specific route, e.g.: + * $reregisterRoutes->reregisterUsing('welcome', function () { + * Route::get('/tenant-welcome', fn () => 'Current tenant: ' . tenant()->getTenantKey()) + * ->middleware(['universal', InitializeTenancyByPath::class]) + * ->name('tenant.welcome'); + * }); + * + * To make Livewire v2 (2.12.2+) work with kernel path identification, + * use this closure to override the livewire.message-localized route: + * + * $reregisterRoutes->reregisterUsing('livewire.message-localized', function (Route $route) { + * $route->setUri(str($route->uri())->replaceFirst('locale', $tenantParameter = PathTenantResolver::tenantParameterName())); + * $route->parameterNames[0] = $tenantParameter; + * $route->middleware('tenant'); + * }); + * + * To see the default behavior of re-registering the universal routes, check out the reregisterRoute() method in ReregisterRoutesAsTenant. + * @see CloneRoutesAsTenant + */ + + $reregisterRoutes->handle(); + } } protected function bootEvents() @@ -163,14 +215,15 @@ class TenancyServiceProvider extends ServiceProvider protected function mapRoutes() { if (file_exists(base_path('routes/tenant.php'))) { - Route::namespace(static::$controllerNamespace) + RouteFacade::namespace(static::$controllerNamespace) + ->middleware('tenant') ->group(base_path('routes/tenant.php')); } } protected function makeTenancyMiddlewareHighestPriority() { - // PreventAccessFromCentralDomains has even higher priority than the identification middleware + // PreventAccessFromUnwantedDomains has even higher priority than the identification middleware $tenancyMiddleware = array_merge([Middleware\PreventAccessFromUnwantedDomains::class], config('tenancy.identification.middleware')); foreach (array_reverse($tenancyMiddleware) as $middleware) { diff --git a/assets/config.php b/assets/config.php index 3875aca1..05220836 100644 --- a/assets/config.php +++ b/assets/config.php @@ -2,9 +2,9 @@ declare(strict_types=1); -use Stancl\Tenancy\CacheManager; use Stancl\Tenancy\Middleware; use Stancl\Tenancy\Resolvers; +use Stancl\Tenancy\RouteMode; return [ /** @@ -62,6 +62,28 @@ return [ Middleware\InitializeTenancyByRequestData::class, ], + /** + * Identification middleware tenancy recognizes as domain identification middleware. + * + * This is used for determining whether to skip the access prevention middleware. + * PreventAccessFromUnwantedDomains is intended to be used only with the middleware included here. + * It will get skipped if it's used with other identification middleware. + * + * If you're using a custom domain identification middleware, add it here. + * + * @see \Stancl\Tenancy\Concerns\UsableWithEarlyIdentification + * @see \Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains + */ + 'domain_identification_middleware' => [ + Middleware\InitializeTenancyByDomain::class, + Middleware\InitializeTenancyBySubdomain::class, + Middleware\InitializeTenancyByDomainOrSubdomain::class, + ], + + 'path_identification_middleware' => [ + Middleware\InitializeTenancyByPath::class, + ], + /** * Tenant resolvers used by the package. * @@ -300,6 +322,13 @@ return [ */ 'routes' => true, + /** + * Make all routes central, tenant, or universal by default. + * + * To override the default route mode, apply the middleware of another route mode ('central', 'tenant', 'universal') to the route. + */ + 'default_route_mode' => RouteMode::CENTRAL, + /** * Parameters used by the tenants:migrate command. */ diff --git a/src/Actions/CloneRoutesAsTenant.php b/src/Actions/CloneRoutesAsTenant.php new file mode 100644 index 00000000..f296e8ee --- /dev/null +++ b/src/Actions/CloneRoutesAsTenant.php @@ -0,0 +1,171 @@ + $routesToClone Only clone non-skipped routes without the tenant parameter. */ + $routesToClone = collect($this->router->getRoutes()->get())->filter(function (Route $route) use ($tenantParameterName) { + return ! (in_array($tenantParameterName, $route->parameterNames()) || in_array($route->getName(), $this->skippedRoutes)); + }); + + if ($this->config->get('tenancy.default_route_mode') !== RouteMode::UNIVERSAL) { + // Only clone routes with route-level path identification and universal routes + $routesToClone = $routesToClone->where(function (Route $route) { + $routeIsUniversal = tenancy()->routeHasMiddleware($route, 'universal'); + + return PathIdentificationManager::pathIdentificationOnRoute($route) || $routeIsUniversal; + }); + } + + $this->router->prefix($routePrefix)->group(fn () => $routesToClone->each(fn (Route $route) => $this->cloneRoute($route))); + } + + /** + * Make the action clone a specific route using the provided callback instead of the default one. + */ + public function cloneUsing(string $routeName, Closure $callback): static + { + $this->cloneRouteUsing[$routeName] = $callback; + + return $this; + } + + /** + * Skip a route's cloning. + */ + public function skipRoute(string $routeName): static + { + $this->skippedRoutes[] = $routeName; + + return $this; + } + + /** + * Clone a route using a callback specified in the $cloneRouteUsing property (using the cloneUsing method). + * If there's no callback specified for the route, use the default way of cloning routes. + */ + protected function cloneRoute(Route $route): void + { + $routeName = $route->getName(); + + // If the route's cloning callback exists + // Use the callback to clone the route instead of the default way of cloning routes + if ($routeName && $customRouteCallback = data_get($this->cloneRouteUsing, $routeName)) { + $customRouteCallback($route); + + return; + } + + $routesAreUniversalByDefault = $this->config->get('tenancy.default_route_mode') === RouteMode::UNIVERSAL; + $routeHasIdentificationMiddleware = tenancy()->routeHasIdentificationMiddleware($route); + $routeHasPathIdentification = PathIdentificationManager::pathIdentificationOnRoute($route); + $pathIdentificationMiddlewareInGlobalStack = PathIdentificationManager::pathIdentificationInGlobalStack(); + + // Determine if the passed route should get cloned + // The route should be cloned if it has path identification middleware + // Or if the route doesn't have identification middleware and path identification middleware + // Is not used globally or the routes are universal by default + $shouldCloneRoute = $routeHasPathIdentification || + (! $routeHasIdentificationMiddleware && ($routesAreUniversalByDefault || $pathIdentificationMiddlewareInGlobalStack)); + + if ($shouldCloneRoute) { + $newRoute = $this->createNewRoute($route); + $routeIsUniversal = tenancy()->routeHasMiddleware($newRoute, 'universal'); + + // Add the 'tenant' flag to the new route if the route is universal + // Or if it isn't universal and it doesn't have the identification middlware (= it isn't "flagged" as tenant by having the MW) + if ((! $routeHasPathIdentification && ! $routeIsUniversal) || $routeIsUniversal || $routesAreUniversalByDefault) { + $newRoute->middleware('tenant'); + } + + $this->copyMiscRouteProperties($route, $newRoute); + } + } + + protected function createNewRoute(Route $route): Route + { + $method = strtolower($route->methods()[0]); + $routeName = $route->getName(); + $tenantRouteNamePrefix = PathIdentificationManager::getTenantRouteNamePrefix(); + + /** @var Route $newRoute */ + $newRoute = $this->router->$method($route->uri(), $route->action); + + // Delete middleware from the new route and + // Add original route middleware to ensure there's no duplicate middleware + unset($newRoute->action['middleware']); + + $newRoute->middleware(tenancy()->getRouteMiddleware($route)); + + if ($routeName && ! $route->named($tenantRouteNamePrefix . '*')) { + // Clear the route name so that `name()` sets the route name instead of suffixing it + unset($newRoute->action['as']); + + $newRoute->name($tenantRouteNamePrefix . $routeName); + } + + return $newRoute; + } + + /** + * Copy misc properties of the original route to the new route. + */ + protected function copyMiscRouteProperties(Route $originalRoute, Route $newRoute): void + { + $newRoute + ->setBindingFields($originalRoute->bindingFields()) + ->setFallback($originalRoute->isFallback) + ->setWheres($originalRoute->wheres) + ->block($originalRoute->locksFor(), $originalRoute->waitsFor()) + ->withTrashed($originalRoute->allowsTrashedBindings()) + ->setDefaults($originalRoute->defaults); + } +} diff --git a/src/Actions/CreateStorageSymlinksAction.php b/src/Actions/CreateStorageSymlinksAction.php index eac5d933..41327a63 100644 --- a/src/Actions/CreateStorageSymlinksAction.php +++ b/src/Actions/CreateStorageSymlinksAction.php @@ -16,19 +16,19 @@ class CreateStorageSymlinksAction { use DealsWithTenantSymlinks; - public static function handle(Tenant|Collection|LazyCollection $tenants, bool $relativeLink = false, bool $force = false): void + public function __invoke(Tenant|Collection|LazyCollection $tenants, bool $relativeLink = false, bool $force = false): void { $tenants = $tenants instanceof Tenant ? collect([$tenants]) : $tenants; /** @var Tenant $tenant */ foreach ($tenants as $tenant) { - foreach (static::possibleTenantSymlinks($tenant) as $publicPath => $storagePath) { - static::createLink($publicPath, $storagePath, $tenant, $relativeLink, $force); + foreach ($this->possibleTenantSymlinks($tenant) as $publicPath => $storagePath) { + $this->createLink($publicPath, $storagePath, $tenant, $relativeLink, $force); } } } - protected static function createLink(string $publicPath, string $storagePath, Tenant $tenant, bool $relativeLink, bool $force): void + protected function createLink(string $publicPath, string $storagePath, Tenant $tenant, bool $relativeLink, bool $force): void { event(new CreatingStorageSymlink($tenant)); diff --git a/src/Actions/RemoveStorageSymlinksAction.php b/src/Actions/RemoveStorageSymlinksAction.php index a3660e7a..1108b892 100644 --- a/src/Actions/RemoveStorageSymlinksAction.php +++ b/src/Actions/RemoveStorageSymlinksAction.php @@ -15,21 +15,21 @@ class RemoveStorageSymlinksAction { use DealsWithTenantSymlinks; - public static function handle(Tenant|Collection|LazyCollection $tenants): void + public function __invoke(Tenant|Collection|LazyCollection $tenants): void { $tenants = $tenants instanceof Tenant ? collect([$tenants]) : $tenants; /** @var Tenant $tenant */ foreach ($tenants as $tenant) { - foreach (static::possibleTenantSymlinks($tenant) as $publicPath => $storagePath) { - static::removeLink($publicPath, $tenant); + foreach ($this->possibleTenantSymlinks($tenant) as $publicPath => $storagePath) { + $this->removeLink($publicPath, $tenant); } } } - protected static function removeLink(string $publicPath, Tenant $tenant): void + protected function removeLink(string $publicPath, Tenant $tenant): void { - if (static::symlinkExists($publicPath)) { + if ($this->symlinkExists($publicPath)) { event(new RemovingStorageSymlink($tenant)); app()->make('files')->delete($publicPath); diff --git a/src/Bootstrappers/Integrations/FortifyRouteTenancyBootstrapper.php b/src/Bootstrappers/Integrations/FortifyRouteTenancyBootstrapper.php new file mode 100644 index 00000000..cf3a082e --- /dev/null +++ b/src/Bootstrappers/Integrations/FortifyRouteTenancyBootstrapper.php @@ -0,0 +1,57 @@ + 'tenant_route_name' + public static array $fortifyRedirectTenantMap = [ + // 'logout' => 'welcome', + ]; + + // Fortify home route name + public static string|null $fortifyHome = 'dashboard'; + protected array|null $originalFortifyConfig = null; + + public function __construct( + protected Repository $config, + ) { + } + + public function bootstrap(Tenant $tenant): void + { + $this->originalFortifyConfig = $this->config->get('fortify'); + + $this->useTenantRoutesInFortify(); + } + + public function revert(): void + { + $this->config->set('fortify', $this->originalFortifyConfig); + } + + protected function useTenantRoutesInFortify(): void + { + // Regenerate the URLs after the behavior of the route() helper has been modified + // in UrlBindingBootstrapper to generate URLs specific to the current tenant + $tenantRoutes = array_map(fn (string $routeName) => route($routeName), static::$fortifyRedirectTenantMap); + + if (static::$fortifyHome) { + $this->config->set('fortify.home', route(static::$fortifyHome)); + } + + $this->config->set('fortify.redirects', array_merge($this->config->get('fortify.redirects') ?? [], $tenantRoutes)); + } +} diff --git a/src/Bootstrappers/UrlBindingBootstrapper.php b/src/Bootstrappers/UrlBindingBootstrapper.php new file mode 100644 index 00000000..a795ed4f --- /dev/null +++ b/src/Bootstrappers/UrlBindingBootstrapper.php @@ -0,0 +1,69 @@ +useTenancyUrlGenerator(); + } + + public function revert(): void + { + $this->app->bind('url', fn () => $this->originalUrlGenerator); + } + + /** + * Make 'url' resolve to an instance of TenancyUrlGenerator. + * + * @see \Illuminate\Routing\RoutingServiceProvider registerUrlGenerator() + */ + protected function useTenancyUrlGenerator(): void + { + $this->app->extend('url', function (UrlGenerator $urlGenerator, Application $app) { + $newGenerator = new TenancyUrlGenerator( + $app['router']->getRoutes(), + $urlGenerator->getRequest(), + $app['config']->get('app.asset_url'), + ); + + $newGenerator->setSessionResolver(function () { + return $this->app['session'] ?? null; + }); + + $newGenerator->setKeyResolver(function () { + return $this->app->make('config')->get('app.key'); + }); + + return $newGenerator; + }); + } +} diff --git a/src/Commands/Link.php b/src/Commands/Link.php index d49cc7f2..7d712290 100644 --- a/src/Commands/Link.php +++ b/src/Commands/Link.php @@ -44,14 +44,14 @@ class Link extends Command protected function removeLinks(LazyCollection $tenants): void { - RemoveStorageSymlinksAction::handle($tenants); + (new RemoveStorageSymlinksAction)($tenants); $this->components->info('The links have been removed.'); } protected function createLinks(LazyCollection $tenants): void { - CreateStorageSymlinksAction::handle( + (new CreateStorageSymlinksAction)( $tenants, (bool) ($this->option('relative') ?? false), (bool) ($this->option('force') ?? false), diff --git a/src/Concerns/DealsWithEarlyIdentification.php b/src/Concerns/DealsWithEarlyIdentification.php new file mode 100644 index 00000000..fc6973c8 --- /dev/null +++ b/src/Concerns/DealsWithEarlyIdentification.php @@ -0,0 +1,144 @@ +middleware()`). + * The surface-level middleware could contain middleware groups, + * and to accurately get all the specific middleware, we need to unpack them. + * The unpacked middleware groups could also have middleware groups inside them, + * so we further unpack these, three times. + * + * For example, a route has a 'surface' middleware group. + * The 'surface' group has a 'first-level' group, and that group has a 'second-level' group (three middleware group layers). + * The 'second-level' group has a specific middleware (e.g. SomeMiddleware). + * Using the getRouteMiddleware method on that route will get you all the middleware the route has, including SomeMiddleware. + * + * Note that the unpacking doesn't go further than three layers – if 'second-level' had 'third-level' that would have ThirdLevelMiddleware, + * the middleware returned by this method won't include ThirdLevelMiddleware because the 'third-level' group won't get unpacked. + */ + public static function getRouteMiddleware(Route $route): array + { + $routeMiddleware = $route->middleware(); + $middlewareGroups = RouteFacade::getMiddlewareGroups(); + $unpackGroupMiddleware = function (array $middleware) use ($middlewareGroups) { + $innerMiddleware = []; + + foreach ($middleware as $inner) { + if (! $inner instanceof Closure && isset($middlewareGroups[$inner])) { + $innerMiddleware = Arr::wrap($middlewareGroups[$inner]); + } + } + + return $innerMiddleware; + }; + + return array_unique(array_merge( + $routeMiddleware, + $firstLevelUnpackedGroupMiddleware = $unpackGroupMiddleware($routeMiddleware), + $thirdLevelUnpackedGroupMiddleware = $unpackGroupMiddleware($firstLevelUnpackedGroupMiddleware), + $unpackGroupMiddleware($thirdLevelUnpackedGroupMiddleware) + )); + } + + /** + * Check if the passed route has the passed middleware + * three layers deep – explained in the annotation of getRouteMiddleware(). + */ + public static function routeHasMiddleware(Route $route, string $middleware): bool + { + return in_array($middleware, static::getRouteMiddleware($route)); + } + + /** + * Check if a route has identification middleware. + */ + public static function routeHasIdentificationMiddleware(Route $route): bool + { + foreach (static::getRouteMiddleware($route) as $middleware) { + if (in_array($middleware, static::middleware())) { + return true; + } + } + + return false; + } + + /** + * Check if a route uses domain identification. + */ + public static function routeHasDomainIdentificationMiddleware(Route $route): bool + { + $routeMiddleware = static::getRouteMiddleware($route); + + foreach (config('tenancy.identification.domain_identification_middleware') as $middleware) { + if (in_array($middleware, $routeMiddleware)) { + return true; + } + } + + return false; + } + + /** + * Obtain route from the passed request. + * If the route isn't directly available on the request, + * find the route that matches the passed request. + */ + public function getRoute(Request $request): Route + { + /** @var ?Route $route */ + $route = $request->route(); + + if (! $route) { + /** @var Router $router */ + $router = app(Router::class); + $route = $router->getRoutes()->match($request); + } + + return $route; + } +} diff --git a/src/Concerns/DealsWithTenantSymlinks.php b/src/Concerns/DealsWithTenantSymlinks.php index 5f3baf5b..c59928bc 100644 --- a/src/Concerns/DealsWithTenantSymlinks.php +++ b/src/Concerns/DealsWithTenantSymlinks.php @@ -18,7 +18,7 @@ trait DealsWithTenantSymlinks * * @return Collection */ - protected static function possibleTenantSymlinks(Tenant $tenant): Collection + protected function possibleTenantSymlinks(Tenant $tenant): Collection { $diskUrls = config('tenancy.filesystem.url_override'); $disks = config('tenancy.filesystem.root_override'); @@ -41,7 +41,7 @@ trait DealsWithTenantSymlinks } /** Determine if the provided path is an existing symlink. */ - protected static function symlinkExists(string $link): bool + protected function symlinkExists(string $link): bool { return file_exists($link) && is_link($link); } diff --git a/src/Concerns/UsableWithEarlyIdentification.php b/src/Concerns/UsableWithEarlyIdentification.php new file mode 100644 index 00000000..f018b794 --- /dev/null +++ b/src/Concerns/UsableWithEarlyIdentification.php @@ -0,0 +1,118 @@ +getRouteMiddleware($route); + $universalFlagUsed = in_array('universal', $routeMiddleware); + $defaultToUniversalRoutes = config('tenancy.default_route_mode') === RouteMode::UNIVERSAL; + + // Route is universal only if it doesn't have the central/tenant flag + $routeIsUniversal = ($universalFlagUsed || $defaultToUniversalRoutes) && + ! (in_array('central', $routeMiddleware) || in_array('tenant', $routeMiddleware)); + + if ($routeIsUniversal && $this instanceof IdentificationMiddleware) { + /** @phpstan-ignore-next-line */ + throw_unless($this instanceof UsableWithUniversalRoutes, MiddlewareNotUsableWithUniversalRoutesException::class); + + return $this->determineUniversalRouteContextFromRequest(request()) === Context::CENTRAL; + } + + // If the middleware is not in the global stack (= it's used directly on the route) + // And the route isn't universal, don't skip it + if (! static::inGlobalStack()) { + return false; + } + + // Now that we're sure the MW isn't used in the global MW stack, we determine whether to skip it + if ($this instanceof PreventAccessFromUnwantedDomains) { + // Skip access prevention if the route directly uses a non-domain identification middleware + return tenancy()->routeHasIdentificationMiddleware($route) && ! tenancy()->routeHasDomainIdentificationMiddleware($route); + } + + return $this->shouldIdentificationMiddlewareBeSkipped($route); + } + + protected function determineUniversalRouteContextFromRequest(Request $request): Context + { + $route = tenancy()->getRoute($request); + + // Check if this is the identification middleware the route should be using + // Route-level identification middleware is prioritized + $middlewareUsed = tenancy()->routeHasMiddleware($route, static::class) || ! tenancy()->routeHasIdentificationMiddleware($route) && static::inGlobalStack(); + + /** @var UsableWithUniversalRoutes $this */ + return $middlewareUsed && $this->requestHasTenant($request) ? Context::TENANT : Context::CENTRAL; + } + + protected function shouldIdentificationMiddlewareBeSkipped(Route $route): bool + { + if (! static::inGlobalStack()) { + return false; + } + + $request = app(Request::class); + + if (! $request->attributes->get('_tenancy_kernel_identification_skipped')) { + if ( + // Skip identification if the current route is central + // The route is central if defaulting is set to central and the route isn't flagged as tenant or it doesn't have identification middleware + tenancy()->getMiddlewareContext($route) === RouteMode::CENTRAL + // Don't skip identification if the central route is considered universal + && (config('tenancy.default_route_mode') !== RouteMode::UNIVERSAL || ! tenancy()->routeHasMiddleware($route, 'universal')) + ) { + return true; + } + + // Skip kernel identification if the route uses route-level identification + if (tenancy()->routeHasIdentificationMiddleware($route)) { + // Remember that it was attempted to identify a tenant using kernel identification + // By making the $kernelIdentificationSkipped property of the current Tenancy instance true + // So that the next identification middleware gets executed (= route-level identification MW doesn't get skipped) + $request->attributes->set('_tenancy_kernel_identification_skipped', true); + + // Skip kernel identification so that route-level identification middleware can get used + return true; + } + } + + return false; + } + + public static function inGlobalStack(): bool + { + return app(Kernel::class)->hasMiddleware(static::class); + } +} diff --git a/src/Concerns/UsableWithUniversalRoutes.php b/src/Concerns/UsableWithUniversalRoutes.php new file mode 100644 index 00000000..fca6ca1b --- /dev/null +++ b/src/Concerns/UsableWithUniversalRoutes.php @@ -0,0 +1,26 @@ +tenant); + (new CreateStorageSymlinksAction)($this->tenant); } } diff --git a/src/Jobs/RemoveStorageSymlinks.php b/src/Jobs/RemoveStorageSymlinks.php index 3022da79..8579175f 100644 --- a/src/Jobs/RemoveStorageSymlinks.php +++ b/src/Jobs/RemoveStorageSymlinks.php @@ -35,6 +35,6 @@ class RemoveStorageSymlinks implements ShouldQueue */ public function handle() { - RemoveStorageSymlinksAction::handle($this->tenant); + (new RemoveStorageSymlinksAction)($this->tenant); } } diff --git a/src/Listeners/ForgetTenantParameter.php b/src/Listeners/ForgetTenantParameter.php new file mode 100644 index 00000000..ce5d324e --- /dev/null +++ b/src/Listeners/ForgetTenantParameter.php @@ -0,0 +1,36 @@ +routeHasIdentificationMiddleware($event->route) && + tenancy()->getMiddlewareContext($event->route) === RouteMode::TENANT + ) { + $event->route->forgetParameter(PathIdentificationManager::getTenantParameterName()); + } + } +} diff --git a/src/Middleware/InitializeTenancyByDomain.php b/src/Middleware/InitializeTenancyByDomain.php index be9b2f66..a2175195 100644 --- a/src/Middleware/InitializeTenancyByDomain.php +++ b/src/Middleware/InitializeTenancyByDomain.php @@ -6,11 +6,15 @@ namespace Stancl\Tenancy\Middleware; use Closure; use Illuminate\Http\Request; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; +use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes; use Stancl\Tenancy\Resolvers\DomainTenantResolver; use Stancl\Tenancy\Tenancy; -class InitializeTenancyByDomain extends IdentificationMiddleware +class InitializeTenancyByDomain extends IdentificationMiddleware implements UsableWithUniversalRoutes { + use UsableWithEarlyIdentification; + public static ?Closure $onFail = null; public function __construct( @@ -22,6 +26,11 @@ class InitializeTenancyByDomain extends IdentificationMiddleware /** @return \Illuminate\Http\Response|mixed */ public function handle(Request $request, Closure $next): mixed { + if ($this->shouldBeSkipped(tenancy()->getRoute($request))) { + // Allow accessing central route in kernel identification + return $next($request); + } + if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) { // Always bypass tenancy initialization when host is in central domains return $next($request); @@ -33,4 +42,13 @@ class InitializeTenancyByDomain extends IdentificationMiddleware $request->getHost() ); } + + /** + * Domain identification request has a tenant if it's + * not hitting a domain specifically defined as central in the config. + */ + public function requestHasTenant(Request $request): bool + { + return ! in_array($request->host(), config('tenancy.central_domains')); + } } diff --git a/src/Middleware/InitializeTenancyByDomainOrSubdomain.php b/src/Middleware/InitializeTenancyByDomainOrSubdomain.php index 1a30001a..cb4461f8 100644 --- a/src/Middleware/InitializeTenancyByDomainOrSubdomain.php +++ b/src/Middleware/InitializeTenancyByDomainOrSubdomain.php @@ -5,19 +5,52 @@ declare(strict_types=1); namespace Stancl\Tenancy\Middleware; use Closure; +use Exception; use Illuminate\Http\Request; +use Illuminate\Http\Response; use Illuminate\Support\Str; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; -class InitializeTenancyByDomainOrSubdomain +class InitializeTenancyByDomainOrSubdomain extends InitializeTenancyBySubdomain { + use UsableWithEarlyIdentification; + /** @return \Illuminate\Http\Response|mixed */ public function handle(Request $request, Closure $next): mixed { - if ($this->isSubdomain($request->getHost())) { - return app(InitializeTenancyBySubdomain::class)->handle($request, $next); - } else { - return app(InitializeTenancyByDomain::class)->handle($request, $next); + if ($this->shouldBeSkipped(tenancy()->getRoute($request))) { + return $next($request); } + + if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) { + // Always bypass tenancy initialization when host is in central domains + return $next($request); + } + + $domain = $request->getHost(); + + if ($this->isSubdomain($domain)) { + $domain = $this->makeSubdomain($domain); + + if (is_object($domain) && $domain instanceof Exception) { + $onFail = static::$onFail ?? function ($e) { + throw $e; + }; + + return $onFail($domain, $request, $next); + } + + // If a Response instance was returned, we return it immediately. + if (is_object($domain) && $domain instanceof Response) { + return $domain; + } + } + + return $this->initializeTenancy( + $request, + $next, + $domain + ); } protected function isSubdomain(string $hostname): bool diff --git a/src/Middleware/InitializeTenancyByPath.php b/src/Middleware/InitializeTenancyByPath.php index fc27cae0..3de3e25a 100644 --- a/src/Middleware/InitializeTenancyByPath.php +++ b/src/Middleware/InitializeTenancyByPath.php @@ -6,17 +6,25 @@ namespace Stancl\Tenancy\Middleware; use Closure; use Illuminate\Http\Request; -use Illuminate\Routing\Route; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\URL; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; +use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes; use Stancl\Tenancy\Contracts\Tenant; use Stancl\Tenancy\Events\InitializingTenancy; use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException; use Stancl\Tenancy\Resolvers\PathTenantResolver; +use Stancl\Tenancy\RouteMode; use Stancl\Tenancy\Tenancy; +use Stancl\Tenancy\TenancyUrlGenerator; -class InitializeTenancyByPath extends IdentificationMiddleware +/** + * @see Stancl\Tenancy\Listeners\ForgetTenantParameter + */ +class InitializeTenancyByPath extends IdentificationMiddleware implements UsableWithUniversalRoutes { + use UsableWithEarlyIdentification; + public static ?Closure $onFail = null; public function __construct( @@ -28,12 +36,19 @@ class InitializeTenancyByPath extends IdentificationMiddleware /** @return \Illuminate\Http\Response|mixed */ public function handle(Request $request, Closure $next): mixed { - $route = $this->route($request); + $route = tenancy()->getRoute($request); - // Only initialize tenancy if tenant is the first parameter + if ($this->shouldBeSkipped($route)) { + return $next($request); + } + + // Used with *route-level* identification, takes precedence over what may have been configured for global stack middleware + TenancyUrlGenerator::$prefixRouteNames = true; + + // Only initialize tenancy if the route has the tenant parameter. // We don't want to initialize tenancy if the tenant is // simply injected into some route controller action. - if ($route->parameterNames()[0] === PathTenantResolver::tenantParameterName()) { + if (in_array(PathTenantResolver::tenantParameterName(), $route->parameterNames())) { $this->setDefaultTenantForRouteParametersWhenInitializingTenancy(); return $this->initializeTenancy( @@ -46,25 +61,6 @@ class InitializeTenancyByPath extends IdentificationMiddleware } } - protected function route(Request $request): Route - { - /** @var ?Route $route */ - $route = $request->route(); - - if (! $route) { - // Create a fake $route instance that has enough information for this middleware's needs - $route = new Route($request->method(), $request->getUri(), []); - /** - * getPathInfo() returns the path except the root domain. - * We fetch the first parameter because tenant parameter is *always* first. - */ - $route->parameters[PathTenantResolver::tenantParameterName()] = explode('/', ltrim($request->getPathInfo(), '/'))[0]; - $route->parameterNames[] = PathTenantResolver::tenantParameterName(); - } - - return $route; - } - protected function setDefaultTenantForRouteParametersWhenInitializingTenancy(): void { Event::listen(InitializingTenancy::class, function (InitializingTenancy $event) { @@ -76,4 +72,19 @@ class InitializeTenancyByPath extends IdentificationMiddleware ]); }); } + + /** + * Path identification request has a tenant if the middleware context is tenant. + * + * With path identification, we can just check the MW context because we're re-registering the universal routes, + * and the routes are flagged with the 'tenant' MW group (= their MW context is tenant). + * + * With other identification middleware, we have to determine the context differently because we only have one + * truly universal route available ('truly universal' because with path identification, applying 'universal' to a route just means that + * it should get re-registered, whereas with other ID MW, it means that the route you apply the 'universal' flag to will be accessible in both contexts). + */ + public function requestHasTenant(Request $request): bool + { + return tenancy()->getMiddlewareContext(tenancy()->getRoute($request)) === RouteMode::TENANT; + } } diff --git a/src/Middleware/InitializeTenancyByRequestData.php b/src/Middleware/InitializeTenancyByRequestData.php index 925907f0..4645e426 100644 --- a/src/Middleware/InitializeTenancyByRequestData.php +++ b/src/Middleware/InitializeTenancyByRequestData.php @@ -6,11 +6,17 @@ namespace Stancl\Tenancy\Middleware; use Closure; use Illuminate\Http\Request; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; +use Stancl\Tenancy\Concerns\UsableWithUniversalRoutes; +use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException; use Stancl\Tenancy\Resolvers\RequestDataTenantResolver; use Stancl\Tenancy\Tenancy; +use Stancl\Tenancy\TenancyUrlGenerator; -class InitializeTenancyByRequestData extends IdentificationMiddleware +class InitializeTenancyByRequestData extends IdentificationMiddleware implements UsableWithUniversalRoutes { + use UsableWithEarlyIdentification; + public static string $header = 'X-Tenant'; public static string $cookie = 'X-Tenant'; public static string $queryParameter = 'tenant'; @@ -25,6 +31,14 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware /** @return \Illuminate\Http\Response|mixed */ public function handle(Request $request, Closure $next): mixed { + if ($this->shouldBeSkipped(tenancy()->getRoute($request))) { + // Allow accessing central route in kernel identification + return $next($request); + } + + // Used with *route-level* identification, takes precedence over what may have been configured for global stack middleware + TenancyUrlGenerator::$prefixRouteNames = false; + if ($request->method() !== 'OPTIONS') { return $this->initializeTenancy($request, $next, $this->getPayload($request)); } @@ -32,19 +46,30 @@ class InitializeTenancyByRequestData extends IdentificationMiddleware return $next($request); } - protected function getPayload(Request $request): ?string + protected function getPayload(Request $request): string|null { - $payload = null; - if (static::$header && $request->hasHeader(static::$header)) { $payload = $request->header(static::$header); } elseif (static::$queryParameter && $request->has(static::$queryParameter)) { $payload = $request->get(static::$queryParameter); } elseif (static::$cookie && $request->hasCookie(static::$cookie)) { $payload = $request->cookie(static::$cookie); + } else { + $payload = null; } - /** @var ?string $payload */ - return $payload; + if (is_string($payload) || is_null($payload)) { + return $payload; + } + + throw new TenantCouldNotBeIdentifiedByRequestDataException($payload); + } + + /** + * Check if the request has the tenant payload. + */ + public function requestHasTenant(Request $request): bool + { + return (bool) $this->getPayload($request); } } diff --git a/src/Middleware/InitializeTenancyBySubdomain.php b/src/Middleware/InitializeTenancyBySubdomain.php index 3cf3e0d3..142d7025 100644 --- a/src/Middleware/InitializeTenancyBySubdomain.php +++ b/src/Middleware/InitializeTenancyBySubdomain.php @@ -9,10 +9,13 @@ use Exception; use Illuminate\Http\Request; use Illuminate\Http\Response; use Illuminate\Support\Str; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; use Stancl\Tenancy\Exceptions\NotASubdomainException; class InitializeTenancyBySubdomain extends InitializeTenancyByDomain { + use UsableWithEarlyIdentification; + /** * The index of the subdomain fragment in the hostname * split by `.`. 0 for first fragment, 1 if you prefix @@ -27,6 +30,11 @@ class InitializeTenancyBySubdomain extends InitializeTenancyByDomain /** @return Response|mixed */ public function handle(Request $request, Closure $next): mixed { + if ($this->shouldBeSkipped(tenancy()->getRoute($request))) { + // Allow accessing central route in kernel identification + return $next($request); + } + if (in_array($request->getHost(), config('tenancy.central_domains', []), true)) { // Always bypass tenancy initialization when host is in central domains return $next($request); diff --git a/src/Middleware/PreventAccessFromUnwantedDomains.php b/src/Middleware/PreventAccessFromUnwantedDomains.php index 977d2021..1c609cfb 100644 --- a/src/Middleware/PreventAccessFromUnwantedDomains.php +++ b/src/Middleware/PreventAccessFromUnwantedDomains.php @@ -7,11 +7,23 @@ namespace Stancl\Tenancy\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Routing\Route; -use Illuminate\Support\Facades\Route as Router; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; +use Stancl\Tenancy\Context; +use Stancl\Tenancy\RouteMode; -// todo come up with a better name +/** + * todo come up with a better name. + * + * Prevents accessing central domains in the tenant context/tenant domains in the central context. + * The access isn't prevented if the request is trying to access a route flagged as 'universal', + * or if this middleware should be skipped. + * + * @see UsableWithEarlyIdentification – more info about the skipping part + */ class PreventAccessFromUnwantedDomains { + use UsableWithEarlyIdentification; + /** * Set this property if you want to customize the on-fail behavior. */ @@ -20,14 +32,14 @@ class PreventAccessFromUnwantedDomains /** @return \Illuminate\Http\Response|mixed */ public function handle(Request $request, Closure $next): mixed { - /** @var Route $route */ - $route = $request->route(); + $route = tenancy()->getRoute($request); + $routeIsUniversal = tenancy()->routeHasMiddleware($route, 'universal') || config('tenancy.default_route_mode') === RouteMode::UNIVERSAL; - if ($this->routeHasMiddleware($route, 'universal')) { + if ($this->shouldBeSkipped($route) || $routeIsUniversal) { return $next($request); } - if (in_array($request->getHost(), config('tenancy.central_domains'), true)) { + if ($this->accessingTenantRouteFromCentralDomain($request, $route) || $this->accessingCentralRouteFromTenantDomain($request, $route)) { $abortRequest = static::$abortRequest ?? function () { abort(404); }; @@ -38,24 +50,23 @@ class PreventAccessFromUnwantedDomains return $next($request); } - protected function routeHasMiddleware(Route $route, string $middleware): bool + protected function accessingTenantRouteFromCentralDomain(Request $request, Route $route): bool { - /** @var array $routeMiddleware */ - $routeMiddleware = $route->middleware(); + return tenancy()->getMiddlewareContext($route) === RouteMode::TENANT // Current route's middleware context is tenant + && $this->isCentralDomain($request); // The request comes from a domain that IS present in the configured `tenancy.central_domains` + } - if (in_array($middleware, $routeMiddleware, true)) { - return true; - } + protected function accessingCentralRouteFromTenantDomain(Request $request, Route $route): bool + { + return tenancy()->getMiddlewareContext($route) === RouteMode::CENTRAL // Current route's middleware context is central + && ! $this->isCentralDomain($request); // The request comes from a domain that ISN'T present in the configured `tenancy.central_domains` + } - // Loop one level deep and check if the route's middleware - // groups have the searched middleware group inside them - $middlewareGroups = Router::getMiddlewareGroups(); - foreach ($route->gatherMiddleware() as $inner) { - if (! $inner instanceof Closure && isset($middlewareGroups[$inner]) && in_array($middleware, $middlewareGroups[$inner], true)) { - return true; - } - } - - return false; + /** + * Check if the request's host name is present in the configured `tenancy.central_domains`. + */ + protected function isCentralDomain(Request $request): bool + { + return in_array($request->getHost(), config('tenancy.central_domains'), true); } } diff --git a/src/PathIdentificationManager.php b/src/PathIdentificationManager.php new file mode 100644 index 00000000..48914964 --- /dev/null +++ b/src/PathIdentificationManager.php @@ -0,0 +1,59 @@ + tenancy()->routeHasMiddleware($route, $middleware)); + } + + public static function pathIdentificationInGlobalStack(): bool + { + return static::checkPathIdentificationMiddleware(fn ($middleware) => $middleware::inGlobalStack()); + } + + protected static function checkPathIdentificationMiddleware(Closure $closure): bool + { + foreach (static::getPathIdentificationMiddleware() as $middleware) { + if ($closure($middleware)) { + return true; + } + } + + return false; + } + + protected static function getPathIdentificationMiddleware(): array + { + return config('tenancy.identification.path_identification_middleware'); + } +} diff --git a/src/Resolvers/PathTenantResolver.php b/src/Resolvers/PathTenantResolver.php index 090ea365..e7b4ebcb 100644 --- a/src/Resolvers/PathTenantResolver.php +++ b/src/Resolvers/PathTenantResolver.php @@ -19,6 +19,7 @@ class PathTenantResolver extends Contracts\CachedTenantResolver $id = $route->parameter(static::tenantParameterName()); if ($id) { + // Forget the tenant parameter so that we don't have to accept it in route action methods $route->forgetParameter(static::tenantParameterName()); if ($tenant = tenancy()->find($id)) { @@ -40,4 +41,9 @@ class PathTenantResolver extends Contracts\CachedTenantResolver { return config('tenancy.identification.resolvers.' . static::class . '.tenant_parameter_name') ?? 'tenant'; } + + public static function tenantRouteNamePrefix(): string + { + return config('tenancy.identification.resolvers.' . static::class . '.tenant_route_name_prefix') ?? static::tenantParameterName() . '.'; + } } diff --git a/src/RouteMode.php b/src/RouteMode.php new file mode 100644 index 00000000..51210fe4 --- /dev/null +++ b/src/RouteMode.php @@ -0,0 +1,12 @@ + true]` by default) + */ +class TenancyUrlGenerator extends UrlGenerator +{ + /** + * Parameter which bypasses the behavior modification of route() and temporarySignedRoute(). + * + * E.g. route('tenant') => app.test/{tenant}/tenant (or app.test/tenant?tenant=tenantKey if the route doesn't accept the tenant parameter) + * route('tenant', [$bypassParameter => true]) => app.test/tenant. + */ + public static string $bypassParameter = 'central'; + + /** + * Determine if the route names of routes generated using + * `route()` or `temporarySignedRoute()` should get prefixed with the tenant route name prefix. + * + * Set this to true when using path identification. + */ + public static bool $prefixRouteNames = false; + + /** + * Determine if the tenant parameter should get passed + * to the links generated by `route()` or `temporarySignedRoute()`. + */ + public static bool $passTenantParameterToRoutes = true; + + /** + * Override the route() method so that the route name gets prefixed + * and the tenant parameter gets added when in tenant context. + */ + public function route($name, $parameters = [], $absolute = true) + { + [$name, $parameters] = $this->prepareRouteInputs($name, Arr::wrap($parameters)); + + return parent::route($name, $parameters, $absolute); + } + + /** + * Override the temporarySignedRoute() method so that the route name gets prefixed + * and the tenant parameter gets added when in tenant context. + */ + public function temporarySignedRoute($name, $expiration, $parameters = [], $absolute = true) + { + [$name, $parameters] = $this->prepareRouteInputs($name, Arr::wrap($parameters)); + + return parent::temporarySignedRoute($name, $expiration, $parameters, $absolute); + } + + /** + * Return bool indicating if the bypass parameter was in $parameters. + */ + protected function routeBehaviorModificationBypassed(mixed $parameters): bool + { + if (isset($parameters[static::$bypassParameter])) { + return (bool) $parameters[static::$bypassParameter]; + } + + return false; + } + + /** + * Takes a route name and an array of parameters to return the prefixed route name + * and the route parameters with the tenant parameter added. + * + * To skip these modifications, pass the bypass parameter in route parameters. + * Before returning the modified route inputs, the bypass parameter is removed from the parameters. + */ + protected function prepareRouteInputs(string $name, array $parameters): array + { + if (! $this->routeBehaviorModificationBypassed($parameters)) { + $name = $this->prefixRouteName($name); + $parameters = $this->addTenantParameter($parameters); + } + + // Remove bypass parameter from the route parameters + unset($parameters[static::$bypassParameter]); + + return [$name, $parameters]; + } + + /** + * If $prefixRouteNames is true, prefix the passed route name. + */ + protected function prefixRouteName(string $name): string + { + $tenantPrefix = PathIdentificationManager::getTenantRouteNamePrefix(); + + if (static::$prefixRouteNames && ! str($name)->startsWith($tenantPrefix)) { + $name = str($name)->after($tenantPrefix)->prepend($tenantPrefix)->toString(); + } + + return $name; + } + + /** + * If `tenant()` isn't null, add tenant paramter to the passed parameters. + */ + protected function addTenantParameter(array $parameters): array + { + return tenant() && static::$passTenantParameterToRoutes ? array_merge($parameters, [PathIdentificationManager::getTenantParameterName() => tenant()->getTenantKey()]) : $parameters; + } +} diff --git a/tests/ActionTest.php b/tests/ActionTest.php index cc0950ea..c9de07d8 100644 --- a/tests/ActionTest.php +++ b/tests/ActionTest.php @@ -37,7 +37,7 @@ test('create storage symlinks action works', function() { $this->assertDirectoryDoesNotExist($publicPath = public_path("public-$tenantKey")); - CreateStorageSymlinksAction::handle($tenant); + (new CreateStorageSymlinksAction)($tenant); $this->assertDirectoryExists($publicPath); $this->assertEquals(storage_path("app/public/"), readlink($publicPath)); @@ -59,11 +59,11 @@ test('remove storage symlinks action works', function() { tenancy()->initialize($tenant); - CreateStorageSymlinksAction::handle($tenant); + (new CreateStorageSymlinksAction)($tenant); $this->assertDirectoryExists($publicPath = public_path("public-$tenantKey")); - RemoveStorageSymlinksAction::handle($tenant); + (new RemoveStorageSymlinksAction)($tenant); $this->assertDirectoryDoesNotExist($publicPath); }); diff --git a/tests/BootstrapperTest.php b/tests/BootstrapperTest.php index 9260c9c9..fc09d3f8 100644 --- a/tests/BootstrapperTest.php +++ b/tests/BootstrapperTest.php @@ -15,6 +15,7 @@ use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Storage; use Stancl\Tenancy\Events\TenancyEnded; use Stancl\Tenancy\Jobs\CreateDatabase; +use Stancl\Tenancy\TenancyUrlGenerator; use Stancl\Tenancy\Events\TenantCreated; use Stancl\Tenancy\Events\TenantDeleted; use Stancl\Tenancy\Events\DeletingTenant; @@ -22,6 +23,7 @@ use Stancl\Tenancy\TenancyBroadcastManager; use Illuminate\Filesystem\FilesystemAdapter; use Illuminate\Broadcasting\BroadcastManager; use Stancl\Tenancy\Events\TenancyInitialized; +use Illuminate\Contracts\Routing\UrlGenerator; use Stancl\Tenancy\Jobs\CreateStorageSymlinks; use Stancl\Tenancy\Jobs\RemoveStorageSymlinks; use Stancl\Tenancy\Listeners\BootstrapTenancy; @@ -31,12 +33,16 @@ use Stancl\Tenancy\Listeners\RevertToCentralContext; use Stancl\Tenancy\Bootstrappers\CacheTagsBootstrapper; use Stancl\Tenancy\Bootstrappers\UrlTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\MailTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\UrlBindingBootstrapper; use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper; use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain; use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\BroadcastTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\PrefixCacheTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\Integrations\FortifyRouteTenancyBootstrapper; +use Stancl\Tenancy\Middleware\InitializeTenancyByPath; +use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData; beforeEach(function () { $this->mockConsoleOutput = false; @@ -65,12 +71,11 @@ afterEach(function () { PrefixCacheTenancyBootstrapper::$tenantCacheStores = []; TenancyBroadcastManager::$tenantBroadcasters = ['pusher', 'ably']; BroadcastTenancyBootstrapper::$credentialsMap = []; + TenancyUrlGenerator::$prefixRouteNames = false; }); test('database data is separated', function () { - config(['tenancy.bootstrappers' => [ - DatabaseTenancyBootstrapper::class, - ]]); + config(['tenancy.bootstrappers' => [DatabaseTenancyBootstrapper::class]]); $tenant1 = Tenant::create(); $tenant2 = Tenant::create(); @@ -352,6 +357,8 @@ test('local storage public urls are generated correctly', function() { }); test('BroadcastTenancyBootstrapper binds TenancyBroadcastManager to BroadcastManager and reverts the binding when tenancy is ended', function() { + config(['tenancy.bootstrappers' => [BroadcastTenancyBootstrapper::class]]); + expect(app(BroadcastManager::class))->toBeInstanceOf(BroadcastManager::class); tenancy()->initialize(Tenant::create()); @@ -367,6 +374,7 @@ test('BroadcastTenancyBootstrapper maps tenant broadcaster credentials to config config([ 'broadcasting.connections.testing.driver' => 'testing', 'broadcasting.connections.testing.message' => $defaultMessage = 'default', + 'tenancy.bootstrappers' => [BroadcastTenancyBootstrapper::class], ]); BroadcastTenancyBootstrapper::$credentialsMap = [ @@ -395,6 +403,7 @@ test('BroadcastTenancyBootstrapper makes the app use broadcasters with the corre 'broadcasting.default' => 'testing', 'broadcasting.connections.testing.driver' => 'testing', 'broadcasting.connections.testing.message' => $defaultMessage = 'default', + 'tenancy.bootstrappers' => [BroadcastTenancyBootstrapper::class], ]); TenancyBroadcastManager::$tenantBroadcasters[] = 'testing'; @@ -436,7 +445,8 @@ test('MailTenancyBootstrapper maps tenant mail credentials to config as specifie config([ 'mail.default' => 'smtp', 'mail.mailers.smtp.username' => $defaultUsername = 'default username', - 'mail.mailers.smtp.password' => 'no password' + 'mail.mailers.smtp.password' => 'no password', + 'tenancy.bootstrappers' => [MailTenancyBootstrapper::class], ]); $tenant = Tenant::create(['smtp_password' => $password = 'testing password']); @@ -454,7 +464,11 @@ test('MailTenancyBootstrapper maps tenant mail credentials to config as specifie test('MailTenancyBootstrapper reverts the config and mailer credentials to default when tenancy ends', function() { MailTenancyBootstrapper::$credentialsMap = ['mail.mailers.smtp.password' => 'smtp_password']; - config(['mail.default' => 'smtp', 'mail.mailers.smtp.password' => $defaultPassword = 'no password']); + config([ + 'mail.default' => 'smtp', + 'mail.mailers.smtp.password' => $defaultPassword = 'no password', + 'tenancy.bootstrappers' => [MailTenancyBootstrapper::class], + ]); tenancy()->initialize(Tenant::create(['smtp_password' => $tenantPassword = 'testing password'])); @@ -470,18 +484,8 @@ test('MailTenancyBootstrapper reverts the config and mailer credentials to defau assertMailerTransportUsesPassword($defaultPassword); }); -function getDiskPrefix(string $disk): string -{ - /** @var FilesystemAdapter $disk */ - $disk = Storage::disk($disk); - $adapter = $disk->getAdapter(); - $prefix = invade(invade($adapter)->prefixer)->prefix; - - return $prefix; -} - test('url bootstrapper overrides the root url when tenancy gets initialized and reverts the url to the central one after tenancy ends', function() { - config(['tenancy.bootstrappers.url' => UrlTenancyBootstrapper::class]); + config(['tenancy.bootstrappers' => [UrlTenancyBootstrapper::class]]); Route::group([ 'middleware' => InitializeTenancyBySubdomain::class, @@ -524,3 +528,106 @@ test('url bootstrapper overrides the root url when tenancy gets initialized and expect(URL::to('/'))->toBe($baseUrl); expect(config('app.url'))->toBe($baseUrl); }); + +test('url binding tenancy bootstrapper swaps the url generator instance correctly', function() { + config(['tenancy.bootstrappers' => [UrlBindingBootstrapper::class]]); + + tenancy()->initialize(Tenant::create()); + expect(app('url'))->toBeInstanceOf(TenancyUrlGenerator::class); + expect(url())->toBeInstanceOf(TenancyUrlGenerator::class); + + tenancy()->end(); + expect(app('url'))->toBeInstanceOf(UrlGenerator::class); + expect(url())->toBeInstanceOf(UrlGenerator::class); +}); + +test('url binding tenancy bootstrapper changes route helper behavior correctly', function() { + Route::get('/central/home', fn () => route('home'))->name('home'); + // Tenant route name prefix is 'tenant.' by default + Route::get('/{tenant}/home', fn () => route('tenant.home'))->name('tenant.home')->middleware(['tenant', InitializeTenancyByPath::class]); + Route::get('/query-string', fn () => route('query-string'))->name('query-string')->middleware(['tenant', InitializeTenancyByRequestData::class]); + + $tenant = Tenant::create(); + $tenantKey = $tenant->getTenantKey(); + $centralRouteUrl = route('home'); + $tenantRouteUrl = route('tenant.home', ['tenant' => $tenantKey]); + $queryStringCentralUrl = route('query-string'); + $queryStringTenantUrl = route('query-string', ['tenant' => $tenantKey]); + TenancyUrlGenerator::$bypassParameter = 'bypassParameter'; + $bypassParameter = TenancyUrlGenerator::$bypassParameter; + + config(['tenancy.bootstrappers' => [UrlBindingBootstrapper::class]]); + TenancyUrlGenerator::$prefixRouteNames = true; + + tenancy()->initialize($tenant); + // The $prefixRouteNames property is true + // The route name passed to the route() helper ('home') gets prefixed prefixed with 'tenant.' automatically + expect(route('home'))->toBe($tenantRouteUrl); + + // The 'tenant.home' route name doesn't get prefixed because it is already prefixed with 'tenant.' + // Also, the route receives the tenant parameter automatically + expect(route('tenant.home'))->toBe($tenantRouteUrl); + + // The $bypassParameter parameter ('central' by default) can bypass the route name prefixing + // When the bypass parameter is true, the generated route URL points to the route named 'home' + // Also, check if the bypass parameter gets removed from the generated URL query string + expect(route('home', [$bypassParameter => true]))->toBe($centralRouteUrl) + ->not()->toContain($bypassParameter); + // When the bypass parameter is false, the generated route URL points to the prefixed route ('tenant.home') + expect(route('home', [$bypassParameter => false]))->toBe($tenantRouteUrl) + ->not()->toContain($bypassParameter); + + TenancyUrlGenerator::$prefixRouteNames = false; + // Route names don't get prefixed – TenancyUrlGenerator::$prefixRouteNames is false + expect(route('home', [$bypassParameter => true]))->toBe($centralRouteUrl); + expect(route('query-string'))->toBe($queryStringTenantUrl); + + TenancyUrlGenerator::$passTenantParameterToRoutes = false; + expect(route('query-string'))->toBe($queryStringCentralUrl); + + TenancyUrlGenerator::$passTenantParameterToRoutes = true; + expect(route('query-string'))->toBe($queryStringTenantUrl); + + // Ending tenancy reverts route() behavior changes + tenancy()->end(); + + expect(route('home'))->toBe($centralRouteUrl); + expect(route('query-string'))->toBe($queryStringCentralUrl); + expect(route('tenant.home', ['tenant' => $tenantKey]))->toBe($tenantRouteUrl); + + // Route-level identification + pest()->get("http://localhost/central/home")->assertSee($centralRouteUrl); + pest()->get("http://localhost/$tenantKey/home")->assertSee($tenantRouteUrl); + pest()->get("http://localhost/query-string?tenant=$tenantKey")->assertSee($queryStringTenantUrl); +})->group('string'); + +test('fortify route tenancy bootstrapper updates fortify config correctly', function() { + config(['tenancy.bootstrappers' => [FortifyRouteTenancyBootstrapper::class]]); + + Route::get('/', function () { + return true; + })->name($tenantHomeRouteName = 'tenant.home'); + + FortifyRouteTenancyBootstrapper::$fortifyHome = $tenantHomeRouteName; + FortifyRouteTenancyBootstrapper::$fortifyRedirectTenantMap = ['logout' => FortifyRouteTenancyBootstrapper::$fortifyHome]; + $originalFortifyHome = config('fortify.home'); + $originalFortifyRedirects = config('fortify.redirects'); + + tenancy()->initialize(Tenant::create()); + expect(config('fortify.home'))->toBe($homeUrl = route($tenantHomeRouteName)); + expect(config('fortify.redirects'))->toBe(['logout' => $homeUrl]); + + tenancy()->end(); + expect(config('fortify.home'))->toBe($originalFortifyHome); + expect(config('fortify.redirects'))->toBe($originalFortifyRedirects); +}); + +function getDiskPrefix(string $disk): string +{ + /** @var FilesystemAdapter $disk */ + $disk = Storage::disk($disk); + $adapter = $disk->getAdapter(); + $prefix = invade(invade($adapter)->prefixer)->prefix; + + return $prefix; +} diff --git a/tests/BroadcastingTest.php b/tests/BroadcastingTest.php index 9505b537..808bfe53 100644 --- a/tests/BroadcastingTest.php +++ b/tests/BroadcastingTest.php @@ -12,9 +12,11 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy; use Stancl\Tenancy\Tests\Etc\TestingBroadcaster; use Stancl\Tenancy\Listeners\RevertToCentralContext; use Illuminate\Contracts\Broadcasting\Broadcaster as BroadcasterContract; +use Stancl\Tenancy\Bootstrappers\BroadcastTenancyBootstrapper; beforeEach(function () { withTenantDatabases(); + config(['tenancy.bootstrappers' => [BroadcastTenancyBootstrapper::class]]); TenancyBroadcastManager::$tenantBroadcasters = ['pusher', 'ably']; Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class); diff --git a/tests/DatabaseUsersTest.php b/tests/DatabaseUsersTest.php index 4f6ef723..7b2af158 100644 --- a/tests/DatabaseUsersTest.php +++ b/tests/DatabaseUsersTest.php @@ -25,6 +25,13 @@ beforeEach(function () { 'tenancy.database.template_tenant_connection' => 'mysql', ]); + // Reset static property + PermissionControlledMySQLDatabaseManager::$grants = [ + 'ALTER', 'ALTER ROUTINE', 'CREATE', 'CREATE ROUTINE', 'CREATE TEMPORARY TABLES', 'CREATE VIEW', + 'DELETE', 'DROP', 'EVENT', 'EXECUTE', 'INDEX', 'INSERT', 'LOCK TABLES', 'REFERENCES', 'SELECT', + 'SHOW VIEW', 'TRIGGER', 'UPDATE', + ]; + Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) { return $event->tenant; })->toListener()); @@ -82,6 +89,13 @@ test('correct grants are given to users', function () { $query = DB::connection('mysql')->select("SHOW GRANTS FOR `{$tenant->database()->getUsername()}`@`%`")[1]; expect($query->{"Grants for {$user}@%"})->toStartWith('GRANT CREATE, ALTER, ALTER ROUTINE ON'); // @mysql because that's the hostname within the docker network + + // Reset static property + PermissionControlledMySQLDatabaseManager::$grants = [ + 'ALTER', 'ALTER ROUTINE', 'CREATE', 'CREATE ROUTINE', 'CREATE TEMPORARY TABLES', 'CREATE VIEW', + 'DELETE', 'DROP', 'EVENT', 'EXECUTE', 'INDEX', 'INSERT', 'LOCK TABLES', 'REFERENCES', 'SELECT', + 'SHOW VIEW', 'TRIGGER', 'UPDATE', + ]; }); test('having existing databases without users and switching to permission controlled mysql manager doesnt break existing dbs', function () { diff --git a/tests/EarlyIdentificationTest.php b/tests/EarlyIdentificationTest.php index ddec56fe..d78a62c8 100644 --- a/tests/EarlyIdentificationTest.php +++ b/tests/EarlyIdentificationTest.php @@ -2,83 +2,214 @@ declare(strict_types=1); +use Illuminate\Support\Arr; +use Illuminate\Routing\Route; +use Stancl\Tenancy\RouteMode; +use Stancl\Tenancy\Tests\Etc\Tenant; use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\Facades\Event; -use Illuminate\Support\Facades\Route; use Stancl\Tenancy\Events\TenancyInitialized; -use Stancl\Tenancy\Middleware\InitializeTenancyByDomain; -use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain; +use Illuminate\Support\Facades\Route as RouteFacade; +use Stancl\Tenancy\Actions\CloneRoutesAsTenant; use Stancl\Tenancy\Middleware\InitializeTenancyByPath; -use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData; +use Stancl\Tenancy\Middleware\InitializeTenancyByDomain; use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain; +use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper; +use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData; +use Stancl\Tenancy\Tests\Etc\EarlyIdentification\Models\Post; use Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains; -use Stancl\Tenancy\Tests\Etc\EarlyIdentification\Controller; -use Stancl\Tenancy\Tests\Etc\Tenant; +use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain; +use Stancl\Tenancy\Tests\Etc\EarlyIdentification\ControllerWithMiddleware; +use Stancl\Tenancy\Tests\Etc\EarlyIdentification\ControllerWithRouteMiddleware; beforeEach(function () { config()->set([ - 'tenancy.token' => 'central-abc123', + 'tenancy.test_service_token' => 'token:central', ]); Event::listen(TenancyInitialized::class, function (TenancyInitialized $event) { config()->set([ - 'tenancy.token' => $event->tenancy->tenant->getTenantKey() . '-abc123', + 'tenancy.test_service_token' => 'token:' . $event->tenancy->tenant->getTenantKey(), ]); }); }); -test('early identification works with path identification', function () { - app(Kernel::class)->pushMiddleware(InitializeTenancyByPath::class); +test('early identification works with path identification', function (bool $useKernelIdentification, RouteMode $defaultRouteMode) { + $identificationMiddleware = InitializeTenancyByPath::class; - Route::group([ - 'prefix' => '/{tenant}', - ], function () { - Route::get('/foo', [Controller::class, 'index'])->name('foo'); - }); - - Tenant::create([ - 'id' => 'acme', - ]); - - $response = pest()->get('/acme/foo')->assertOk(); - - assertTenancyInitializedInEarlyIdentificationRequest($response->getContent()); - - // check if default parameter feature is working fine by asserting that the route WITHOUT the tenant parameter - // matches the route WITH the tenant parameter - expect(route('foo'))->toBe(route('foo', ['tenant' => 'acme'])); -}); - -test('early identification works with request data identification', function (string $type) { - app(Kernel::class)->pushMiddleware(InitializeTenancyByRequestData::class); - - Route::get('/foo', [Controller::class, 'index'])->name('foo'); - - $tenant = Tenant::create([ - 'id' => 'acme', - ]); - - if ($type === 'header') { - $response = pest()->get('/foo', ['X-Tenant' => $tenant->id])->assertOk(); - } elseif ($type === 'queryParameter') { - $response = pest()->get("/foo?tenant=$tenant->id")->assertOk(); + if ($useKernelIdentification) { + $controller = ControllerWithMiddleware::class; + app(Kernel::class)->pushMiddleware($identificationMiddleware); + } else { + $controller = ControllerWithRouteMiddleware::class; + RouteFacade::middlewareGroup('tenant', [$identificationMiddleware]); } - assertTenancyInitializedInEarlyIdentificationRequest($response->getContent()); + config(['tenancy.bootstrappers' => [DatabaseTenancyBootstrapper::class]]); + config(['tenancy.default_route_mode' => $defaultRouteMode]); + + // Migrate users and comments tables on central connection + pest()->artisan('migrate', [ + '--path' => __DIR__ . '/Etc/EarlyIdentification/path/migrations', + '--realpath' => true, + ])->assertExitCode(0); + + $centralPost = Post::create(['title' => 'central post']); + $centralComment = $centralPost->comments()->create(['comment' => 'central comment']); + + /** + * @var Route $tenantRoute + * @var Route $commentTenantRoute + * + * The Route instance is always assigned to this variable + */ + $tenantRoute = null; + $commentTenantRoute = null; + $tenantRouteMiddleware = ['tenant', 'web']; + + // If defaulting to tenant routes + // With kernel identification, we make the tenant route have no MW (except 'web') + // And with route-level identification, we make the route have only the identification middleware + 'web' + if ($defaultRouteMode === RouteMode::TENANT) { + $tenantRouteMiddleware = $useKernelIdentification ? ['web'] : [$identificationMiddleware, 'web']; + } + + RouteFacade::group([ + 'middleware' => $tenantRouteMiddleware, + 'prefix' => '/{tenant}', + ], function () use ($controller, &$tenantRoute, &$commentTenantRoute) { + $tenantRoute = RouteFacade::get('/tenant-route', [$controller, 'index'])->name('tenant-route'); + $commentTenantRoute = RouteFacade::get('/{post}/comment/{comment}/edit', [$controller, 'computePost'])->name('comment-tenant-route'); + }); + + RouteFacade::group([ + 'middleware' => ['central', 'web'], + ], function () use ($controller) { + RouteFacade::get('/central/home', function () { + return 'central-home'; + }); + RouteFacade::get('/{post}/edit', [$controller, 'computePost']); + RouteFacade::get('/{post}/comment/{comment}/edit', [$controller, 'computePost']); + }); + + $tenant = Tenant::create(['tenancy_db_name' => pest()->randomString()]); + + // Migrate users and comments tables on tenant connection + pest()->artisan('tenants:migrate', [ + '--path' => __DIR__ . '/Etc/EarlyIdentification/path/migrations', + '--realpath' => true, + ])->assertExitCode(0); + + tenancy()->initialize($tenant); + $tenantPost = Post::create(['title' => 'tenant post']); + $tenantComment = $tenantPost->comments()->create(['comment' => 'tenant comment']); + tenancy()->end(); + + // Central routes are accessible and tenancy doesn't get initialized in early identification when the routes get accessed + pest()->get('/central/home')->assertOk(); + pest()->get("/{$centralPost->id}/edit")->assertOk()->assertContent('central post'); + pest()->get("/{$centralPost->id}/comment/{$centralComment->id}/edit")->assertOk()->assertContent($centralPost->title . '-' . $centralComment->comment); + assertTenancyInitializedInEarlyIdentificationRequest(false); + + // Tenant routes are accessible and tenancy gets initialized in early identification when the routes get accessed + pest()->get("/{$tenant->id}/{$tenantPost->id}/comment/{$tenantComment->id}/edit") + ->assertOk() + ->assertContent($tenantPost->title . '-' . $tenantComment->comment); + assertTenancyInitializedInEarlyIdentificationRequest(); + + // Tenant routes that use path identification receive the tenant parameter automatically + // (setDefaultTenantForRouteParametersWhenInitializingTenancy() in Stancl\Tenancy\Middleware\InitializeTenancyByPath) + expect(route('tenant-route'))->toBe(route('tenant-route', ['tenant' => $tenant->getTenantKey()])); })->with([ - 'using request header parameter' => 'header', - 'using request query parameter' => 'queryParameter' + 'route-level identification' => false, + 'kernel identification' => true, +// Creates a matrix (multiple with()) +])->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, ]); -// The name of this test is suffixed by the dataset — domain / subdomain / domainOrSubdomain identification -test('early identification works', function (string $middleware, string $domain, string $url) { - app(Kernel::class)->pushMiddleware($middleware); +test('early identification works with request data identification', function (string $type, bool $useKernelIdentification, RouteMode $defaultRouteMode) { + $identificationMiddleware = InitializeTenancyByRequestData::class; + if ($useKernelIdentification) { + $controller = ControllerWithMiddleware::class; + app(Kernel::class)->pushMiddleware($identificationMiddleware); + } else { + $controller = ControllerWithRouteMiddleware::class; + RouteFacade::middlewareGroup('tenant', [$identificationMiddleware]); + } + + config(['tenancy.default_route_mode' => $defaultRouteMode]); + + $tenantRouteMiddleware = 'tenant'; + + // If defaulting to tenant routes + // With kernel identification, we make the tenant route have no MW + // And with route-level identification, we make the route have only the identification middleware + if ($defaultRouteMode === RouteMode::TENANT) { + $tenantRouteMiddleware = $useKernelIdentification ? null : $identificationMiddleware; + } + + RouteFacade::get('/tenant-route', [$controller, 'index'])->middleware($tenantRouteMiddleware); + RouteFacade::get('/central-route', fn () => 'central route')->middleware($defaultRouteMode === RouteMode::TENANT ? 'central' : null); + + $tenantKey = Tenant::create()->getTenantKey(); + + // Central route is accessible for every $type + pest()->get('/central-route')->assertOk()->assertContent('central route'); + + $response = match ($type) { + 'header' => pest()->get('/tenant-route', ['X-Tenant' => $tenantKey]), + 'queryParameter' => pest()->get("/tenant-route?tenant={$tenantKey}"), + 'cookie' => pest()->withUnencryptedCookie('X-Tenant', $tenantKey) + ->get('/tenant-route'), + }; + + $response->assertOk()->assertSee('token:' . $tenantKey); +})->with([ + 'using request header parameter' => 'header', + 'using request query parameter' => 'queryParameter', + 'using request cookie parameter' => 'cookie', +// Creates a matrix (multiple with()) +])->with([ + 'route-level identification' => false, + 'kernel identification' => true, +])->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, +]); + +test('early identification works with domain identification', function (string $middleware, string $domain, bool $useKernelIdentification, RouteMode $defaultRouteMode) { config(['tenancy.tenant_model' => Tenant::class]); + config(['tenancy.default_route_mode' => $defaultRouteMode]); - Route::get('/foo', [Controller::class, 'index']) - ->middleware(PreventAccessFromUnwantedDomains::class) - ->name('foo'); + if ($useKernelIdentification) { + $controller = ControllerWithMiddleware::class; + app(Kernel::class)->pushMiddleware($middleware); + app(Kernel::class)->pushMiddleware(PreventAccessFromUnwantedDomains::class); + } else { + $controller = ControllerWithRouteMiddleware::class; + RouteFacade::middlewareGroup('tenant', [$middleware, PreventAccessFromUnwantedDomains::class]); + } + + // Tenant route + $tenantRoute = RouteFacade::get('/tenant-route', [$controller, 'index']); + + // Central route + $centralRoute = RouteFacade::get('/central-route', function () { + return 'central route'; + }); + + $defaultToTenantRoutes = $defaultRouteMode === RouteMode::TENANT; + + // Test defaulting to route mode (central/tenant context) + if ($useKernelIdentification) { + $routeThatShouldReceiveMiddleware = $defaultToTenantRoutes ? $centralRoute : $tenantRoute; + $routeThatShouldReceiveMiddleware->middleware($defaultToTenantRoutes ? 'central' : 'tenant'); + } elseif (! $defaultToTenantRoutes) { + $tenantRoute->middleware('tenant'); + } $tenant = Tenant::create(); @@ -86,19 +217,173 @@ test('early identification works', function (string $middleware, string $domain, 'domain' => $domain, ]); - $response = pest()->get($url)->assertOk(); + if ($domain === 'foo') { + $domain = 'foo.localhost'; + } - assertTenancyInitializedInEarlyIdentificationRequest($response->getContent()); + pest()->get('http://localhost/central-route')->assertOk()->assertContent('central route'); // Central route is accessible + + $response = pest()->get("http://{$domain}/tenant-route"); + + if ($defaultToTenantRoutes === $useKernelIdentification || $useKernelIdentification) { + $response->assertOk(); + assertTenancyInitializedInEarlyIdentificationRequest(); + } elseif (! $defaultToTenantRoutes) { + $response->assertNotFound(); + assertTenancyInitializedInEarlyIdentificationRequest(false); + } + + // Expect tenancy is initialized (or not) for the right tenant at the tenant route + expect($response->getContent())->toBe('token:' . (tenant()?->getTenantKey() ?? 'central')); })->with([ - 'domain identification' => ['middleware' => InitializeTenancyByDomain::class, 'domain' => 'foo.test', 'url' => 'http://foo.test/foo'], - 'subdomain identification' => ['middleware' => InitializeTenancyBySubdomain::class, 'domain' => 'foo', 'url' => 'http://foo.localhost/foo'], - 'domainOrSubdomain identification using domain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo.test', 'url' => 'http://foo.test/foo'], - 'domainOrSubdomain identification using subdomain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo', 'url' => 'http://foo.localhost/foo'], + 'domain identification' => ['middleware' => InitializeTenancyByDomain::class, 'domain' => 'foo.test'], + 'subdomain identification' => ['middleware' => InitializeTenancyBySubdomain::class, 'domain' => 'foo'], + 'domainOrSubdomain identification using domain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo.test'], + 'domainOrSubdomain identification using subdomain' => ['middleware' => InitializeTenancyByDomainOrSubdomain::class, 'domain' => 'foo'], +// Creates a matrix (multiple with()) +])->with([ + 'route-level identification' => false, + 'kernel identification' => true, +])->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, ]); -function assertTenancyInitializedInEarlyIdentificationRequest(string|false $string): void +test('the tenant parameter is only removed from tenant routes when using path identification', function (bool $kernelIdentification, bool $pathIdentification) { + if ($kernelIdentification) { + $middleware = $pathIdentification ? InitializeTenancyByPath::class : InitializeTenancyByDomain::class; + + app(Kernel::class)->pushMiddleware($middleware); + + RouteFacade::get('/{tenant}/central-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter']) + ->middleware('central') + ->name('central-route'); + + RouteFacade::get('/{tenant}/tenant-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter']) + ->middleware('tenant') + ->name('tenant-route'); + + $tenant = Tenant::create(); + $tenantKey = $tenant->getTenantKey(); + + // Expect route to receive the tenant parameter + $response = pest()->get($tenantKey . '/central-route')->assertOk(); + expect((bool) $response->getContent())->toBeTrue(); + + if ($pathIdentification) { + // Tenant parameter is removed from tenant routes using kernel path identification (Stancl\Tenancy\Listeners\ForgetTenantParameter) + $response = pest()->get($tenantKey . '/tenant-route')->assertOk(); + expect((bool) $response->getContent())->toBeFalse(); + } else { + // Tenant parameter is not removed from tenant routes using other kernel identification MW + $tenant->domains()->create(['domain' => $domain = $tenantKey . '.localhost']); + + $response = pest()->get("http://{$domain}/{$tenantKey}/tenant-route")->assertOk(); + expect((bool) $response->getContent())->toBeTrue(); + } + } else { + RouteFacade::middlewareGroup('tenant', [$pathIdentification ? InitializeTenancyByPath::class : InitializeTenancyByDomain::class]); + + // Route-level identification + RouteFacade::get('/{tenant}/central-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter']) + ->middleware('central') + ->name('central-route'); + + RouteFacade::get('/{tenant}/tenant-route', [ControllerWithMiddleware::class, 'routeHasTenantParameter']) + ->middleware('tenant') + ->name('tenant-route'); + + $tenant = Tenant::create(); + $tenantKey = $tenant->getTenantKey(); + + if ($pathIdentification) { + // Tenant parameter isn't removed from central routes + $response = pest()->get("http://localhost/{$tenantKey}/central-route")->assertOk(); + expect((bool) $response->getContent())->toBeTrue(); + + // Tenant parameter is removed from tenant routes that are using kernel path identification (in PathTenantResolver) + $response = pest()->get("http://localhost/{$tenantKey}/tenant-route")->assertOk(); + expect((bool) $response->getContent())->toBeFalse(); + } else { + $tenant->domains()->create(['domain' => $domain = $tenantKey . '.localhost']); + + // Tenant parameter is not removed from tenant routes that are using other identification MW + $response = pest()->get("http://{$domain}/{$tenantKey}/tenant-route")->assertOk(); + expect((bool) $response->getContent())->toBeTrue(); + } + } +})->with([ + 'kernel path identification' => ['kernelIdentification' => true, 'pathIdentification' => true], + 'route-level path identification' => ['kernelIdentification' => false, 'pathIdentification' => true], + 'kernel domain identification' => ['kernelIdentification' => true, 'pathIdentification' => false], + 'route-level domain identification' => ['kernelIdentification' => false, 'pathIdentification' => false], +]); + +test('route level identification is prioritized over kernel identification', function ( + string|array $kernelIdentificationMiddleware, + string|array $routeIdentificationMiddleware, + string $routeUri, + string $domainToVisit, + string|null $domain = null, + RouteMode $defaultRouteMode, +) { + $tenant = Tenant::create(); + $domainToVisit = str_replace('{tenantKey}', $tenant->getTenantKey(), $domainToVisit); + + config(['tenancy.default_route_mode' => $defaultRouteMode]); + + if ($domain) { + $tenant->domains()->create(['domain' => str_replace('{tenantKey}', $tenant->getTenantKey(), $domain)]); + } + + foreach (Arr::wrap($kernelIdentificationMiddleware) as $identificationMiddleware) { + app(Kernel::class)->pushMiddleware($identificationMiddleware); + } + + // We're testing *non-early* route-level identification so that we can assert that early kernel identification got skipped + // Also, ignore the defaulting when the identification MW is applied directly on the route + // The route is automatically considered tenant if it has identification middleware (unless it also has the 'universal' middleware) + RouteFacade::get($routeUri, [ControllerWithMiddleware::class, 'index'])->middleware($routeIdentificationMiddleware); + + pest()->get($domainToVisit)->assertOk(); + + // Kernel (early) identification skipped + expect(app()->make('controllerRunsInTenantContext'))->toBeFalse(); +})->with([ + 'kernel request data identification mw' => ['kernelMiddleware' => InitializeTenancyByRequestData::class], + 'kernel path identification mw' => ['kernelMiddleware' => InitializeTenancyByPath::class], + 'kernel domain identification mw' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class]], + 'kernel subdomain identification mw' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class]], + 'kernel domainOrSubdomain identification mw using domain' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class]], + 'kernel domainOrSubdomain identification mw using subdomain' => ['kernelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class]], +// Creates a matrix (multiple with()) +])->with([ + 'route level request data identification mw' => ['routeLevelMiddleware' => InitializeTenancyByRequestData::class, 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://localhost/tenant-route?tenant={tenantKey}', 'domain' => null], + 'route level path identification mw' => ['routeLevelMiddleware' => InitializeTenancyByPath::class, 'routeUri' => '/{tenant}/tenant-route', 'domainToVisit' => 'http://localhost/{tenantKey}/tenant-route', 'domain' => null], + 'route level domain identification mw' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.test/tenant-route', 'domain' => '{tenantKey}.test'], + 'route level subdomain identification mw' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.localhost/tenant-route', 'domain' => '{tenantKey}'], + 'route level domainOrSubdomain identification mw using domain' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.test/tenant-route', 'domain' => '{tenantKey}.test'], + 'route level domainOrSubdomain identification mw using subdomain' => ['routeLevelMiddleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class], 'routeUri' => '/tenant-route', 'domainToVisit' => 'http://{tenantKey}.localhost/tenant-route', 'domain' => '{tenantKey}'], +]) +->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, +]); + +test('routes with path identification middleware can get prefixed using the reregister action', function() { + $tenantKey = Tenant::create()->getTenantKey(); + + RouteFacade::get('/home', fn () => tenant()?->getTenantKey())->name('home')->middleware(InitializeTenancyByPath::class); + + pest()->get("http://localhost/$tenantKey/home")->assertNotFound(); + + app(CloneRoutesAsTenant::class)->handle(); + + pest()->get("http://localhost/$tenantKey/home")->assertOk(); +}); + +function assertTenancyInitializedInEarlyIdentificationRequest(bool $expect = true): void { - expect($string)->toBe(tenant()->getTenantKey() . '-abc123'); // Assert that the service class returns tenant value - expect(app()->make('additionalMiddlewareRunsInTenantContext'))->toBeTrue(); // Assert that middleware added in the controller constructor runs in tenant context - expect(app()->make('controllerRunsInTenantContext'))->toBeTrue(); // Assert that tenancy is initialized in the controller constructor + expect(app()->make('additionalMiddlewareRunsInTenantContext'))->toBe($expect); // Assert that middleware added in the controller constructor runs in tenant context + expect(app()->make('controllerRunsInTenantContext'))->toBe($expect); // Assert that tenancy is initialized in the controller constructor } diff --git a/tests/Etc/EarlyIdentification/Controller.php b/tests/Etc/EarlyIdentification/Controller.php deleted file mode 100644 index 69898593..00000000 --- a/tests/Etc/EarlyIdentification/Controller.php +++ /dev/null @@ -1,19 +0,0 @@ -instance('controllerRunsInTenantContext', tenancy()->initialized); - $this->middleware(AdditionalMiddleware::class); - } - - public function index(): string - { - return $this->service->token; - } -} diff --git a/tests/Etc/EarlyIdentification/ControllerWithMiddleware.php b/tests/Etc/EarlyIdentification/ControllerWithMiddleware.php new file mode 100644 index 00000000..7773f86b --- /dev/null +++ b/tests/Etc/EarlyIdentification/ControllerWithMiddleware.php @@ -0,0 +1,37 @@ +instance('controllerRunsInTenantContext', tenancy()->initialized); + $this->middleware(AdditionalMiddleware::class); + } + + public function computePost(Post $post, Comment|null $comment = null): string + { + $post = $post->title; + $comment = $comment ? '-' . $comment->comment : ''; + + return $post . $comment; + } + + public function index(): string + { + return $this->service->token; + } + + public function routeHasTenantParameter(Request $request): bool + { + return $request->route()->hasParameter(PathTenantResolver::tenantParameterName()); + } +} diff --git a/tests/Etc/EarlyIdentification/ControllerWithRouteMiddleware.php b/tests/Etc/EarlyIdentification/ControllerWithRouteMiddleware.php new file mode 100644 index 00000000..797a65fe --- /dev/null +++ b/tests/Etc/EarlyIdentification/ControllerWithRouteMiddleware.php @@ -0,0 +1,44 @@ +instance('controllerRunsInTenantContext', tenancy()->initialized); + } + + public static function middleware() + { + return [ + new Middleware(AdditionalMiddleware::class) + ]; + } + + public function computePost(Post $post, Comment|null $comment = null): string + { + $post = $post->title; + $comment = $comment ? '-' . $comment->comment : ''; + + return $post . $comment; + } + + public function index(): string + { + return $this->service->token; + } + + public function routeHasTenantParameter(Request $request): bool + { + return $request->route()->hasParameter(PathTenantResolver::tenantParameterName()); + } +} diff --git a/tests/Etc/EarlyIdentification/Models/Comment.php b/tests/Etc/EarlyIdentification/Models/Comment.php new file mode 100644 index 00000000..902ca711 --- /dev/null +++ b/tests/Etc/EarlyIdentification/Models/Comment.php @@ -0,0 +1,17 @@ +belongsTo(Post::class, 'post_id'); + } +} diff --git a/tests/Etc/EarlyIdentification/Models/Post.php b/tests/Etc/EarlyIdentification/Models/Post.php new file mode 100644 index 00000000..8cab4424 --- /dev/null +++ b/tests/Etc/EarlyIdentification/Models/Post.php @@ -0,0 +1,17 @@ +hasMany(Comment::class, 'post_id'); + } +} diff --git a/tests/Etc/EarlyIdentification/Service.php b/tests/Etc/EarlyIdentification/Service.php index 29d9414c..1cd6b3b4 100644 --- a/tests/Etc/EarlyIdentification/Service.php +++ b/tests/Etc/EarlyIdentification/Service.php @@ -10,6 +10,6 @@ class Service public function __construct() { - $this->token = config('tenancy.token'); + $this->token = config('tenancy.test_service_token'); } } diff --git a/tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_comments_table.php b/tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_comments_table.php new file mode 100644 index 00000000..05b46dd9 --- /dev/null +++ b/tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_comments_table.php @@ -0,0 +1,29 @@ +increments('id'); + $table->string('comment'); + $table->unsignedInteger('post_id'); + }); + } + + public function down() + { + Schema::drop('comments'); + } +} diff --git a/tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_posts_table.php b/tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_posts_table.php new file mode 100644 index 00000000..942975c0 --- /dev/null +++ b/tests/Etc/EarlyIdentification/path/migrations/2019_08_08_000001_create_posts_table.php @@ -0,0 +1,28 @@ +increments('id'); + $table->string('title'); + }); + } + + public function down() + { + Schema::drop('posts'); + } +} diff --git a/tests/EventListenerTest.php b/tests/EventListenerTest.php index 673b2ccc..7c82d92d 100644 --- a/tests/EventListenerTest.php +++ b/tests/EventListenerTest.php @@ -20,6 +20,10 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy; use Stancl\Tenancy\Listeners\QueueableListener; use Stancl\Tenancy\Tests\Etc\Tenant; +beforeEach(function () { + FooListener::$shouldQueue = false; +}); + test('listeners can be synchronous', function () { Queue::fake(); Event::listen(TenantCreated::class, FooListener::class); @@ -44,6 +48,9 @@ test('listeners can be queued by setting a static property', function () { }); expect(app()->bound('foo'))->toBeFalse(); + + // Reset static property + FooListener::$shouldQueue = false; }); test('ing events can be used to cancel tenant model actions', function () { diff --git a/tests/MailTest.php b/tests/MailTest.php index dc48648a..a46b2466 100644 --- a/tests/MailTest.php +++ b/tests/MailTest.php @@ -12,6 +12,7 @@ use Stancl\Tenancy\Bootstrappers\MailTenancyBootstrapper; beforeEach(function() { config(['mail.default' => 'smtp']); + config(['tenancy.bootstrappers' => [MailTenancyBootstrapper::class]]); MailTenancyBootstrapper::$credentialsMap = []; Event::listen(TenancyInitialized::class, BootstrapTenancy::class); diff --git a/tests/PathIdentificationTest.php b/tests/PathIdentificationTest.php index 32880c4f..f1998ce4 100644 --- a/tests/PathIdentificationTest.php +++ b/tests/PathIdentificationTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\Facades\Route; use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException; use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException; @@ -10,6 +11,11 @@ use Stancl\Tenancy\Resolvers\PathTenantResolver; use Stancl\Tenancy\Tests\Etc\Tenant; beforeEach(function () { + // Make sure the tenant parameter is set to 'tenant' + config(['tenancy.identification.resolvers.' . PathTenantResolver::class . '.tenant_parameter_name' => 'tenant']); + + InitializeTenancyByPath::$onFail = null; + Route::group([ 'prefix' => '/{tenant}', 'middleware' => InitializeTenancyByPath::class, @@ -70,9 +76,11 @@ test('onfail logic can be customized', function () { pest() ->get('/acme/foo/abc/xyz') ->assertContent('foo'); + + InitializeTenancyByPath::$onFail = null; }); -test('an exception is thrown when the routes first parameter is not tenant', function () { +test('an exception is thrown when the route does not have the tenant parameter', function () { Route::group([ // 'prefix' => '/{tenant}', -- intentionally commented 'middleware' => InitializeTenancyByPath::class, @@ -140,3 +148,35 @@ test('tenant parameter is set for all routes as the default parameter once the t expect(route('baz', ['a' => 1, 'b' => 2]))->toBe('http://localhost/acme/baz/1/2'); // assert the full route string pest()->get(route('baz', ['a' => 1, 'b' => 2]))->assertOk(); // Assert route don't need tenant parameter }); + +test('tenant parameter does not have to be the first in order to initialize tenancy', function() { + Tenant::create([ + 'id' => $tenantId = 'another-tenant', + ]); + + Route::get('/another/route/{a}/{tenant}/{b}', function ($a, $b) { + return "$a + $b + " . tenant()->getTenantKey(); + })->middleware(InitializeTenancyByPath::class)->name('tenant-parameter-is-second'); + + pest()->get("/another/route/foo/$tenantId/bar")->assertSee("foo + bar + $tenantId"); +}); + +test('central route can have a parameter with the same name as the tenant parameter', function() { + config(['tenancy.identification.resolvers.' . PathTenantResolver::class . '.tenant_parameter_name' => 'team']); + $tenantKey = Tenant::create()->getTenantKey(); + + Route::get('/central/route/{team}/{a}/{b}', function ($team, $a, $b) { + return "$a + $b + $team"; + })->middleware('central')->name('central-route'); + + pest()->get("/central/route/{$tenantKey}/foo/bar")->assertSee("foo + bar + {$tenantKey}"); + + expect(tenancy()->initialized)->toBeFalse(); + + // With kernel path identification + app(Kernel::class)->pushMiddleware(InitializeTenancyByPath::class); + + pest()->get("/central/route/{$tenantKey}/foo/bar")->assertSee("foo + bar + {$tenantKey}"); + + expect(tenancy()->initialized)->toBeFalse(); +}); diff --git a/tests/PreventAccessFromUnwantedDomainsTest.php b/tests/PreventAccessFromUnwantedDomainsTest.php new file mode 100644 index 00000000..7143ce97 --- /dev/null +++ b/tests/PreventAccessFromUnwantedDomainsTest.php @@ -0,0 +1,235 @@ +set([ + 'tenancy.default_route_mode' => $defaultRouteMode, + ]); + + if ($defaultRouteMode === RouteMode::TENANT) { + // Apply `central` middleware to central routes if routes default to `tenant` + $centralMiddleware = ['central', PreventAccessFromUnwantedDomains::class]; + $tenantMiddleware = [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class]; + } else { + // Apply `tenant` middleware to `tenant` routes if routes default to `central` + $centralMiddleware = [PreventAccessFromUnwantedDomains::class]; + $tenantMiddleware = ['tenant', PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class]; + } + + // Central route + Route::get('central-route', function () { + return 'central-route'; + })->middleware($centralMiddleware); + + // Tenant route + Route::get('tenant-route', function () { + return 'tenant-route'; + })->middleware($tenantMiddleware); + + $tenant = Tenant::create(); + $tenant->domains()->create([ + 'domain' => 'foo.localhost', + ]); + + // Accessing tenant routes on central domains and vice versa is not allowed + pest()->get('http://localhost/tenant-route')->assertNotFound(); + pest()->get('http://foo.localhost/central-route')->assertNotFound(); + + // Accessing central routes from central domains and vice versa is allowed + pest()->get('http://localhost/central-route')->assertOk(); + pest()->get('http://foo.localhost/tenant-route')->assertOk(); +})->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, +]); + +test('correct routes are accessible in kernel identification', function (RouteMode $defaultRouteMode) { + // Defaulting to tenant routes only works when using identification middleware globally + app(Kernel::class)->pushMiddleware(PreventAccessFromUnwantedDomains::class); + app(Kernel::class)->pushMiddleware(InitializeTenancyByDomain::class); + + config()->set([ + 'tenancy.default_route_mode' => $defaultRouteMode, + ]); + + $defaultToTenantRoutes = $defaultRouteMode === RouteMode::TENANT; + + // Test that if we're defaulting to a route mode, we don't have to specify the mode middleware ('tenant'/'central') explicitly + if ($defaultToTenantRoutes) { + // Apply `central` middleware to central routes if routes default to tenant context + $centralMiddleware = ['central']; + $tenantMiddleware = []; + } else { + // Apply `tenant` middleware to tenant routes if routes default to `central` + $centralMiddleware = []; + $tenantMiddleware = ['tenant']; + } + + // Central route + Route::get('central-route', function () { + return 'central-route'; + })->middleware($centralMiddleware); + + // Tenant route + Route::get('tenant-route', function () { + return 'tenant-route'; + })->middleware($tenantMiddleware); + + // Route without the mode middleware + Route::get('package-route', function () { + return 'package-route'; + }); + + $tenant = Tenant::create(); + $tenant->domains()->create([ + 'domain' => 'foo.localhost', + ]); + + // Central route on central domain is accessible + pest()->get('http://localhost/central-route')->assertOk(); + expect(tenancy()->initialized)->toBeFalse(); + + // Central route on tenant domain is not accessible + pest()->get('http://foo.localhost/central-route')->assertNotFound(); + expect(tenancy()->initialized)->toBeFalse(); + + // Tenant route on tenant domain is accessible + pest()->get('http://foo.localhost/tenant-route')->assertOk(); + expect(tenancy()->initialized)->toBeTrue(); + tenancy()->end(); + + // Tenant route on central domain is not accessible + pest()->get('http://localhost/tenant-route')->assertNotFound(); + expect(tenancy()->initialized)->toBeFalse(); + + if ($defaultToTenantRoutes) { + // Routes default to tenant – package route is accessible from `tenant` domains + pest()->get('http://foo.localhost/package-route')->assertOk(); + expect(tenancy()->initialized)->toBeTrue(); + tenancy()->end(); + + // Package route isn't accessible from `central` domains + pest()->get('http://localhost/package-route')->assertNotFound(); + } else { + // Routes default to central – package route is accessible from `central` domains + pest()->get('http://localhost/package-route')->assertOk(); + expect(tenancy()->initialized)->toBeFalse(); + + // Package route isn't accessible from `tenant` domains + pest()->get('http://foo.localhost/package-route')->assertNotFound(); + } +})->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, +]); + +test('kernel PreventAccessFromUnwantedDomains does not get skipped when route level domain identification is used', function (string $domainIdentificationMiddleware, string $domain) { + // With route-level *domain identification* MW (without PreventAccessFromUnwantedDomains) + // PreventAccessFromUnwantedDomains shouldn't be skipped + config([ + 'tenancy.test_service_token' => 'token:central', + ]); + + app(Kernel::class)->pushMiddleware(PreventAccessFromUnwantedDomains::class); + Route::middlewareGroup('tenant', [$domainIdentificationMiddleware]); + + Route::get('tenant-route', [ControllerWithMiddleware::class, 'index'])->middleware('tenant')->name('tenant-route'); + Route::get('central-route', [ControllerWithMiddleware::class, 'index'])->middleware('central')->name('central-route'); + + $tenant = Tenant::create(); + $tenant->domains()->create([ + 'domain' => $domain, + ]); + + if ($domain === 'foo') { + $domain = 'foo.localhost'; + } + + // Tenant route is not accessible on central domain + pest()->get('http://localhost/tenant-route')->assertNotFound(); + expect(tenancy()->initialized)->toBeFalse(); + + // Central route is not accessible on tenant domain + pest()->get("http://$domain/central-route")->assertNotFound(); + expect(tenancy()->initialized)->toBeFalse(); + + // Tenant route is accessible on tenant domain + pest()->get("http://$domain/tenant-route")->assertOk(); + expect(tenancy()->initialized)->toBeTrue(); + tenancy()->end(); + + // Central route is accessible on central domain + pest()->get('http://localhost/central-route')->assertOk(); + expect(tenancy()->initialized)->toBeFalse(); +})->with([ + 'domain identification mw' => [InitializeTenancyByDomain::class, 'foo.test'], + 'subdomain identification mw' => [InitializeTenancyBySubdomain::class, 'foo'], + 'domainOrSubdomain identification mw using domain' => [InitializeTenancyByDomainOrSubdomain::class, 'foo.test'], + 'domainOrSubdomain identification mw using subdomain' => [InitializeTenancyByDomainOrSubdomain::class, 'foo'], +]); + +test('placement of domain identification and access prevention middleware can get mixed', function ( + array $globalMiddleware, + array $routeMiddleware, + array $centralRouteMiddleware +) { + config([ + 'tenancy.test_service_token' => 'token:central', + ]); + + foreach ($globalMiddleware as $middleware) { + app(Kernel::class)->pushMiddleware($middleware); + } + + // Make sure the central route has the prevention MW + // If it isn't used globally and it's not passed in $centralRouteMiddleware + if (! in_array(PreventAccessFromUnwantedDomains::class, array_merge($centralRouteMiddleware, $globalMiddleware))) { + $centralRouteMiddleware[] = PreventAccessFromUnwantedDomains::class; + } + + $tenant = Tenant::create(); + $subdomain = $tenant->domains()->create(['domain' => 'foo'])->domain; + + Route::get('tenant-route', fn () => 'tenant route')->middleware(['tenant', ...$routeMiddleware]); + Route::get('central-route', fn () => 'central route')->middleware($centralRouteMiddleware); + + pest()->get("http://$subdomain.localhost/tenant-route")->assertOk(); + expect(tenancy()->initialized)->toBeTrue(); + tenancy()->end(); + pest()->get("http://$subdomain.localhost/central-route")->assertNotFound(); + + pest()->get("http://localhost/tenant-route")->assertNotFound(); + pest()->get("http://localhost/central-route")->assertOk(); + expect(tenancy()->initialized)->toBeFalse(); +})->with([ + 'kernel identification, route-level access prevention' => [ + 'global_middleware' => [InitializeTenancyBySubdomain::class], + 'route_middleware' => [PreventAccessFromUnwantedDomains::class], + ], + 'route-level identification, kernel access prevention' => [ + 'global_middleware' => [PreventAccessFromUnwantedDomains::class], + 'route_middleware' => [InitializeTenancyBySubdomain::class], + ], + 'kernel identification, kernel access prevention' => [ + 'global_middleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class], + 'route_middleware' => [], + ], + 'route-level identification, route-level access prevention' => [ + 'global_middleware' => [], + 'route_middleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class], + ], +// Creates a matrix (multiple with()) +])->with([ + 'central route middleware' => [['central']], + 'central route middleware with access prevention' => [['central', PreventAccessFromUnwantedDomains::class]], +]); diff --git a/tests/RequestDataIdentificationTest.php b/tests/RequestDataIdentificationTest.php index e10c00e1..104beb7c 100644 --- a/tests/RequestDataIdentificationTest.php +++ b/tests/RequestDataIdentificationTest.php @@ -3,6 +3,7 @@ declare(strict_types=1); use Illuminate\Support\Facades\Route; +use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException; use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData; use Stancl\Tenancy\Tests\Etc\Tenant; @@ -13,19 +14,16 @@ beforeEach(function () { ], ]); - Route::middleware(InitializeTenancyByRequestData::class)->get('/test', function () { + InitializeTenancyByRequestData::$header = 'X-Tenant'; + InitializeTenancyByRequestData::$cookie = 'X-Tenant'; + InitializeTenancyByRequestData::$queryParameter = 'tenant'; + + Route::middleware(['tenant', InitializeTenancyByRequestData::class])->get('/test', function () { return 'Tenant id: ' . tenant('id'); }); }); -afterEach(function () { - InitializeTenancyByRequestData::$header = 'X-Tenant'; - InitializeTenancyByRequestData::$cookie = 'X-Tenant'; - InitializeTenancyByRequestData::$queryParameter = 'tenant'; -}); - test('header identification works', function () { - InitializeTenancyByRequestData::$header = 'X-Tenant'; $tenant = Tenant::create(); $this @@ -36,8 +34,6 @@ test('header identification works', function () { }); test('query parameter identification works', function () { - InitializeTenancyByRequestData::$queryParameter = 'tenant'; - $tenant = Tenant::create(); $this @@ -47,12 +43,16 @@ test('query parameter identification works', function () { }); test('cookie identification works', function () { - InitializeTenancyByRequestData::$cookie = 'X-Tenant'; $tenant = Tenant::create(); $this ->withoutExceptionHandling() ->withUnencryptedCookie('X-Tenant', $tenant->id) - ->get('test',) + ->get('test') ->assertSee($tenant->id); }); + +test('middleware throws exception when tenant data is not provided in the request', function () { + pest()->expectException(TenantCouldNotBeIdentifiedByRequestDataException::class); + $this->withoutExceptionHandling()->get('test'); +}); diff --git a/tests/ResourceSyncingTest.php b/tests/ResourceSyncingTest.php index a988178e..322645dd 100644 --- a/tests/ResourceSyncingTest.php +++ b/tests/ResourceSyncingTest.php @@ -631,6 +631,8 @@ test('the listener can be queued', function () { Queue::assertPushed(CallQueuedListener::class, function (CallQueuedListener $job) { return $job->class === UpdateSyncedResource::class; }); + + UpdateSyncedResource::$shouldQueue = false; }); test('an event is fired for all touched resources', function () { diff --git a/tests/ResourceSyncingUsingPolymorphicTest.php b/tests/ResourceSyncingUsingPolymorphicTest.php index 408fd4ef..5af56ec3 100644 --- a/tests/ResourceSyncingUsingPolymorphicTest.php +++ b/tests/ResourceSyncingUsingPolymorphicTest.php @@ -44,6 +44,7 @@ beforeEach(function () { Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class); + // todo1 Is this cleanup needed? UpdateSyncedResource::$shouldQueue = false; // Global state cleanup Event::listen(SyncedResourceSaved::class, UpdateSyncedResource::class); @@ -395,4 +396,3 @@ class TenantCompanyUsingPolymorphic extends Model implements Syncable ]; } } - diff --git a/tests/RouteMiddlewareTest.php b/tests/RouteMiddlewareTest.php new file mode 100644 index 00000000..9d894dc5 --- /dev/null +++ b/tests/RouteMiddlewareTest.php @@ -0,0 +1,87 @@ +pushMiddleware($kernelMiddleware = InitializeTenancyByRequestData::class); + Route::middlewareGroup('additional', [AdditionalMiddleware::class, $duplicateMiddleware = InitializeTenancyByDomain::class]); + Route::middlewareGroup('tenant', [$duplicateMiddleware, 'additional']); + Route::middlewareGroup('middleware', ['tenant']); + + $route = Route::get('/testing-route', function () { + return 'testing route'; + })->middleware([PreventAccessFromUnwantedDomains::class, 'middleware']); + + $expectedRouteMiddleware = [PreventAccessFromUnwantedDomains::class, AdditionalMiddleware::class, InitializeTenancyByDomain::class]; + + $routeMiddleware = tenancy()->getRouteMiddleware($route); + + expect($routeMiddleware)->toContain(...$expectedRouteMiddleware); + + // Assert that there's no duplicate middleware + expect(array_filter($routeMiddleware, fn ($middleware) => $middleware === $duplicateMiddleware)) + ->toContain($duplicateMiddleware)->toHaveCount(1); + + expect($routeMiddleware)->not()->toContain($kernelMiddleware); +}); + +test('tenancy detects presence of route middleware correctly', function (string $identificationMiddleware) { + // Kernel middleware should get ignored + app(Kernel::class)->pushMiddleware(InitializeTenancyByRequestData::class); + + // The 'second-level' group has the identification middleware + // The 'surface' group has a 'first-level' group, and that group has a 'second-level' group (three middleware group layers) + // Test that the identification middleware is detected even when packed in a middleware group three layers deep + Route::middlewareGroup($middlewareGroup = 'surface', ['first-level']); + Route::middlewareGroup('first-level', ['second-level']); + Route::middlewareGroup('second-level', [$identificationMiddleware]); + + $routeWithIdentificationMiddleware = Route::get('/tenant-route', function () { + return 'tenant route'; + })->middleware($middlewareGroup); + + $route = Route::get('/central-route', function () { + return 'central route'; + }); + + expect(tenancy()->routeHasMiddleware($routeWithIdentificationMiddleware, $identificationMiddleware))->toBeTrue(); + expect(tenancy()->routeHasMiddleware($route, $identificationMiddleware))->toBeFalse(); + + // Look specifically for identification middleware + expect(tenancy()->routeHasIdentificationMiddleware($routeWithIdentificationMiddleware))->toBeTrue(); + expect(tenancy()->routeHasIdentificationMiddleware($route))->toBeFalse(); +})->with([ + InitializeTenancyByPath::class, + InitializeTenancyByRequestData::class, + InitializeTenancyByDomain::class, + InitializeTenancyBySubdomain::class, + InitializeTenancyByDomainOrSubdomain::class, +]); + +test('domain identification middleware is configurable', function() { + $route = Route::get('/welcome-route', fn () => 'welcome')->middleware([InitializeTenancyByDomain::class]); + + config(['tenancy.identification.domain_identification_middleware' => []]); + + expect(tenancy()->routeHasDomainIdentificationMiddleware($route))->toBeFalse(); + + // Set domain identification middleware list back to default + config(['tenancy.identification.domain_identification_middleware' => [ + InitializeTenancyByDomain::class, + InitializeTenancyBySubdomain::class, + InitializeTenancyByDomainOrSubdomain::class, + ]]); + + expect(tenancy()->routeHasDomainIdentificationMiddleware($route))->toBeTrue(); +}); diff --git a/tests/TenantDatabaseManagerTest.php b/tests/TenantDatabaseManagerTest.php index c776d7a1..03718c66 100644 --- a/tests/TenantDatabaseManagerTest.php +++ b/tests/TenantDatabaseManagerTest.php @@ -26,6 +26,10 @@ use Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLSchemaManager; use Stancl\Tenancy\Database\TenantDatabaseManagers\SQLiteDatabaseManager; use Stancl\Tenancy\Tests\Etc\Tenant; +beforeEach(function () { + SQLiteDatabaseManager::$path = null; +}); + test('databases can be created and deleted', function ($driver, $databaseManager) { Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) { return $event->tenant; @@ -388,6 +392,8 @@ test('path used by sqlite manager can be customized', function () { ]); expect(file_exists($customPath . '/' . $name))->toBeTrue(); + + SQLiteDatabaseManager::$path = null; }); test('the tenant connection template can be specified either by name or as a connection array', function () { diff --git a/tests/TestCase.php b/tests/TestCase.php index 36d5fc9f..64581c04 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -6,17 +6,20 @@ namespace Stancl\Tenancy\Tests; use PDO; use Dotenv\Dotenv; -use Stancl\Tenancy\Facades\Tenancy; +use Stancl\Tenancy\Tenancy; use Stancl\Tenancy\Tests\Etc\Tenant; use Illuminate\Support\Facades\Redis; -use Stancl\Tenancy\Bootstrappers\PrefixCacheTenancyBootstrapper; use Illuminate\Foundation\Application; use Stancl\Tenancy\Facades\GlobalCache; use Stancl\Tenancy\TenancyServiceProvider; -use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper; -use Stancl\Tenancy\Bootstrappers\BroadcastTenancyBootstrapper; +use Stancl\Tenancy\Facades\Tenancy as TenancyFacade; use Stancl\Tenancy\Bootstrappers\UrlTenancyBootstrapper; use Stancl\Tenancy\Bootstrappers\MailTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\BroadcastTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper; +use Stancl\Tenancy\Bootstrappers\PrefixCacheTenancyBootstrapper; abstract class TestCase extends \Orchestra\Testbench\TestCase { @@ -106,10 +109,11 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase '--realpath' => true, '--force' => true, ], - 'tenancy.bootstrappers.redis' => RedisTenancyBootstrapper::class, // todo1 change this to []? two tests in TenantDatabaseManagerTest are failing with that - 'tenancy.bootstrappers.broadcast' => BroadcastTenancyBootstrapper::class, // todo1 change this to []? two tests in TenantDatabaseManagerTest are failing with that - 'tenancy.bootstrappers.mail' => MailTenancyBootstrapper::class, - 'tenancy.bootstrappers.url' => UrlTenancyBootstrapper::class, + 'tenancy.bootstrappers' => [ + DatabaseTenancyBootstrapper::class, + FilesystemTenancyBootstrapper::class, + UrlTenancyBootstrapper::class, + ], 'queue.connections.central' => [ 'driver' => 'sync', 'central' => true, @@ -135,7 +139,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase protected function getPackageAliases($app) { return [ - 'Tenancy' => Tenancy::class, + 'Tenancy' => TenancyFacade::class, 'GlobalCache' => GlobalCache::class, ]; } diff --git a/tests/UniversalRouteTest.php b/tests/UniversalRouteTest.php index d520e580..94db6db8 100644 --- a/tests/UniversalRouteTest.php +++ b/tests/UniversalRouteTest.php @@ -2,119 +2,532 @@ declare(strict_types=1); -use Illuminate\Support\Facades\Route; -use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException; -use Stancl\Tenancy\Middleware\InitializeTenancyByDomain; -use Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains; +use Stancl\Tenancy\Tenancy; +use Illuminate\Http\Request; +use Illuminate\Routing\Route; use Stancl\Tenancy\Tests\Etc\Tenant; use Illuminate\Contracts\Http\Kernel; +use Stancl\Tenancy\Resolvers\PathTenantResolver; +use Illuminate\Routing\Controller as BaseController; +use Illuminate\Support\Facades\Route as RouteFacade; +use Stancl\Tenancy\Actions\CloneRoutesAsTenant; +use Stancl\Tenancy\Middleware\InitializeTenancyByPath; +use Stancl\Tenancy\Middleware\IdentificationMiddleware; +use Stancl\Tenancy\Resolvers\RequestDataTenantResolver; +use Stancl\Tenancy\Middleware\InitializeTenancyByDomain; +use Stancl\Tenancy\Concerns\UsableWithEarlyIdentification; +use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain; +use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData; +use Stancl\Tenancy\Middleware\PreventAccessFromUnwantedDomains; +use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain; +use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException; +use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException; +use Stancl\Tenancy\Exceptions\MiddlewareNotUsableWithUniversalRoutesException; +use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByRequestDataException; +use Stancl\Tenancy\RouteMode; -test('a route can work in both central and tenant context', function (array $routeMiddleware, string|null $globalMiddleware) { - if ($globalMiddleware) { - app(Kernel::class)->pushMiddleware($globalMiddleware); +test('a route can be universal using domain identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + // Instead of a global 'universal' MW, we use the default_route_mode config key to make routes universal by default + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } } - Route::middlewareGroup('universal', []); - - Route::get('/foo', function () { + RouteFacade::get('/foo', function () { return tenancy()->initialized ? 'Tenancy is initialized.' : 'Tenancy is not initialized.'; })->middleware($routeMiddleware); - $tenant = Tenant::create([ - 'id' => 'acme', - ]); + $tenant = Tenant::create(); + $tenant->domains()->create([ - 'domain' => 'acme.localhost', + 'domain' => $tenantDomain = $tenant->getTenantKey() . '.localhost', ]); pest()->get("http://localhost/foo") ->assertSuccessful() ->assertSee('Tenancy is not initialized.'); - pest()->get("http://acme.localhost/foo") + pest()->get("http://{$tenantDomain}/foo") ->assertSuccessful() ->assertSee('Tenancy is initialized.'); -})->with('identification types'); +})->with('domain identification types'); -test('making one route universal doesnt make all routes universal', function (array $routeMiddleware, string|null $globalMiddleware) { - if ($globalMiddleware) { - app(Kernel::class)->pushMiddleware($globalMiddleware); +test('a route can be universal using subdomain identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } } - Route::middlewareGroup('universal', []); + RouteFacade::get('/foo', function () { + return tenancy()->initialized + ? 'Tenancy is initialized.' + : 'Tenancy is not initialized.'; + })->middleware($routeMiddleware); - Route::middleware($routeMiddleware)->group(function () { - Route::get('/nonuniversal', function () { - return tenant('id'); - }); + $tenant = Tenant::create(); + $tenantKey = $tenant->getTenantKey(); - Route::get('/universal', function () { - return tenancy()->initialized - ? 'Tenancy is initialized.' - : 'Tenancy is not initialized.'; - })->middleware('universal'); - }); - - $tenant = Tenant::create([ - 'id' => 'acme', - ]); $tenant->domains()->create([ - 'domain' => 'acme.localhost', + 'domain' => $tenantKey, ]); - pest()->get("http://localhost/universal") + pest()->get("http://localhost/foo") ->assertSuccessful() ->assertSee('Tenancy is not initialized.'); - pest()->get("http://acme.localhost/universal") + pest()->get("http://{$tenantKey}.localhost/foo") + ->assertSuccessful() + ->assertSee('Tenancy is initialized.'); +})->with('subdomain identification types'); + +test('a route can be universal using domainOrSubdomain identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } + } + + RouteFacade::get('/foo', function () { + return tenancy()->initialized + ? 'Tenancy is initialized.' + : 'Tenancy is not initialized.'; + })->middleware($routeMiddleware); + + $tenant = Tenant::create(); + + $tenant->domains()->create([ + 'domain' => $tenantDomain = 'tenant-domain.test', + ]); + + $tenant->domains()->create([ + 'domain' => $tenantSubdomain = 'tenant-subdomain', + ]); + + pest()->get("http://localhost/foo") + ->assertSuccessful() + ->assertSee('Tenancy is not initialized.'); + + // Domain identification + pest()->get("http://{$tenantDomain}/foo") ->assertSuccessful() ->assertSee('Tenancy is initialized.'); - tenancy()->end(); - - pest()->get('http://localhost/nonuniversal') - ->assertStatus(404); - - pest()->get('http://acme.localhost/nonuniversal') + // Subdomain identification + pest()->get("http://{$tenantSubdomain}.localhost/foo") ->assertSuccessful() - ->assertSee('acme'); -})->with([ - 'early identification' => [ - 'route_middleware' => [PreventAccessFromUnwantedDomains::class], - 'global_middleware' => InitializeTenancyByDomain::class, - ], - 'route-level identification' => [ - 'route_middleware' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class], - 'global_middleware' => null, - ] -]); + ->assertSee('Tenancy is initialized.'); +})->with('domainOrSubdomain identification types'); -test('it throws correct exception when route is universal and tenant does not exist', function (array $routeMiddleware, string|null $globalMiddleware) { - if ($globalMiddleware) { - app(Kernel::class)->pushMiddleware($globalMiddleware); +test('a route can be universal using request data identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } } - Route::middlewareGroup('universal', []); + RouteFacade::get('/foo', function () { + return tenancy()->initialized + ? 'Tenancy is initialized.' + : 'Tenancy is not initialized.'; + })->middleware($routeMiddleware); - Route::get('/foo', function () { + $tenantKey = Tenant::create()->getTenantKey(); + + pest()->get("http://localhost/foo") + ->assertSuccessful() + ->assertSee('Tenancy is not initialized.'); + + pest()->get("http://localhost/foo?tenant={$tenantKey}") + ->assertSuccessful() + ->assertSee('Tenancy is initialized.'); +})->with('request data identification types'); + +test('a route can be universal using path identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } + } + + RouteFacade::get('/foo', function () { + return tenancy()->initialized + ? 'Tenancy is initialized.' + : 'Tenancy is not initialized.'; + })->middleware($routeMiddleware); + + /** @var CloneRoutesAsTenant $reregisterRoutesAction */ + $reregisterRoutesAction = app(CloneRoutesAsTenant::class); + + $reregisterRoutesAction->handle(); + + $tenantKey = Tenant::create()->getTenantKey(); + + pest()->get("http://localhost/foo") + ->assertSuccessful() + ->assertSee('Tenancy is not initialized.'); + + pest()->get("http://localhost/{$tenantKey}/foo") + ->assertSuccessful() + ->assertSee('Tenancy is initialized.'); +})->with('path identification types'); + +test('correct exception is thrown when route is universal and tenant could not be identified using domain identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } + } + + RouteFacade::get('/foo', function () { return tenancy()->initialized ? 'Tenancy is initialized.' : 'Tenancy is not initialized.'; })->middleware($routeMiddleware); pest()->expectException(TenantCouldNotBeIdentifiedOnDomainException::class); - $this->withoutExceptionHandling()->get('http://acme.localhost/foo'); -})->with('identification types'); + $this->withoutExceptionHandling()->get('http://nonexistent_domain.localhost/foo'); +})->with('domain identification types'); -dataset('identification types', [ - 'early identification' => [ - 'route_middleware' => ['universal', PreventAccessFromUnwantedDomains::class], - 'global_middleware' => InitializeTenancyByDomain::class, - ], - 'route-level identification' => [ - 'route_middleware' => ['universal', PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class], - 'global_middleware' => null, - ] +test('correct exception is thrown when route is universal and tenant could not be identified using subdomain identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } + } + + RouteFacade::get('/foo', function () { + return tenancy()->initialized + ? 'Tenancy is initialized.' + : 'Tenancy is not initialized.'; + })->middleware($routeMiddleware); + + pest()->expectException(TenantCouldNotBeIdentifiedOnDomainException::class); + $this->withoutExceptionHandling()->get('http://nonexistent_subdomain.localhost/foo'); +})->with('subdomain identification types'); + +test('correct exception is thrown when route is universal and tenant could not be identified using path identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } + } + + RouteFacade::get('/foo', fn () => tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.')->middleware($routeMiddleware)->name('foo'); + + /** @var CloneRoutesAsTenant $reregisterRoutesAction */ + $reregisterRoutesAction = app(CloneRoutesAsTenant::class); + + $reregisterRoutesAction->handle(); + + pest()->expectException(TenantCouldNotBeIdentifiedByPathException::class); + $this->withoutExceptionHandling()->get('http://localhost/non_existent/foo'); +})->with('path identification types'); + +test('correct exception is thrown when route is universal and tenant could not be identified using request data identification', function (array $routeMiddleware, array $globalMiddleware) { + foreach ($globalMiddleware as $middleware) { + if ($middleware === 'universal') { + config(['tenancy.default_route_mode' => RouteMode::UNIVERSAL]); + } else { + app(Kernel::class)->pushMiddleware($middleware); + } + } + + RouteFacade::get('/foo', function () { + return tenancy()->initialized + ? 'Tenancy is initialized.' + : 'Tenancy is not initialized.'; + })->middleware($routeMiddleware); + + pest()->expectException(TenantCouldNotBeIdentifiedByRequestDataException::class); + $this->withoutExceptionHandling()->get('http://localhost/foo?tenant=nonexistent_tenant'); +})->with('request data identification types'); + +test('tenant and central flags override the universal flag', function () { + app(Kernel::class)->pushMiddleware(InitializeTenancyByRequestData::class); + $tenant = Tenant::create(); + + $route = RouteFacade::get('/route', fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware('universal'); + + // Route is universal + pest()->get('/route')->assertOk()->assertSee('Tenancy not initialized.'); + pest()->get('/route?tenant=' . $tenant->getTenantKey())->assertOk()->assertSee('Tenancy initialized.'); + tenancy()->end(); + + // Route is in tenant context + $route->action['middleware'] = ['universal', 'tenant']; + + pest()->get('/route')->assertServerError(); // "Tenant could not be identified by request data with payload..." + pest()->get('/route?tenant=' . $tenant->getTenantKey())->assertOk()->assertSee('Tenancy initialized.'); + tenancy()->end(); + + // Route is in central context + $route->action['middleware'] = ['universal', 'central']; + + pest()->get('/route')->assertOk()->assertSee('Tenancy not initialized.'); + pest()->get('/route?tenant=' . $tenant->getTenantKey())->assertOk()->assertSee('Tenancy not initialized.'); // Route is accessible, but the context is central +}); + +test('a route can be flagged as universal in both route modes', function (RouteMode $defaultRouteMode) { + app(Kernel::class)->pushMiddleware(InitializeTenancyBySubdomain::class); + app(Kernel::class)->pushMiddleware(PreventAccessFromUnwantedDomains::class); + + config(['tenancy.default_route_mode' => $defaultRouteMode]); + + RouteFacade::get('/universal', fn () => tenant() ? 'Tenancy is initialized.' : 'Tenancy is not initialized.')->middleware('universal'); + + Tenant::create()->domains()->create(['domain' => $tenantSubdomain = 'tenant-subdomain']); + + pest()->get("http://localhost/universal") + ->assertSuccessful() + ->assertSee('Tenancy is not initialized.'); + + pest()->get("http://{$tenantSubdomain}.localhost/universal") + ->assertSuccessful() + ->assertSee('Tenancy is initialized.'); +})->with([ + 'default to tenant routes' => RouteMode::TENANT, + 'default to central routes' => RouteMode::CENTRAL, ]); + +test('ReregisterRoutesAsTenant registers prefixed duplicates of universal routes correctly', function (bool $kernelIdentification, bool $useController) { + $routeMiddleware = ['universal']; + + if ($kernelIdentification) { + app(Kernel::class)->pushMiddleware(InitializeTenancyByPath::class); + } else { + $routeMiddleware[] = InitializeTenancyByPath::class; + } + + config(['tenancy.identification.resolvers.' . PathTenantResolver::class . '.tenant_parameter_name' => $tenantParameterName = 'team']); + config(['tenancy.identification.resolvers.' . PathTenantResolver::class . '.tenant_route_name_prefix' => $tenantRouteNamePrefix = 'team-route.']); + + // Test that routes with controllers as well as routes with closure actions get re-registered correctly + $universalRoute = RouteFacade::get('/home', $useController ? Controller::class : fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware($routeMiddleware)->name('home'); + $centralRoute = RouteFacade::get('/central', fn () => true)->name('central'); + + expect($routes = RouteFacade::getRoutes()->get())->toContain($universalRoute); + expect($routes)->toContain($centralRoute); + + /** @var CloneRoutesAsTenant $reregisterRoutesAction */ + $reregisterRoutesAction = app(CloneRoutesAsTenant::class); + + $reregisterRoutesAction->handle(); + + expect($routesAfterRegisteringDuplicates = RouteFacade::getRoutes()->get()) + ->toContain($universalRoute) + ->toContain($centralRoute); + + $newRoute = collect($routesAfterRegisteringDuplicates)->filter(fn ($route) => ! in_array($route, $routes))->first(); + + expect($newRoute->uri())->toBe('{' . $tenantParameterName . '}' . '/' . $universalRoute->uri()); + expect(tenancy()->getRouteMiddleware($newRoute))->toBe(array_merge(tenancy()->getRouteMiddleware($universalRoute), ['tenant'])); + + $tenant = Tenant::create(); + + pest()->get(route($centralRouteName = $universalRoute->getName()))->assertSee('Tenancy not initialized.'); + pest()->get(route($tenantRouteName = $newRoute->getName(), [$tenantParameterName => $tenant->getTenantKey()]))->assertSee('Tenancy initialized.'); + + expect($tenantRouteName)->toBe($tenantRouteNamePrefix . $universalRoute->getName()); + expect($centralRouteName)->toBe($universalRoute->getName()); +})->with([ + 'kernel identification' => true, + 'route-level identification' => false, +// Creates a matrix (multiple with()) +])->with([ + 'use controller' => true, + 'use closure' => false +]); + +test('tenant resolver methods return the correct names for configured values', function (string $configurableParameter, string $value) { + $configurableParameterConfigKey = 'tenancy.identification.resolvers.' . PathTenantResolver::class . '.' . $configurableParameter; + + config([$configurableParameterConfigKey => $value]); + + // Note: The names of the methods are NOT dynamic (PathTenantResolver::tenantParameterName(), PathTenantResolver::tenantRouteNamePrefix()) + $resolverMethodName = str($configurableParameter)->camel()->toString(); + + expect(PathTenantResolver::$resolverMethodName())->toBe($value); +})->with([ + ['tenant_parameter_name', 'parameter'], + ['tenant_route_name_prefix', 'prefix'] +]); + +test('ReregisterRoutesAsTenant only re-registers routes with path identification by default', function () { + app(Kernel::class)->pushMiddleware(InitializeTenancyByPath::class); + + $currentRouteCount = fn () => count(RouteFacade::getRoutes()->get()); + + $initialRouteCount = $currentRouteCount(); + + // Path identification is used globally, and this route doesn't use a specific identification middleware, meaning path identification is used and the route should get re-registered + RouteFacade::get('/home', fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware('universal')->name('home'); + // The route uses a specific identification middleware other than InitializeTenancyByPath – the route shouldn't get re-registered + RouteFacade::get('/home-domain-id', fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware(['universal', InitializeTenancyByDomain::class])->name('home-domain-id'); + + expect($currentRouteCount())->toBe($newRouteCount = $initialRouteCount + 2); + + /** @var CloneRoutesAsTenant $reregisterRoutesAction */ + $reregisterRoutesAction = app(CloneRoutesAsTenant::class); + + $reregisterRoutesAction->handle(); + + // Only one of the two routes gets re-registered + expect($currentRouteCount())->toBe($newRouteCount + 1); +}); + +test('custom callbacks can be used for reregistering universal routes', function () { + RouteFacade::get('/home', fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware('universal')->name($routeName = 'home'); + + /** @var CloneRoutesAsTenant $reregisterRoutesAction */ + $reregisterRoutesAction = app(CloneRoutesAsTenant::class); + $currentRouteCount = fn () => count(RouteFacade::getRoutes()->get()); + $initialRouteCount = $currentRouteCount(); + + // Skip re-registering the 'home' route + $reregisterRoutesAction->cloneUsing($routeName, function (Route $route) { + return; + })->handle(); + + // Expect route count to stay the same because the 'home' route re-registration gets skipped + expect($initialRouteCount)->toEqual($currentRouteCount()); + + // Modify the 'home' route re-registration so that a different route is registered + $reregisterRoutesAction->cloneUsing($routeName, function (Route $route) { + RouteFacade::get('/newly-registered-route', fn() => true)->name('new.home'); + })->handle(); + + expect($currentRouteCount())->toEqual($initialRouteCount + 1); +}); + +test('reregistration of specific routes can get skipped', function () { + RouteFacade::get('/home', fn () => tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.')->middleware('universal')->name($routeName = 'home'); + + /** @var CloneRoutesAsTenant $reregisterRoutesAction */ + $reregisterRoutesAction = app(CloneRoutesAsTenant::class); + $currentRouteCount = fn () => count(RouteFacade::getRoutes()->get()); + $initialRouteCount = $currentRouteCount(); + + // Skip re-registering the 'home' route + $reregisterRoutesAction->skipRoute($routeName)->handle(); + + // Expect route count to stay the same because the 'home' route re-registration gets skipped + expect($initialRouteCount)->toEqual($currentRouteCount()); +}); + + +test('identification middleware works with universal routes only when it implements MiddlewareUsableWithUniversalRoutes', function () { + $tenantKey = Tenant::create()->getTenantKey(); + $routeAction = fn () => tenancy()->initialized ? $tenantKey : 'Tenancy is not initialized.'; + + // Route with the package's request data identification middleware – implements MiddlewareUsableWithUniversalRoutes + RouteFacade::get('/universal-route', $routeAction)->middleware(['universal', InitializeTenancyByRequestData::class]); + + // Routes with custom request data identification middleware – does not implement MiddlewareUsableWithUniversalRoutes + RouteFacade::get('/custom-mw-universal-route', $routeAction)->middleware(['universal', CustomMiddleware::class]); + RouteFacade::get('/custom-mw-tenant-route', $routeAction)->middleware(['tenant', CustomMiddleware::class]); + + // Ensure the custom identification middleware works with non-universal routes + // This is tested here because this is the only test where the custom MW is used + // No exception is thrown for this request since the route uses the TENANT middleware, not the UNIVERSAL middleware + pest()->get('http://localhost/custom-mw-tenant-route?tenant=' . $tenantKey)->assertOk()->assertSee($tenantKey); + + pest()->get('http://localhost/universal-route')->assertOk(); + pest()->get('http://localhost/universal-route?tenant=' . $tenantKey)->assertOk()->assertSee($tenantKey); + + pest()->expectException(MiddlewareNotUsableWithUniversalRoutesException::class); + $this->withoutExceptionHandling()->get('http://localhost/custom-mw-universal-route'); +}); + +foreach ([ + 'domain identification types' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomain::class], + 'subdomain identification types' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyBySubdomain::class], + 'domainOrSubdomain identification types' => [PreventAccessFromUnwantedDomains::class, InitializeTenancyByDomainOrSubdomain::class], + 'path identification types' => [InitializeTenancyByPath::class], + 'request data identification types' => [InitializeTenancyByRequestData::class], +] as $datasetName => $middleware) { + dataset($datasetName, [ + 'kernel identification' => [ + 'route_middleware' => ['universal'], + 'global_middleware' => $middleware, + ], + 'route-level identification' => [ + 'route_middleware' => ['universal', ...$middleware], + 'global_middleware' => [], + ], + 'kernel identification + defaulting to universal routes' => [ + 'route_middleware' => [], + 'global_middleware' => ['universal', ...$middleware], + ], + 'route-level identification + defaulting to universal routes' => [ + 'route_middleware' => $middleware, + 'global_middleware' => ['universal'], + ], + ]); +} + +class Controller extends BaseController +{ + public function __invoke() + { + return tenant() ? 'Tenancy initialized.' : 'Tenancy not initialized.'; + } +} + +class CustomMiddleware extends IdentificationMiddleware +{ + use UsableWithEarlyIdentification; + + public static string $header = 'X-Tenant'; + public static string $cookie = 'X-Tenant'; + public static string $queryParameter = 'tenant'; + + public function __construct( + protected Tenancy $tenancy, + protected RequestDataTenantResolver $resolver, + ) { + } + + /** @return \Illuminate\Http\Response|mixed */ + public function handle(Request $request, Closure $next): mixed + { + if ($this->shouldBeSkipped(tenancy()->getRoute($request))) { + // Allow accessing central route in kernel identification + return $next($request); + } + + return $this->initializeTenancy($request, $next, $this->getPayload($request)); + } + + protected function getPayload(Request $request): string|array|null + { + if (static::$header && $request->hasHeader(static::$header)) { + return $request->header(static::$header); + } elseif (static::$queryParameter && $request->has(static::$queryParameter)) { + return $request->get(static::$queryParameter); + } elseif (static::$cookie && $request->hasCookie(static::$cookie)) { + return $request->cookie(static::$cookie); + } + + return null; + } +}