Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 35 additions & 6 deletions ProcessMaker/Http/Middleware/TrustHosts.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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,
]);
Expand All @@ -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.
Expand All @@ -67,4 +96,4 @@ protected function hostIsValid(string $host, string $pattern): bool

return preg_match('/' . str_replace('/', '\/', $pattern) . '/i', $host) === 1;
}
}
}
6 changes: 6 additions & 0 deletions ProcessMaker/Multitenancy/Tenant.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
105 changes: 105 additions & 0 deletions ProcessMaker/Multitenancy/TenantDomainCache.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
<?php

namespace ProcessMaker\Multitenancy;

use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Cache;
use Throwable;

class TenantDomainCache
{
public const CACHE_KEY = 'multitenancy.tenant_domains';

public const TTL_SECONDS = 86400;

public const STORE = 'landlord';

/**
* Domain => tenant id map for TrustHosts (and future resolve).
*
* @return array<string, int>
*/
public static function map(): array
{
if (!config('app.multitenancy')) {
return [];
}

return self::cachedMap() ?? self::refreshMap();
}

/**
* @return list<string>
*/
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<string, int>|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<string, int>
*/
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<string, int>
*/
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);
}
}
8 changes: 8 additions & 0 deletions config/cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -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:',
],

],

/*
Expand Down
56 changes: 52 additions & 4 deletions tests/Feature/Http/Middleware/TrustHostsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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()
Expand Down Expand Up @@ -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());
}
}
}
Loading
Loading