An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
fix(traffic): validate sentinel app keys, gate caddy log volume + swarm toggle, null-safe link
Aditya Tripathi0c06b5e0d106
diff --git a/app/Livewire/Dashboard/TrafficAnalytics.php b/app/Livewire/Dashboard/TrafficAnalytics.phpindex 5270644582..e5565674fc 100644--- a/app/Livewire/Dashboard/TrafficAnalytics.php+++ b/app/Livewire/Dashboard/TrafficAnalytics.php@@ -71,7 +71,7 @@ class TrafficAnalytics extends Component$appRows[] = ['uuid' => $uuid,- 'name' => Application::whereUuid($uuid)->first()?->name ?? $uuid,+ 'name' => Application::ownedByCurrentTeam()->whereUuid($uuid)->first()?->name ?? $uuid,'requests' => (int) ($appOverview['requests'] ?? 0),'bandwidth' => (int) ($appOverview['bytesIn'] ?? 0) + (int) ($appOverview['bytesOut'] ?? 0),];diff --git a/app/Livewire/Server/Analytics.php b/app/Livewire/Server/Analytics.phpindex c24655f2c8..eebee3b530 100644--- a/app/Livewire/Server/Analytics.php+++ b/app/Livewire/Server/Analytics.php@@ -129,7 +129,7 @@ class Analytics extends Component$rows[] = ['uuid' => $uuid,- 'name' => Application::whereUuid($uuid)->first()?->name ?? $uuid,+ 'name' => Application::ownedByCurrentTeam()->whereUuid($uuid)->first()?->name ?? $uuid,'requests' => (int) ($overview['requests'] ?? 0),'bandwidth' => (int) ($overview['bytesIn'] ?? 0) + (int) ($overview['bytesOut'] ?? 0),];diff --git a/app/Livewire/Server/Sentinel.php b/app/Livewire/Server/Sentinel.phpindex aabcabbcee..cc2828086f 100644--- a/app/Livewire/Server/Sentinel.php+++ b/app/Livewire/Server/Sentinel.php@@ -144,6 +144,11 @@ class Sentinel extends Component{try {$this->authorize('update', $this->server);+ if ($this->server->isSwarm() || $this->server->isBuildServer()) {+ $this->dispatch('error', 'Traffic analytics is not supported on Swarm/Build servers.');++ return;+ }$enable = ! $this->server->isTrafficAnalyticsEnabled();ConfigureTrafficAnalytics::run($this->server, $enable);$this->server->refresh();diff --git a/app/Services/SentinelTrafficClient.php b/app/Services/SentinelTrafficClient.phpindex 0bceaae747..eae4c2f168 100644--- a/app/Services/SentinelTrafficClient.php+++ b/app/Services/SentinelTrafficClient.php@@ -13,12 +13,20 @@ class SentinelTrafficClient{private string $base = 'http://localhost:8888/api';+ /** @var array<int, string> */+ private const ALLOWED_DIMENSIONS = [+ 'status', 'method', 'country', 'referer', 'browser', 'os', 'device', 'protocol', 'scheme', 'tls', 'cache', 'bot',+ ];+public function __construct(protected Server $server) {}// NOTE: Sentinel's traffic API expects `from`/`to` as ISO-8601 Zulu strings// (e.g. "2024-01-14T10:00:00Z"), confirmed against sentinel/API.md.public function overview(?string $appKey, string $from, string $to): TrafficOverviewData{+ if ($appKey !== null) {+ $this->assertSafeKey($appKey);+ }$path = $appKey ? "/app/{$appKey}/traffic/overview" : '/traffic/overview';$json = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to])), true) ?? [];@@ -27,16 +35,23 @@ class SentinelTrafficClientpublic function paths(?string $appKey, string $from, string $to, int $limit = 50): Collection{+ if ($appKey !== null) {+ $this->assertSafeKey($appKey);+ }$path = $appKey ? "/app/{$appKey}/traffic/paths" : '/traffic/paths';- $rows = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to, 'limit' => $limit])), true) ?? [];+ $rows = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to, 'limit' => (int) $limit])), true) ?? [];return collect($rows)->map(fn ($r) => TrafficPathData::fromSentinel($r));}public function breakdown(?string $appKey, string $dimension, string $from, string $to, int $limit = 50): Collection{+ if ($appKey !== null) {+ $this->assertSafeKey($appKey);+ }+ $this->assertSafeDimension($dimension);$path = $appKey ? "/app/{$appKey}/traffic/breakdown/{$dimension}" : "/traffic/breakdown/{$dimension}";- $rows = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to, 'limit' => $limit])), true) ?? [];+ $rows = json_decode($this->raw($this->url($path, ['from' => $from, 'to' => $to, 'limit' => (int) $limit])), true) ?? [];return collect($rows)->map(fn ($r) => TrafficBreakdownData::fromSentinel($r));}@@ -53,6 +68,25 @@ class SentinelTrafficClientreturn data_get($json, 'attribution');}+ /**+ * Reject anything that isn't a bare CUID2/UUID or hostname before it is+ * interpolated into a shell-quoted `docker exec ... curl` command+ * (see remoteFetch()). No quotes, spaces, slashes, or shell metacharacters.+ */+ private function assertSafeKey(string $value): void+ {+ if ($value === '' || ! preg_match('/\A[A-Za-z0-9._:-]+\z/', $value)) {+ throw new \InvalidArgumentException('Invalid traffic analytics app key.');+ }+ }++ private function assertSafeDimension(string $dimension): void+ {+ if (! in_array($dimension, self::ALLOWED_DIMENSIONS, true)) {+ throw new \InvalidArgumentException('Invalid traffic analytics dimension.');+ }+ }+private function url(string $path, array $query = []): string{// Colons in ISO-8601 Zulu timestamps are safe in a query string; keep themdiff --git a/bootstrap/helpers/proxy.php b/bootstrap/helpers/proxy.phpindex a6c3b3ca7a..1d24772f30 100644--- a/bootstrap/helpers/proxy.php+++ b/bootstrap/helpers/proxy.php@@ -408,11 +408,13 @@ function generateDefaultProxyConfiguration(Server $server, array $custom_command"{$proxy_path}/dynamic:/dynamic","{$proxy_path}/config:/config","{$proxy_path}/data:/data",- "{$proxy_path}:/traffic",],],],];+ if ($server->isTrafficAnalyticsEnabled()) {+ $config['services']['caddy']['volumes'][] = "{$proxy_path}:/traffic";+ }} else {return null;}diff --git a/resources/views/livewire/project/application/analytics.blade.php b/resources/views/livewire/project/application/analytics.blade.phpindex 66634a9b6b..767d9c5bc9 100644--- a/resources/views/livewire/project/application/analytics.blade.php+++ b/resources/views/livewire/project/application/analytics.blade.php@@ -10,19 +10,21 @@ $dimensionLabels = ['os' => 'Operating systems','device' => 'Devices',];+$analyticsServerUuid = $application->destination?->server?->uuid;?><div class="flex flex-col gap-6">@if (! $enabled)<x-application.settings-section id="analytics-section" title="Analytics"helper="Inspect Cloudflare-style traffic statistics reported by Sentinel.">- <x-slot:actions>- <a class="button"- href="{{ route('server.sentinel', ['server_uuid' => $application->destination->server->uuid]) }}"- {{ wireNavigate() }}>- Server settings- <x-external-link />- </a>- </x-slot:actions>+ @if ($analyticsServerUuid)+ <x-slot:actions>+ <a class="button" href="{{ route('server.sentinel', ['server_uuid' => $analyticsServerUuid]) }}"+ {{ wireNavigate() }}>+ Server settings+ <x-external-link />+ </a>+ </x-slot:actions>+ @endif<x-empty size="sm" title="Traffic analytics is not enabled"description="Enable Sentinel traffic analytics for this server to start collecting request analytics."icon-name="network" />diff --git a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.phpindex c4c0b7e929..4525520539 100644--- a/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/ApplicationAnalyticsTest.php@@ -132,3 +132,18 @@ it('shows an empty state when traffic analytics is disabled for the server', fun->assertSee('Analytics')->assertDontSee('Unique visitors');});++it('renders the disabled empty-state without crashing when the application has no destination', function () {+ $application = Application::factory()->create([+ 'environment_id' => $this->environment->id,+ 'destination_id' => null,+ 'destination_type' => null,+ ]);++ expect($application->destination)->toBeNull();++ Livewire::test(Analytics::class, ['application' => $application])+ ->assertOk()+ ->assertSee('Analytics')+ ->assertDontSee('Server settings');+});diff --git a/tests/Feature/TrafficAnalytics/CaddyProxyVolumeTest.php b/tests/Feature/TrafficAnalytics/CaddyProxyVolumeTest.phpnew file mode 100644index 0000000000..be99d63702--- /dev/null+++ b/tests/Feature/TrafficAnalytics/CaddyProxyVolumeTest.php@@ -0,0 +1,58 @@+<?php++use App\Models\PrivateKey;+use App\Models\Server;+use App\Models\User;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Process;+use Symfony\Component\Yaml\Yaml;++uses(RefreshDatabase::class);++beforeEach(function () {+ // generateDefaultProxyConfiguration() synchronously persists the config to the+ // server over SSH (SaveProxyConfiguration); fake the process layer so tests+ // don't attempt a real SSH connection.+ Process::fake();++ $user = User::factory()->create();+ $this->team = $user->teams()->first();++ $this->privateKey = PrivateKey::create([+ 'name' => 'Test Key',+ 'private_key' => '-----BEGIN OPENSSH PRIVATE KEY-----+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW+QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk+hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA+AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV+uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==+-----END OPENSSH PRIVATE KEY-----',+ 'team_id' => $this->team->id,+ ]);+});++it('does not mount the traffic volume for caddy when traffic analytics is disabled', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id, 'private_key_id' => $this->privateKey->id]);+ $server->proxy->set('type', 'CADDY');+ $server->save();+ $server->settings->is_traffic_analytics_enabled = false;+ $server->settings->save();++ $config = Yaml::parse(generateDefaultProxyConfiguration($server->fresh()));++ expect($config['services']['caddy']['volumes'])+ ->not->toContain($server->proxyPath().':/traffic');+});++it('mounts the traffic volume for caddy when traffic analytics is enabled', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id, 'private_key_id' => $this->privateKey->id]);+ $server->proxy->set('type', 'CADDY');+ $server->save();+ $server->settings->is_traffic_analytics_enabled = true;+ $server->settings->save();++ $config = Yaml::parse(generateDefaultProxyConfiguration($server->fresh()));++ expect($config['services']['caddy']['volumes'])+ ->toContain($server->proxyPath().':/traffic');+});diff --git a/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php b/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.phpindex 777d2411db..c395a7dcd8 100644--- a/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/DashboardTrafficAnalyticsTest.php@@ -1,8 +1,12 @@<?phpuse App\Livewire\Dashboard\TrafficAnalytics;+use App\Models\Application;+use App\Models\Environment;use App\Models\PrivateKey;+use App\Models\Project;use App\Models\Server;+use App\Models\StandaloneDocker;use App\Models\Team;use App\Models\User;use App\Services\SentinelTrafficClient;@@ -108,6 +112,39 @@ it('renders the team traffic summary aggregated across servers with an approxima->assertSee('approximate');});+it('does not disclose another team application name in the top apps list', function () {+ $server = Server::factory()->create([+ 'team_id' => $this->team->id,+ 'private_key_id' => $this->privateKey->id,+ ]);+ $server->settings->is_traffic_analytics_enabled = true;+ $server->settings->save();++ $otherTeam = Team::factory()->create();+ $otherProject = Project::factory()->create(['team_id' => $otherTeam->id]);+ $otherEnvironment = Environment::factory()->create(['project_id' => $otherProject->id]);+ $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);+ $otherDestination = StandaloneDocker::factory()->create(['server_id' => $otherServer->id, 'network' => 'other-team-test']);++ $otherTeamApplication = Application::factory()->create([+ 'name' => 'Secret Other Team App',+ 'environment_id' => $otherEnvironment->id,+ 'destination_id' => $otherDestination->id,+ 'destination_type' => StandaloneDocker::class,+ ]);++ $fake = new FakeDashboardTrafficClient($server);+ $fake->responses = fakeDashboardTrafficResponses(1000);+ $fake->responses['/traffic/apps'] = json_encode([$otherTeamApplication->uuid]);++ app()->bind(SentinelTrafficClient::class, fn () => $fake);++ Livewire::test(TrafficAnalytics::class)+ ->assertOk()+ ->assertDontSee('Secret Other Team App')+ ->assertSee($otherTeamApplication->uuid);+});+it('shows a failure empty-state instead of an all-zero KPI panel when every server fetch fails', function () {$serverOne = Server::factory()->create(['team_id' => $this->team->id,diff --git a/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php b/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.phpindex 5e86d30aa2..6c12041194 100644--- a/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php+++ b/tests/Feature/TrafficAnalytics/SentinelTrafficClientTest.php@@ -48,3 +48,57 @@ it('builds server-wide overview url when appKey is null', function () {$client->overview(null, 'a', 'b');expect($client->captured[0])->toContain('/api/traffic/overview')->not->toContain('/app/');});++it('rejects a malicious app key that would break out of the shell quoting', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $client = new FakeTrafficClient($server);++ expect(fn () => $client->overview("x'; touch /tmp/pwned; '", 'a', 'b'))+ ->toThrow(InvalidArgumentException::class);+ expect(fn () => $client->breakdown('foo bar', 'country', 'a', 'b'))+ ->toThrow(InvalidArgumentException::class);+ expect($client->captured)->toBeEmpty();+});++it('rejects a dimension outside the known fixed set', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $client = new FakeTrafficClient($server);++ expect(fn () => $client->breakdown(null, "status'; touch /tmp/pwned; '", 'a', 'b'))+ ->toThrow(InvalidArgumentException::class);+ expect($client->captured)->toBeEmpty();+});++it('accepts a CUID2-like app key and builds the url', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $client = new FakeTrafficClient($server);+ $client->response = json_encode(['requests' => 0]);++ $client->overview('cm2abc123xyz456uuid', 'a', 'b');++ expect($client->captured[0])->toContain('/api/app/cm2abc123xyz456uuid/traffic/overview');+});++it('accepts a hostname-shaped app key and builds the url', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $client = new FakeTrafficClient($server);+ $client->response = json_encode(['requests' => 0]);++ $client->overview('app.example.com', 'a', 'b');++ expect($client->captured[0])->toContain('/api/app/app.example.com/traffic/overview');+});++it('accepts every known dimension and rejects unknown ones', function () {+ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $client = new FakeTrafficClient($server);+ $client->response = json_encode([]);++ foreach (['status', 'method', 'country', 'referer', 'browser', 'os', 'device', 'protocol', 'scheme', 'tls', 'cache', 'bot'] as $dimension) {+ $client->breakdown(null, $dimension, 'a', 'b');+ }+ expect($client->captured)->toHaveCount(12);++ expect(fn () => $client->breakdown(null, 'not-a-real-dimension', 'a', 'b'))+ ->toThrow(InvalidArgumentException::class);+});diff --git a/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.phpindex 42bcbc9b4c..d3306748fe 100644--- a/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/ServerAnalyticsTest.php@@ -121,6 +121,37 @@ it('renders server-wide analytics with a per-app leaderboard when enabled', func->assertSee('Leaderboard App');});+it('does not disclose another team application name for a sentinel-reported uuid', function () {+ $server = Server::factory()->create([+ 'team_id' => $this->team->id,+ 'private_key_id' => $this->privateKey->id,+ ]);+ $server->settings->is_traffic_analytics_enabled = true;+ $server->settings->save();++ $otherTeam = Team::factory()->create();+ $otherProject = Project::factory()->create(['team_id' => $otherTeam->id]);+ $otherEnvironment = Environment::factory()->create(['project_id' => $otherProject->id]);+ $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);+ $otherDestination = StandaloneDocker::factory()->create(['server_id' => $otherServer->id, 'network' => 'other-team-test']);++ $otherTeamApplication = Application::factory()->create([+ 'name' => 'Secret Other Team App',+ 'environment_id' => $otherEnvironment->id,+ 'destination_id' => $otherDestination->id,+ 'destination_type' => StandaloneDocker::class,+ ]);++ $fake = new FakeServerAnalyticsTrafficClient($server);+ $fake->responses = fakeServerAnalyticsResponses([$otherTeamApplication->uuid]);+ app()->bind(SentinelTrafficClient::class, fn () => $fake);++ Livewire::test(Analytics::class, ['server_uuid' => $server->uuid])+ ->assertOk()+ ->assertDontSee('Secret Other Team App')+ ->assertSee($otherTeamApplication->uuid);+});+it('shows an empty state when traffic analytics is disabled for the server', function () {$server = Server::factory()->create(['team_id' => $this->team->id,diff --git a/tests/Feature/TrafficAnalytics/ToggleTrafficAnalyticsTest.php b/tests/Feature/TrafficAnalytics/ToggleTrafficAnalyticsTest.phpindex 89fbb56bfd..aa693bbda8 100644--- a/tests/Feature/TrafficAnalytics/ToggleTrafficAnalyticsTest.php+++ b/tests/Feature/TrafficAnalytics/ToggleTrafficAnalyticsTest.php@@ -32,3 +32,35 @@ it('toggles traffic analytics via the sentinel settings component', function ()expect($server->fresh()->isTrafficAnalyticsEnabled())->toBeTrue();});++it('does not enable traffic analytics on a swarm server', function () {+ ConfigureTrafficAnalytics::partialMock()->shouldReceive('handle')->never();++ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $server->settings->is_swarm_manager = true;+ $server->settings->save();++ expect($server->isTrafficAnalyticsEnabled())->toBeFalse();++ Livewire::test(Sentinel::class, ['server' => $server])+ ->call('toggleTrafficAnalytics')+ ->assertHasNoErrors();++ expect($server->fresh()->isTrafficAnalyticsEnabled())->toBeFalse();+});++it('does not enable traffic analytics on a build server', function () {+ ConfigureTrafficAnalytics::partialMock()->shouldReceive('handle')->never();++ $server = Server::factory()->create(['team_id' => $this->team->id]);+ $server->settings->is_build_server = true;+ $server->settings->save();++ expect($server->isTrafficAnalyticsEnabled())->toBeFalse();++ Livewire::test(Sentinel::class, ['server' => $server])+ ->call('toggleTrafficAnalytics')+ ->assertHasNoErrors();++ expect($server->fresh()->isTrafficAnalyticsEnabled())->toBeFalse();+});