Skip to content

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.

refactor(auth): enforce team member authorization across app

Andras Bacsaib878dc8102c5
diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php
index ddef74226a..9471307f36 100644
--- a/app/Http/Controllers/Api/ApplicationsController.php
+++ b/app/Http/Controllers/Api/ApplicationsController.php
@@ -54,6 +54,10 @@ class ApplicationsController extends Controller
]);
}
+ if ($application->is_shown_once ?? false) {
+ $application->makeHidden(['value', 'real_value']);
+ }
+
return serializeApiResponse($application);
}
diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php
index ee4d84f10a..791972eb5f 100644
--- a/app/Http/Controllers/Api/ServicesController.php
+++ b/app/Http/Controllers/Api/ServicesController.php
@@ -35,6 +35,10 @@ class ServicesController extends Controller
]);
}
+ if ($service->is_shown_once ?? false) {
+ $service->makeHidden(['value', 'real_value']);
+ }
+
return serializeApiResponse($service);
}
diff --git a/app/Http/Middleware/ApiAbility.php b/app/Http/Middleware/ApiAbility.php
index 324eeebaa3..d42e091360 100644
--- a/app/Http/Middleware/ApiAbility.php
+++ b/app/Http/Middleware/ApiAbility.php
@@ -6,9 +6,34 @@ use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
class ApiAbility extends CheckForAnyAbility
{
+ /**
+ * Permissions that only admins/owners may use.
+ */
+ private const MEMBER_DISALLOWED_ABILITIES = [
+ 'root',
+ 'write',
+ 'write:sensitive',
+ 'deploy',
+ 'read:sensitive',
+ ];
+
public function handle($request, $next, ...$abilities)
{
try {
+ $token = $request->user()->currentAccessToken();
+ $teamId = (int) data_get($token, 'team_id');
+
+ if ($teamId && ! $request->user()->isAdminOfTeam($teamId)) {
+ $tokenAbilities = $token->abilities ?? [];
+ $disallowed = array_intersect($tokenAbilities, self::MEMBER_DISALLOWED_ABILITIES);
+
+ if (! empty($disallowed)) {
+ return response()->json([
+ 'message' => 'This API token has permissions ('.implode(', ', $disallowed).') that exceed your current role as a team member. Members are restricted to read-only API access. Please revoke this token and create a new one with only read permissions.',
+ ], 403);
+ }
+ }
+
if ($request->user()->tokenCan('root')) {
return $next($request);
}
diff --git a/app/Http/Middleware/ApiSensitiveData.php b/app/Http/Middleware/ApiSensitiveData.php
index 49584ddb3f..8d7c51d111 100644
--- a/app/Http/Middleware/ApiSensitiveData.php
+++ b/app/Http/Middleware/ApiSensitiveData.php
@@ -10,10 +10,13 @@ class ApiSensitiveData
public function handle(Request $request, Closure $next)
{
$token = $request->user()->currentAccessToken();
+ $hasTokenPermission = $token->can('root') || $token->can('read:sensitive');
+ $teamId = (int) data_get($token, 'team_id');
+ $isAdmin = $teamId ? $request->user()->isAdminOfTeam($teamId) : false;
- // Allow access to sensitive data if token has root or read:sensitive permission
+ // Allow access to sensitive data only if token has permission AND user is admin/owner
$request->attributes->add([
- 'can_read_sensitive' => $token->can('root') || $token->can('read:sensitive'),
+ 'can_read_sensitive' => $hasTokenPermission && $isAdmin,
]);
return $next($request);
diff --git a/app/Livewire/Boarding/Index.php b/app/Livewire/Boarding/Index.php
index 0f6f45d83d..289f8c181b 100644
--- a/app/Livewire/Boarding/Index.php
+++ b/app/Livewire/Boarding/Index.php
@@ -8,12 +8,15 @@ use App\Models\Project;
use App\Models\Server;
use App\Models\Team;
use App\Services\ConfigurationRepository;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
class Index extends Component
{
+ use AuthorizesRequests;
+
protected $listeners = [
'refreshBoardingIndex' => 'validateServer',
'prerequisitesInstalled' => 'handlePrerequisitesInstalled',
@@ -172,6 +175,9 @@ class Index extends Component
public function skipBoarding()
{
+ if (auth()->user()?->isMember()) {
+ return redirect()->route('dashboard');
+ }
Team::find(currentTeam()->id)->update([
'show_boarding' => false,
]);
@@ -257,6 +263,7 @@ class Index extends Component
]);
try {
+ $this->authorize('create', PrivateKey::class);
$privateKey = PrivateKey::createAndStore([
'name' => $this->privateKeyName,
'description' => $this->privateKeyDescription,
@@ -280,6 +287,12 @@ class Index extends Component
'remoteServerUser' => 'required|string',
]);
+ try {
+ $this->authorize('create', Server::class);
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
+
$this->privateKey = formatPrivateKey($this->privateKey);
$foundServer = Server::whereIp($this->remoteServerHost)->first();
if ($foundServer) {
diff --git a/app/Livewire/Project/AddEmpty.php b/app/Livewire/Project/AddEmpty.php
index 974f0608a6..3430c69bb9 100644
--- a/app/Livewire/Project/AddEmpty.php
+++ b/app/Livewire/Project/AddEmpty.php
@@ -4,11 +4,14 @@ namespace App\Livewire\Project;
use App\Models\Project;
use App\Support\ValidationPatterns;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
class AddEmpty extends Component
{
+ use AuthorizesRequests;
+
public string $name;
public string $description = '';
@@ -29,6 +32,7 @@ class AddEmpty extends Component
public function submit()
{
try {
+ $this->authorize('create', Project::class);
$this->validate();
$project = Project::create([
'name' => $this->name,
diff --git a/app/Livewire/Project/Application/Deployment/Show.php b/app/Livewire/Project/Application/Deployment/Show.php
index 954670582a..189dcca9bd 100644
--- a/app/Livewire/Project/Application/Deployment/Show.php
+++ b/app/Livewire/Project/Application/Deployment/Show.php
@@ -123,6 +123,8 @@ class Show extends Component
public function downloadAllLogs(): string
{
+ $this->authorize('update', $this->application);
+
$logs = decode_remote_command_output($this->application_deployment_queue, includeAll: true)
->map(function ($line) {
$prefix = '';
diff --git a/app/Livewire/Project/Application/DeploymentNavbar.php b/app/Livewire/Project/Application/DeploymentNavbar.php
index ebdc014ae1..f71b7f7530 100644
--- a/app/Livewire/Project/Application/DeploymentNavbar.php
+++ b/app/Livewire/Project/Application/DeploymentNavbar.php
@@ -6,11 +6,14 @@ use App\Enums\ApplicationDeploymentStatus;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Server;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Carbon;
use Livewire\Component;
class DeploymentNavbar extends Component
{
+ use AuthorizesRequests;
+
public ApplicationDeploymentQueue $application_deployment_queue;
public Application $application;
@@ -35,10 +38,15 @@ class DeploymentNavbar extends Component
public function show_debug()
{
- $this->application->settings->is_debug_enabled = ! $this->application->settings->is_debug_enabled;
- $this->application->settings->save();
- $this->is_debug_enabled = $this->application->settings->is_debug_enabled;
- $this->dispatch('refreshQueue');
+ try {
+ $this->authorize('update', $this->application);
+ $this->application->settings->is_debug_enabled = ! $this->application->settings->is_debug_enabled;
+ $this->application->settings->save();
+ $this->is_debug_enabled = $this->application->settings->is_debug_enabled;
+ $this->dispatch('refreshQueue');
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
}
public function force_start()
diff --git a/app/Livewire/Project/CloneMe.php b/app/Livewire/Project/CloneMe.php
index 3b3e42619a..58a181f2fa 100644
--- a/app/Livewire/Project/CloneMe.php
+++ b/app/Livewire/Project/CloneMe.php
@@ -11,11 +11,14 @@ use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Support\ValidationPatterns;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
class CloneMe extends Component
{
+ use AuthorizesRequests;
+
public string $project_uuid;
public string $environment_uuid;
@@ -91,6 +94,7 @@ class CloneMe extends Component
public function clone(string $type)
{
try {
+ $this->authorize('create', Project::class);
$this->validate([
'selectedDestination' => 'required',
'newName' => ValidationPatterns::nameRules(),
diff --git a/app/Livewire/Project/Database/Heading.php b/app/Livewire/Project/Database/Heading.php
index ef2163f14f..94773feb19 100644
--- a/app/Livewire/Project/Database/Heading.php
+++ b/app/Livewire/Project/Database/Heading.php
@@ -90,6 +90,7 @@ class Heading extends Component
$this->authorize('manage', $this->database);
$activity = RestartDatabase::run($this->database);
+ $this->js("window.dispatchEvent(new CustomEvent('startdatabase'))");
$this->dispatch('activityMonitor', $activity->id, ServiceStatusChanged::class);
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -102,6 +103,7 @@ class Heading extends Component
$this->authorize('manage', $this->database);
$activity = StartDatabase::run($this->database);
+ $this->js("window.dispatchEvent(new CustomEvent('startdatabase'))");
$this->dispatch('activityMonitor', $activity->id, ServiceStatusChanged::class);
} catch (\Throwable $e) {
return handleError($e, $this);
diff --git a/app/Livewire/Project/Edit.php b/app/Livewire/Project/Edit.php
index a2d73eb5f3..1314c9e4b6 100644
--- a/app/Livewire/Project/Edit.php
+++ b/app/Livewire/Project/Edit.php
@@ -4,10 +4,13 @@ namespace App\Livewire\Project;
use App\Models\Project;
use App\Support\ValidationPatterns;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
class Edit extends Component
{
+ use AuthorizesRequests;
+
public Project $project;
public string $name;
@@ -54,6 +57,7 @@ class Edit extends Component
public function submit()
{
try {
+ $this->authorize('update', $this->project);
$this->syncData(true);
$this->dispatch('success', 'Project updated.');
} catch (\Throwable $e) {
diff --git a/app/Livewire/Project/EnvironmentEdit.php b/app/Livewire/Project/EnvironmentEdit.php
index 529b9d7b19..9b9a3670db 100644
--- a/app/Livewire/Project/EnvironmentEdit.php
+++ b/app/Livewire/Project/EnvironmentEdit.php
@@ -5,11 +5,14 @@ namespace App\Livewire\Project;
use App\Models\Application;
use App\Models\Project;
use App\Support\ValidationPatterns;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Component;
class EnvironmentEdit extends Component
{
+ use AuthorizesRequests;
+
public Project $project;
public Application $application;
@@ -62,6 +65,7 @@ class EnvironmentEdit extends Component
public function submit()
{
try {
+ $this->authorize('update', $this->environment);
$this->syncData(true);
redirectRoute($this, 'project.environment.edit', [
'environment_uuid' => $this->environment->uuid,
diff --git a/app/Livewire/Project/Service/Heading.php b/app/Livewire/Project/Service/Heading.php
index adc2b151b0..20502393bd 100644
--- a/app/Livewire/Project/Service/Heading.php
+++ b/app/Livewire/Project/Service/Heading.php
@@ -105,6 +105,7 @@ class Heading extends Component
try {
$this->authorize('deploy', $this->service);
$activity = StartService::run($this->service, pullLatestImages: true);
+ $this->js("window.dispatchEvent(new CustomEvent('startservice'))");
$this->dispatch('activityMonitor', $activity->id);
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -125,6 +126,7 @@ class Heading extends Component
$activity->save();
}
$activity = StartService::run($this->service, pullLatestImages: true, stopBeforeStart: true);
+ $this->js("window.dispatchEvent(new CustomEvent('startservice'))");
$this->dispatch('activityMonitor', $activity->id);
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -152,6 +154,7 @@ class Heading extends Component
return;
}
$activity = StartService::run($this->service, stopBeforeStart: true);
+ $this->js("window.dispatchEvent(new CustomEvent('startservice'))");
$this->dispatch('activityMonitor', $activity->id);
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -169,6 +172,7 @@ class Heading extends Component
return;
}
$activity = StartService::run($this->service, pullLatestImages: true, stopBeforeStart: true);
+ $this->js("window.dispatchEvent(new CustomEvent('startservice'))");
$this->dispatch('activityMonitor', $activity->id);
} catch (\Throwable $e) {
return handleError($e, $this);
diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/All.php b/app/Livewire/Project/Shared/EnvironmentVariable/All.php
index 55e388b78a..766e2a9b9b 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/All.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/All.php
@@ -72,7 +72,7 @@ class All extends Component
$query->orderBy('order');
}
- return $query->get();
+ return $this->nullLockedValues($query->get());
}
public function getEnvironmentVariablesPreviewProperty()
@@ -86,7 +86,21 @@ class All extends Component
$query->orderBy('order');
}
- return $query->get();
+ return $this->nullLockedValues($query->get());
+ }
+
+ private function nullLockedValues($envs)
+ {
+ $isMember = auth()->user()?->isMember();
+
+ $envs->each(function ($env) use ($isMember) {
+ if ($env->is_shown_once || $isMember) {
+ $env->value = null;
+ $env->real_value = null;
+ }
+ });
+
+ return $envs;
}
public function getDevView()
@@ -99,7 +113,12 @@ class All extends Component
private function formatEnvironmentVariables($variables)
{
- return $variables->map(function ($item) {
+ $isMember = auth()->user()?->isMember();
+
+ return $variables->map(function ($item) use ($isMember) {
+ if ($isMember) {
+ return "$item->key=(Hidden, only admins can view)";
+ }
if ($item->is_shown_once) {
return "$item->key=(Locked Secret, delete and add again to change)";
}
diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
index 2030f631e1..1dc01cc482 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/Show.php
@@ -52,6 +52,8 @@ class Show extends Component
public bool $is_redis_credential = false;
+ public bool $isValueHidden = false;
+
public array $problematicVariables = [];
protected $listeners = [
@@ -134,6 +136,13 @@ class Show extends Component
$this->is_really_required = $this->env->is_really_required ?? false;
$this->is_shared = $this->env->is_shared ?? false;
$this->real_value = $this->env->real_value;
+
+ if ($this->env->is_shown_once || auth()->user()?->isMember()) {
+ $this->value = null;
+ $this->real_value = null;
+ }
+
+ $this->isValueHidden = auth()->user()?->isMember() ?? false;
}
}
diff --git a/app/Livewire/Security/ApiTokens.php b/app/Livewire/Security/ApiTokens.php
index d22d5d9fc9..af2ae189a9 100644
--- a/app/Livewire/Security/ApiTokens.php
+++ b/app/Livewire/Security/ApiTokens.php
@@ -4,6 +4,7 @@ namespace App\Livewire\Security;
use App\Models\InstanceSettings;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+use Illuminate\Support\Str;
use Laravel\Sanctum\PersonalAccessToken;
use Livewire\Component;
@@ -25,6 +26,8 @@ class ApiTokens extends Component
public bool $canUseDeployPermissions = false;
+ public bool $canUseSensitivePermissions = false;
+
public function render()
{
return view('livewire.security.api-tokens');
@@ -36,6 +39,7 @@ class ApiTokens extends Component
$this->canUseRootPermissions = auth()->user()->can('useRootPermissions', PersonalAccessToken::class);
$this->canUseWritePermissions = auth()->user()->can('useWritePermissions', PersonalAccessToken::class);
$this->canUseDeployPermissions = auth()->user()->can('useDeployPermissions', PersonalAccessToken::class);
+ $this->canUseSensitivePermissions = auth()->user()->can('useSensitivePermissions', PersonalAccessToken::class);
$this->getTokens();
}
@@ -70,6 +74,13 @@ class ApiTokens extends Component
return;
}
+ if ($permissionToUpdate == 'read:sensitive' && ! $this->canUseSensitivePermissions) {
+ $this->dispatch('error', 'You do not have permission to use read:sensitive permissions.');
+ $this->permissions = array_diff($this->permissions, ['read:sensitive']);
+
+ return;
+ }
+
if ($permissionToUpdate == 'root') {
$this->permissions = ['root'];
} elseif ($permissionToUpdate == 'read:sensitive' && ! in_array('read', $this->permissions)) {
@@ -102,12 +113,16 @@ class ApiTokens extends Component
throw new \Exception('You do not have permission to create tokens with deploy permissions.');
}
+ if (in_array('read:sensitive', $this->permissions) && ! $this->canUseSensitivePermissions) {
+ throw new \Exception('You do not have permission to create tokens with read:sensitive permissions.');
+ }
+
$this->validate([
'description' => 'required|min:3|max:255',
]);
$token = auth()->user()->createToken($this->description, array_values($this->permissions));
$this->getTokens();
- session()->flash('token', $token->plainTextToken);
+ session()->flash('token', Str::after($token->plainTextToken, '|'));
} catch (\Exception $e) {
return handleError($e, $this);
}
diff --git a/app/Livewire/Server/CloudflareTunnel.php b/app/Livewire/Server/CloudflareTunnel.php
index 24f8e022e1..2ab8298543 100644
--- a/app/Livewire/Server/CloudflareTunnel.php
+++ b/app/Livewire/Server/CloudflareTunnel.php
@@ -72,12 +72,16 @@ class CloudflareTunnel extends Component
public function manualCloudflareConfig()
{
- $this->authorize('update', $this->server);
- $this->isCloudflareTunnelsEnabled = true;
- $this->server->settings->is_cloudflare_tunnel = true;
- $this->server->settings->save();
- $this->server->refresh();
- $this->dispatch('success', 'Cloudflare Tunnel enabled.');
+ try {
+ $this->authorize('update', $this->server);
+ $this->isCloudflareTunnelsEnabled = true;
+ $this->server->settings->is_cloudflare_tunnel = true;
+ $this->server->settings->save();
+ $this->server->refresh();
+ $this->dispatch('success', 'Cloudflare Tunnel enabled.');
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
}
public function automatedCloudflareConfig()
diff --git a/app/Livewire/Server/Destinations.php b/app/Livewire/Server/Destinations.php
index 117b43ad64..622bc1d1ea 100644
--- a/app/Livewire/Server/Destinations.php
+++ b/app/Livewire/Server/Destinations.php
@@ -69,6 +69,11 @@ class Destinations extends Component
public function scan()
{
+ try {
+ $this->authorize('update', $this->server);
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
if ($this->server->isSwarm()) {
$alreadyAddedNetworks = $this->server->swarmDockers;
} else {
diff --git a/app/Livewire/Server/Proxy/DynamicConfigurations.php b/app/Livewire/Server/Proxy/DynamicConfigurations.php
index 6ea9e7c3de..f824645aa6 100644
--- a/app/Livewire/Server/Proxy/DynamicConfigurations.php
+++ b/app/Livewire/Server/Proxy/DynamicConfigurations.php
@@ -3,11 +3,14 @@
namespace App\Livewire\Server\Proxy;
use App\Models\Server;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Livewire\Component;
class DynamicConfigurations extends Component
{
+ use AuthorizesRequests;
+
public ?Server $server = null;
public $parameters = [];
@@ -35,6 +38,11 @@ class DynamicConfigurations extends Component
public function loadDynamicConfigurations()
{
+ try {
+ $this->authorize('view', $this->server);
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
$proxy_path = $this->server->proxyPath();
$files = instant_remote_process(["mkdir -p $proxy_path/dynamic && ls -1 {$proxy_path}/dynamic"], $this->server);
$files = collect(explode("\n", $files))->filter(fn ($file) => ! empty($file));
diff --git a/app/Livewire/Server/Show.php b/app/Livewire/Server/Show.php
index 38053386e5..462c5de84c 100644
--- a/app/Livewire/Server/Show.php
+++ b/app/Livewire/Server/Show.php
@@ -404,6 +404,7 @@ class Show extends Component
public function checkHetznerServerStatus(bool $manual = false)
{
try {
+ $this->authorize('view', $this->server);
if (! $this->server->hetzner_server_id || ! $this->server->cloudProviderToken) {
$this->dispatch('error', 'This server is not associated with a Hetzner Cloud server or token.');
@@ -468,6 +469,7 @@ class Show extends Component
public function startHetznerServer()
{
try {
+ $this->authorize('update', $this->server);
if (! $this->server->hetzner_server_id || ! $this->server->cloudProviderToken) {
$this->dispatch('error', 'This server is not associated with a Hetzner Cloud server or token.');
diff --git a/app/Livewire/Settings/Advanced.php b/app/Livewire/Settings/Advanced.php
index 16361ce798..c48af76a88 100644
--- a/app/Livewire/Settings/Advanced.php
+++ b/app/Livewire/Settings/Advanced.php
@@ -4,11 +4,14 @@ namespace App\Livewire\Settings;
use App\Models\InstanceSettings;
use App\Rules\ValidIpOrCidr;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Validate;
use Livewire\Component;
class Advanced extends Component
{
+ use AuthorizesRequests;
+
public InstanceSettings $settings;
#[Validate('boolean')]
@@ -72,6 +75,7 @@ class Advanced extends Component
public function submit()
{
try {
+ $this->authorize('update', $this->settings);
$this->validate();
$this->custom_dns_servers = str($this->custom_dns_servers)->replaceEnd(',', '')->trim();
@@ -137,6 +141,7 @@ class Advanced extends Component
public function instantSave()
{
try {
+ $this->authorize('update', $this->settings);
$this->settings->is_registration_enabled = $this->is_registration_enabled;
$this->settings->do_not_track = $this->do_not_track;
$this->settings->is_dns_validation_enabled = $this->is_dns_validation_enabled;
@@ -155,6 +160,7 @@ class Advanced extends Component
public function toggleTwoStepConfirmation($password): bool
{
+ $this->authorize('update', $this->settings);
if (! verifyPasswordConfirmation($password, $this)) {
return false;
}
diff --git a/app/Livewire/Settings/Index.php b/app/Livewire/Settings/Index.php
index 9a51d107da..5a7c741723 100644
--- a/app/Livewire/Settings/Index.php
+++ b/app/Livewire/Settings/Index.php
@@ -4,12 +4,15 @@ namespace App\Livewire\Settings;
use App\Models\InstanceSettings;
use App\Models\Server;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Validate;
use Livewire\Component;
class Index extends Component
{
+ use AuthorizesRequests;
+
public InstanceSettings $settings;
public ?Server $server = null;
@@ -86,6 +89,7 @@ class Index extends Component
public function instantSave($isSave = true)
{
+ $this->authorize('update', $this->settings);
$this->validate();
$this->settings->fqdn = $this->fqdn ? trim($this->fqdn) : $this->fqdn;
$this->settings->public_port_min = $this->public_port_min;
@@ -103,6 +107,7 @@ class Index extends Component
public function confirmDomainUsage()
{
+ $this->authorize('update', $this->settings);
$this->forceSaveDomains = true;
$this->showDomainConflictModal = false;
$this->submit();
@@ -111,6 +116,7 @@ class Index extends Component
public function submit()
{
try {
+ $this->authorize('update', $this->settings);
$error_show = false;
$this->resetErrorBag();
@@ -172,6 +178,7 @@ class Index extends Component
public function buildHelperImage()
{
try {
+ $this->authorize('update', $this->settings);
if (! isDev()) {
$this->dispatch('error', 'Building helper image is only available in development mode.');
diff --git a/app/Livewire/Settings/Updates.php b/app/Livewire/Settings/Updates.php
index 01a67c38ca..88a8945d0a 100644
--- a/app/Livewire/Settings/Updates.php
+++ b/app/Livewire/Settings/Updates.php
@@ -5,11 +5,14 @@ namespace App\Livewire\Settings;
use App\Jobs\CheckForUpdatesJob;
use App\Models\InstanceSettings;
use App\Models\Server;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Validate;
use Livewire\Component;
class Updates extends Component
{
+ use AuthorizesRequests;
+
public InstanceSettings $settings;
public ?Server $server = null;
@@ -25,6 +28,9 @@ class Updates extends Component
public function mount()
{
+ if (! isInstanceAdmin()) {
+ return redirect()->route('dashboard');
+ }
if (! isCloud()) {
$this->server = Server::findOrFail(0);
}
@@ -38,6 +44,7 @@ class Updates extends Component
public function instantSave()
{
try {
+ $this->authorize('update', $this->settings);
if ($this->settings->is_auto_update_enabled === true) {
$this->validate([
'auto_update_frequency' => ['required', 'string'],
@@ -56,6 +63,7 @@ class Updates extends Component
public function submit()
{
try {
+ $this->authorize('update', $this->settings);
$this->resetErrorBag();
$this->validate();
@@ -88,6 +96,7 @@ class Updates extends Component
public function checkManually()
{
+ $this->authorize('update', $this->settings);
CheckForUpdatesJob::dispatchSync();
$this->dispatch('updateAvailable');
$settings = instanceSettings();
diff --git a/app/Livewire/SettingsBackup.php b/app/Livewire/SettingsBackup.php
index 84f5c6081a..cfd188b403 100644
--- a/app/Livewire/SettingsBackup.php
+++ b/app/Livewire/SettingsBackup.php
@@ -7,12 +7,15 @@ use App\Models\S3Storage;
use App\Models\ScheduledDatabaseBackup;
use App\Models\Server;
use App\Models\StandalonePostgresql;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
use Livewire\Component;
class SettingsBackup extends Component
{
+ use AuthorizesRequests;
+
public InstanceSettings $settings;
public Server $server;
@@ -76,6 +79,7 @@ class SettingsBackup extends Component
public function addCoolifyDatabase()
{
try {
+ $this->authorize('update', $this->settings);
$server = Server::findOrFail(0);
$out = instant_remote_process(['docker inspect coolify-db'], $server);
$envs = format_docker_envs_to_json($out);
@@ -120,14 +124,19 @@ class SettingsBackup extends Component
public function submit()
{
- $this->validate();
-
- $this->database->update([
- 'name' => $this->name,
- 'description' => $this->description,
- 'postgres_user' => $this->postgres_user,
- 'postgres_password' => $this->postgres_password,
- ]);
- $this->dispatch('success', 'Backup updated.');
+ try {
+ $this->authorize('update', $this->settings);
+ $this->validate();
+
+ $this->database->update([
+ 'name' => $this->name,
+ 'description' => $this->description,
+ 'postgres_user' => $this->postgres_user,
+ 'postgres_password' => $this->postgres_password,
+ ]);
+ $this->dispatch('success', 'Backup updated.');
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
}
}
diff --git a/app/Livewire/SettingsEmail.php b/app/Livewire/SettingsEmail.php
index ca48e9b167..5ed012b37b 100644
--- a/app/Livewire/SettingsEmail.php
+++ b/app/Livewire/SettingsEmail.php
@@ -5,6 +5,7 @@ namespace App\Livewire;
use App\Models\InstanceSettings;
use App\Models\Team;
use App\Notifications\TransactionalEmails\Test;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Validate;
@@ -12,6 +13,8 @@ use Livewire\Component;
class SettingsEmail extends Component
{
+ use AuthorizesRequests;
+
public InstanceSettings $settings;
#[Locked]
@@ -103,6 +106,7 @@ class SettingsEmail extends Component
public function submit()
{
try {
+ $this->authorize('update', $this->settings);
$this->resetErrorBag();
$this->syncData(true);
$this->dispatch('success', 'Transactional email settings updated.');
@@ -114,6 +118,7 @@ class SettingsEmail extends Component
public function instantSave(string $type)
{
try {
+ $this->authorize('update', $this->settings);
$currentSmtpEnabled = $this->settings->smtp_enabled;
$currentResendEnabled = $this->settings->resend_enabled;
$this->resetErrorBag();
@@ -141,6 +146,7 @@ class SettingsEmail extends Component
public function submitSmtp()
{
try {
+ $this->authorize('update', $this->settings);
$this->validate([
'smtpEnabled' => 'boolean',
'smtpFromAddress' => 'required|email',
@@ -184,6 +190,7 @@ class SettingsEmail extends Component
public function submitResend()
{
try {
+ $this->authorize('update', $this->settings);
$this->validate([
'resendEnabled' => 'boolean',
'resendApiKey' => 'required|string',
@@ -214,6 +221,7 @@ class SettingsEmail extends Component
public function sendTestEmail()
{
try {
+ $this->authorize('update', $this->settings);
$this->validate([
'testEmailAddress' => 'required|email',
], [
diff --git a/app/Livewire/SettingsOauth.php b/app/Livewire/SettingsOauth.php
index 6f949b7167..44ea4f611e 100644
--- a/app/Livewire/SettingsOauth.php
+++ b/app/Livewire/SettingsOauth.php
@@ -3,10 +3,13 @@
namespace App\Livewire;
use App\Models\OauthSetting;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
class SettingsOauth extends Component
{
+ use AuthorizesRequests;
+
public $oauth_settings_map;
protected function rules()
@@ -131,6 +134,7 @@ class SettingsOauth extends Component
public function instantSave(string $provider)
{
try {
+ $this->authorize('update', instanceSettings());
$this->updateOauthSettings($provider);
} catch (\Exception $e) {
return handleError($e, $this);
@@ -139,7 +143,12 @@ class SettingsOauth extends Component
public function submit()
{
- $this->updateOauthSettings();
- $this->dispatch('success', 'Instance settings updated successfully!');
+ try {
+ $this->authorize('update', instanceSettings());
+ $this->updateOauthSettings();
+ $this->dispatch('success', 'Instance settings updated successfully!');
+ } catch (\Throwable $e) {
+ return handleError($e, $this);
+ }
}
}
diff --git a/app/Livewire/SharedVariables/Environment/Show.php b/app/Livewire/SharedVariables/Environment/Show.php
index 0bdc1503f4..9a40e9cadd 100644
--- a/app/Livewire/SharedVariables/Environment/Show.php
+++ b/app/Livewire/SharedVariables/Environment/Show.php
@@ -72,7 +72,12 @@ class Show extends Component
private function formatEnvironmentVariables($variables)
{
- return $variables->map(function ($item) {
+ $isMember = auth()->user()?->isMember();
+
+ return $variables->map(function ($item) use ($isMember) {
+ if ($isMember) {
+ return "$item->key=(Hidden, only admins can view)";
+ }
if ($item->is_shown_once) {
return "$item->key=(Locked Secret, delete and add again to change)";
}
diff --git a/app/Livewire/SharedVariables/Project/Show.php b/app/Livewire/SharedVariables/Project/Show.php
index 008f4af5a0..b41f3262d3 100644
--- a/app/Livewire/SharedVariables/Project/Show.php
+++ b/app/Livewire/SharedVariables/Project/Show.php
@@ -73,7 +73,12 @@ class Show extends Component
private function formatEnvironmentVariables($variables)
{
- return $variables->map(function ($item) {
+ $isMember = auth()->user()?->isMember();
+
+ return $variables->map(function ($item) use ($isMember) {
+ if ($isMember) {
+ return "$item->key=(Hidden, only admins can view)";
+ }
if ($item->is_shown_once) {
return "$item->key=(Locked Secret, delete and add again to change)";
}
diff --git a/app/Livewire/SharedVariables/Team/Index.php b/app/Livewire/SharedVariables/Team/Index.php
index 93e12f376d..35da5ae62a 100644
--- a/app/Livewire/SharedVariables/Team/Index.php
+++ b/app/Livewire/SharedVariables/Team/Index.php
@@ -67,7 +67,12 @@ class Index extends Component
private function formatEnvironmentVariables($variables)
{
- return $variables->map(function ($item) {
+ $isMember = auth()->user()?->isMember();
+
+ return $variables->map(function ($item) use ($isMember) {
+ if ($isMember) {
+ return "$item->key=(Hidden, only admins can view)";
+ }
if ($item->is_shown_once) {
return "$item->key=(Locked Secret, delete and add again to change)";
}
diff --git a/app/Livewire/Tags/Show.php b/app/Livewire/Tags/Show.php
index fc5b133749..28d6440a96 100644
--- a/app/Livewire/Tags/Show.php
+++ b/app/Livewire/Tags/Show.php
@@ -5,6 +5,7 @@ namespace App\Livewire\Tags;
use App\Http\Controllers\Api\DeployController;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Tag;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Title;
@@ -13,6 +14,8 @@ use Livewire\Component;
#[Title('Tags | Coolify')]
class Show extends Component
{
+ use AuthorizesRequests;
+
#[Locked]
public ?string $tagName = null;
@@ -73,6 +76,12 @@ class Show extends Component
public function redeployAll()
{
try {
+ $this->applications->each(function ($resource) {
+ $this->authorize('deploy', $resource);
+ });
+ $this->services->each(function ($resource) {
+ $this->authorize('deploy', $resource);
+ });
$message = collect([]);
$this->applications->each(function ($resource) use ($message) {
$deploy = new DeployController;
diff --git a/app/Livewire/Team/AdminView.php b/app/Livewire/Team/AdminView.php
index c8d44d42be..cbc8f67b63 100644
--- a/app/Livewire/Team/AdminView.php
+++ b/app/Livewire/Team/AdminView.php
@@ -25,6 +25,9 @@ class AdminView extends Component
public function submitSearch()
{
+ if (! isInstanceAdmin()) {
+ return;
+ }
if ($this->search !== '') {
$this->users = User::where(function ($query) {
$query->where('name', 'like', "%{$this->search}%")
@@ -39,6 +42,9 @@ class AdminView extends Component
public function getUsers()
{
+ if (! isInstanceAdmin()) {
+ return;
+ }
$users = User::where('id', '!=', auth()->id())->get();
if ($users->count() > $this->number_of_users_to_show) {
$this->lots_of_users = true;
diff --git a/app/Policies/ApiTokenPolicy.php b/app/Policies/ApiTokenPolicy.php
index 5eb1a05ebd..ba9bade012 100644
--- a/app/Policies/ApiTokenPolicy.php
+++ b/app/Policies/ApiTokenPolicy.php
@@ -78,4 +78,12 @@ class ApiTokenPolicy
{
return $user->isAdmin() || $user->isOwner();
}
+
+ /**
+ * Determine whether the user can use read:sensitive permissions for API tokens.
+ */
+ public function useSensitivePermissions(User $user): bool
+ {
+ return $user->isAdmin() || $user->isOwner();
+ }
}
diff --git a/app/Policies/S3StoragePolicy.php b/app/Policies/S3StoragePolicy.php
index 982c7c5236..81cbd164f0 100644
--- a/app/Policies/S3StoragePolicy.php
+++ b/app/Policies/S3StoragePolicy.php
@@ -36,8 +36,7 @@ class S3StoragePolicy
*/
public function update(User $user, S3Storage $storage): bool
{
- // return $user->teams->contains('id', $storage->team_id) && $user->isAdmin();
- return $user->teams->contains('id', $storage->team_id);
+ return $user->teams->contains('id', $storage->team_id) && $user->isAdminOfTeam($storage->team_id);
}
/**
@@ -45,8 +44,7 @@ class S3StoragePolicy
*/
public function delete(User $user, S3Storage $storage): bool
{
- // return $user->teams->contains('id', $storage->team_id) && $user->isAdmin();
- return $user->teams->contains('id', $storage->team_id);
+ return $user->teams->contains('id', $storage->team_id) && $user->isAdminOfTeam($storage->team_id);
}
/**
@@ -70,6 +68,6 @@ class S3StoragePolicy
*/
public function validateConnection(User $user, S3Storage $storage): bool
{
- return $user->teams->contains('id', $storage->team_id);
+ return $user->teams->contains('id', $storage->team_id) && $user->isAdminOfTeam($storage->team_id);
}
}
diff --git a/app/View/Components/Forms/Button.php b/app/View/Components/Forms/Button.php
index b544442616..8511c87db8 100644
--- a/app/View/Components/Forms/Button.php
+++ b/app/View/Components/Forms/Button.php
@@ -14,6 +14,7 @@ class Button extends Component
*/
public function __construct(
public bool $disabled = false,
+ public bool $authDisabled = false,
public bool $noStyle = false,
public ?string $modalId = null,
public string $defaultClass = 'button',
@@ -28,6 +29,7 @@ class Button extends Component
if (! $hasPermission) {
$this->disabled = true;
+ $this->authDisabled = true;
}
}
diff --git a/resources/css/utilities.css b/resources/css/utilities.css
index 02be0c0c4c..349a12ed06 100644
--- a/resources/css/utilities.css
+++ b/resources/css/utilities.css
@@ -122,7 +122,11 @@
}
@utility button {
- @apply flex gap-2 justify-center items-center px-2 h-8 text-sm text-black normal-case rounded-sm border-2 outline-0 cursor-pointer font-medium bg-white border-neutral-200 hover:bg-neutral-100 dark:bg-coolgray-100 dark:text-white dark:hover:text-white dark:hover:bg-coolgray-200 dark:border-coolgray-300 hover:text-black disabled:cursor-not-allowed min-w-fit dark:disabled:text-neutral-600 disabled:border-transparent disabled:hover:bg-transparent disabled:bg-transparent disabled:text-neutral-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-coollabs dark:focus-visible:ring-warning focus-visible:ring-offset-2 dark:focus-visible:ring-offset-base;
+ @apply flex gap-2 justify-center items-center px-2 h-8 text-sm text-black normal-case rounded-sm border-2 outline-0 cursor-pointer font-medium bg-white border-neutral-200 hover:bg-neutral-100 dark:bg-coolgray-100 dark:text-white dark:hover:text-white dark:hover:bg-coolgray-200 dark:border-coolgray-300 hover:text-black disabled:cursor-not-allowed min-w-fit dark:disabled:text-neutral-600 disabled:border-neutral-200 dark:disabled:border-coolgray-300 disabled:hover:bg-transparent disabled:bg-transparent disabled:text-neutral-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-coollabs dark:focus-visible:ring-warning focus-visible:ring-offset-2 dark:focus-visible:ring-offset-base;
+}
+
+@utility auth-tooltip {
+ @apply fixed z-[99] px-2.5 py-1.5 text-xs rounded-sm pointer-events-none whitespace-nowrap text-neutral-700 bg-neutral-200 dark:text-neutral-300 dark:bg-coolgray-400;
}
@utility alert-success {
diff --git a/resources/views/components/forms/button.blade.php b/resources/views/components/forms/button.blade.php
index 96cdb4420f..f1efd8c6cd 100644
--- a/resources/views/components/forms/button.blade.php
+++ b/resources/views/components/forms/button.blade.php
@@ -1,3 +1,24 @@
+@if ($authDisabled)
+<span class="relative inline-flex"
+ x-data="{ visible: false, _t: null }"
+ @mouseenter="_t = setTimeout(() => {
+ visible = true;
+ $nextTick(() => requestAnimationFrame(() => {
+ const tip = $refs.tip;
+ if (!tip) return;
+ const r = $el.getBoundingClientRect();
+ const t = tip.getBoundingClientRect();
+ let top = r.top - t.height - 6;
+ let left = r.left;
+ if (top < 4) top = r.bottom + 6;
+ if (left + t.width > innerWidth - 8) left = innerWidth - 8 - t.width;
+ if (left < 4) left = 4;
+ tip.style.top = top + 'px';
+ tip.style.left = left + 'px';
+ }));
+ }, 300)"
+ @mouseleave="clearTimeout(_t); visible = false">
+@endif
<button @disabled($disabled) {{ $attributes->merge(['class' => $defaultClass]) }}
{{ $attributes->merge(['type' => 'button']) }}
@isset($confirm)
@@ -18,3 +39,9 @@
@endif
@endif
</button>
+@if ($authDisabled)
+ <div x-ref="tip" x-show="visible" x-cloak class="auth-tooltip">
+ You do not have permission to perform this action.
+ </div>
+</span>
+@endif
diff --git a/resources/views/components/modal-confirmation.blade.php b/resources/views/components/modal-confirmation.blade.php
index 73939092e7..7ad46b6a13 100644
--- a/resources/views/components/modal-confirmation.blade.php
+++ b/resources/views/components/modal-confirmation.blade.php
@@ -6,6 +6,7 @@
'buttonFullWidth' => false,
'customButton' => null,
'disabled' => false,
+ 'authDisabled' => false,
'dispatchAction' => false,
'submitAction' => 'delete',
'content' => null,
@@ -145,11 +146,11 @@
@else
@if ($disabled)
@if ($buttonFullWidth)
- <x-forms.button class="w-full" isError disabled wire:target>
+ <x-forms.button class="w-full" isError disabled :authDisabled="$authDisabled" wire:target>
{{ $buttonTitle }}
</x-forms.button>
@else
- <x-forms.button isError disabled wire:target>
+ <x-forms.button isError disabled :authDisabled="$authDisabled" wire:target>
{{ $buttonTitle }}
</x-forms.button>
@endif
diff --git a/resources/views/livewire/project/application/deployment/show.blade.php b/resources/views/livewire/project/application/deployment/show.blade.php
index 28872f4bc3..5861cef30a 100644
--- a/resources/views/livewire/project/application/deployment/show.blade.php
+++ b/resources/views/livewire/project/application/deployment/show.blade.php
@@ -246,6 +246,7 @@
class="block w-full px-4 py-2 text-left text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-coolgray-300">
Download displayed logs
</button>
+ @can('update', $application)
<button x-on:click="
downloadingAllLogs = true;
$wire.downloadAllLogs().then(logs => {
@@ -276,6 +277,7 @@
Downloading...
</span>
</button>
+ @endcan
</div>
</div>
</div>
diff --git a/resources/views/livewire/project/application/heading.blade.php b/resources/views/livewire/project/application/heading.blade.php
index 5db6d4c5c9..c73a824bbc 100644
--- a/resources/views/livewire/project/application/heading.blade.php
+++ b/resources/views/livewire/project/application/heading.blade.php
@@ -85,7 +85,7 @@
</x-forms.button>
@endif
@endif
- <x-modal-confirmation :disabled="!auth()->user()->can('deploy', $application)" title="Confirm Application Stopping?" buttonTitle="Stop"
+ <x-modal-confirmation :disabled="!auth()->user()->can('deploy', $application)" :authDisabled="!auth()->user()->can('deploy', $application)" title="Confirm Application Stopping?" buttonTitle="Stop"
submitAction="stop" :checkboxes="$checkboxes" :actions="[
'This application will be stopped.',
'All non-persistent data of this application will be deleted.',
diff --git a/resources/views/livewire/project/database/heading.blade.php b/resources/views/livewire/project/database/heading.blade.php
index 56c92110fb..890323102e 100644
--- a/resources/views/livewire/project/database/heading.blade.php
+++ b/resources/views/livewire/project/database/heading.blade.php
@@ -40,7 +40,7 @@
@if ($database->destination->server->isFunctional())
<div class="flex flex-wrap gap-2 items-center">
@if (!str($database->status)->startsWith('exited'))
- <x-modal-confirmation :disabled="!auth()->user()->can('manage', $database)" title="Confirm Database Restart?" buttonTitle="Restart" submitAction="restart"
+ <x-modal-confirmation :disabled="!auth()->user()->can('manage', $database)" :authDisabled="!auth()->user()->can('manage', $database)" title="Confirm Database Restart?" buttonTitle="Restart" submitAction="restart"
:actions="[
'This database will be unavailable during the restart.',
'If the database is currently in use data could be lost.',
@@ -58,7 +58,7 @@
Restart
</x-slot:button-title>
</x-modal-confirmation>
- <x-modal-confirmation :disabled="!auth()->user()->can('manage', $database)" title="Confirm Database Stopping?" buttonTitle="Stop" submitAction="stop"
+ <x-modal-confirmation :disabled="!auth()->user()->can('manage', $database)" :authDisabled="!auth()->user()->can('manage', $database)" title="Confirm Database Stopping?" buttonTitle="Stop" submitAction="stop"
:checkboxes="$checkboxes" :actions="[
'This database will be stopped.',
'If the database is currently in use data could be lost.',
@@ -80,7 +80,7 @@
</x-slot:button-title>
</x-modal-confirmation>
@else
- <button @disabled(!auth()->user()->can('manage', $database)) @click="$wire.dispatch('startEvent')" class="gap-2 button">
+ <x-forms.button canGate="manage" :canResource="$database" @click="$wire.dispatch('startEvent')" class="gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 dark:text-warning" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" fill="none" stroke-linecap="round"
stroke-linejoin="round">
@@ -88,17 +88,15 @@
<path d="M7 4v16l13 -8z" />
</svg>
Start
- </button>
+ </x-forms.button>
@endif
@script
<script>
$wire.$on('startEvent', () => {
- window.dispatchEvent(new CustomEvent('startdatabase'));
$wire.$call('start');
});
$wire.$on('restartEvent', () => {
$wire.$dispatch('info', 'Restarting database.');
- window.dispatchEvent(new CustomEvent('startdatabase'));
$wire.$call('restart');
});
</script>
diff --git a/resources/views/livewire/project/service/heading.blade.php b/resources/views/livewire/project/service/heading.blade.php
index af057813c1..db21f33176 100644
--- a/resources/views/livewire/project/service/heading.blade.php
+++ b/resources/views/livewire/project/service/heading.blade.php
@@ -40,7 +40,7 @@
</svg>
Restart
</x-forms.button>
- <x-modal-confirmation :disabled="!auth()->user()->can('stop', $service)" title="Confirm Service Stopping?" buttonTitle="Stop" :dispatchEvent="true"
+ <x-modal-confirmation :disabled="!auth()->user()->can('stop', $service)" :authDisabled="!auth()->user()->can('stop', $service)" title="Confirm Service Stopping?" buttonTitle="Stop" :dispatchEvent="true"
submitAction="stop" dispatchEventType="stopEvent" :checkboxes="$checkboxes" :actions="[__('service.stop'), __('resource.non_persistent')]"
:confirmWithText="false" :confirmWithPassword="false" step1ButtonText="Continue" step2ButtonText="Confirm">
<x-slot:button-title>
@@ -68,7 +68,7 @@
</svg>
Restart
</x-forms.button>
- <x-modal-confirmation :disabled="!auth()->user()->can('stop', $service)" title="Confirm Service Stopping?" buttonTitle="Stop" :dispatchEvent="true"
+ <x-modal-confirmation :disabled="!auth()->user()->can('stop', $service)" :authDisabled="!auth()->user()->can('stop', $service)" title="Confirm Service Stopping?" buttonTitle="Stop" :dispatchEvent="true"
submitAction="stop" dispatchEventType="stopEvent" :checkboxes="$checkboxes" :actions="[__('service.stop'), __('resource.non_persistent')]"
:confirmWithText="false" :confirmWithPassword="false" step1ButtonText="Continue" step2ButtonText="Confirm">
<x-slot:button-title>
@@ -86,7 +86,7 @@
</x-slot:button-title>
</x-modal-confirmation>
@elseif (str($service->status)->contains('exited'))
- <button @disabled(!auth()->user()->can('deploy', $service)) @click="$wire.dispatch('startEvent')" class="gap-2 button">
+ <x-forms.button canGate="deploy" :canResource="$service" @click="$wire.dispatch('startEvent')" class="gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 dark:text-warning" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" fill="none" stroke-linecap="round"
stroke-linejoin="round">
@@ -94,9 +94,9 @@
<path d="M7 4v16l13 -8z" />
</svg>
Deploy
- </button>
+ </x-forms.button>
@else
- <x-modal-confirmation :disabled="!auth()->user()->can('stop', $service)" title="Confirm Service Stopping?" buttonTitle="Stop" :dispatchEvent="true"
+ <x-modal-confirmation :disabled="!auth()->user()->can('stop', $service)" :authDisabled="!auth()->user()->can('stop', $service)" title="Confirm Service Stopping?" buttonTitle="Stop" :dispatchEvent="true"
submitAction="stop" dispatchEventType="stopEvent" :checkboxes="$checkboxes" :actions="[__('service.stop'), __('resource.non_persistent')]"
:confirmWithText="false" :confirmWithPassword="false" step1ButtonText="Continue" step2ButtonText="Confirm">
<x-slot:button-title>
@@ -113,7 +113,7 @@
Stop
</x-slot:button-title>
</x-modal-confirmation>
- <button @disabled(!auth()->user()->can('deploy', $service)) @click="$wire.dispatch('startEvent')" class="gap-2 button">
+ <x-forms.button canGate="deploy" :canResource="$service" @click="$wire.dispatch('startEvent')" class="gap-2">
<svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 dark:text-warning" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" fill="none" stroke-linecap="round"
stroke-linejoin="round">
@@ -121,7 +121,7 @@
<path d="M7 4v16l13 -8z" />
</svg>
Deploy
- </button>
+ </x-forms.button>
@endif
</div>
@else
@@ -149,11 +149,9 @@
);
return;
}
- window.dispatchEvent(new CustomEvent('startservice'));
$wire.$call('start');
});
$wire.$on('forceDeployEvent', () => {
- window.dispatchEvent(new CustomEvent('startservice'));
$wire.$call('forceDeploy');
});
$wire.$on('restartEvent', async () => {
@@ -166,12 +164,10 @@
}
$wire.$dispatch('info',
'Gracefully stopping service.<br/><br/>It could take a while depending on the service.');
- window.dispatchEvent(new CustomEvent('startservice'));
$wire.$call('restart');
});
$wire.$on('pullAndRestartEvent', () => {
$wire.$dispatch('info', 'Pulling new images and restarting service.');
- window.dispatchEvent(new CustomEvent('startservice'));
$wire.$call('pullAndRestartEvent');
});
$wire.on('imagePulled', () => {
diff --git a/resources/views/livewire/project/shared/environment-variable/show.blade.php b/resources/views/livewire/project/shared/environment-variable/show.blade.php
index 68e1d7e7d9..0bcb127ba5 100644
--- a/resources/views/livewire/project/shared/environment-variable/show.blade.php
+++ b/resources/views/livewire/project/shared/environment-variable/show.blade.php
@@ -139,15 +139,22 @@
@else
<div class="flex flex-col w-full gap-2 lg:flex-row">
<x-forms.input disabled id="key" />
- <x-forms.env-var-input
- disabled
- type="password"
- id="value"
- :availableVars="$this->availableSharedVariables"
- :projectUuid="data_get($parameters, 'project_uuid')"
- :environmentUuid="data_get($parameters, 'environment_uuid')" />
- @if ($is_shared)
- <x-forms.input disabled type="password" id="real_value" />
+ @if ($isValueHidden)
+ <div class="w-full">
+ <input disabled type="text" value="Hidden (only admins can view)"
+ class="input italic !text-neutral-500 dark:!text-neutral-500" />
+ </div>
+ @else
+ <x-forms.env-var-input
+ disabled
+ type="password"
+ id="value"
+ :availableVars="$this->availableSharedVariables"
+ :projectUuid="data_get($parameters, 'project_uuid')"
+ :environmentUuid="data_get($parameters, 'environment_uuid')" />
+ @if ($is_shared)
+ <x-forms.input disabled type="password" id="real_value" />
+ @endif
@endif
</div>
@endcan
diff --git a/resources/views/livewire/project/shared/health-checks.blade.php b/resources/views/livewire/project/shared/health-checks.blade.php
index 47837b2304..01f42dacec 100644
--- a/resources/views/livewire/project/shared/health-checks.blade.php
+++ b/resources/views/livewire/project/shared/health-checks.blade.php
@@ -3,7 +3,7 @@
<h2>Healthchecks</h2>
<x-forms.button canGate="update" :canResource="$resource" type="submit">Save</x-forms.button>
@if (!$healthCheckEnabled)
- <x-modal-confirmation :disabled="!auth()->user()->can('update', $resource)" title="Confirm Healthcheck Enable?" buttonTitle="Enable Healthcheck"
+ <x-modal-confirmation :disabled="!auth()->user()->can('update', $resource)" :authDisabled="!auth()->user()->can('update', $resource)" title="Confirm Healthcheck Enable?" buttonTitle="Enable Healthcheck"
submitAction="toggleHealthcheck" :actions="['Enable healthcheck for this resource.']"
warningMessage="If the health check fails, your application will become inaccessible. Please review the <a href='https://coolify.io/docs/knowledge-base/health-checks' target='_blank' class='underline text-white'>Health Checks</a> guide before proceeding!"
step2ButtonText="Enable Healthcheck" :confirmWithText="false" :confirmWithPassword="false"
diff --git a/resources/views/livewire/project/shared/scheduled-task/show.blade.php b/resources/views/livewire/project/shared/scheduled-task/show.blade.php
index f312c0bf38..6777e96a03 100644
--- a/resources/views/livewire/project/shared/scheduled-task/show.blade.php
+++ b/resources/views/livewire/project/shared/scheduled-task/show.blade.php
@@ -13,36 +13,43 @@
<div class="flex flex-col gap-2 pb-2">
<div class="flex gap-2 items-end">
<h2>Scheduled Task</h2>
- <x-forms.button type="submit">
+ <x-forms.button canGate="update" :canResource="$resource" type="submit">
Save
</x-forms.button>
@if ($resource->isRunning())
- <x-forms.button type="button" wire:click="executeNow">
- Execute Now
- </x-forms.button>
+ @can('update', $resource)
+ <x-forms.button type="button" wire:click="executeNow">
+ Execute Now
+ </x-forms.button>
+ @endcan
@endif
- <x-modal-confirmation title="Confirm Scheduled Task Deletion?" isErrorButton buttonTitle="Delete"
- submitAction="delete({{ $task->id }})" :actions="['The selected scheduled task will be permanently deleted.']" confirmationText="{{ $task->name }}"
- confirmationLabel="Please confirm the execution of the actions by entering the Scheduled Task Name below"
- shortConfirmationLabel="Scheduled Task Name" :confirmWithPassword="false"
- step2ButtonText="Permanently Delete" />
-
+ @can('update', $resource)
+ <x-modal-confirmation title="Confirm Scheduled Task Deletion?" isErrorButton buttonTitle="Delete"
+ submitAction="delete({{ $task->id }})" :actions="['The selected scheduled task will be permanently deleted.']" confirmationText="{{ $task->name }}"
+ confirmationLabel="Please confirm the execution of the actions by entering the Scheduled Task Name below"
+ shortConfirmationLabel="Scheduled Task Name" :confirmWithPassword="false"
+ step2ButtonText="Permanently Delete" />
+ @endcan
</div>
<div class="w-48">
- <x-forms.checkbox instantSave id="isEnabled" label="Enabled" />
+ @can('update', $resource)
+ <x-forms.checkbox instantSave id="isEnabled" label="Enabled" />
+ @else
+ <x-forms.checkbox disabled id="isEnabled" label="Enabled" />
+ @endcan
</div>
<div class="flex gap-2 w-full">
- <x-forms.input placeholder="Name" id="name" label="Name" required />
- <x-forms.input placeholder="php artisan schedule:run" id="command" label="Command" required />
- <x-forms.input placeholder="0 0 * * * or daily" id="frequency" label="Frequency" required />
- <x-forms.input type="number" placeholder="300" id="timeout"
+ <x-forms.input :disabled="!auth()->user()->can('update', $resource)" placeholder="Name" id="name" label="Name" required />
+ <x-forms.input :disabled="!auth()->user()->can('update', $resource)" placeholder="php artisan schedule:run" id="command" label="Command" required />
+ <x-forms.input :disabled="!auth()->user()->can('update', $resource)" placeholder="0 0 * * * or daily" id="frequency" label="Frequency" required />
+ <x-forms.input :disabled="!auth()->user()->can('update', $resource)" type="number" placeholder="300" id="timeout"
helper="Maximum execution time in seconds (60-36000)." label="Timeout (seconds)" required />
@if ($type === 'application')
- <x-forms.input placeholder="php"
+ <x-forms.input :disabled="!auth()->user()->can('update', $resource)" placeholder="php"
helper="You can leave this empty if your resource only has one container." id="container"
label="Container name" />
@elseif ($type === 'service')
- <x-forms.input placeholder="php"
+ <x-forms.input :disabled="!auth()->user()->can('update', $resource)" placeholder="php"
helper="You can leave this empty if your resource only has one service in your stack. Otherwise use the stack name, without the random generated ID. So if you have a mysql service in your stack, use mysql."
id="container" label="Service name" />
@endif
diff --git a/resources/views/livewire/security/api-tokens.blade.php b/resources/views/livewire/security/api-tokens.blade.php
index 1a7b6eb794..bf04aad2ac 100644
--- a/resources/views/livewire/security/api-tokens.blade.php
+++ b/resources/views/livewire/security/api-tokens.blade.php
@@ -18,21 +18,23 @@
<x-forms.input required id="description" label="Description" />
<x-forms.button type="submit">Create</x-forms.button>
</div>
- <div class="flex">
- Permissions
- <x-helper class="px-1" helper="These permissions will be granted to the token." /><span
- class="pr-1">:</span>
- <div class="flex gap-1 font-bold dark:text-white">
- @if ($permissions)
+ <div class="flex items-center gap-2">
+ <span>Permissions</span>
+ <x-helper helper="These permissions will be granted to the token." />
+ @if ($permissions)
+ <div class="flex gap-1.5 flex-wrap">
@foreach ($permissions as $permission)
- <div>{{ $permission }}</div>
+ <span
+ class="px-2 py-0.5 text-xs rounded-sm font-medium {{ $permission === 'root' ? 'bg-red-500/20 text-red-400' : ($permission === 'write' || $permission === 'write:sensitive' ? 'bg-amber-500/20 text-amber-400' : ($permission === 'deploy' ? 'bg-blue-500/20 text-blue-400' : 'bg-neutral-500/20 text-neutral-300')) }}">
+ {{ $permission }}
+ </span>
@endforeach
- @endif
- </div>
+ </div>
+ @endif
</div>
<h4>Token Permissions</h4>
- <div class="w-64">
+ <div class="w-96">
@if ($canUseRootPermissions)
<x-forms.checkbox label="root" wire:model.live="permissions" domValue="root"
helper="Root access, be careful!" :checked="in_array('root', $permissions)"></x-forms.checkbox>
@@ -59,9 +61,14 @@
@endif
<x-forms.checkbox label="read" domValue="read" wire:model.live="permissions" domValue="read"
:checked="in_array('read', $permissions)"></x-forms.checkbox>
- <x-forms.checkbox label="read:sensitive" wire:model.live="permissions" domValue="read:sensitive"
- helper="Responses will include secrets, logs, passwords, and compose file contents."
- :checked="in_array('read:sensitive', $permissions)"></x-forms.checkbox>
+ @if ($canUseSensitivePermissions)
+ <x-forms.checkbox label="read:sensitive" wire:model.live="permissions" domValue="read:sensitive"
+ helper="Responses will include secrets, logs, passwords, and compose file contents."
+ :checked="in_array('read:sensitive', $permissions)"></x-forms.checkbox>
+ @else
+ <x-forms.checkbox label="read:sensitive (admin/owner only)" disabled domValue="read:sensitive"
+ helper="Read:sensitive access requires admin or owner role" :checked="false"></x-forms.checkbox>
+ @endif
@endif
</div>
@if (in_array('root', $permissions))
@@ -70,44 +77,74 @@
</form>
@endcan
@if (session()->has('token'))
- <div class="py-4 font-bold dark:text-warning">Please copy this token now. For your security, it won't be shown
- again.
+ <div class="p-4 my-4 border rounded dark:border-coolgray-200 dark:bg-coolgray-100">
+ <div class="pb-2 font-bold dark:text-warning">Please copy this token now. For your security, it won't
+ be shown again.</div>
+ <div class="relative" x-data="{ copied: false, isSecure: window.isSecureContext }">
+ <input type="text" value="{{ session('token') }}" readonly
+ class="input !text-white !bg-coolgray-200 font-mono" />
+ <button x-show="isSecure"
+ @click.prevent="copied = true; navigator.clipboard.writeText({{ Js::from(session('token')) }}); setTimeout(() => copied = false, 1000)"
+ class="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 text-gray-400 hover:text-gray-300 transition-colors"
+ title="Copy to clipboard">
+ <svg x-show="!copied" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
+ d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
+ </svg>
+ <svg x-show="copied" class="w-5 h-5 text-green-500" fill="none" stroke="currentColor"
+ viewBox="0 0 24 24">
+ <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
+ d="M5 13l4 4L19 7" />
+ </svg>
+ </button>
+ </div>
</div>
- <div class="pb-4 font-bold dark:text-white"> {{ session('token') }}</div>
@endif
- <h3 class="py-4">Issued Tokens</h3>
- <div class="grid gap-2 lg:grid-cols-1">
- @forelse ($tokens as $token)
- <div wire:key="token-{{ $token->id }}"
- class="flex flex-col gap-1 p-2 border dark:border-coolgray-200 hover:no-underline">
- <div>Description: {{ $token->name }}</div>
- <div>Last used: {{ $token->last_used_at ? $token->last_used_at->diffForHumans() : 'Never' }}</div>
- <div class="flex gap-1">
- @if ($token->abilities)
- Permissions:
- @foreach ($token->abilities as $ability)
- <div class="font-bold dark:text-white">{{ $ability }}</div>
- @endforeach
+ <div x-data="{ search: '' }">
+ <div class="flex items-center justify-between py-4">
+ <h3>Issued Tokens</h3>
+ @if ($tokens->count() > 1)
+ <input type="text" x-model="search" placeholder="Filter tokens..."
+ class="input w-64" />
+ @endif
+ </div>
+ <div class="flex flex-col gap-2">
+ @forelse ($tokens as $token)
+ <div wire:key="token-{{ $token->id }}"
+ x-show="!search || '{{ strtolower($token->name) }} {{ strtolower(implode(' ', $token->abilities ?? [])) }}'.includes(search.toLowerCase())"
+ class="flex items-center justify-between p-3 border rounded dark:border-coolgray-200">
+ <div>
+ <div class="flex items-center gap-2">
+ <span class="font-bold dark:text-white">{{ $token->name }}</span>
+ @if ($token->abilities)
+ @foreach ($token->abilities as $ability)
+ <span
+ class="px-2 py-0.5 text-xs rounded-sm font-medium {{ $ability === 'root' ? 'bg-red-500/20 text-red-400' : ($ability === 'write' || $ability === 'write:sensitive' ? 'bg-amber-500/20 text-amber-400' : ($ability === 'deploy' ? 'bg-blue-500/20 text-blue-400' : 'bg-neutral-500/20 text-neutral-300')) }}">
+ {{ $ability }}
+ </span>
+ @endforeach
+ @endif
+ </div>
+ <div class="text-xs text-neutral-400">
+ Last used: {{ $token->last_used_at ? $token->last_used_at->diffForHumans() : 'Never' }}
+ </div>
+ </div>
+ @if (auth()->id() === $token->tokenable_id)
+ <x-modal-confirmation title="Confirm API Token Revocation?" isErrorButton
+ buttonTitle="Revoke" submitAction="revoke({{ data_get($token, 'id') }})"
+ :actions="[
+ 'This API Token will be revoked and permanently deleted.',
+ 'Any API call made with this token will fail.',
+ ]" confirmationText="{{ $token->name }}"
+ confirmationLabel="Please confirm the execution of the actions by entering the API Token Description below"
+ shortConfirmationLabel="API Token Description" :confirmWithPassword="false"
+ step2ButtonText="Revoke API Token" />
@endif
</div>
-
- @if (auth()->id() === $token->tokenable_id)
- <x-modal-confirmation title="Confirm API Token Revocation?" isErrorButton buttonTitle="Revoke token"
- submitAction="revoke({{ data_get($token, 'id') }})" :actions="[
- 'This API Token will be revoked and permanently deleted.',
- 'Any API call made with this token will fail.',
- ]"
- confirmationText="{{ $token->name }}"
- confirmationLabel="Please confirm the execution of the actions by entering the API Token Description below"
- shortConfirmationLabel="API Token Description" :confirmWithPassword="false"
- step2ButtonText="Revoke API Token" />
- @endif
- </div>
- @empty
- <div>
- <div>No API tokens found.</div>
- </div>
- @endforelse
+ @empty
+ <div class="text-neutral-400">No API tokens found.</div>
+ @endforelse
+ </div>
</div>
@endif
</div>
diff --git a/tests/Feature/Authorization/EnvironmentVariableValueHidingTest.php b/tests/Feature/Authorization/EnvironmentVariableValueHidingTest.php
new file mode 100644
index 0000000000..e30e2ad62f
--- /dev/null
+++ b/tests/Feature/Authorization/EnvironmentVariableValueHidingTest.php
@@ -0,0 +1,274 @@
+<?php
+
+use App\Livewire\Project\Shared\EnvironmentVariable\All as EnvironmentVariableAll;
+use App\Livewire\Project\Shared\EnvironmentVariable\Show as EnvironmentVariableShow;
+use App\Models\Application;
+use App\Models\EnvironmentVariable;
+use App\Models\InstanceSettings;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\StandaloneDocker;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ InstanceSettings::updateOrCreate(['id' => 0], ['is_api_enabled' => true]);
+
+ $this->team = Team::factory()->create();
+
+ $this->admin = User::factory()->create();
+ $this->admin->teams()->attach($this->team, ['role' => 'admin']);
+
+ $this->member = User::factory()->create();
+ $this->member->teams()->attach($this->team, ['role' => 'member']);
+
+ $keyId = DB::table('private_keys')->insertGetId([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'Test Key',
+ 'private_key' => 'test-key',
+ 'team_id' => $this->team->id,
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ]);
+
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $keyId,
+ ]);
+
+ StandaloneDocker::withoutEvents(function () {
+ $this->destination = StandaloneDocker::firstOrCreate(
+ ['server_id' => $this->server->id, 'network' => 'coolify'],
+ ['uuid' => (string) Str::uuid(), 'name' => 'test-docker']
+ );
+ });
+
+ $this->project = Project::create([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'Test Project',
+ 'team_id' => $this->team->id,
+ ]);
+
+ $this->environment = $this->project->environments()->first();
+
+ $this->application = Application::factory()->create([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'Test App',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ ]);
+
+ $this->unlockedEnv = EnvironmentVariable::create([
+ 'key' => 'UNLOCKED_VAR',
+ 'value' => 'secret-unlocked-value',
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ 'is_preview' => false,
+ 'is_shown_once' => false,
+ 'is_multiline' => false,
+ 'is_literal' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => true,
+ ]);
+
+ $this->lockedEnv = EnvironmentVariable::create([
+ 'key' => 'LOCKED_VAR',
+ 'value' => 'secret-locked-value',
+ 'resourceable_type' => Application::class,
+ 'resourceable_id' => $this->application->id,
+ 'is_preview' => false,
+ 'is_shown_once' => true,
+ 'is_multiline' => false,
+ 'is_literal' => false,
+ 'is_runtime' => true,
+ 'is_buildtime' => true,
+ ]);
+});
+
+// --- Livewire Show component: locked env values ---
+
+test('admin sees unlocked env value in Show component', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableShow::class, [
+ 'env' => $this->unlockedEnv,
+ 'type' => 'application',
+ ]);
+
+ expect($component->get('value'))->toBe('secret-unlocked-value');
+});
+
+test('admin cannot see locked env value in Show component', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableShow::class, [
+ 'env' => $this->lockedEnv,
+ 'type' => 'application',
+ ]);
+
+ expect($component->get('value'))->toBeNull();
+ expect($component->get('real_value'))->toBeNull();
+});
+
+test('member cannot see any env value in Show component', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableShow::class, [
+ 'env' => $this->unlockedEnv,
+ 'type' => 'application',
+ ]);
+
+ expect($component->get('value'))->toBeNull();
+ expect($component->get('real_value'))->toBeNull();
+});
+
+test('member has isValueHidden flag set to true', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableShow::class, [
+ 'env' => $this->unlockedEnv,
+ 'type' => 'application',
+ ]);
+
+ expect($component->get('isValueHidden'))->toBeTrue();
+});
+
+test('admin has isValueHidden flag set to false', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableShow::class, [
+ 'env' => $this->unlockedEnv,
+ 'type' => 'application',
+ ]);
+
+ expect($component->get('isValueHidden'))->toBeFalse();
+});
+
+// --- Livewire All component: dev view ---
+
+test('admin dev view shows unlocked env value', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableAll::class, [
+ 'resource' => $this->application,
+ ]);
+
+ expect($component->get('variables'))->toContain('UNLOCKED_VAR=secret-unlocked-value');
+});
+
+test('admin dev view hides locked env value', function () {
+ $this->actingAs($this->admin);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableAll::class, [
+ 'resource' => $this->application,
+ ]);
+
+ expect($component->get('variables'))->toContain('LOCKED_VAR=(Locked Secret, delete and add again to change)');
+ expect($component->get('variables'))->not->toContain('secret-locked-value');
+});
+
+test('member dev view hides all env values', function () {
+ $this->actingAs($this->member);
+ session(['currentTeam' => $this->team]);
+
+ $component = Livewire::test(EnvironmentVariableAll::class, [
+ 'resource' => $this->application,
+ ]);
+
+ expect($component->get('variables'))->not->toContain('secret-unlocked-value');
+ expect($component->get('variables'))->not->toContain('secret-locked-value');
+ expect($component->get('variables'))->toContain('UNLOCKED_VAR=(Hidden');
+});
+
+// --- API: locked env values hidden ---
+
+test('API hides locked env value even with read:sensitive token', function () {
+ session(['currentTeam' => $this->team]);
+ $token = $this->admin->createToken('admin-sensitive', ['read', 'read:sensitive']);
+
+ $response = $this->withHeaders([
+ 'Authorization' => 'Bearer '.$token->plainTextToken,
+ ])->getJson("/api/v1/applications/{$this->application->uuid}/envs");
+
+ $response->assertOk();
+
+ $envs = collect($response->json());
+ $locked = $envs->firstWhere('key', 'LOCKED_VAR');
+ $unlocked = $envs->firstWhere('key', 'UNLOCKED_VAR');
+
+ expect($locked)->not->toBeNull();
+ expect($locked)->not->toHaveKey('value');
+ expect($locked)->not->toHaveKey('real_value');
+
+ expect($unlocked)->not->toBeNull();
+ expect($unlocked)->toHaveKey('value');
+});
+
+test('API hides locked env value with root token', function () {
+ session(['currentTeam' => $this->team]);
+ $token = $this->admin->createToken('admin-root', ['root']);
+
+ $response = $this->withHeaders([
+ 'Authorization' => 'Bearer '.$token->plainTextToken,
+ ])->getJson("/api/v1/applications/{$this->application->uuid}/envs");
+
+ $response->assertOk();
+
+ $envs = collect($response->json());
+ $locked = $envs->firstWhere('key', 'LOCKED_VAR');
+
+ expect($locked)->not->toBeNull();
+ expect($locked)->not->toHaveKey('value');
+ expect($locked)->not->toHaveKey('real_value');
+});
+
+// --- API: member role hides env values ---
+
+test('API hides env values for member even with read:sensitive token', function () {
+ session(['currentTeam' => $this->team]);
+ $token = $this->member->createToken('member-sensitive', ['read', 'read:sensitive']);
+
+ $response = $this->withHeaders([
+ 'Authorization' => 'Bearer '.$token->plainTextToken,
+ ])->getJson("/api/v1/applications/{$this->application->uuid}/envs");
+
+ $response->assertOk();
+
+ $envs = collect($response->json());
+ $unlocked = $envs->firstWhere('key', 'UNLOCKED_VAR');
+
+ expect($unlocked)->not->toBeNull();
+ expect($unlocked)->not->toHaveKey('value');
+ expect($unlocked)->not->toHaveKey('real_value');
+});
+
+test('API shows env values for admin with read:sensitive token', function () {
+ session(['currentTeam' => $this->team]);
+ $token = $this->admin->createToken('admin-sensitive-2', ['read', 'read:sensitive']);
+
+ $response = $this->withHeaders([
+ 'Authorization' => 'Bearer '.$token->plainTextToken,
+ ])->getJson("/api/v1/applications/{$this->application->uuid}/envs");
+
+ $response->assertOk();
+
+ $envs = collect($response->json());
+ $unlocked = $envs->firstWhere('key', 'UNLOCKED_VAR');
+
+ expect($unlocked)->not->toBeNull();
+ expect($unlocked)->toHaveKey('value');
+});
diff --git a/tests/Feature/Authorization/LegacyMemberTokenTest.php b/tests/Feature/Authorization/LegacyMemberTokenTest.php
new file mode 100644
index 0000000000..2733279859
--- /dev/null
+++ b/tests/Feature/Authorization/LegacyMemberTokenTest.php
@@ -0,0 +1,127 @@
+<?php
+
+use App\Models\InstanceSettings;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ InstanceSettings::create(['id' => 0, 'is_api_enabled' => true]);
+
+ $this->team = Team::factory()->create();
+ $this->member = User::factory()->create();
+ $this->admin = User::factory()->create();
+
+ $this->team->members()->attach($this->member->id, ['role' => 'member']);
+ $this->team->members()->attach($this->admin->id, ['role' => 'admin']);
+
+ session(['currentTeam' => $this->team]);
+});
+
+function apiRequest($test, string $token, string $method = 'get', string $url = '/api/v1/version')
+{
+ return $test->withHeaders([
+ 'Authorization' => 'Bearer '.$token,
+ 'Content-Type' => 'application/json',
+ ])->{$method.'Json'}($url);
+}
+
+describe('member with legacy elevated token is rejected', function () {
+ test('member with legacy write token gets 403 with descriptive message', function () {
+ $token = $this->member->createToken('legacy-write', ['read', 'write']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(403);
+ $response->assertJsonFragment([
+ 'message' => 'This API token has permissions (write) that exceed your current role as a team member. Members are restricted to read-only API access. Please revoke this token and create a new one with only read permissions.',
+ ]);
+ });
+
+ test('member with legacy deploy token gets 403', function () {
+ $token = $this->member->createToken('legacy-deploy', ['read', 'deploy']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(403);
+ $response->assertSee('deploy');
+ $response->assertSee('revoke this token');
+ });
+
+ test('member with legacy root token gets 403', function () {
+ $token = $this->member->createToken('legacy-root', ['root']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(403);
+ $response->assertSee('root');
+ });
+
+ test('member with legacy read:sensitive token gets 403', function () {
+ $token = $this->member->createToken('legacy-sensitive', ['read', 'read:sensitive']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(403);
+ $response->assertSee('read:sensitive');
+ });
+
+ test('member with legacy write:sensitive token gets 403', function () {
+ $token = $this->member->createToken('legacy-ws', ['read', 'write:sensitive']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(403);
+ $response->assertSee('write:sensitive');
+ });
+
+ test('member with multiple disallowed abilities lists them all', function () {
+ $token = $this->member->createToken('legacy-multi', ['read', 'write', 'deploy', 'read:sensitive']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(403);
+ $json = $response->json();
+ expect($json['message'])->toContain('write');
+ expect($json['message'])->toContain('deploy');
+ expect($json['message'])->toContain('read:sensitive');
+ });
+});
+
+describe('member with read-only token passes through', function () {
+ test('member with read token can access read endpoints', function () {
+ $token = $this->member->createToken('read-only', ['read']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(200);
+ });
+});
+
+describe('admin with elevated token passes through', function () {
+ test('admin with write token is not blocked', function () {
+ $token = $this->admin->createToken('admin-write', ['read', 'write']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(200);
+ });
+
+ test('admin with root token is not blocked', function () {
+ $token = $this->admin->createToken('admin-root', ['root']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(200);
+ });
+
+ test('admin with deploy token is not blocked', function () {
+ $token = $this->admin->createToken('admin-deploy', ['read', 'deploy']);
+
+ $response = apiRequest($this, $token->plainTextToken);
+
+ $response->assertStatus(200);
+ });
+});
diff --git a/tests/Unit/Policies/ApiTokenPolicyTest.php b/tests/Unit/Policies/ApiTokenPolicyTest.php
index 98b59319a3..98c60aae8c 100644
--- a/tests/Unit/Policies/ApiTokenPolicyTest.php
+++ b/tests/Unit/Policies/ApiTokenPolicyTest.php
@@ -165,3 +165,29 @@ it('denies member from using deploy permissions', function () {
$policy = new ApiTokenPolicy;
expect($policy->useDeployPermissions($user))->toBeFalse();
});
+
+it('allows admin to use sensitive permissions', function () {
+ $user = Mockery::mock(User::class)->makePartial();
+ $user->shouldReceive('isAdmin')->andReturn(true);
+
+ $policy = new ApiTokenPolicy;
+ expect($policy->useSensitivePermissions($user))->toBeTrue();
+});
+
+it('allows owner to use sensitive permissions', function () {
+ $user = Mockery::mock(User::class)->makePartial();
+ $user->shouldReceive('isAdmin')->andReturn(false);
+ $user->shouldReceive('isOwner')->andReturn(true);
+
+ $policy = new ApiTokenPolicy;
+ expect($policy->useSensitivePermissions($user))->toBeTrue();
+});
+
+it('denies member from using sensitive permissions', function () {
+ $user = Mockery::mock(User::class)->makePartial();
+ $user->shouldReceive('isAdmin')->andReturn(false);
+ $user->shouldReceive('isOwner')->andReturn(false);
+
+ $policy = new ApiTokenPolicy;
+ expect($policy->useSensitivePermissions($user))->toBeFalse();
+});
diff --git a/tests/Unit/Policies/S3StoragePolicyTest.php b/tests/Unit/Policies/S3StoragePolicyTest.php
index 4ea580d0fa..70ffdf7182 100644
--- a/tests/Unit/Policies/S3StoragePolicyTest.php
+++ b/tests/Unit/Policies/S3StoragePolicyTest.php
@@ -52,7 +52,23 @@ it('allows team admin to update S3 storage from their team', function () {
expect($policy->update($user, $storage))->toBeTrue();
});
-it('denies team member to update S3 storage from another team', function () {
+it('denies team member to update S3 storage from their team', function () {
+ $teams = collect([
+ (object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
+ ]);
+
+ $user = Mockery::mock(User::class)->makePartial();
+ $user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
+
+ $storage = Mockery::mock(S3Storage::class)->makePartial();
+ $storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
+ $storage->team_id = 1;
+
+ $policy = new S3StoragePolicy;
+ expect($policy->update($user, $storage))->toBeFalse();
+});
+
+it('denies team admin to update S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
@@ -68,9 +84,9 @@ it('denies team member to update S3 storage from another team', function () {
expect($policy->update($user, $storage))->toBeFalse();
});
-it('allows team member to delete S3 storage from their team', function () {
+it('allows team admin to delete S3 storage from their team', function () {
$teams = collect([
- (object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
+ (object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
@@ -84,7 +100,23 @@ it('allows team member to delete S3 storage from their team', function () {
expect($policy->delete($user, $storage))->toBeTrue();
});
-it('denies team member to delete S3 storage from another team', function () {
+it('denies team member to delete S3 storage from their team', function () {
+ $teams = collect([
+ (object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
+ ]);
+
+ $user = Mockery::mock(User::class)->makePartial();
+ $user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
+
+ $storage = Mockery::mock(S3Storage::class)->makePartial();
+ $storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
+ $storage->team_id = 1;
+
+ $policy = new S3StoragePolicy;
+ expect($policy->delete($user, $storage))->toBeFalse();
+});
+
+it('denies team admin to delete S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'owner']],
]);
@@ -116,9 +148,9 @@ it('denies non-admin to create S3 storage', function () {
expect($policy->create($user))->toBeFalse();
});
-it('allows team member to validate connection of S3 storage from their team', function () {
+it('allows team admin to validate connection of S3 storage from their team', function () {
$teams = collect([
- (object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
+ (object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
@@ -132,7 +164,23 @@ it('allows team member to validate connection of S3 storage from their team', fu
expect($policy->validateConnection($user, $storage))->toBeTrue();
});
-it('denies team member to validate connection of S3 storage from another team', function () {
+it('denies team member to validate connection of S3 storage from their team', function () {
+ $teams = collect([
+ (object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
+ ]);
+
+ $user = Mockery::mock(User::class)->makePartial();
+ $user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
+
+ $storage = Mockery::mock(S3Storage::class)->makePartial();
+ $storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
+ $storage->team_id = 1;
+
+ $policy = new S3StoragePolicy;
+ expect($policy->validateConnection($user, $storage))->toBeFalse();
+});
+
+it('denies team admin to validate connection of S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);