From f9799ab8bc5d792f7a4b802637a84ec4c5758de4 Mon Sep 17 00:00:00 2001 From: Nolan Ehrstrom Date: Wed, 18 Nov 2026 09:47:41 -0800 Subject: [PATCH 1/3] fix: keep Octane TrustHosts from narrowing to the last tenant Under multitenancy, SwitchTenant rewrites app.url per request. TrustHosts was deriving trusted hosts from that value, so FrankenPHP workers rejected later tenant Host headers with SuspiciousOperationException. Co-authored-by: Cursor --- ProcessMaker/Http/Middleware/TrustHosts.php | 41 +++++- ProcessMaker/Multitenancy/Tenant.php | 6 + .../Multitenancy/TenantDomainCache.php | 77 +++++++++++ config/cache.php | 8 ++ .../Http/Middleware/TrustHostsTest.php | 56 +++++++- .../Multitenancy/TenantDomainCacheTest.php | 120 ++++++++++++++++++ 6 files changed, 298 insertions(+), 10 deletions(-) create mode 100644 ProcessMaker/Multitenancy/TenantDomainCache.php create mode 100644 tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php 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..475dd54bdd --- /dev/null +++ b/ProcessMaker/Multitenancy/TenantDomainCache.php @@ -0,0 +1,77 @@ + tenant id map for TrustHosts (and future resolve). + * + * @return array + */ + public static function map(): array + { + if (!config('app.multitenancy')) { + return []; + } + + try { + return self::store()->remember(self::CACHE_KEY, self::TTL_SECONDS, function () { + return self::loadFromDatabase(); + }); + } catch (Throwable $e) { + report($e); + + return self::loadFromDatabase(); + } + } + + /** + * @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 + */ + private static function loadFromDatabase(): array + { + try { + return Tenant::query() + ->whereNotNull('domain') + ->where('domain', '!=', '') + ->pluck('id', 'domain') + ->map(fn ($id) => (int) $id) + ->all(); + } catch (QueryException $e) { + return []; + } + } + + 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..0a208ec483 --- /dev/null +++ b/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php @@ -0,0 +1,120 @@ + 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) + ); + } + + 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(); + }); + } +} From c542787771e8e592b586f86bd9e9935caf2e4658 Mon Sep 17 00:00:00 2001 From: Nolan Ehrstrom Date: Wed, 18 Nov 2026 11:40:26 -0800 Subject: [PATCH 2/3] Fix tenant domain cache --- .../Multitenancy/TenantDomainCache.php | 40 ++++++++++++------- .../Multitenancy/TenantDomainCacheTest.php | 16 ++++++++ 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/ProcessMaker/Multitenancy/TenantDomainCache.php b/ProcessMaker/Multitenancy/TenantDomainCache.php index 475dd54bdd..3d1e7941c5 100644 --- a/ProcessMaker/Multitenancy/TenantDomainCache.php +++ b/ProcessMaker/Multitenancy/TenantDomainCache.php @@ -26,14 +26,30 @@ public static function map(): array } try { - return self::store()->remember(self::CACHE_KEY, self::TTL_SECONDS, function () { - return self::loadFromDatabase(); - }); + $cached = self::store()->get(self::CACHE_KEY); + if (is_array($cached)) { + return $cached; + } } catch (Throwable $e) { report($e); + } + + try { + $map = self::loadFromDatabase(); + } catch (QueryException $e) { + // Transient landlord DB failure — do not cache an empty map. + report($e); + + return []; + } - return self::loadFromDatabase(); + try { + self::store()->put(self::CACHE_KEY, $map, self::TTL_SECONDS); + } catch (Throwable $e) { + report($e); } + + return $map; } /** @@ -58,16 +74,12 @@ public static function forget(): void */ private static function loadFromDatabase(): array { - try { - return Tenant::query() - ->whereNotNull('domain') - ->where('domain', '!=', '') - ->pluck('id', 'domain') - ->map(fn ($id) => (int) $id) - ->all(); - } catch (QueryException $e) { - return []; - } + return Tenant::query() + ->whereNotNull('domain') + ->where('domain', '!=', '') + ->pluck('id', 'domain') + ->map(fn ($id) => (int) $id) + ->all(); } private static function store() diff --git a/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php b/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php index 0a208ec483..b3860b686c 100644 --- a/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php +++ b/tests/unit/ProcessMaker/Multitenancy/TenantDomainCacheTest.php @@ -6,6 +6,7 @@ use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; use ProcessMaker\Multitenancy\Tenant; use ProcessMaker\Multitenancy\TenantDomainCache; @@ -100,6 +101,21 @@ public function test_saving_a_tenant_forgets_the_cache(): void ); } + 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')) { From 76fe361e006b43610f63deb2cf6aef53b2931693 Mon Sep 17 00:00:00 2001 From: Nolan Ehrstrom Date: Wed, 18 Nov 2026 13:03:28 -0800 Subject: [PATCH 3/3] Reduce TenantDomainCache::map returns for Sonar php:S1142. Co-authored-by: Cursor --- .../Multitenancy/TenantDomainCache.php | 52 ++++++++++++------- 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/ProcessMaker/Multitenancy/TenantDomainCache.php b/ProcessMaker/Multitenancy/TenantDomainCache.php index 3d1e7941c5..bfbb5bca85 100644 --- a/ProcessMaker/Multitenancy/TenantDomainCache.php +++ b/ProcessMaker/Multitenancy/TenantDomainCache.php @@ -25,6 +25,31 @@ public static function map(): array 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)) { @@ -34,10 +59,18 @@ public static function map(): array 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. + // Transient landlord DB failure: do not cache an empty map. report($e); return []; @@ -52,23 +85,6 @@ public static function map(): array return $map; } - /** - * @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 */