coolify/app/Http/Middleware/TrustHosts.php
Andras Bacsai 5ce0670ca4 fix: ensure negative cache results are stored in TrustHosts middleware
Problem:
- Cache::remember() does not cache null return values
- When no FQDN was configured, the closure returned null
- This caused DB queries on every request, defeating the cache

Solution:
- Use empty string ('') as sentinel value instead of null
- Convert sentinel back to null after retrieving from cache
- Now both positive and negative results are cached properly

Changes:
- Return empty string from closure instead of null
- Add explicit sentinel-to-null conversion after cache retrieval
- Add test to verify negative caching works correctly

This ensures zero DB queries even when FQDN is not configured.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-15 22:15:55 +02:00

52 lines
1.6 KiB
PHP

<?php
namespace App\Http\Middleware;
use App\Models\InstanceSettings;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
use Illuminate\Support\Facades\Cache;
use Spatie\Url\Url;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
$trustedHosts = [];
// Trust the configured FQDN from InstanceSettings (cached to avoid DB query on every request)
// Use empty string as sentinel value instead of null so negative results are cached
$fqdnHost = Cache::remember('instance_settings_fqdn_host', 300, function () {
try {
$settings = InstanceSettings::get();
if ($settings && $settings->fqdn) {
$url = Url::fromString($settings->fqdn);
$host = $url->getHost();
return $host ?: '';
}
} catch (\Exception $e) {
// If instance settings table doesn't exist yet (during installation),
// return empty string (sentinel) so this result is cached
}
return '';
});
// Convert sentinel value back to null for consumption
$fqdnHost = $fqdnHost !== '' ? $fqdnHost : null;
if ($fqdnHost) {
$trustedHosts[] = $fqdnHost;
}
// Trust all subdomains of APP_URL as fallback
$trustedHosts[] = $this->allSubdomainsOfApplicationUrl();
return array_filter($trustedHosts);
}
}