diff --git a/ProcessMaker/Http/Middleware/TrustHosts.php b/ProcessMaker/Http/Middleware/TrustHosts.php index 0afcc7c242..64cce31bd4 100644 --- a/ProcessMaker/Http/Middleware/TrustHosts.php +++ b/ProcessMaker/Http/Middleware/TrustHosts.php @@ -3,28 +3,35 @@ namespace ProcessMaker\Http\Middleware; use Illuminate\Http\Middleware\TrustHosts as Middleware; -use Closure; use Illuminate\Http\Request; +use ProcessMaker\Multitenancy\SwitchTenant; +use ProcessMaker\Multitenancy\TenantDomainCache; class TrustHosts extends Middleware { public function hosts(): array { $hosts = array_filter([ - $this->allSubdomainsOfApplicationUrl(), + $this->applicationUrlPattern(), ]); + if (config('app.multitenancy')) { + foreach (TenantDomainCache::domains() as $domain) { + $hosts[] = $this->hostPattern($domain); + } + } + $trustedHostsEnv = config('app.trusted_hosts_links', ''); if ($trustedHostsEnv !== '') { foreach (array_filter(array_map('trim', explode(',', $trustedHostsEnv))) as $host) { if (str_contains($host, '://')) { $host = parse_url($host, PHP_URL_HOST) ?: $host; } - $hosts[] = '^(.+\.)?' . preg_quote($host) . '$'; + $hosts[] = $this->hostPattern($host); } } - return array_values($hosts); + return array_values(array_unique($hosts)); } public function handle(Request $request, $next) @@ -46,7 +53,7 @@ public function handle(Request $request, $next) } } - if (! $trusted) { + if (!$trusted) { \Log::warning('Rejected request with untrusted X-Forwarded-Host', [ 'forwarded_host' => $forwardedHost, ]); @@ -57,6 +64,28 @@ public function handle(Request $request, $next) return parent::handle($request, $next); } + /** + * Prefer the landlord APP_URL under multitenancy so Octane does not narrow + * trusted hosts to whichever tenant last called SwitchTenant. + */ + protected function applicationUrlPattern(): ?string + { + $url = config('app.url'); + + if (config('app.multitenancy') && SwitchTenant::$landlordValues) { + $url = SwitchTenant::$landlordValues['app']['url'] ?? $url; + } + + $host = parse_url((string) $url, PHP_URL_HOST); + + return $host ? $this->hostPattern($host) : null; + } + + protected function hostPattern(string $host): string + { + return '^(.+\.)?' . preg_quote($host) . '$'; + } + /** * Match a host against a trusted pattern using Symfony's getHost() rules: * lowercase and strip a trailing :port before comparing. @@ -67,4 +96,4 @@ protected function hostIsValid(string $host, string $pattern): bool return preg_match('/' . str_replace('/', '\/', $pattern) . '/i', $host) === 1; } -} \ No newline at end of file +} diff --git a/ProcessMaker/Multitenancy/Tenant.php b/ProcessMaker/Multitenancy/Tenant.php index 4b2b9f091a..2fc6e00c79 100644 --- a/ProcessMaker/Multitenancy/Tenant.php +++ b/ProcessMaker/Multitenancy/Tenant.php @@ -20,6 +20,12 @@ class Tenant extends SpatieTenant 'password' => 'encrypted', ]; + protected static function booted(): void + { + static::saved(fn () => TenantDomainCache::forget()); + static::deleted(fn () => TenantDomainCache::forget()); + } + public static function setBootstrappedTenant(Application $app, ?array $tenantData) { $app->instance(self::BOOTSTRAPPED_TENANT, $tenantData); diff --git a/ProcessMaker/Multitenancy/TenantDomainCache.php b/ProcessMaker/Multitenancy/TenantDomainCache.php new file mode 100644 index 0000000000..bfbb5bca85 --- /dev/null +++ b/ProcessMaker/Multitenancy/TenantDomainCache.php @@ -0,0 +1,105 @@ + tenant id map for TrustHosts (and future resolve). + * + * @return array + */ + public static function map(): array + { + if (!config('app.multitenancy')) { + return []; + } + + return self::cachedMap() ?? self::refreshMap(); + } + + /** + * @return list + */ + public static function domains(): array + { + return array_keys(self::map()); + } + + public static function forget(): void + { + try { + self::store()->forget(self::CACHE_KEY); + } catch (Throwable $e) { + report($e); + } + } + + /** + * @return array|null + */ + private static function cachedMap(): ?array + { + try { + $cached = self::store()->get(self::CACHE_KEY); + if (is_array($cached)) { + return $cached; + } + } catch (Throwable $e) { + report($e); + } + + return null; + } + + /** + * @return array + */ + private static function refreshMap(): array + { + try { + $map = self::loadFromDatabase(); + } catch (QueryException $e) { + // Transient landlord DB failure: do not cache an empty map. + report($e); + + return []; + } + + try { + self::store()->put(self::CACHE_KEY, $map, self::TTL_SECONDS); + } catch (Throwable $e) { + report($e); + } + + return $map; + } + + /** + * @return array + */ + private static function loadFromDatabase(): array + { + return Tenant::query() + ->whereNotNull('domain') + ->where('domain', '!=', '') + ->pluck('id', 'domain') + ->map(fn ($id) => (int) $id) + ->all(); + } + + private static function store() + { + return Cache::store(self::STORE); + } +} diff --git a/config/cache.php b/config/cache.php index e7333eb826..e9c96abc52 100644 --- a/config/cache.php +++ b/config/cache.php @@ -108,6 +108,14 @@ 'prefix' => env('CACHE_SETTING_PREFIX', 'settings:'), ], + // Fixed prefix so PrefixCacheTask tenant prefixes cannot hide this store. + 'landlord' => [ + 'driver' => env('CACHE_DRIVER', 'redis'), + 'connection' => 'default', + 'lock_connection' => 'default', + 'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_') . '_cache_') . 'landlord:', + ], + ], /* diff --git a/tests/Feature/Http/Middleware/TrustHostsTest.php b/tests/Feature/Http/Middleware/TrustHostsTest.php index 8e896191f3..051158437a 100644 --- a/tests/Feature/Http/Middleware/TrustHostsTest.php +++ b/tests/Feature/Http/Middleware/TrustHostsTest.php @@ -2,10 +2,13 @@ namespace Tests\Feature\Http\Middleware; -use Tests\TestCase; -use ProcessMaker\Http\Middleware\TrustHosts; use Illuminate\Http\Request; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Config; +use ProcessMaker\Http\Middleware\TrustHosts; +use ProcessMaker\Multitenancy\SwitchTenant; +use ProcessMaker\Multitenancy\TenantDomainCache; +use Tests\TestCase; class TrustHostsTest extends TestCase { @@ -15,6 +18,15 @@ protected function setUp(): void { parent::setUp(); $this->middleware = new TrustHosts($this->app); + SwitchTenant::$landlordValues = null; + TenantDomainCache::forget(); + } + + protected function tearDown(): void + { + SwitchTenant::$landlordValues = null; + TenantDomainCache::forget(); + parent::tearDown(); } public function test_valid_trusted_host() @@ -108,11 +120,47 @@ public function test_invalid_trusted_host_with_port_still_rejected() public function test_missing_forwarded_host() { $request = Request::create('https://example.processmaker.net'); - + + $response = $this->middleware->handle($request, function ($req) { + return response()->json(['status' => 'success']); + }); + + $this->assertEquals(200, $response->status()); + } + + public function test_multitenancy_trusts_cached_tenant_domains_after_app_url_switch() + { + Config::set('app.multitenancy', true); + Config::set('app.url', 'https://landlord.example.test'); + SwitchTenant::$landlordValues = [ + 'app' => ['url' => 'https://landlord.example.test'], + ]; + + Cache::store(TenantDomainCache::STORE)->put( + TenantDomainCache::CACHE_KEY, + [ + 'acme.example.test' => 1, + 'widgets.example.test' => 2, + ], + TenantDomainCache::TTL_SECONDS + ); + + // Simulate Octane after SwitchTenant narrowed config app.url to one tenant. + Config::set('app.url', 'https://acme.example.test'); + + $hosts = $this->middleware->hosts(); + + $this->assertContains('^(.+\.)?' . preg_quote('landlord.example.test') . '$', $hosts); + $this->assertContains('^(.+\.)?' . preg_quote('acme.example.test') . '$', $hosts); + $this->assertContains('^(.+\.)?' . preg_quote('widgets.example.test') . '$', $hosts); + + $request = Request::create('https://widgets.example.test'); + $request->headers->set('X-Forwarded-Host', 'widgets.example.test'); + $response = $this->middleware->handle($request, function ($req) { return response()->json(['status' => 'success']); }); $this->assertEquals(200, $response->status()); } -} \ No newline at end of file +} diff --git a/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php b/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php new file mode 100644 index 0000000000..b3860b686c --- /dev/null +++ b/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php @@ -0,0 +1,136 @@ + true, + // Reuse the test DB so landlord Tenant queries work in CI. + 'database.connections.landlord.database' => config('database.connections.processmaker.database'), + ]); + + $this->ensureTenantsTable(); + TenantDomainCache::forget(); + Tenant::query()->delete(); + } + + protected function tearDown(): void + { + TenantDomainCache::forget(); + parent::tearDown(); + } + + public function test_map_returns_empty_when_multitenancy_disabled(): void + { + config(['app.multitenancy' => false]); + + $this->assertSame([], TenantDomainCache::map()); + } + + public function test_map_caches_domain_to_id_and_forget_clears_it(): void + { + $first = Tenant::create([ + 'domain' => 'acme.example.test', + 'name' => 'Acme', + 'database' => 'tenant_acme_' . uniqid(), + 'config' => ['app.url' => 'https://acme.example.test'], + ]); + $second = Tenant::create([ + 'domain' => 'widgets.example.test', + 'name' => 'Widgets', + 'database' => 'tenant_widgets_' . uniqid(), + 'config' => ['app.url' => 'https://widgets.example.test'], + ]); + + // Creates clear the cache via model events; populate once. + $map = TenantDomainCache::map(); + + $this->assertSame([ + 'acme.example.test' => $first->id, + 'widgets.example.test' => $second->id, + ], $map); + $this->assertTrue( + Cache::store(TenantDomainCache::STORE)->has(TenantDomainCache::CACHE_KEY) + ); + + TenantDomainCache::forget(); + + $this->assertFalse( + Cache::store(TenantDomainCache::STORE)->has(TenantDomainCache::CACHE_KEY) + ); + } + + public function test_saving_a_tenant_forgets_the_cache(): void + { + Tenant::create([ + 'domain' => 'before.example.test', + 'name' => 'Before', + 'database' => 'tenant_before_' . uniqid(), + 'config' => ['app.url' => 'https://before.example.test'], + ]); + + TenantDomainCache::map(); + $this->assertTrue( + Cache::store(TenantDomainCache::STORE)->has(TenantDomainCache::CACHE_KEY) + ); + + Tenant::create([ + 'domain' => 'after.example.test', + 'name' => 'After', + 'database' => 'tenant_after_' . uniqid(), + 'config' => ['app.url' => 'https://after.example.test'], + ]); + + $this->assertFalse( + Cache::store(TenantDomainCache::STORE)->has(TenantDomainCache::CACHE_KEY) + ); + } + + public function test_map_does_not_cache_empty_result_when_database_query_fails(): void + { + config([ + 'database.connections.landlord.database' => 'nonexistent_landlord_' . uniqid(), + ]); + DB::purge('landlord'); + + $map = TenantDomainCache::map(); + + $this->assertSame([], $map); + $this->assertFalse( + Cache::store(TenantDomainCache::STORE)->has(TenantDomainCache::CACHE_KEY) + ); + } + + private function ensureTenantsTable(): void + { + if (Schema::connection('landlord')->hasTable('tenants')) { + return; + } + + Schema::connection('landlord')->create('tenants', function (Blueprint $table) { + $table->id(); + $table->string('name'); + $table->string('domain')->unique(); + $table->string('database')->unique(); + $table->string('username')->nullable(); + $table->text('password')->nullable(); + $table->json('config')->nullable(); + $table->timestamps(); + }); + } +}