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.

feat(audit): log account, resource, and instance settings changes

Andras Bacsai16a8c7999d65
diff --git a/app/Http/Controllers/Api/ServiceApplicationsController.php b/app/Http/Controllers/Api/ServiceApplicationsController.php
index 49380f2a42..586ee7f538 100644
--- a/app/Http/Controllers/Api/ServiceApplicationsController.php
+++ b/app/Http/Controllers/Api/ServiceApplicationsController.php
@@ -373,6 +373,13 @@ class ServiceApplicationsController extends Controller
$serviceApplication->refresh();
+ auditLog('api.service_application.updated', [
+ 'team_id' => $teamId,
+ 'service_uuid' => $service->uuid,
+ 'service_application_uuid' => $serviceApplication->uuid,
+ 'changed_fields' => array_keys($payload),
+ ]);
+
return response()->json($this->removeSensitiveData($serviceApplication));
}
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php
index 8add69a697..52a0868c92 100644
--- a/app/Http/Controllers/Controller.php
+++ b/app/Http/Controllers/Controller.php
@@ -132,7 +132,8 @@ class Controller extends BaseController
[$user, $invitation] = $credentials;
$team = $invitation->team;
- if (! $user->teams()->where('team_id', $team->id)->exists()) {
+ $alreadyMember = $user->teams()->where('team_id', $team->id)->exists();
+ if (! $alreadyMember) {
$user->teams()->attach($team->id, ['role' => $invitation->role]);
}
@@ -141,17 +142,18 @@ class Controller extends BaseController
])->save();
$invitation->delete();
- return [$user, $team];
+ return [$user, $team, $invitation, $alreadyMember];
});
if (! $acceptedInvitation) {
return redirect()->route('login')->with('error', 'Invitation has expired or been revoked.');
}
- [$user, $team] = $acceptedInvitation;
+ [$user, $team, $invitation, $alreadyMember] = $acceptedInvitation;
Auth::login($user);
session(['currentTeam' => $team]);
+ $this->auditInvitationAccepted($user, $invitation, $alreadyMember);
return redirect()->route('dashboard');
}
@@ -253,14 +255,34 @@ class Controller extends BaseController
if ($user->teams()->where('team_id', $invitation->team->id)->exists()) {
$invitation->delete();
+ $this->auditInvitationAccepted($user, $invitation, alreadyMember: true);
return redirect()->route('team.index');
}
$user->teams()->attach($invitation->team->id, ['role' => $invitation->role]);
$invitation->delete();
+ $this->auditInvitationAccepted($user, $invitation, alreadyMember: false);
refreshSession($invitation->team);
return redirect()->route('team.index');
}
+
+ private function auditInvitationAccepted(User $user, TeamInvitation $invitation, bool $alreadyMember): void
+ {
+ auditLog('ui.team_invitation.accepted', [
+ 'team_id' => $invitation->team_id,
+ 'invitation_uuid' => $invitation->uuid,
+ 'invitation_email' => $invitation->email,
+ 'role' => $invitation->role,
+ 'via' => $invitation->via,
+ 'already_member' => $alreadyMember,
+ 'member_id' => $user->id,
+ 'member_name' => $user->name,
+ 'member_email' => $user->email,
+ 'actor_id' => $user->id,
+ 'actor_name' => $user->name,
+ 'actor_email' => $user->email,
+ ]);
+ }
}
diff --git a/app/Livewire/Admin/Index.php b/app/Livewire/Admin/Index.php
index 535ed2bf0c..71e0f6eb71 100644
--- a/app/Livewire/Admin/Index.php
+++ b/app/Livewire/Admin/Index.php
@@ -70,6 +70,14 @@ class Index extends Component
abort(404);
}
$team_to_switch_to = $user->resolveStoredTeam() ?? $user->teams->first();
+ auditLog('ui.user.impersonated', [
+ 'team_id' => currentTeam()?->id,
+ 'resource' => 'user',
+ 'user_name' => $user->name,
+ 'target_user_id' => $user->id,
+ 'target_user_email' => $user->email,
+ 'target_team_id' => $team_to_switch_to?->id,
+ ]);
Auth::login($user);
refreshSession($team_to_switch_to);
diff --git a/app/Livewire/Concerns/AuditsStorageChanges.php b/app/Livewire/Concerns/AuditsStorageChanges.php
new file mode 100644
index 0000000000..007f651b03
--- /dev/null
+++ b/app/Livewire/Concerns/AuditsStorageChanges.php
@@ -0,0 +1,79 @@
+<?php
+
+namespace App\Livewire\Concerns;
+
+use App\Models\Application;
+use App\Models\LocalFileVolume;
+use App\Models\LocalPersistentVolume;
+use App\Models\ServiceApplication;
+use App\Models\ServiceDatabase;
+use Illuminate\Database\Eloquent\Model;
+
+/**
+ * Records `ui.{application|service|database}.storage_*` audit events that mirror the storage API events.
+ * File content is never part of the context.
+ */
+trait AuditsStorageChanges
+{
+ /**
+ * @param 'created'|'updated'|'deleted' $action
+ * @param array<string, mixed> $extra
+ */
+ protected function auditStorageChange(Model $resource, string $action, LocalPersistentVolume|LocalFileVolume $storage, array $extra = []): void
+ {
+ [$resourceKey, $resourceContext] = $this->storageAuditResourceContext($resource);
+
+ auditLog("ui.{$resourceKey}.storage_{$action}", array_merge([
+ 'team_id' => $resource->team()?->id,
+ ], $resourceContext, [
+ 'storage_uuid' => $storage->uuid ?? null,
+ 'storage_id' => $storage->id,
+ 'storage_type' => $this->storageAuditType($storage),
+ 'storage_name' => $storage instanceof LocalPersistentVolume ? $storage->name : null,
+ 'mount_path' => $storage->mount_path,
+ 'host_path' => $storage instanceof LocalFileVolume ? $storage->fs_path : $storage->host_path,
+ ], $extra));
+ }
+
+ /**
+ * @return array{0: string, 1: array<string, mixed>}
+ */
+ private function storageAuditResourceContext(Model $resource): array
+ {
+ if ($resource instanceof Application) {
+ return ['application', [
+ 'application_uuid' => $resource->uuid,
+ 'application_name' => $resource->name,
+ ]];
+ }
+
+ if ($resource instanceof ServiceApplication || $resource instanceof ServiceDatabase) {
+ $subResourceKey = $resource instanceof ServiceApplication ? 'service_application' : 'service_database';
+
+ return ['service', [
+ 'service_uuid' => $resource->service?->uuid,
+ 'service_name' => $resource->service?->name,
+ "{$subResourceKey}_uuid" => $resource->uuid,
+ "{$subResourceKey}_name" => $resource->name,
+ ]];
+ }
+
+ return ['database', [
+ 'database_uuid' => $resource->getAttribute('uuid'),
+ 'database_name' => $resource->getAttribute('name'),
+ ]];
+ }
+
+ private function storageAuditType(LocalPersistentVolume|LocalFileVolume $storage): string
+ {
+ if ($storage instanceof LocalPersistentVolume) {
+ return 'persistent';
+ }
+
+ return match (true) {
+ (bool) $storage->is_host_file => 'host_file',
+ (bool) $storage->is_directory => 'directory',
+ default => 'file',
+ };
+ }
+}
diff --git a/app/Livewire/Destination/New/Docker.php b/app/Livewire/Destination/New/Docker.php
index 2569743878..702bc29f4f 100644
--- a/app/Livewire/Destination/New/Docker.php
+++ b/app/Livewire/Destination/New/Docker.php
@@ -98,6 +98,14 @@ class Docker extends Component
}
}
+ auditLog('ui.destination.created', [
+ 'team_id' => $this->selectedServer->team_id,
+ 'destination_uuid' => $docker->uuid,
+ 'destination_name' => $docker->name,
+ 'destination_type' => $isSwarm ? 'swarm' : 'standalone',
+ 'server_uuid' => $this->selectedServer->uuid,
+ ]);
+
return redirectRoute($this, 'destination.show', [$docker->uuid]);
} catch (\Throwable $e) {
return handleError($e, $this);
diff --git a/app/Livewire/Destination/Show.php b/app/Livewire/Destination/Show.php
index b0ab4d183e..e887abed9e 100644
--- a/app/Livewire/Destination/Show.php
+++ b/app/Livewire/Destination/Show.php
@@ -3,6 +3,7 @@
namespace App\Livewire\Destination;
use App\Models\StandaloneDocker;
+use App\Models\SwarmDocker;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
@@ -50,7 +51,13 @@ class Show extends Component
$this->destination->name = $this->name;
$this->destination->network = $this->network;
$this->destination->server->ip = $this->serverIp;
+ $changedFields = auditChangedFields($this->destination);
$this->destination->save();
+ if ($changedFields !== []) {
+ auditLog('ui.destination.updated', $this->auditContext([
+ 'changed_fields' => $changedFields,
+ ]));
+ }
} else {
$this->name = $this->destination->name;
$this->network = $this->destination->network;
@@ -83,7 +90,9 @@ class Show extends Component
instant_remote_process(["docker network disconnect {$safeNetwork} coolify-proxy"], $this->destination->server, throwError: false);
instant_remote_process([dockerNetworkRemoveCommand($this->destination->network)], $this->destination->server);
}
+ $auditContext = $this->auditContext();
$this->destination->delete();
+ auditLog('ui.destination.deleted', $auditContext);
return redirectRoute($this, 'destination.index');
} catch (\Throwable $e) {
@@ -91,6 +100,21 @@ class Show extends Component
}
}
+ /**
+ * @param array<string, mixed> $context
+ * @return array<string, mixed>
+ */
+ private function auditContext(array $context = []): array
+ {
+ return array_merge([
+ 'team_id' => $this->destination->server?->team_id,
+ 'destination_uuid' => $this->destination->uuid,
+ 'destination_name' => $this->destination->name,
+ 'destination_type' => $this->destination instanceof SwarmDocker ? 'swarm' : 'standalone',
+ 'server_uuid' => $this->destination->server?->uuid,
+ ], $context);
+ }
+
public function render()
{
return view('livewire.destination.show');
diff --git a/app/Livewire/ForcePasswordReset.php b/app/Livewire/ForcePasswordReset.php
index 2463c68e49..d303abf92a 100644
--- a/app/Livewire/ForcePasswordReset.php
+++ b/app/Livewire/ForcePasswordReset.php
@@ -47,10 +47,19 @@ class ForcePasswordReset extends Component
try {
$this->rateLimit(10);
$this->validate();
- auth()->user()->fill([
+ $user = auth()->user();
+ // Changing the password invalidates the session, which clears the current team.
+ $teamId = $user->currentTeam()?->id;
+ $user->fill([
'password' => Hash::make($this->password),
'force_password_reset' => false,
])->save();
+ auditLog('ui.user.password_changed', [
+ 'team_id' => $teamId,
+ 'resource' => 'user',
+ 'user_name' => $user->name,
+ 'reason' => 'forced_reset',
+ ]);
return redirect()->route('dashboard');
} catch (\Throwable $e) {
diff --git a/app/Livewire/Project/Application/Backup/Create.php b/app/Livewire/Project/Application/Backup/Create.php
index f26d81b887..9b80c8832a 100644
--- a/app/Livewire/Project/Application/Backup/Create.php
+++ b/app/Livewire/Project/Application/Backup/Create.php
@@ -111,14 +111,26 @@ class Create extends Component
}
try {
- $backup = $target->scheduledBackups()->updateOrCreate(
- [],
- [
- 'team_id' => currentTeam()->id,
- 'frequency' => $this->frequency,
- 'enabled' => true,
- ],
- );
+ $backup = $target->scheduledBackups()->firstOrNew();
+ $backup->fill([
+ 'team_id' => currentTeam()->id,
+ 'frequency' => $this->frequency,
+ 'enabled' => true,
+ ]);
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ if ($backup->wasRecentlyCreated || $changedFields !== []) {
+ auditLog('ui.volume_backup.schedule_set', [
+ 'team_id' => $backup->team_id,
+ 'resource_type' => 'application',
+ 'resource_uuid' => $this->application->uuid,
+ 'resource_name' => $this->application->name,
+ 'storage_uuid' => $target->uuid,
+ 'backup_uuid' => $backup->uuid,
+ 'created' => $backup->wasRecentlyCreated,
+ ...($backup->wasRecentlyCreated ? [] : ['changed_fields' => $changedFields]),
+ ]);
+ }
$this->dispatch('success', $backup->wasRecentlyCreated ? 'Scheduled storage backup created.' : 'Scheduled storage backup updated.');
redirectRoute($this, 'project.application.backup.show', [
diff --git a/app/Livewire/Project/Application/Deployment/Show.php b/app/Livewire/Project/Application/Deployment/Show.php
index a1657f55bf..a33efe5f80 100644
--- a/app/Livewire/Project/Application/Deployment/Show.php
+++ b/app/Livewire/Project/Application/Deployment/Show.php
@@ -4,10 +4,13 @@ namespace App\Livewire\Project\Application\Deployment;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
+use App\Traits\AuditsApplicationSettings;
use Livewire\Component;
class Show extends Component
{
+ use AuditsApplicationSettings;
+
public Application $application;
public ApplicationDeploymentQueue $application_deployment_queue;
@@ -71,7 +74,7 @@ class Show extends Component
try {
$this->authorize('update', $this->application);
$this->application->settings->is_debug_enabled = ! $this->application->settings->is_debug_enabled;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
$this->is_debug_enabled = $this->application->settings->is_debug_enabled;
$this->application_deployment_queue->refresh();
} catch (\Throwable $e) {
diff --git a/app/Livewire/Project/Application/DeploymentNavbar.php b/app/Livewire/Project/Application/DeploymentNavbar.php
index fd97ac35eb..05b0165080 100644
--- a/app/Livewire/Project/Application/DeploymentNavbar.php
+++ b/app/Livewire/Project/Application/DeploymentNavbar.php
@@ -6,13 +6,14 @@ use App\Enums\ApplicationDeploymentStatus;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Server;
+use App\Traits\AuditsApplicationSettings;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Carbon;
use Livewire\Component;
class DeploymentNavbar extends Component
{
- use AuthorizesRequests;
+ use AuditsApplicationSettings, AuthorizesRequests;
public ApplicationDeploymentQueue $application_deployment_queue;
@@ -43,7 +44,7 @@ class DeploymentNavbar extends Component
try {
$this->authorize('update', $this->application);
$this->application->settings->is_debug_enabled = ! $this->application->settings->is_debug_enabled;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
$this->is_debug_enabled = $this->application->settings->is_debug_enabled;
$this->dispatch('refreshQueue');
} catch (\Throwable $e) {
diff --git a/app/Livewire/Project/Application/Domains.php b/app/Livewire/Project/Application/Domains.php
index fef335ade0..1f7f782551 100644
--- a/app/Livewire/Project/Application/Domains.php
+++ b/app/Livewire/Project/Application/Domains.php
@@ -12,6 +12,7 @@ use App\Models\Server;
use App\Support\DomainPortOverrides;
use App\Support\DomainUrlParts;
use App\Support\ValidationPatterns;
+use App\Traits\AuditsApplicationSettings;
use App\Traits\ListensToTeamChannel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
@@ -22,6 +23,7 @@ use Livewire\Component;
class Domains extends Component
{
+ use AuditsApplicationSettings;
use AuthorizesRequests;
use InteractsWithCloudflareDomainConnect;
use InteractsWithDnsProviders;
@@ -247,7 +249,7 @@ class Domains extends Component
$this->validateOnly('isForceHttpsEnabled');
$this->application->settings->is_force_https_enabled = $this->isForceHttpsEnabled;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
$this->resetDefaultLabels();
$this->dispatch('configurationChanged')->to(ConfigurationChecker::class);
$this->dispatch('success', 'HTTP to HTTPS redirect updated.');
diff --git a/app/Livewire/Project/Application/General.php b/app/Livewire/Project/Application/General.php
index 531aa834c0..5d272b36fa 100644
--- a/app/Livewire/Project/Application/General.php
+++ b/app/Livewire/Project/Application/General.php
@@ -10,6 +10,7 @@ use App\Models\Application;
use App\Rules\ValidGitBranch;
use App\Services\Dns\ManagedDnsRecordCleanup;
use App\Support\ValidationPatterns;
+use App\Traits\AuditsApplicationSettings;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
@@ -20,6 +21,7 @@ use Livewire\Features\SupportEvents\Event;
class General extends Component
{
+ use AuditsApplicationSettings;
use AuthorizesRequests;
public string $applicationId;
@@ -416,7 +418,7 @@ class General extends Component
$this->application->settings->is_container_label_escape_enabled = $this->isContainerLabelEscapeEnabled;
$this->application->settings->is_container_label_readonly_enabled = $this->isContainerLabelReadonlyEnabled;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
} else {
// From model to properties
$this->name = $this->application->name;
@@ -629,7 +631,7 @@ class General extends Component
if ($this->buildPack !== 'nixpacks' && $this->buildPack !== 'railpack') {
$this->isStatic = false;
$this->application->settings->is_static = false;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
} else {
$this->resetDefaultLabels(false);
}
diff --git a/app/Livewire/Project/Application/PreviewDomains.php b/app/Livewire/Project/Application/PreviewDomains.php
index 65ba5afba7..5e9a942a63 100644
--- a/app/Livewire/Project/Application/PreviewDomains.php
+++ b/app/Livewire/Project/Application/PreviewDomains.php
@@ -489,7 +489,20 @@ class PreviewDomains extends Component
foreach ($this->domainRows as $index => $row) {
$this->domainRows[$index]['url'] = DomainPortOverrides::withoutPort($row['url']);
}
+ $changedFields = array_values(array_intersect(
+ auditChangedFields($this->preview),
+ ['fqdn', 'docker_compose_domains', 'domain_port_overrides'],
+ ));
$this->preview->save();
+ if ($changedFields !== []) {
+ auditLog('ui.application.preview_updated', [
+ 'team_id' => $this->preview->application->team()?->id,
+ 'application_uuid' => $this->preview->application->uuid,
+ 'application_name' => $this->preview->application->name,
+ 'pull_request_id' => $this->preview->pull_request_id,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
$dnsCleanup->queueReleaseOfRemovedHostnames($this->preview, $previousDnsHostnames, currentTeam()->id);
$this->persistDnsStatuses();
$this->refreshDomains();
diff --git a/app/Livewire/Project/Application/Previews.php b/app/Livewire/Project/Application/Previews.php
index 86dbf4e800..edcd09e05c 100644
--- a/app/Livewire/Project/Application/Previews.php
+++ b/app/Livewire/Project/Application/Previews.php
@@ -7,13 +7,14 @@ use App\Events\ServiceStatusChanged;
use App\Jobs\DeleteResourceJob;
use App\Models\Application;
use App\Models\ApplicationPreview;
+use App\Traits\AuditsApplicationSettings;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection;
use Livewire\Component;
class Previews extends Component
{
- use AuthorizesRequests;
+ use AuditsApplicationSettings, AuthorizesRequests;
protected $listeners = ['previewDomainsChanged' => 'refreshPreviewDomains'];
@@ -62,7 +63,7 @@ class Previews extends Component
$this->application->settings->is_preview_deployments_enabled = $this->isPreviewDeploymentsEnabled;
$this->application->settings->is_pr_deployments_public_enabled = $this->isPrDeploymentsPublicEnabled;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
$this->dispatch('success', 'Settings saved.');
$this->dispatch('configurationChanged');
@@ -127,7 +128,11 @@ class Previews extends Component
$this->validateOnly("previewDockerTags.{$previewKey}");
$preview->docker_registry_image_tag = $this->previewDockerTags[$previewKey] ?? null;
+ $changedFields = $preview->isDirty('docker_registry_image_tag') ? ['docker_registry_image_tag'] : [];
$preview->save();
+ if ($changedFields !== []) {
+ $this->auditPreviewEvent('ui.application.preview_updated', $preview->pull_request_id, $changedFields);
+ }
$this->dispatch('success', 'Preview saved.<br><br>Do not forget to redeploy the preview to apply the changes.');
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -148,6 +153,7 @@ class Previews extends Component
'pull_request_html_url' => $pull_request_html_url,
'docker_compose_domains' => $this->application->docker_compose_domains,
]);
+ $this->auditPreviewEvent('ui.application.preview_created', $pull_request_id);
}
$found->generate_preview_fqdn_compose();
$this->application->refresh();
@@ -162,10 +168,10 @@ class Previews extends Component
'pull_request_html_url' => $pull_request_html_url ?? '',
'docker_registry_image_tag' => $docker_registry_image_tag,
]);
+ $this->auditPreviewEvent('ui.application.preview_created', $pull_request_id);
}
if ($found && $this->application->build_pack === 'dockerimage' && str($docker_registry_image_tag)->isNotEmpty()) {
- $found->docker_registry_image_tag = $docker_registry_image_tag;
- $found->save();
+ $this->saveDockerTagWithAudit($found, $docker_registry_image_tag);
}
$found->generate_preview_fqdn(generateWithoutApplicationDomain: true);
$this->application->refresh();
@@ -221,10 +227,10 @@ class Previews extends Component
'pull_request_html_url' => $pull_request_html_url ?? '',
'docker_registry_image_tag' => $docker_registry_image_tag,
]);
+ $this->auditPreviewEvent('ui.application.preview_created', $pull_request_id);
}
if ($found && $this->application->build_pack === 'dockerimage' && str($docker_registry_image_tag)->isNotEmpty()) {
- $found->docker_registry_image_tag = $docker_registry_image_tag;
- $found->save();
+ $this->saveDockerTagWithAudit($found, $docker_registry_image_tag);
}
$result = queue_application_deployment(
application: $this->application,
@@ -256,6 +262,28 @@ class Previews extends Component
}
}
+ private function saveDockerTagWithAudit(ApplicationPreview $preview, string $dockerRegistryImageTag): void
+ {
+ $preview->docker_registry_image_tag = $dockerRegistryImageTag;
+ $changed = $preview->isDirty('docker_registry_image_tag');
+ $preview->save();
+ if ($changed) {
+ $this->auditPreviewEvent('ui.application.preview_updated', $preview->pull_request_id, ['docker_registry_image_tag']);
+ }
+ }
+
+ /** @param array<int, string> $changedFields */
+ private function auditPreviewEvent(string $event, int $pullRequestId, array $changedFields = []): void
+ {
+ auditLog($event, array_filter([
+ 'team_id' => $this->application->team()?->id,
+ 'application_uuid' => $this->application->uuid,
+ 'application_name' => $this->application->name,
+ 'pull_request_id' => $pullRequestId,
+ 'changed_fields' => $changedFields,
+ ], fn ($value): bool => $value !== []));
+ }
+
protected function setDeploymentUuid()
{
$this->deployment_uuid = new_public_id();
@@ -350,6 +378,7 @@ class Previews extends Component
// Soft delete immediately for instant UI feedback
$preview->delete();
+ $this->auditPreviewEvent('ui.application.preview_deleted', $pull_request_id);
// Dispatch the job for async cleanup (container stopping + force delete)
DeleteResourceJob::dispatch($preview);
diff --git a/app/Livewire/Project/Application/Rollback.php b/app/Livewire/Project/Application/Rollback.php
index b070ae1cc8..f6a8e386b4 100644
--- a/app/Livewire/Project/Application/Rollback.php
+++ b/app/Livewire/Project/Application/Rollback.php
@@ -3,12 +3,14 @@
namespace App\Livewire\Project\Application;
use App\Models\Application;
+use App\Traits\AuditsApplicationSettings;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Validate;
use Livewire\Component;
class Rollback extends Component
{
+ use AuditsApplicationSettings;
use AuthorizesRequests;
public Application $application;
@@ -38,7 +40,7 @@ class Rollback extends Component
$this->authorize('update', $this->application);
$this->validate();
$this->application->settings->docker_images_to_keep = $this->dockerImagesToKeep;
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
$this->dispatch('success', 'Settings saved.');
} catch (\Throwable $e) {
return handleError($e, $this);
diff --git a/app/Livewire/Project/Application/Swarm.php b/app/Livewire/Project/Application/Swarm.php
index ac867e69aa..a3f99eff68 100644
--- a/app/Livewire/Project/Application/Swarm.php
+++ b/app/Livewire/Project/Application/Swarm.php
@@ -3,13 +3,14 @@
namespace App\Livewire\Project\Application;
use App\Models\Application;
+use App\Traits\AuditsApplicationSettings;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Validate;
use Livewire\Component;
class Swarm extends Component
{
- use AuthorizesRequests;
+ use AuditsApplicationSettings, AuthorizesRequests;
public Application $application;
@@ -39,7 +40,7 @@ class Swarm extends Component
$this->application->swarm_placement_constraints = $this->swarmPlacementConstraints ? base64_encode($this->swarmPlacementConstraints) : null;
$this->application->settings->is_swarm_only_worker_nodes = $this->isSwarmOnlyWorkerNodes;
$this->application->save();
- $this->application->settings->save();
+ $this->saveApplicationSettingsWithAudit($this->application);
} else {
$this->swarmReplicas = $this->application->swarm_replicas;
if ($this->application->swarm_placement_constraints) {
diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php
index 279a475f4e..0507529696 100644
--- a/app/Livewire/Project/Database/BackupEdit.php
+++ b/app/Livewire/Project/Database/BackupEdit.php
@@ -131,7 +131,10 @@ class BackupEdit extends Component
$this->status = $database->status;
}
- private function syncData(bool $toModel = false): void
+ /**
+ * @return array<int, string> Names of the backup fields the save changed.
+ */
+ private function syncData(bool $toModel = false): array
{
if ($toModel) {
$this->backup->enabled = $this->backupEnabled;
@@ -157,7 +160,10 @@ class BackupEdit extends Component
$this->backup->timeout = $this->timeout;
$this->backup->missing_backup_notification_days = $this->missingBackupNotificationDays;
$this->customValidate();
+ $changedFields = auditChangedFields($this->backup);
$this->backup->save();
+
+ return $changedFields;
} else {
$this->backupEnabled = $this->backup->enabled;
$this->frequency = $this->backup->frequency;
@@ -176,6 +182,8 @@ class BackupEdit extends Component
$this->timeout = $this->backup->timeout;
$this->missingBackupNotificationDays = $this->backup->missing_backup_notification_days;
}
+
+ return [];
}
public function delete($password, $selectedActions = [])
@@ -301,7 +309,7 @@ class BackupEdit extends Component
try {
$this->authorize('manageBackups', $this->backup->database);
- $this->syncData(true);
+ $this->auditBackupScheduleUpdated($this->syncData(true));
$this->dispatch('success', 'Backup updated successfully.');
} catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
@@ -314,7 +322,10 @@ class BackupEdit extends Component
$this->authorize('manageBackups', $this->backup->database);
$this->backupEnabled = ! $this->backupEnabled;
- $this->backup->update(['enabled' => $this->backupEnabled]);
+ $this->backup->enabled = $this->backupEnabled;
+ $changedFields = auditChangedFields($this->backup);
+ $this->backup->save();
+ $this->auditBackupScheduleUpdated($changedFields);
$this->dispatch('success', $this->backupEnabled ? 'Backup enabled.' : 'Backup disabled.');
} catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
@@ -368,6 +379,25 @@ class BackupEdit extends Component
$this->validate();
}
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditBackupScheduleUpdated(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ $database = $this->backup->database;
+ auditLog('ui.database.backup_schedule_updated', [
+ 'team_id' => $database?->team()?->id,
+ 'database_uuid' => $database?->uuid,
+ 'database_name' => $database?->name,
+ 'backup_uuid' => $this->backup->uuid,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
private function availableS3StorageIds(): Collection
{
$storages = collect($this->availableS3Storages);
@@ -395,7 +425,7 @@ class BackupEdit extends Component
try {
$this->authorize('manageBackups', $this->backup->database);
- $this->syncData(true);
+ $this->auditBackupScheduleUpdated($this->syncData(true));
$this->dispatch('success', 'Backup updated successfully.');
} catch (\Throwable $e) {
$this->dispatch('error', $e->getMessage());
diff --git a/app/Livewire/Project/Database/CreateScheduledBackup.php b/app/Livewire/Project/Database/CreateScheduledBackup.php
index 96d2ac7aaf..235eec202e 100644
--- a/app/Livewire/Project/Database/CreateScheduledBackup.php
+++ b/app/Livewire/Project/Database/CreateScheduledBackup.php
@@ -83,6 +83,14 @@ class CreateScheduledBackup extends Component
}
$databaseBackup = ScheduledDatabaseBackup::create($payload);
+ auditLog('ui.database.backup_schedule_created', [
+ 'team_id' => $database->team()?->id,
+ 'database_uuid' => $database->uuid,
+ 'database_name' => $database->name,
+ 'backup_uuid' => $databaseBackup->uuid,
+ 'frequency' => $databaseBackup->frequency,
+ 'save_s3' => (bool) $databaseBackup->save_s3,
+ ]);
if ($database->getMorphClass() === ServiceDatabase::class) {
$service = $database->service;
$this->redirectRoute('project.service.volume-backups.index', [
diff --git a/app/Livewire/Project/Database/ScheduledBackups.php b/app/Livewire/Project/Database/ScheduledBackups.php
index aa7e9f43ce..ece99b45f4 100644
--- a/app/Livewire/Project/Database/ScheduledBackups.php
+++ b/app/Livewire/Project/Database/ScheduledBackups.php
@@ -52,6 +52,12 @@ class ScheduledBackups extends Component
$backup = $this->database->scheduledBackups->find($scheduled_backup_id);
$backup->delete();
+ auditLog('ui.database.backup_schedule_deleted', [
+ 'team_id' => $this->database->team()?->id,
+ 'database_uuid' => $this->database->uuid,
+ 'database_name' => $this->database->name,
+ 'backup_uuid' => $backup->uuid,
+ ]);
$this->dispatch('success', 'Scheduled backup deleted.');
$this->refreshScheduledBackups();
} catch (\Throwable $e) {
diff --git a/app/Livewire/Project/Database/Sqlite/ConnectApplication.php b/app/Livewire/Project/Database/Sqlite/ConnectApplication.php
index d336c162ce..b2dadd0d18 100644
--- a/app/Livewire/Project/Database/Sqlite/ConnectApplication.php
+++ b/app/Livewire/Project/Database/Sqlite/ConnectApplication.php
@@ -2,6 +2,7 @@
namespace App\Livewire\Project\Database\Sqlite;
+use App\Livewire\Concerns\AuditsStorageChanges;
use App\Models\Application;
use App\Models\LocalPersistentVolume;
use App\Models\StandaloneSqlite;
@@ -14,6 +15,7 @@ use Symfony\Component\Yaml\Yaml;
class ConnectApplication extends Component
{
+ use AuditsStorageChanges;
use AuthorizesRequests;
public StandaloneSqlite $database;
@@ -105,7 +107,7 @@ class ConnectApplication extends Component
throw new \Exception("{$application->name} already mounts this database volume.");
}
- LocalPersistentVolume::create([
+ $volume = LocalPersistentVolume::create([
'name' => $this->volumeName,
'mount_path' => $this->mountPath,
'host_path' => null,
@@ -114,6 +116,7 @@ class ConnectApplication extends Component
'resource_type' => $application->getMorphClass(),
'is_preview_suffix_enabled' => false,
]);
+ $this->auditStorageChange($application, 'created', $volume, $this->sqliteAuditContext());
return redirect()->route('project.application.persistent-storage', $this->applicationRouteParameters($application));
} catch (\Throwable $e) {
@@ -153,6 +156,9 @@ class ConnectApplication extends Component
$this->authorize('update', $volume->resource ?? $this->database);
$volume->delete();
+ if ($volume->resource !== null) {
+ $this->auditStorageChange($volume->resource, 'deleted', $volume, $this->sqliteAuditContext());
+ }
$this->dispatch('success', 'Application unlinked. Redeploy it to apply the change.');
}
@@ -162,6 +168,17 @@ class ConnectApplication extends Component
return view('livewire.project.database.sqlite.connect-application');
}
+ /**
+ * @return array{standalone_sqlite_uuid: string, standalone_sqlite_name: string}
+ */
+ private function sqliteAuditContext(): array
+ {
+ return [
+ 'standalone_sqlite_uuid' => $this->database->uuid,
+ 'standalone_sqlite_name' => $this->database->name,
+ ];
+ }
+
/**
* Applications owned by the current team that run on the same server as the database.
*
diff --git a/app/Livewire/Project/Service/Domains.php b/app/Livewire/Project/Service/Domains.php
index dfa7f3af60..f70d521150 100644
--- a/app/Livewire/Project/Service/Domains.php
+++ b/app/Livewire/Project/Service/Domains.php
@@ -210,7 +210,9 @@ class Domains extends Component
$domains = $noindex ? $domains->push($domain) : $domains->reject(fn (string $item) => $item === $domain);
$application->setNoindexDomains($domains);
+ $changedFields = auditChangedFields($application);
$application->save();
+ $this->auditServiceApplicationUpdate($application, $changedFields);
$this->service->parse();
$this->refreshDomains();
$this->dispatch('configurationChanged')->to(ConfigurationChecker::class);
@@ -226,7 +228,9 @@ class Domains extends Component
$this->validateOnly("forceHttpsRedirects.{$serviceApplicationId}");
$application->is_force_https_enabled = $enabled;
+ $changedFields = auditChangedFields($application);
$application->save();
+ $this->auditServiceApplicationUpdate($application, $changedFields);
$this->service->parse();
$this->refreshDomains();
$this->dispatch('configurationChanged')->to(ConfigurationChecker::class);
@@ -805,7 +809,8 @@ class Domains extends Component
$this->pendingRedirectServiceApplicationId = $serviceApplicationId;
$addedDomains = [];
- $saved = DB::transaction(function () use ($app, $redirect, &$addedDomains): bool {
+ $changedFields = [];
+ $saved = DB::transaction(function () use ($app, $redirect, &$addedDomains, &$changedFields): bool {
// Promote the optional www/non-www suggestion to a real domain for redirects.
if (in_array($redirect, ['www', 'non-www'], true)) {
$domainsBeforePairing = collect($this->splitDomains($app->fqdn));
@@ -822,6 +827,7 @@ class Domains extends Component
}
$app->redirect = $redirect;
+ $changedFields = auditChangedFields($app);
$app->save();
updateCompose($app);
$this->service->parse();
@@ -832,6 +838,7 @@ class Domains extends Component
if (! $saved) {
return;
}
+ $this->auditServiceApplicationUpdate($app, $changedFields);
$this->pendingAction = null;
$this->pendingRedirectServiceApplicationId = null;
@@ -1595,11 +1602,14 @@ class Domains extends Component
$this->dispatch('warning', __('warning.sslipdomain'));
}
- DB::transaction(function () use ($app): void {
+ $changedFields = [];
+ DB::transaction(function () use ($app, &$changedFields): void {
+ $changedFields = auditChangedFields($app);
$app->save();
updateCompose($app);
$this->service->parse();
});
+ $this->auditServiceApplicationUpdate($app, $changedFields);
if (str($app->fqdn)->contains(',')) {
$this->dispatch('warning', 'Some services do not support multiple domains, which can lead to problems and is NOT RECOMMENDED.<br><br>Only use multiple domains if you know what you are doing.');
@@ -1714,6 +1724,27 @@ class Domains extends Component
return null;
}
+ /**
+ * Records `ui.service_application.updated`; nothing is recorded when no attribute changed.
+ *
+ * @param array<int, string> $changedFields
+ */
+ private function auditServiceApplicationUpdate(ServiceApplication $application, array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.service_application.updated', [
+ 'team_id' => $this->service->team()?->id,
+ 'service_uuid' => $this->service->uuid,
+ 'service_name' => $this->service->name,
+ 'service_application_uuid' => $application->uuid,
+ 'service_application_name' => $application->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
protected function findServiceApp(?int $id): ?ServiceApplication
{
if (! $id) {
diff --git a/app/Livewire/Project/Service/FileStorage.php b/app/Livewire/Project/Service/FileStorage.php
index fcbc100a1a..0c19e73915 100644
--- a/app/Livewire/Project/Service/FileStorage.php
+++ b/app/Livewire/Project/Service/FileStorage.php
@@ -2,6 +2,7 @@
namespace App\Livewire\Project\Service;
+use App\Livewire\Concerns\AuditsStorageChanges;
use App\Models\Application;
use App\Models\LocalFileVolume;
use App\Models\ScheduledVolumeBackup;
@@ -23,6 +24,7 @@ use Livewire\Component;
class FileStorage extends Component
{
+ use AuditsStorageChanges;
use AuthorizesRequests;
public LocalFileVolume $fileStorage;
@@ -121,11 +123,14 @@ class FileStorage extends Component
: route('project.application.backup.show', [...$parameters, 'backup_uuid' => $backup->uuid]);
}
- private function syncData(bool $toModel = false): void
+ /**
+ * @return array<int, string> Names of the file storage fields the save changed.
+ */
+ private function syncData(bool $toModel = false): array
{
if ($toModel) {
if ($this->fileStorage->is_too_large) {
- return;
+ return [];
}
$this->validate();
@@ -134,13 +139,18 @@ class FileStorage extends Component
$this->fileStorage->is_based_on_git = $this->isBasedOnGit;
$this->fileStorage->is_preview_suffix_enabled = $this->isPreviewSuffixEnabled;
+ $changedFields = auditChangedFields($this->fileStorage);
$this->fileStorage->save();
+
+ return $changedFields;
} else {
// Sync from model
$this->content = auth()->user()?->can('update', $this->resource) ? $this->fileStorage->content : null;
$this->isBasedOnGit = $this->fileStorage->is_based_on_git;
$this->isPreviewSuffixEnabled = $this->fileStorage->is_preview_suffix_enabled ?? true;
}
+
+ return [];
}
public function convertToDirectory()
@@ -156,8 +166,10 @@ class FileStorage extends Component
$this->fileStorage->is_directory = true;
$this->fileStorage->content = null;
$this->fileStorage->is_based_on_git = false;
+ $changedFields = auditChangedFields($this->fileStorage);
$this->fileStorage->save();
$this->fileStorage->saveStorageOnServer();
+ $this->auditFileStorageUpdate($changedFields, 'converted_to_directory');
} catch (\Throwable $e) {
return handleError($e, $this);
} finally {
@@ -203,8 +215,10 @@ class FileStorage extends Component
if (data_get($this->resource, 'settings.is_preserve_repository_enabled')) {
$this->fileStorage->is_based_on_git = true;
}
+ $changedFields = auditChangedFields($this->fileStorage);
$this->fileStorage->save();
$this->fileStorage->saveStorageOnServer();
+ $this->auditFileStorageUpdate($changedFields, 'converted_to_file');
} catch (\Throwable $e) {
return handleError($e, $this);
} finally {
@@ -233,11 +247,15 @@ class FileStorage extends Component
} elseif ($this->fileStorage->is_host_file) {
$message = 'Host file mount removed.';
}
- if ($this->permanently_delete && ! $this->fileStorage->is_host_file) {
+ $deletedFromServer = $this->permanently_delete && ! $this->fileStorage->is_host_file;
+ if ($deletedFromServer) {
$message = 'Directory deleted from the server.';
$this->fileStorage->deleteStorageOnServer();
}
$this->fileStorage->delete();
+ $this->auditStorageChange($this->resource, 'deleted', $this->fileStorage, [
+ 'deleted_from_server' => $deletedFromServer,
+ ]);
$this->dispatch('configurationChanged');
$this->dispatch('success', $message);
} catch (\Throwable $e) {
@@ -275,8 +293,10 @@ class FileStorage extends Component
$this->fileStorage->content = $this->content;
$this->fileStorage->is_based_on_git = $this->isBasedOnGit;
$this->fileStorage->is_preview_suffix_enabled = $this->isPreviewSuffixEnabled;
+ $changedFields = auditChangedFields($this->fileStorage);
$this->fileStorage->save();
$this->fileStorage->saveStorageOnServer();
+ $this->auditFileStorageUpdate($changedFields);
$this->dispatch('success', 'File updated.');
} catch (\Throwable $e) {
$this->fileStorage->setRawAttributes($original);
@@ -301,10 +321,25 @@ class FileStorage extends Component
return;
}
- $this->syncData(true);
+ $this->auditFileStorageUpdate($this->syncData(true));
$this->dispatch('success', 'File updated.');
}
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditFileStorageUpdate(array $changedFields, ?string $operation = null): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ $this->auditStorageChange($this->resource, 'updated', $this->fileStorage, array_filter([
+ 'changed_fields' => $changedFields,
+ 'operation' => $operation,
+ ], fn ($value) => $value !== null));
+ }
+
public function render()
{
return view('livewire.project.service.file-storage', [
diff --git a/app/Livewire/Project/Service/Index.php b/app/Livewire/Project/Service/Index.php
index abdcada989..e486f8c07a 100644
--- a/app/Livewire/Project/Service/Index.php
+++ b/app/Livewire/Project/Service/Index.php
@@ -258,6 +258,7 @@ class Index extends Component
$containerRemoved = app(DeleteService::class)->removeSubresourceContainer($this->serviceDatabase);
$this->serviceDatabase->delete();
+ $this->auditServiceSubResource('deleted', $this->serviceDatabase, ['container_removed' => $containerRemoved]);
$containerRemoved
? $this->dispatch('success', 'Database deleted.')
: $this->dispatch('warning', 'Database deleted from Coolify. The server does not respond, so its container is removed when the service starts again.');
@@ -312,8 +313,8 @@ class Index extends Component
->except('database_uuid')
->all();
- DB::transaction(function () use ($service, $serviceDatabase) {
- $service->applications()->create([
+ $serviceApplication = DB::transaction(function () use ($service, $serviceDatabase) {
+ $serviceApplication = $service->applications()->create([
'name' => $serviceDatabase->name,
'human_name' => $serviceDatabase->human_name,
'description' => $serviceDatabase->description,
@@ -324,7 +325,12 @@ class Index extends Component
'is_migrated' => true,
]);
$serviceDatabase->delete();
+
+ return $serviceApplication;
});
+ $this->auditServiceSubResource('converted_to_application', $serviceDatabase, [
+ 'service_application_uuid' => $serviceApplication->uuid,
+ ]);
return redirectRoute($this, 'project.service.configuration', $redirectParams);
} catch (\Throwable $e) {
@@ -381,11 +387,17 @@ class Index extends Component
private function persistPublicAccess(): void
{
- $this->serviceDatabase->update([
+ $this->serviceDatabase->fill([
'is_public' => $this->isPublic,
'public_port' => $this->publicPort ?: null,
'public_port_timeout' => $this->publicPortTimeout ?: null,
]);
+ $changedFields = auditChangedFields($this->serviceDatabase);
+ $this->serviceDatabase->save();
+ $this->auditServiceSubResourceUpdate($this->serviceDatabase, $changedFields, [
+ 'is_public' => (bool) $this->serviceDatabase->is_public,
+ 'public_port' => $this->serviceDatabase->public_port,
+ ]);
}
public function submitDatabase()
@@ -394,7 +406,9 @@ class Index extends Component
$this->authorize('update', $this->serviceDatabase);
$this->validate();
$this->syncDatabaseData(true);
+ $changedFields = auditChangedFields($this->serviceDatabase);
$this->serviceDatabase->save();
+ $this->auditServiceSubResourceUpdate($this->serviceDatabase, $changedFields);
$this->serviceDatabase->refresh();
$this->syncDatabaseData(false);
updateCompose($this->serviceDatabase);
@@ -448,10 +462,13 @@ class Index extends Component
'maxRestartCount' => 'integer|min:0',
]);
- $this->serviceApplication->update([
+ $this->serviceApplication->fill([
'max_restart_count' => $validated['maxRestartCount'],
'restart_limit_reached' => false,
]);
+ $changedFields = auditChangedFields($this->serviceApplication);
+ $this->serviceApplication->save();
+ $this->auditServiceSubResourceUpdate($this->serviceApplication, $changedFields);
$this->dispatch('success', 'Max restart count saved.');
}
@@ -472,7 +489,9 @@ class Index extends Component
$this->serviceApplication->is_gzip_enabled = $this->isGzipEnabled;
$this->serviceApplication->is_stripprefix_enabled = $this->isStripprefixEnabled;
$this->serviceApplication->exclude_from_status = $this->excludeFromStatus;
+ $changedFields = auditChangedFields($this->serviceApplication);
$this->serviceApplication->save();
+ $this->auditServiceSubResourceUpdate($this->serviceApplication, $changedFields);
$this->dispatch('success', 'Settings saved.');
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -490,7 +509,9 @@ class Index extends Component
return;
}
$this->syncApplicationData(true);
+ $changedFields = auditChangedFields($this->serviceApplication);
$this->serviceApplication->save();
+ $this->auditServiceSubResourceUpdate($this->serviceApplication, $changedFields);
$this->dispatch('success', 'You need to restart the service for the changes to take effect.');
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -508,6 +529,7 @@ class Index extends Component
$containerRemoved = app(DeleteService::class)->removeSubresourceContainer($this->serviceApplication);
$this->serviceApplication->delete();
+ $this->auditServiceSubResource('deleted', $this->serviceApplication, ['container_removed' => $containerRemoved]);
$containerRemoved
? $this->dispatch('success', 'Application deleted.')
: $this->dispatch('warning', 'Application deleted from Coolify. The server does not respond, so its container is removed when the service starts again.');
@@ -532,8 +554,8 @@ class Index extends Component
$redirectParams = collect($this->parameters)
->except('database_uuid')
->all();
- DB::transaction(function () use ($service, $serviceApplication) {
- $service->databases()->create([
+ $serviceDatabase = DB::transaction(function () use ($service, $serviceApplication) {
+ $serviceDatabase = $service->databases()->create([
'name' => $serviceApplication->name,
'human_name' => $serviceApplication->human_name,
'description' => $serviceApplication->description,
@@ -544,7 +566,12 @@ class Index extends Component
'is_migrated' => true,
]);
$serviceApplication->delete();
+
+ return $serviceDatabase;
});
+ $this->auditServiceSubResource('converted_to_database', $serviceApplication, [
+ 'service_database_uuid' => $serviceDatabase->uuid,
+ ]);
return redirectRoute($this, 'project.service.configuration', $redirectParams);
} catch (\Throwable $e) {
@@ -630,7 +657,9 @@ class Index extends Component
}
$this->validate();
+ $changedFields = auditChangedFields($this->serviceApplication);
$this->serviceApplication->save();
+ $this->auditServiceSubResourceUpdate($this->serviceApplication, $changedFields);
$this->serviceApplication->refresh();
app(ManagedDnsRecordCleanup::class)->queueReleaseOfRemovedHostnames($this->serviceApplication, $previousDnsHostnames, currentTeam()->id);
$this->syncApplicationData(false);
@@ -656,4 +685,39 @@ class Index extends Component
{
return view('livewire.project.service.index');
}
+
+ /**
+ * Records `ui.service_{application|database}.updated` with the attributes that the save changed.
+ *
+ * @param array<int, string> $changedFields Fields changed by the save, captured before it.
+ * @param array<string, mixed> $extra
+ */
+ private function auditServiceSubResourceUpdate(ServiceApplication|ServiceDatabase $resource, array $changedFields, array $extra = []): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ $this->auditServiceSubResource('updated', $resource, ['changed_fields' => $changedFields, ...$extra]);
+ }
+
+ /**
+ * Mirrors the context of `api.service_database.updated` for service applications and databases.
+ *
+ * @param array<string, mixed> $extra
+ */
+ private function auditServiceSubResource(string $action, ServiceApplication|ServiceDatabase $resource, array $extra = []): void
+ {
+ $resourceKey = $resource instanceof ServiceApplication ? 'service_application' : 'service_database';
+ $service = $resource->service ?? $this->service;
+
+ auditLog("ui.{$resourceKey}.{$action}", [
+ 'team_id' => $service?->team()?->id,
+ 'service_uuid' => $service?->uuid,
+ 'service_name' => $service?->name,
+ "{$resourceKey}_uuid" => $resource->uuid,
+ "{$resourceKey}_name" => $resource->name,
+ ...$extra,
+ ]);
+ }
}
diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.php
index 0827a59994..3509fbcad6 100644
--- a/app/Livewire/Project/Service/Storage.php
+++ b/app/Livewire/Project/Service/Storage.php
@@ -2,6 +2,7 @@
namespace App\Livewire\Project\Service;
+use App\Livewire\Concerns\AuditsStorageChanges;
use App\Livewire\Project\Shared\Storages\All as StorageList;
use App\Models\Application;
use App\Models\LocalFileVolume;
@@ -18,6 +19,7 @@ use Livewire\Component;
class Storage extends Component
{
+ use AuditsStorageChanges;
use AuthorizesRequests;
use ListensToTeamChannel;
@@ -283,13 +285,14 @@ class Storage extends Component
$name = $this->resource->uuid.'-'.$this->name;
- LocalPersistentVolume::create([
+ $volume = LocalPersistentVolume::create([
'name' => $name,
'mount_path' => $this->mount_path,
'host_path' => null,
'resource_id' => $this->resource->id,
'resource_type' => $this->resource->getMorphClass(),
]);
+ $this->auditStorageChange($this->resource, 'created', $volume);
$this->clearForm();
$this->activeTab = 'volumes';
$this->refreshStorages();
@@ -315,7 +318,7 @@ class Storage extends Component
$fs_path = confineFileMountPath($this->fileStorageHostPath(), $this->file_storage_path, 'file storage path');
- LocalFileVolume::create([
+ $fileVolume = LocalFileVolume::create([
'fs_path' => $fs_path,
'mount_path' => $this->file_storage_path,
'content' => $this->file_storage_content,
@@ -323,6 +326,7 @@ class Storage extends Component
'resource_id' => $this->resource->id,
'resource_type' => get_class($this->resource),
]);
+ $this->auditStorageChange($this->resource, 'created', $fileVolume);
$this->clearForm();
$this->activeTab = 'files';
@@ -348,7 +352,7 @@ class Storage extends Component
$this->host_file_storage_source = validateHostFileMountPath($this->host_file_storage_source, 'host file source path');
$this->host_file_storage_destination = validateFileMountPath($this->host_file_storage_destination, 'host file destination path');
- LocalFileVolume::create([
+ $hostFileVolume = LocalFileVolume::create([
'fs_path' => $this->host_file_storage_source,
'mount_path' => $this->host_file_storage_destination,
'content' => null,
@@ -357,6 +361,7 @@ class Storage extends Component
'resource_id' => $this->resource->id,
'resource_type' => get_class($this->resource),
]);
+ $this->auditStorageChange($this->resource, 'created', $hostFileVolume);
$this->clearForm();
$this->activeTab = 'files';
@@ -391,13 +396,14 @@ class Storage extends Component
$server = $this->resource->service?->server ?? $this->resource->destination->server;
LocalFileVolume::assertRemotePathIsConfined($this->fileStorageHostPath(), $this->file_storage_directory_source, $server);
- LocalFileVolume::create([
+ $directoryVolume = LocalFileVolume::create([
'fs_path' => $this->file_storage_directory_source,
'mount_path' => $this->file_storage_directory_destination,
'is_directory' => true,
'resource_id' => $this->resource->id,
'resource_type' => get_class($this->resource),
]);
+ $this->auditStorageChange($this->resource, 'created', $directoryVolume);
$this->clearForm();
$this->activeTab = 'directories';
diff --git a/app/Livewire/Project/Service/VolumeBackup/Create.php b/app/Livewire/Project/Service/VolumeBackup/Create.php
index 430e89a2c1..560139f71f 100644
--- a/app/Livewire/Project/Service/VolumeBackup/Create.php
+++ b/app/Livewire/Project/Service/VolumeBackup/Create.php
@@ -68,11 +68,26 @@ class Create extends Component
}
try {
- $backup = $target->scheduledBackups()->updateOrCreate([], [
+ $backup = $target->scheduledBackups()->firstOrNew();
+ $backup->fill([
'team_id' => currentTeam()->id,
'frequency' => $this->frequency,
'enabled' => true,
]);
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ if ($backup->wasRecentlyCreated || $changedFields !== []) {
+ auditLog('ui.volume_backup.schedule_set', [
+ 'team_id' => $backup->team_id,
+ 'resource_type' => 'service',
+ 'resource_uuid' => $this->service->uuid,
+ 'resource_name' => $this->service->name,
+ 'storage_uuid' => $target->uuid,
+ 'backup_uuid' => $backup->uuid,
+ 'created' => $backup->wasRecentlyCreated,
+ ...($backup->wasRecentlyCreated ? [] : ['changed_fields' => $changedFields]),
+ ]);
+ }
$this->dispatch('success', $backup->wasRecentlyCreated ? 'Scheduled storage backup created.' : 'Scheduled storage backup updated.');
redirectRoute($this, 'project.service.volume-backups.show', [
'project_uuid' => $this->service->project()->uuid,
diff --git a/app/Livewire/Project/Shared/EnvironmentVariable/All.php b/app/Livewire/Project/Shared/EnvironmentVariable/All.php
index cc45568d2e..32a8e7e28a 100644
--- a/app/Livewire/Project/Shared/EnvironmentVariable/All.php
+++ b/app/Livewire/Project/Shared/EnvironmentVariable/All.php
@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Shared\EnvironmentVariable;
use App\Models\Application;
use App\Models\EnvironmentVariable;
use App\Support\ValidationPatterns;
+use App\Traits\AuditsApplicationSettings;
use App\Traits\EnvironmentVariableProtection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
@@ -14,7 +15,7 @@ use Livewire\Component;
class All extends Component
{
- use AuthorizesRequests, EnvironmentVariableProtection;
+ use AuditsApplicationSettings, AuthorizesRequests, EnvironmentVariableProtection;
public $resource;
@@ -128,7 +129,11 @@ class All extends Component
$this->page = 1;
$this->resource->settings->is_env_sorting_enabled = $this->is_env_sorting_enabled;
$this->resource->settings->use_build_secrets = $this->use_build_secrets;
- $this->resource->settings->save();
+ if ($this->resource instanceof Application) {
+ $this->saveApplicationSettingsWithAudit($this->resource);
+ } else {
+ $this->resource->settings->save();
+ }
$this->clearEnvironmentVariableCaches();
if ($this->readyToLoad && $this->view === 'dev') {
$this->getDevView();
diff --git a/app/Livewire/Project/Shared/ScheduledTask/Add.php b/app/Livewire/Project/Shared/ScheduledTask/Add.php
index 717007bc04..525a3ccb41 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/Add.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/Add.php
@@ -125,6 +125,14 @@ class Add extends Component
break;
}
$task->save();
+ auditLog('ui.scheduled_task.created', [
+ 'team_id' => $task->team_id,
+ 'scheduled_task_uuid' => $task->uuid,
+ 'scheduled_task_name' => $task->name,
+ 'resource_type' => $this->type,
+ 'resource_uuid' => $this->resource->uuid,
+ 'resource_name' => $this->resource->name,
+ ]);
$this->dispatch('refreshTasks');
$this->dispatch('success', 'Scheduled task added.');
} catch (\Throwable $e) {
diff --git a/app/Livewire/Project/Shared/ScheduledTask/Show.php b/app/Livewire/Project/Shared/ScheduledTask/Show.php
index 3bfe0700d9..4419b2e701 100644
--- a/app/Livewire/Project/Shared/ScheduledTask/Show.php
+++ b/app/Livewire/Project/Shared/ScheduledTask/Show.php
@@ -87,7 +87,10 @@ class Show extends Component
}
}
- private function syncData(bool $toModel = false): void
+ /**
+ * @return array<int, string> Names of the task fields the save changed.
+ */
+ private function syncData(bool $toModel = false): array
{
if ($toModel) {
$this->validate();
@@ -102,7 +105,10 @@ class Show extends Component
$this->task->frequency = str($this->frequency)->trim()->value();
$this->task->container = str($this->container)->trim()->value();
$this->task->timeout = (int) $this->timeout;
+ $changedFields = auditChangedFields($this->task);
$this->task->save();
+
+ return $changedFields;
} else {
$this->isEnabled = $this->task->enabled;
$this->name = $this->task->name;
@@ -111,6 +117,8 @@ class Show extends Component
$this->container = $this->task->container;
$this->timeout = $this->task->timeout ?? 300;
}
+
+ return [];
}
public function toggleEnabled()
@@ -120,7 +128,9 @@ class Show extends Component
$this->authorize('update', $this->task);
$this->isEnabled = ! $this->isEnabled;
$this->task->enabled = $this->isEnabled;
+ $changedFields = auditChangedFields($this->task);
$this->task->save();
+ $this->auditTaskUpdated($changedFields);
$this->dispatch('success', $this->isEnabled ? 'Scheduled task enabled.' : 'Scheduled task disabled.');
} catch (\Exception $e) {
return handleError($e);
@@ -132,7 +142,7 @@ class Show extends Component
try {
$this->authorize('update', $this->resource);
$this->authorize('update', $this->task);
- $this->syncData(true);
+ $this->auditTaskUpdated($this->syncData(true));
$this->dispatch('success', 'Scheduled task updated.');
$this->refreshTasks();
} catch (\Exception $e) {
@@ -145,7 +155,7 @@ class Show extends Component
try {
$this->authorize('update', $this->resource);
$this->authorize('update', $this->task);
- $this->syncData(true);
+ $this->auditTaskUpdated($this->syncData(true));
$this->dispatch('success', 'Scheduled task updated.');
} catch (\Exception $e) {
return handleError($e, $this);
@@ -167,6 +177,7 @@ class Show extends Component
$this->authorize('update', $this->resource);
$this->authorize('delete', $this->task);
$this->task->delete();
+ auditLog('ui.scheduled_task.deleted', $this->taskAuditContext());
if ($this->type === 'application') {
return redirectRoute($this, 'project.application.scheduled-tasks.show', $this->parameters);
@@ -196,4 +207,36 @@ class Show extends Component
return handleError($e);
}
}
+
+ /**
+ * Record changed task field names only; the command can contain secrets.
+ *
+ * @param array<int, string> $changedFields
+ */
+ private function auditTaskUpdated(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.scheduled_task.updated', [
+ ...$this->taskAuditContext(),
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
+ /**
+ * @return array{team_id: int|null, scheduled_task_uuid: string, scheduled_task_name: string, resource_type: string, resource_uuid: string, resource_name: string}
+ */
+ private function taskAuditContext(): array
+ {
+ return [
+ 'team_id' => $this->resource->team()?->id,
+ 'scheduled_task_uuid' => $this->task->uuid,
+ 'scheduled_task_name' => $this->task->name,
+ 'resource_type' => $this->type,
+ 'resource_uuid' => $this->resource->uuid,
+ 'resource_name' => $this->resource->name,
+ ];
+ }
}
diff --git a/app/Livewire/Project/Shared/Storages/All.php b/app/Livewire/Project/Shared/Storages/All.php
index 64d8bb49c4..5cace5c2f1 100644
--- a/app/Livewire/Project/Shared/Storages/All.php
+++ b/app/Livewire/Project/Shared/Storages/All.php
@@ -2,6 +2,7 @@
namespace App\Livewire\Project\Shared\Storages;
+use App\Livewire\Concerns\AuditsStorageChanges;
use App\Livewire\Project\Service\Storage as StorageComponent;
use App\Models\Application;
use App\Models\LocalFileVolume;
@@ -15,6 +16,7 @@ use Livewire\Component;
class All extends Component
{
+ use AuditsStorageChanges;
use AuthorizesRequests;
public $resource;
@@ -100,8 +102,13 @@ class All extends Component
}
$storage->mount_path = $form['mountPath'];
$storage->is_preview_suffix_enabled = (bool) $form['isPreviewSuffixEnabled'];
+ $changedFields = auditChangedFields($storage);
$storage->save();
+ if ($changedFields !== []) {
+ $this->auditStorageChange($this->resource, 'updated', $storage, ['changed_fields' => $changedFields]);
+ }
+
$this->dispatch('success', 'Storage updated successfully');
}
@@ -171,6 +178,9 @@ class All extends Component
}
$storage->delete();
+ $this->auditStorageChange($this->resource, 'deleted', $storage, [
+ 'docker_volume_deleted' => $this->deleteDockerVolume,
+ ]);
$this->refreshList();
$this->dispatch('storageCountsChanged')->to(StorageComponent::class);
$this->dispatch('configurationChanged');
diff --git a/app/Livewire/Project/Shared/Storages/VolumeBackups.php b/app/Livewire/Project/Shared/Storages/VolumeBackups.php
index 0299c98c8b..125aaf42bb 100644
--- a/app/Livewire/Project/Shared/Storages/VolumeBackups.php
+++ b/app/Livewire/Project/Shared/Storages/VolumeBackups.php
@@ -5,6 +5,7 @@ namespace App\Livewire\Project\Shared\Storages;
use App\Actions\Shared\DeleteScheduledVolumeBackup;
use App\Jobs\VolumeBackupJob;
use App\Jobs\VolumeBackupRecoveryJob;
+use App\Models\Application;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
use App\Models\S3Storage;
@@ -194,7 +195,10 @@ class VolumeBackups extends Component
$this->backup = $this->persistBackup(true);
} else {
$this->enabled = ! $this->enabled;
- $this->backup->update(['enabled' => $this->enabled]);
+ $this->backup->enabled = $this->enabled;
+ $changedFields = auditChangedFields($this->backup);
+ $this->backup->save();
+ $this->auditScheduleSet($this->backup, $changedFields);
}
$this->dispatch('success', $this->enabled ? 'Storage backups enabled.' : 'Storage backups disabled.');
@@ -238,11 +242,17 @@ class VolumeBackups extends Component
}
try {
+ $backupUuid = $this->backup->uuid;
DeleteScheduledVolumeBackup::run(
$this->backup,
deleteLocalArchives: in_array('delete_associated_backups_locally', $selectedActions, true),
deleteS3Archives: in_array('delete_associated_backups_s3', $selectedActions, true),
);
+ auditLog('ui.volume_backup.schedule_deleted', [
+ ...$this->auditContext($backupUuid),
+ 'delete_local_archives' => in_array('delete_associated_backups_locally', $selectedActions, true),
+ 'delete_s3_archives' => in_array('delete_associated_backups_s3', $selectedActions, true),
+ ]);
$this->backup = null;
$this->dispatch('success', 'Storage backup schedule deleted.');
$this->redirectRoute($this->routeName('index'), $this->routeParameters(includeBackup: false), navigate: true);
@@ -409,25 +419,65 @@ class VolumeBackups extends Component
private function persistBackup(bool $enabled): ScheduledVolumeBackup
{
- return $this->storage->scheduledBackups()->updateOrCreate(
- [],
- [
- 'team_id' => currentTeam()->id,
- 'frequency' => $this->frequency,
- 'enabled' => $enabled,
- 'save_s3' => $this->saveToS3,
- 'disable_local_backup' => $this->disableLocalBackup,
- 'stop_during_backup' => $this->stopDuringBackup,
- 's3_storage_id' => $this->hasValidS3Storage() ? $this->s3StorageId : $this->backup?->s3_storage_id,
- 'retention_amount_locally' => $this->retentionAmountLocally,
- 'retention_days_locally' => $this->retentionDaysLocally,
- 'retention_max_storage_locally' => $this->retentionMaxStorageLocally,
- 'retention_amount_s3' => $this->retentionAmountS3,
- 'retention_days_s3' => $this->retentionDaysS3,
- 'retention_max_storage_s3' => $this->retentionMaxStorageS3,
- 'timeout' => $this->timeout,
- ],
- );
+ $backup = $this->storage->scheduledBackups()->firstOrNew();
+ $backup->fill([
+ 'team_id' => currentTeam()->id,
+ 'frequency' => $this->frequency,
+ 'enabled' => $enabled,
+ 'save_s3' => $this->saveToS3,
+ 'disable_local_backup' => $this->disableLocalBackup,
+ 'stop_during_backup' => $this->stopDuringBackup,
+ 's3_storage_id' => $this->hasValidS3Storage() ? $this->s3StorageId : $this->backup?->s3_storage_id,
+ 'retention_amount_locally' => $this->retentionAmountLocally,
+ 'retention_days_locally' => $this->retentionDaysLocally,
+ 'retention_max_storage_locally' => $this->retentionMaxStorageLocally,
+ 'retention_amount_s3' => $this->retentionAmountS3,
+ 'retention_days_s3' => $this->retentionDaysS3,
+ 'retention_max_storage_s3' => $this->retentionMaxStorageS3,
+ 'timeout' => $this->timeout,
+ ]);
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ $this->auditScheduleSet($backup, $changedFields);
+
+ return $backup;
+ }
+
+ /**
+ * Record a created schedule, or the changed field names of an updated one.
+ *
+ * @param array<int, string> $changedFields
+ */
+ private function auditScheduleSet(ScheduledVolumeBackup $backup, array $changedFields): void
+ {
+ if (! $backup->wasRecentlyCreated && $changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.volume_backup.schedule_set', [
+ ...$this->auditContext($backup->uuid),
+ 'created' => $backup->wasRecentlyCreated,
+ ...($backup->wasRecentlyCreated ? [] : ['changed_fields' => $changedFields]),
+ ]);
+ }
+
+ /**
+ * @return array{team_id: int|null, resource_type: string, resource_uuid: string, resource_name: string, storage_uuid: string|null, backup_uuid: string}
+ */
+ private function auditContext(string $backupUuid): array
+ {
+ return [
+ 'team_id' => $this->resource->team()?->id,
+ 'resource_type' => match (true) {
+ $this->resource instanceof Service => 'service',
+ $this->resource instanceof Application => 'application',
+ default => 'database',
+ },
+ 'resource_uuid' => $this->resource->uuid,
+ 'resource_name' => $this->resource->name,
+ 'storage_uuid' => $this->storage->uuid,
+ 'backup_uuid' => $backupUuid,
+ ];
}
private function hasValidS3Storage(): bool
diff --git a/app/Livewire/Server/Advanced.php b/app/Livewire/Server/Advanced.php
index 34847a12e6..dc9ffdc373 100644
--- a/app/Livewire/Server/Advanced.php
+++ b/app/Livewire/Server/Advanced.php
@@ -56,7 +56,9 @@ class Advanced extends Component
$this->server->settings->server_disk_usage_notification_threshold = $this->serverDiskUsageNotificationThreshold;
$this->server->settings->server_disk_usage_check_frequency = $this->serverDiskUsageCheckFrequency;
$this->server->settings->server_disk_usage_notification_interval_hours = $this->serverDiskUsageNotificationIntervalHours;
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+ $this->auditSettingsUpdate($changedFields);
} else {
$this->concurrentBuilds = $this->server->settings->concurrent_builds;
$this->dynamicTimeout = $this->server->settings->dynamic_timeout;
@@ -98,4 +100,21 @@ class Advanced extends Component
{
return view('livewire.server.advanced');
}
+
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditSettingsUpdate(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.server.settings_updated', [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
}
diff --git a/app/Livewire/Server/CaCertificate/Show.php b/app/Livewire/Server/CaCertificate/Show.php
index c30de14d3b..5cf36f28a5 100644
--- a/app/Livewire/Server/CaCertificate/Show.php
+++ b/app/Livewire/Server/CaCertificate/Show.php
@@ -77,6 +77,7 @@ class Show extends Component
$this->caCertificate->ssl_certificate = $this->certificateContent;
$this->caCertificate->save();
+ auditLog('ui.server.ca_certificate.updated', $this->auditContext());
$this->loadCaCertificate();
@@ -103,6 +104,7 @@ class Show extends Component
isCaCertificate: true,
validityDays: 10 * 365
);
+ auditLog('ui.server.ca_certificate.regenerated', $this->auditContext());
$this->loadCaCertificate();
@@ -127,6 +129,20 @@ class Show extends Component
remote_process($commands, $this->server);
}
+ /**
+ * Identifies the server only. Certificate and key contents must never reach the audit log.
+ *
+ * @return array<string, mixed>
+ */
+ private function auditContext(): array
+ {
+ return [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ ];
+ }
+
public function render()
{
return view('livewire.server.ca-certificate.show');
diff --git a/app/Livewire/Server/Charts.php b/app/Livewire/Server/Charts.php
index 567034c801..d4cf1c2ad9 100644
--- a/app/Livewire/Server/Charts.php
+++ b/app/Livewire/Server/Charts.php
@@ -54,7 +54,9 @@ class Charts extends Component
$this->server->settings->sentinel_metrics_refresh_rate_seconds = $this->sentinelMetricsRefreshRateSeconds;
$this->server->settings->sentinel_metrics_history_days = $this->sentinelMetricsHistoryDays;
$this->server->settings->sentinel_push_interval_seconds = $this->sentinelPushIntervalSeconds;
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+ $this->auditSentinelUpdate($changedFields);
$this->dispatch('success', 'Metrics settings updated. Restarting Sentinel.');
} catch (\Throwable $e) {
@@ -68,6 +70,7 @@ class Charts extends Component
$this->authorize('update', $this->server);
$this->server->settings->is_metrics_enabled = ! $this->server->settings->is_metrics_enabled;
$this->server->settings->save();
+ $this->auditSentinelUpdate(['is_metrics_enabled']);
$this->server->refresh();
if ($this->server->isMetricsEnabled()) {
@@ -109,6 +112,25 @@ class Charts extends Component
}
}
+ /**
+ * Metrics settings belong to Sentinel, so they use the same event as the Sentinel page and API.
+ *
+ * @param array<int, string> $changedFields
+ */
+ private function auditSentinelUpdate(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.server.sentinel.updated', [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
public function setInterval()
{
if ($this->interval <= 10) {
diff --git a/app/Livewire/Server/CloudflareTunnel.php b/app/Livewire/Server/CloudflareTunnel.php
index df3ad5c197..17cbfa2398 100644
--- a/app/Livewire/Server/CloudflareTunnel.php
+++ b/app/Livewire/Server/CloudflareTunnel.php
@@ -59,6 +59,7 @@ class CloudflareTunnel extends Component
$this->isCloudflareTunnelsEnabled = false;
$this->server->settings->is_cloudflare_tunnel = false;
$this->server->settings->save();
+ auditLog('ui.server.cloudflare_tunnel.disabled', $this->auditContext());
if ($this->server->ip_previous) {
$this->server->update(['ip' => $this->server->ip_previous]);
$this->dispatch('success', 'Cloudflare Tunnel disabled.<br><br>Manually updated the server IP address to its previous IP address.');
@@ -77,6 +78,7 @@ class CloudflareTunnel extends Component
$this->isCloudflareTunnelsEnabled = true;
$this->server->settings->is_cloudflare_tunnel = true;
$this->server->settings->save();
+ auditLog('ui.server.cloudflare_tunnel.enabled', $this->auditContext());
$this->server->refresh();
$this->dispatch('success', 'Cloudflare Tunnel enabled.');
} catch (\Throwable $e) {
@@ -93,6 +95,9 @@ class CloudflareTunnel extends Component
$this->ssh_domain = str($this->ssh_domain)->replace('/', '');
}
$activity = ConfigureCloudflared::run($this->server, $this->cloudflare_token, $this->ssh_domain);
+ auditLog('ui.server.cloudflare_tunnel.configuration_started', $this->auditContext([
+ 'ssh_domain' => (string) $this->ssh_domain,
+ ]));
$this->dispatch('activityMonitor', $activity->id);
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -103,4 +108,17 @@ class CloudflareTunnel extends Component
{
return view('livewire.server.cloudflare-tunnel');
}
+
+ /**
+ * @param array<string, mixed> $context
+ * @return array<string, mixed>
+ */
+ private function auditContext(array $context = []): array
+ {
+ return array_merge([
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ ], $context);
+ }
}
diff --git a/app/Livewire/Server/Destinations.php b/app/Livewire/Server/Destinations.php
index 62d82efd07..c3740a7613 100644
--- a/app/Livewire/Server/Destinations.php
+++ b/app/Livewire/Server/Destinations.php
@@ -37,11 +37,12 @@ class Destinations extends Component
return;
} else {
- SwarmDocker::create([
+ $destination = SwarmDocker::create([
'name' => $this->server->name.'-'.$name,
'network' => $name,
'server_id' => $this->server->id,
]);
+ $this->auditDestinationCreated($destination, 'swarm');
}
} else {
$this->authorize('create', StandaloneDocker::class);
@@ -51,11 +52,12 @@ class Destinations extends Component
return;
} else {
- StandaloneDocker::create([
+ $destination = StandaloneDocker::create([
'name' => $this->server->name.'-'.$name,
'network' => $name,
'server_id' => $this->server->id,
]);
+ $this->auditDestinationCreated($destination, 'standalone');
}
}
}
@@ -86,6 +88,17 @@ class Destinations extends Component
$this->dispatch('success', 'Scan done.');
}
+ private function auditDestinationCreated(StandaloneDocker|SwarmDocker $destination, string $type): void
+ {
+ auditLog('ui.destination.created', [
+ 'team_id' => $this->server->team_id,
+ 'destination_uuid' => $destination->uuid,
+ 'destination_name' => $destination->name,
+ 'destination_type' => $type,
+ 'server_uuid' => $this->server->uuid,
+ ]);
+ }
+
public function render()
{
return view('livewire.server.destinations');
diff --git a/app/Livewire/Server/DockerCleanup.php b/app/Livewire/Server/DockerCleanup.php
index d0a8d8ca9d..486de686f3 100644
--- a/app/Livewire/Server/DockerCleanup.php
+++ b/app/Livewire/Server/DockerCleanup.php
@@ -107,7 +107,9 @@ class DockerCleanup extends Component
$this->server->settings->delete_unused_volumes = $this->deleteUnusedVolumes;
$this->server->settings->delete_unused_networks = $this->deleteUnusedNetworks;
$this->server->settings->disable_application_image_retention = $this->disableApplicationImageRetention;
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+ $this->auditSettingsUpdate($changedFields);
} else {
$this->forceDockerCleanup = $this->server->settings->force_docker_cleanup;
$this->dockerCleanupFrequency = $this->server->settings->docker_cleanup_frequency;
@@ -166,4 +168,21 @@ class DockerCleanup extends Component
{
return view('livewire.server.docker-cleanup');
}
+
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditSettingsUpdate(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.server.docker_cleanup.updated', [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
}
diff --git a/app/Livewire/Server/GithubRunners.php b/app/Livewire/Server/GithubRunners.php
index d0e537640b..3613339f28 100644
--- a/app/Livewire/Server/GithubRunners.php
+++ b/app/Livewire/Server/GithubRunners.php
@@ -191,7 +191,8 @@ class GithubRunners extends Component
$this->prepareRunnerGroup($githubApp);
}
- GithubRunnerConfig::updateOrCreate(['server_id' => $this->server->id], [
+ $config = GithubRunnerConfig::firstOrNew(['server_id' => $this->server->id]);
+ $config->fill([
'github_app_id' => $githubApp->id,
'labels' => $labels,
'max_runners' => $this->maxRunners,
@@ -205,6 +206,9 @@ class GithubRunners extends Component
'is_dedicated' => $this->isDedicated,
'allow_pull_requests' => $this->allowPullRequests,
]);
+ $changedFields = auditChangedFields($config);
+ $config->save();
+ $this->auditConfigSaved($config, $githubApp, $changedFields);
unset($this->config);
$this->syncData();
$this->dispatch('success', 'GitHub runner settings saved.');
@@ -230,6 +234,7 @@ class GithubRunners extends Component
if ($config->is_enabled) {
$config->update(['is_enabled' => false]);
+ auditLog('ui.server.github_runners.disabled', $this->auditContext());
$config->executions()->where('status', GithubRunnerStatus::Idle)->get()
->each(function (GithubRunnerExecution $execution) {
$execution->finish(GithubRunnerStatus::Cancelled, 'Runners were disabled on this server.');
@@ -243,6 +248,7 @@ class GithubRunners extends Component
$this->authorize('update', $config->githubApp);
$this->prepareRunnerGroup($config->githubApp);
$config->update(['is_enabled' => true]);
+ auditLog('ui.server.github_runners.enabled', $this->auditContext());
ProvisionGithubRunnerJob::dispatchQueued($config->github_app_id);
$this->dispatch('success', 'GitHub runners enabled.');
}
@@ -289,6 +295,41 @@ class GithubRunners extends Component
}
}
+ /**
+ * Record a created configuration with its set fields, or the changed field names of an updated one.
+ *
+ * @param array<int, string> $changedFields Fields changed by the save, captured before it.
+ */
+ private function auditConfigSaved(GithubRunnerConfig $config, GithubApp $githubApp, array $changedFields): void
+ {
+ if ($config->wasRecentlyCreated) {
+ $changedFields = array_values(array_diff(array_keys($config->getAttributes()), ['id', 'uuid', 'server_id', 'created_at', 'updated_at']));
+ }
+
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog($config->wasRecentlyCreated ? 'ui.server.github_runners.created' : 'ui.server.github_runners.updated', $this->auditContext([
+ 'github_app_uuid' => $githubApp->uuid,
+ 'github_app_name' => $githubApp->name,
+ 'changed_fields' => $changedFields,
+ ]));
+ }
+
+ /**
+ * @param array<string, mixed> $context
+ * @return array<string, mixed>
+ */
+ private function auditContext(array $context = []): array
+ {
+ return array_merge([
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ ], $context);
+ }
+
public function render()
{
return view('livewire.server.github-runners');
diff --git a/app/Livewire/Server/New/ByDigitalOcean.php b/app/Livewire/Server/New/ByDigitalOcean.php
index 1cfcc56634..95e07643ef 100644
--- a/app/Livewire/Server/New/ByDigitalOcean.php
+++ b/app/Livewire/Server/New/ByDigitalOcean.php
@@ -466,11 +466,17 @@ class ByDigitalOcean extends Component
if ($this->save_cloud_init_script && ! empty($this->cloud_init_script) && ! empty($this->cloud_init_script_name)) {
$this->authorize('create', CloudInitScript::class);
- CloudInitScript::create([
+ $cloudInitScript = CloudInitScript::create([
'team_id' => currentTeam()->id,
'name' => $this->cloud_init_script_name,
'script' => $this->cloud_init_script,
]);
+
+ auditLog('ui.cloud_init_script.created', [
+ 'team_id' => currentTeam()->id,
+ 'cloud_init_script_id' => $cloudInitScript->id,
+ 'cloud_init_script_name' => $cloudInitScript->name,
+ ]);
}
$digitalOceanService = new DigitalOceanService($this->getDigitalOceanToken());
diff --git a/app/Livewire/Server/New/ByHetzner.php b/app/Livewire/Server/New/ByHetzner.php
index 3d704a88e9..aadcb7b0c1 100644
--- a/app/Livewire/Server/New/ByHetzner.php
+++ b/app/Livewire/Server/New/ByHetzner.php
@@ -697,11 +697,17 @@ class ByHetzner extends Component
if ($this->save_cloud_init_script && ! empty($this->cloud_init_script) && ! empty($this->cloud_init_script_name)) {
$this->authorize('create', CloudInitScript::class);
- CloudInitScript::create([
+ $cloudInitScript = CloudInitScript::create([
'team_id' => currentTeam()->id,
'name' => $this->cloud_init_script_name,
'script' => $this->cloud_init_script,
]);
+
+ auditLog('ui.cloud_init_script.created', [
+ 'team_id' => currentTeam()->id,
+ 'cloud_init_script_id' => $cloudInitScript->id,
+ 'cloud_init_script_name' => $cloudInitScript->name,
+ ]);
}
$hetznerToken = $this->getHetznerToken();
diff --git a/app/Livewire/Server/New/ByVultr.php b/app/Livewire/Server/New/ByVultr.php
index 321d8f6588..f3024f29da 100644
--- a/app/Livewire/Server/New/ByVultr.php
+++ b/app/Livewire/Server/New/ByVultr.php
@@ -435,11 +435,17 @@ class ByVultr extends Component
if ($this->save_cloud_init_script && ! empty($this->cloud_init_script) && ! empty($this->cloud_init_script_name)) {
$this->authorize('create', CloudInitScript::class);
- CloudInitScript::create([
+ $cloudInitScript = CloudInitScript::create([
'team_id' => currentTeam()->id,
'name' => $this->cloud_init_script_name,
'script' => $this->cloud_init_script,
]);
+
+ auditLog('ui.cloud_init_script.created', [
+ 'team_id' => currentTeam()->id,
+ 'cloud_init_script_id' => $cloudInitScript->id,
+ 'cloud_init_script_name' => $cloudInitScript->name,
+ ]);
}
$vultrService = new VultrService($this->getVultrToken());
diff --git a/app/Livewire/Server/Proxy.php b/app/Livewire/Server/Proxy.php
index 0bd347ea78..a7e2858e5b 100644
--- a/app/Livewire/Server/Proxy.php
+++ b/app/Livewire/Server/Proxy.php
@@ -97,6 +97,33 @@ class Proxy extends Component
return is_array($traefikVersions) ? $traefikVersions : null;
}
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditProxyUpdate(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.server.proxy.updated', $this->proxyAuditContext([
+ 'changed_fields' => $changedFields,
+ ]));
+ }
+
+ /**
+ * @param array<string, mixed> $context
+ * @return array<string, mixed>
+ */
+ private function proxyAuditContext(array $context = []): array
+ {
+ return array_merge([
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ ], $context);
+ }
+
public function getConfigurationFilePathProperty(): string
{
return rtrim($this->server->proxyPath(), '/').'/docker-compose.yml';
@@ -136,7 +163,9 @@ class Proxy extends Component
$this->authorize('update', $this->server);
$this->validate();
$this->syncData(true);
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+ $this->auditProxyUpdate($changedFields);
$this->dispatch('success', 'Settings saved.');
} catch (\Throwable $e) {
return handleError($e, $this);
@@ -147,8 +176,10 @@ class Proxy extends Component
{
try {
$this->authorize('update', $this->server);
+ $redirectChanged = (bool) data_get($this->server->proxy, 'redirect_enabled', true) !== $this->redirectEnabled;
$this->server->proxy->redirect_enabled = $this->redirectEnabled;
$this->server->save();
+ $this->auditProxyUpdate($redirectChanged ? ['redirect_enabled'] : []);
$this->server->setupDefaultRedirect();
$this->dispatch('success', 'Proxy configuration saved.');
} catch (\Throwable $e) {
@@ -164,6 +195,7 @@ class Proxy extends Component
SaveProxyConfiguration::run($this->server, $this->proxySettings);
$this->server->proxy->redirect_url = $this->redirectUrl;
$this->server->save();
+ auditLog('ui.server.proxy.configuration_saved', $this->proxyAuditContext());
$this->server->setupDefaultRedirect();
$this->dispatch('refreshServerShow');
$this->dispatch('success', 'Proxy configuration saved.');
@@ -180,6 +212,7 @@ class Proxy extends Component
$this->proxySettings = GetProxyConfiguration::run($this->server, forceRegenerate: true);
SaveProxyConfiguration::run($this->server, $this->proxySettings);
$this->server->save();
+ auditLog('ui.server.proxy.configuration_reset', $this->proxyAuditContext());
$this->dispatch('refreshServerShow');
$this->dispatch('success', 'Proxy configuration reset to default.');
} catch (\Throwable $e) {
diff --git a/app/Livewire/Server/Security/TerminalAccess.php b/app/Livewire/Server/Security/TerminalAccess.php
index 999482dcff..2406bdcb33 100644
--- a/app/Livewire/Server/Security/TerminalAccess.php
+++ b/app/Livewire/Server/Security/TerminalAccess.php
@@ -54,6 +54,11 @@ class TerminalAccess extends Component
$this->isTerminalEnabled = $this->server->settings->is_terminal_enabled;
$status = $this->isTerminalEnabled ? 'enabled' : 'disabled';
+ auditLog("ui.server.terminal_access.{$status}", [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ ]);
$this->dispatch('success', "Terminal access has been {$status}.");
return true;
diff --git a/app/Livewire/Server/Sentinel.php b/app/Livewire/Server/Sentinel.php
index 4719033f92..0de1ff766e 100644
--- a/app/Livewire/Server/Sentinel.php
+++ b/app/Livewire/Server/Sentinel.php
@@ -47,7 +47,10 @@ class Sentinel extends Component
$this->syncData();
}
- private function syncData(bool $toModel = false): void
+ /**
+ * @return array<int, string> Names of the settings that changed when saving to the model.
+ */
+ private function syncData(bool $toModel = false): array
{
if ($toModel) {
$this->validate();
@@ -55,7 +58,10 @@ class Sentinel extends Component
$this->server->settings->sentinel_token = $this->sentinelToken;
$this->server->settings->sentinel_custom_url = $this->sentinelCustomUrl;
$this->server->settings->is_sentinel_debug_enabled = $this->isSentinelDebugEnabled;
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+
+ return $changedFields;
} else {
$this->isMetricsEnabled = $this->server->settings->is_metrics_enabled;
$this->sentinelToken = $this->server->settings->sentinel_token;
@@ -64,6 +70,8 @@ class Sentinel extends Component
$this->sentinelUpdatedAt = $this->server->sentinel_updated_at;
$this->sentinelStatus = $this->server->sentinelStatus();
}
+
+ return [];
}
public function handleSentinelRestarted($event)
@@ -179,7 +187,12 @@ class Sentinel extends Component
{
try {
$this->authorize('update', $this->server);
- $this->syncData(true);
+ $changedFields = $this->syncData(true);
+ if ($changedFields !== []) {
+ auditLog('ui.server.sentinel.updated', $this->auditContext([
+ 'changed_fields' => $changedFields,
+ ]));
+ }
$this->restartSentinel();
} catch (\Throwable $e) {
return handleError($e, $this);
diff --git a/app/Livewire/Server/Show.php b/app/Livewire/Server/Show.php
index e596a9c2f9..275622691a 100644
--- a/app/Livewire/Server/Show.php
+++ b/app/Livewire/Server/Show.php
@@ -267,7 +267,9 @@ class Show extends Component
$this->server->settings->server_timezone = $this->serverTimezone;
}
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+ $this->auditSettingsUpdate($changedFields);
} else {
$this->name = $this->server->name;
$this->description = $this->server->description;
@@ -299,6 +301,25 @@ class Show extends Component
}
}
+ /**
+ * Server columns are audited by the model. Settings live on ServerSetting, so record their names here.
+ *
+ * @param array<int, string> $changedFields
+ */
+ private function auditSettingsUpdate(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.server.settings_updated', [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
public function refresh()
{
$this->syncData();
@@ -522,6 +543,11 @@ class Show extends Component
try {
$this->authorize('manageSentinel', $this->server);
$this->server->settings->generateSentinelToken();
+ auditLog('ui.server.sentinel.token_regenerated', [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ ]);
$this->dispatch('success', 'Token regenerated. Restarting Sentinel.');
} catch (\Throwable $e) {
return handleError($e, $this);
diff --git a/app/Livewire/Server/Swarm.php b/app/Livewire/Server/Swarm.php
index 376705dcb7..cacf1f4b92 100644
--- a/app/Livewire/Server/Swarm.php
+++ b/app/Livewire/Server/Swarm.php
@@ -42,7 +42,9 @@ class Swarm extends Component
}
$this->server->settings->is_swarm_manager = $this->isSwarmManager;
$this->server->settings->is_swarm_worker = $this->isSwarmWorker;
+ $changedFields = auditChangedFields($this->server->settings);
$this->server->settings->save();
+ $this->auditSettingsUpdate($changedFields);
} else {
$this->isSwarmManager = $this->server->settings->is_swarm_manager;
$this->isSwarmWorker = $this->server->settings->is_swarm_worker;
@@ -64,4 +66,21 @@ class Swarm extends Component
{
return view('livewire.server.swarm');
}
+
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditSettingsUpdate(array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.server.settings_updated', [
+ 'team_id' => $this->server->team_id,
+ 'server_uuid' => $this->server->uuid,
+ 'server_name' => $this->server->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
}
diff --git a/app/Livewire/Settings/Advanced.php b/app/Livewire/Settings/Advanced.php
index 4bb89c9f08..a3855eac3b 100644
--- a/app/Livewire/Settings/Advanced.php
+++ b/app/Livewire/Settings/Advanced.php
@@ -222,7 +222,7 @@ class Advanced extends Component
$this->settings->webhook_allow_localhost = $this->webhook_allow_localhost;
$this->settings->image_cdn_url = filled($this->image_cdn_url) ? rtrim($this->image_cdn_url, '/') : null;
$this->saveAvatarStorageSetting();
- $this->settings->save();
+ $this->saveAndAudit();
$this->dispatch('success', 'Settings updated!');
} catch (\Exception $e) {
return handleError($e, $this);
@@ -260,7 +260,7 @@ class Advanced extends Component
}
$this->authorize('update', $this->settings);
$this->settings->domain_connect_private_key = null;
- $this->settings->save();
+ $this->saveAndAudit();
$this->domain_connect_private_key = null;
$this->dispatch('success', 'Domain Connect private key removed.');
} catch (\Exception $e) {
@@ -268,6 +268,26 @@ class Advanced extends Component
}
}
+ /**
+ * Save the instance settings and record the changed field names (never their values).
+ */
+ private function saveAndAudit(): void
+ {
+ $changedFields = auditChangedFields($this->settings);
+ $this->settings->save();
+
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.instance.settings.updated', [
+ 'team_id' => null,
+ 'resource' => 'instance',
+ 'section' => 'advanced',
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
private function normalizeDomainConnectPrivateKey(string $key): string
{
$key = str_replace(["\r\n", "\r"], "\n", trim($key));
diff --git a/app/Livewire/Settings/Index.php b/app/Livewire/Settings/Index.php
index 829fbda800..75826f2d4e 100644
--- a/app/Livewire/Settings/Index.php
+++ b/app/Livewire/Settings/Index.php
@@ -104,11 +104,31 @@ class Index extends Component
$this->settings->instance_timezone = $this->instance_timezone;
$this->settings->dev_helper_version = $this->dev_helper_version;
if ($isSave) {
- $this->settings->save();
+ $this->saveAndAudit();
$this->dispatch('success', 'Settings updated!');
}
}
+ /**
+ * Save the instance settings and record the changed field names.
+ */
+ private function saveAndAudit(): void
+ {
+ $changedFields = auditChangedFields($this->settings);
+ $this->settings->save();
+
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.instance.settings.updated', [
+ 'team_id' => null,
+ 'resource' => 'instance',
+ 'section' => 'general',
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
public function confirmDomainUsage()
{
$this->authorize('update', $this->settings);
@@ -169,7 +189,7 @@ class Index extends Component
$this->instantSave(isSave: false);
- $this->settings->save();
+ $this->saveAndAudit();
if ($this->server) {
$this->server->setupDynamicProxyConfiguration();
}
diff --git a/app/Livewire/Settings/Updates.php b/app/Livewire/Settings/Updates.php
index 615cc99246..10b3180640 100644
--- a/app/Livewire/Settings/Updates.php
+++ b/app/Livewire/Settings/Updates.php
@@ -64,7 +64,16 @@ class Updates extends Component
$this->settings->is_auto_update_enabled = $this->is_auto_update_enabled;
$this->settings->docker_registry_url = $validated['docker_registry_url'];
$this->syncRegistryUrlToEnv($validated['docker_registry_url']);
+ $changedFields = auditChangedFields($this->settings);
$this->settings->save();
+ if ($changedFields !== []) {
+ auditLog('ui.instance.settings.updated', [
+ 'team_id' => null,
+ 'resource' => 'instance',
+ 'section' => 'updates',
+ 'changed_fields' => $changedFields,
+ ]);
+ }
$this->dispatch('success', 'Settings updated!');
} catch (ValidationException $e) {
throw $e;
diff --git a/app/Livewire/SettingsBackup.php b/app/Livewire/SettingsBackup.php
index d5d80acbd2..a498f9169b 100644
--- a/app/Livewire/SettingsBackup.php
+++ b/app/Livewire/SettingsBackup.php
@@ -111,6 +111,14 @@ class SettingsBackup extends Component
]);
$this->database->refresh();
$this->backup->refresh();
+ auditLog('ui.database.backup_schedule_created', [
+ 'team_id' => $this->backup->team_id,
+ 'database_uuid' => $this->database->uuid,
+ 'database_name' => $this->database->name,
+ 'backup_uuid' => $this->backup->uuid,
+ 'frequency' => $this->backup->frequency,
+ 'save_s3' => (bool) $this->backup->save_s3,
+ ]);
$this->s3s = S3Storage::whereTeamId(0)->get();
$this->uuid = $this->database->uuid;
diff --git a/app/Livewire/SettingsEmail.php b/app/Livewire/SettingsEmail.php
index 320285970d..ba0be82420 100644
--- a/app/Livewire/SettingsEmail.php
+++ b/app/Livewire/SettingsEmail.php
@@ -92,7 +92,7 @@ class SettingsEmail extends Component
$this->settings->resend_enabled = $this->resendEnabled;
$this->settings->resend_api_key = $this->resendApiKey;
- $this->settings->save();
+ $this->saveAndAudit();
} else {
$this->smtpEnabled = $this->settings->smtp_enabled;
$this->smtpHost = $this->settings->smtp_host;
@@ -137,7 +137,7 @@ class SettingsEmail extends Component
$this->submitResend();
$this->smtpEnabled = $this->settings->smtp_enabled = false;
}
- $this->settings->save();
+ $this->saveAndAudit();
} catch (\Throwable $e) {
if ($type === 'SMTP') {
@@ -227,7 +227,7 @@ class SettingsEmail extends Component
$this->settings->smtp_from_address = $this->smtpFromAddress;
$this->settings->smtp_from_name = $this->smtpFromName;
- $this->settings->save();
+ $this->saveAndAudit();
$this->dispatch('success', 'SMTP settings updated.');
} catch (\Throwable $e) {
@@ -252,7 +252,7 @@ class SettingsEmail extends Component
$this->settings->smtp_from_address = $this->smtpFromAddress;
$this->settings->smtp_from_name = $this->smtpFromName;
- $this->settings->save();
+ $this->saveAndAudit();
$this->dispatch('success', 'Resend settings updated.');
} catch (\Throwable $e) {
@@ -262,6 +262,26 @@ class SettingsEmail extends Component
}
}
+ /**
+ * Save the instance email settings and record the changed field names (never their values).
+ */
+ private function saveAndAudit(): void
+ {
+ $changedFields = auditChangedFields($this->settings);
+ $this->settings->save();
+
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.settings.email.updated', [
+ 'team_id' => null,
+ 'resource' => 'instance',
+ 'section' => 'email',
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
private function validateSmtpSettings(): void
{
$this->validate([
@@ -319,7 +339,7 @@ class SettingsEmail extends Component
$this->settings->smtp_from_address = $this->smtpFromAddress;
$this->settings->smtp_from_name = $this->smtpFromName;
- $this->settings->save();
+ $this->saveAndAudit();
$executed = RateLimiter::attempt(
'test-email:'.$this->team->id,
diff --git a/app/Livewire/Storage/Resources.php b/app/Livewire/Storage/Resources.php
index 1e9b80c3a3..95e7917515 100644
--- a/app/Livewire/Storage/Resources.php
+++ b/app/Livewire/Storage/Resources.php
@@ -2,9 +2,13 @@
namespace App\Livewire\Storage;
+use App\Models\Application;
use App\Models\S3Storage;
use App\Models\ScheduledDatabaseBackup;
use App\Models\ScheduledVolumeBackup;
+use App\Models\Service;
+use App\Models\ServiceApplication;
+use App\Models\ServiceDatabase;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;
@@ -46,11 +50,14 @@ class Resources extends Component
->where('s3_storage_id', $this->storage->id)
->firstOrFail();
- $backup->update([
+ $backup->fill([
'save_s3' => false,
's3_storage_id' => null,
]);
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ $this->auditDatabaseBackupUpdated($backup, $changedFields);
unset($this->selectedStorages[$backupId]);
$this->dispatch('success', 'S3 disabled.', 'S3 backup has been disabled for this schedule.');
@@ -83,8 +90,11 @@ class Resources extends Component
$this->authorize('update', $newStorage);
- $backup->update(['s3_storage_id' => $newStorage->id]);
+ $backup->s3_storage_id = $newStorage->id;
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ $this->auditDatabaseBackupUpdated($backup, $changedFields);
unset($this->selectedStorages[$backupId]);
$this->dispatch('success', 'Backup moved.', "Moved to {$newStorage->name}.");
@@ -99,11 +109,14 @@ class Resources extends Component
->where('s3_storage_id', $this->storage->id)
->firstOrFail();
- $backup->update([
+ $backup->fill([
'save_s3' => false,
's3_storage_id' => null,
]);
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ $this->auditVolumeBackupUpdated($backup, $changedFields);
unset($this->selectedVolumeStorages[$backupId]);
$this->dispatch('success', 'S3 disabled.', 'S3 backup has been disabled for this schedule.');
@@ -138,13 +151,64 @@ class Resources extends Component
$this->authorize('update', $newStorage);
- $backup->update(['s3_storage_id' => $newStorage->id]);
+ $backup->s3_storage_id = $newStorage->id;
+ $changedFields = auditChangedFields($backup);
+ $backup->save();
+ $this->auditVolumeBackupUpdated($backup, $changedFields);
unset($this->selectedVolumeStorages[$backupId]);
$this->dispatch('success', 'Backup moved.', "Moved to {$newStorage->name}.");
}
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditDatabaseBackupUpdated(ScheduledDatabaseBackup $backup, array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ $database = $backup->database;
+ auditLog('ui.database.backup_schedule_updated', [
+ 'team_id' => $this->storage->team_id,
+ 'database_uuid' => $database?->uuid,
+ 'database_name' => $database?->name,
+ 'backup_uuid' => $backup->uuid,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
+ /**
+ * @param array<int, string> $changedFields
+ */
+ private function auditVolumeBackupUpdated(ScheduledVolumeBackup $backup, array $changedFields): void
+ {
+ if ($changedFields === []) {
+ return;
+ }
+
+ $resource = $backup->targetResource();
+ if ($resource instanceof ServiceApplication || $resource instanceof ServiceDatabase) {
+ $resource = $resource->service;
+ }
+
+ auditLog('ui.volume_backup.schedule_set', [
+ 'team_id' => $this->storage->team_id,
+ 'resource_type' => match (true) {
+ $resource instanceof Application => 'application',
+ $resource instanceof Service => 'service',
+ default => 'database',
+ },
+ 'resource_uuid' => $resource?->uuid,
+ 'resource_name' => $resource?->name,
+ 'storage_uuid' => $backup->backupable?->uuid,
+ 'backup_uuid' => $backup->uuid,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+
public function render()
{
$backups = ScheduledDatabaseBackup::where('s3_storage_id', $this->storage->id)
diff --git a/app/Livewire/Subscription/Actions.php b/app/Livewire/Subscription/Actions.php
index ea560b039f..d04856f55e 100644
--- a/app/Livewire/Subscription/Actions.php
+++ b/app/Livewire/Subscription/Actions.php
@@ -68,9 +68,14 @@ class Actions extends Component
return true;
}
+ $previousServerLimit = (int) $this->server_limits;
$result = (new UpdateSubscriptionQuantity)->execute(currentTeam(), $this->quantity);
if ($result['success']) {
+ $this->auditSubscriptionChange('quantity_updated', [
+ 'from_server_limit' => $previousServerLimit,
+ 'to_server_limit' => $this->quantity,
+ ]);
$this->server_limits = $this->quantity;
$this->pricePreview = null;
$this->dispatch('success', 'Server limit updated to '.$this->quantity.'.');
@@ -105,6 +110,7 @@ class Actions extends Component
$result = app(RefundSubscription::class)->execute(currentTeam());
if ($result['success']) {
+ $this->auditSubscriptionChange('refunded');
$this->dispatch('success', 'Subscription refunded successfully.');
$this->redirect(route('subscription.index'), navigate: true);
@@ -127,6 +133,7 @@ class Actions extends Component
$result = app(RefundSubscription::class)->execute(currentTeam());
if ($result['success']) {
+ $this->auditSubscriptionChange('refunded');
$this->dispatch('success', 'Subscription refunded and cancelled successfully.');
$this->redirect(route('subscription.index'), navigate: true);
@@ -162,6 +169,8 @@ class Actions extends Component
$team->subscriptionEnded();
+ $this->auditSubscriptionChange('cancelled', ['cancel_at_period_end' => false]);
+
\Log::info("Subscription {$subscription->stripe_subscription_id} cancelled immediately for team {$team->name}");
$this->dispatch('success', 'Subscription cancelled successfully.');
@@ -186,6 +195,7 @@ class Actions extends Component
$result = (new CancelSubscriptionAtPeriodEnd)->execute(currentTeam());
if ($result['success']) {
+ $this->auditSubscriptionChange('cancellation_scheduled', ['cancel_at_period_end' => true]);
$this->dispatch('success', 'Subscription will be cancelled at the end of the billing period.');
return true;
@@ -201,6 +211,7 @@ class Actions extends Component
$result = (new ResumeSubscription)->execute(currentTeam());
if ($result['success']) {
+ $this->auditSubscriptionChange('resumed');
$this->dispatch('success', 'Subscription resumed successfully.');
return true;
@@ -211,6 +222,24 @@ class Actions extends Component
return true;
}
+ /**
+ * Record a user-triggered subscription change for the current team.
+ *
+ * @param array<string, mixed> $context
+ */
+ private function auditSubscriptionChange(string $action, array $context = []): void
+ {
+ $team = currentTeam();
+
+ auditLog("ui.subscription.{$action}", [
+ 'team_id' => $team?->id,
+ 'resource' => 'subscription',
+ 'subscription_id' => $team?->subscription?->id,
+ 'team_name' => $team?->name,
+ ...$context,
+ ]);
+ }
+
private function checkRefundEligibility(): void
{
if (! isCloud() || ! currentTeam()->subscription?->stripe_subscription_id) {
diff --git a/app/Livewire/Team/AdminView.php b/app/Livewire/Team/AdminView.php
index a31a37d784..c98e972fd6 100644
--- a/app/Livewire/Team/AdminView.php
+++ b/app/Livewire/Team/AdminView.php
@@ -81,6 +81,13 @@ class AdminView extends Component
try {
$user->delete();
+ auditLog('ui.user.deleted', [
+ 'team_id' => currentTeam()?->id,
+ 'resource' => 'user',
+ 'user_name' => $user->name,
+ 'deleted_user_id' => $user->id,
+ 'deleted_user_email' => $user->email,
+ ]);
$this->resetPage();
return true;
diff --git a/app/Livewire/Upgrade.php b/app/Livewire/Upgrade.php
index d548b37249..e2ab094944 100644
--- a/app/Livewire/Upgrade.php
+++ b/app/Livewire/Upgrade.php
@@ -79,6 +79,13 @@ class Upgrade extends Component
report($e);
}
})->afterResponse();
+
+ auditLog('ui.instance.upgrade_started', [
+ 'team_id' => null,
+ 'resource' => 'instance',
+ 'from_version' => config('constants.coolify.version'),
+ 'to_version' => get_latest_version_of_coolify(),
+ ]);
} catch (\Throwable $e) {
return handleError($e, $this);
}
diff --git a/app/Providers/EventServiceProvider.php b/app/Providers/EventServiceProvider.php
index 14b90c2c59..7c44c4553e 100644
--- a/app/Providers/EventServiceProvider.php
+++ b/app/Providers/EventServiceProvider.php
@@ -10,6 +10,10 @@ use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
+use Laravel\Fortify\Events\RecoveryCodesGenerated;
+use Laravel\Fortify\Events\TwoFactorAuthenticationConfirmed;
+use Laravel\Fortify\Events\TwoFactorAuthenticationDisabled;
+use Laravel\Fortify\Events\TwoFactorAuthenticationEnabled;
use SocialiteProviders\Authentik\AuthentikExtendSocialite;
use SocialiteProviders\Azure\AzureExtendSocialite;
use SocialiteProviders\Clerk\ClerkExtendSocialite;
@@ -56,6 +60,18 @@ class EventServiceProvider extends ServiceProvider
Event::listen(PasswordReset::class, function (PasswordReset $event): void {
auditLog('auth.user.password_reset', $this->authContext($event->user));
});
+ Event::listen(TwoFactorAuthenticationEnabled::class, function (TwoFactorAuthenticationEnabled $event): void {
+ auditLog('auth.user.two_factor_enabled', $this->authContext($event->user));
+ });
+ Event::listen(TwoFactorAuthenticationConfirmed::class, function (TwoFactorAuthenticationConfirmed $event): void {
+ auditLog('auth.user.two_factor_confirmed', $this->authContext($event->user));
+ });
+ Event::listen(TwoFactorAuthenticationDisabled::class, function (TwoFactorAuthenticationDisabled $event): void {
+ auditLog('auth.user.two_factor_disabled', $this->authContext($event->user));
+ });
+ Event::listen(RecoveryCodesGenerated::class, function (RecoveryCodesGenerated $event): void {
+ auditLog('auth.user.recovery_codes_regenerated', $this->authContext($event->user));
+ });
}
private function authContext(?object $user): array
diff --git a/app/Services/Auth/OauthLoginService.php b/app/Services/Auth/OauthLoginService.php
index c95b6efdd7..45057eea9a 100644
--- a/app/Services/Auth/OauthLoginService.php
+++ b/app/Services/Auth/OauthLoginService.php
@@ -147,6 +147,7 @@ class OauthLoginService
throw new OauthLoginException('OAuth identity cannot be linked to this account', 'auth.failed.oauth_already_linked');
}
+ $linksExistingUser = $user !== null;
if (! $user) {
if (! $oauthSetting->allowsUserCreation()) {
throw new OauthLoginException('Registration is disabled', 'auth.registration_disabled');
@@ -164,6 +165,9 @@ class OauthLoginService
'raw_claims' => $rawClaims,
'last_login_at' => now(),
]);
+ if ($linksExistingUser) {
+ $this->auditIdentityLinked($user, $provider, $issuer);
+ }
if ($user->created_before_oauth_identities) {
$user->forceFill(['created_before_oauth_identities' => false])->save();
@@ -266,6 +270,7 @@ class OauthLoginService
throw new OauthLoginException('OAuth identity cannot be linked to this account', 'auth.failed.oauth_already_linked');
}
+ $linksExistingUser = $user !== null;
if (! $user) {
if (! $oauthSetting->allowsUserCreation()) {
throw new OauthLoginException('Registration is disabled', 'auth.registration_disabled');
@@ -283,6 +288,9 @@ class OauthLoginService
'raw_claims' => $rawClaims,
'last_login_at' => now(),
]);
+ if ($linksExistingUser) {
+ $this->auditIdentityLinked($user, 'oidc', $issuer);
+ }
return $user;
});
@@ -292,6 +300,45 @@ class OauthLoginService
}
private function createUser(string $name, string $email, OauthSetting $oauthSetting): User
+ {
+ $user = $this->provisionUser($name, $email, $oauthSetting);
+
+ auditLog('auth.user.registered', [
+ ...$this->userAuditContext($user, $user->teams()->first()?->id),
+ 'provider' => $oauthSetting->provider,
+ 'via' => 'oauth',
+ ]);
+
+ return $user;
+ }
+
+ private function auditIdentityLinked(User $user, string $provider, string $issuer): void
+ {
+ auditLog('auth.user.oauth_identity_linked', [
+ ...$this->userAuditContext($user, $user->resolveStoredTeam()?->id ?? $user->teams()->first()?->id),
+ 'provider' => $provider,
+ 'issuer' => $issuer,
+ ]);
+ }
+
+ /**
+ * Context for events recorded before the user is logged in, so the actor is set explicitly.
+ *
+ * @return array<string, mixed>
+ */
+ private function userAuditContext(User $user, ?int $teamId): array
+ {
+ return [
+ 'team_id' => $teamId,
+ 'resource' => 'user',
+ 'user_name' => $user->name,
+ 'actor_id' => $user->id,
+ 'actor_name' => $user->name,
+ 'actor_email' => $user->email,
+ ];
+ }
+
+ private function provisionUser(string $name, string $email, OauthSetting $oauthSetting): User
{
if (User::count() === 0) {
$user = (new User)->forceFill([
diff --git a/app/Services/Dns/CloudflareDnsProvider.php b/app/Services/Dns/CloudflareDnsProvider.php
index c4864900f1..9cc64beb4b 100644
--- a/app/Services/Dns/CloudflareDnsProvider.php
+++ b/app/Services/Dns/CloudflareDnsProvider.php
@@ -288,9 +288,7 @@ class CloudflareDnsProvider
private function forgetDeletedRecord(ManagedDnsRecord $record, ManagedDnsDeletionResult $result, ?Model $resource): ManagedDnsDeletionResult
{
$record->delete();
- if ($result === ManagedDnsDeletionResult::Deleted) {
- $this->auditDnsRecord('deleted', $record->zone, $record->name, $resource);
- }
+ $this->auditDnsRecord($result === ManagedDnsDeletionResult::Deleted ? 'deleted' : 'already_deleted', $record->zone, $record->name, $resource);
return $result;
}
diff --git a/app/Services/Dns/ManagedDnsRecordCleanup.php b/app/Services/Dns/ManagedDnsRecordCleanup.php
index 2fdb4f57be..d8d02dfd73 100644
--- a/app/Services/Dns/ManagedDnsRecordCleanup.php
+++ b/app/Services/Dns/ManagedDnsRecordCleanup.php
@@ -269,7 +269,7 @@ class ManagedDnsRecordCleanup
}
if (! $record->owned || ! $deleteRecord) {
- $record->delete();
+ $this->forget($record, $record->owned ? 'kept_by_user' : 'not_owned', 'info');
return $record->owned ? null : ManagedDnsDeletionResult::NotOwned;
}
@@ -400,13 +400,13 @@ class ManagedDnsRecordCleanup
/**
* Stops tracking the record without touching the provider.
*/
- private function forget(ManagedDnsRecord $record, string $reason): void
+ private function forget(ManagedDnsRecord $record, string $reason, string $level = 'warning'): void
{
$record->delete();
- $this->auditSkipped($record, $reason);
+ $this->auditSkipped($record, $reason, $level);
}
- private function auditSkipped(ManagedDnsRecord $record, string $reason): void
+ private function auditSkipped(ManagedDnsRecord $record, string $reason, string $level = 'warning'): void
{
$source = auth()->check() ? 'ui' : 'system';
auditLog("{$source}.dns_record.delete_skipped", [
@@ -414,7 +414,7 @@ class ManagedDnsRecordCleanup
'hostname' => $record->name,
'provider' => 'cloudflare',
'reason' => $reason,
- ], 'warning');
+ ], $level);
}
/**
diff --git a/app/Traits/AuditsApplicationSettings.php b/app/Traits/AuditsApplicationSettings.php
new file mode 100644
index 0000000000..f2ec5269f0
--- /dev/null
+++ b/app/Traits/AuditsApplicationSettings.php
@@ -0,0 +1,31 @@
+<?php
+
+namespace App\Traits;
+
+use App\Models\Application;
+
+trait AuditsApplicationSettings
+{
+ /**
+ * Save the application's settings and record `ui.application.settings_updated` with the
+ * names of the changed fields. Nothing is recorded when no setting changed.
+ */
+ private function saveApplicationSettingsWithAudit(Application $application): void
+ {
+ $settings = $application->settings;
+ $changedFields = auditChangedFields($settings);
+
+ $settings->save();
+
+ if ($changedFields === []) {
+ return;
+ }
+
+ auditLog('ui.application.settings_updated', [
+ 'team_id' => $application->team()?->id,
+ 'application_uuid' => $application->uuid,
+ 'application_name' => $application->name,
+ 'changed_fields' => $changedFields,
+ ]);
+ }
+}
diff --git a/app/Traits/HasDatabaseStatusInfo.php b/app/Traits/HasDatabaseStatusInfo.php
index b345657c4b..33a8be0d0c 100644
--- a/app/Traits/HasDatabaseStatusInfo.php
+++ b/app/Traits/HasDatabaseStatusInfo.php
@@ -160,6 +160,14 @@ trait HasDatabaseStatusInfo
isPemKeyFileRequired: $existingCert->requiresPemKeyFile(),
);
+ auditLog('ui.database.ssl_certificate_regenerated', [
+ 'team_id' => $server->team_id,
+ 'database_uuid' => $this->database->uuid,
+ 'database_name' => $this->database->name,
+ 'database_type' => $this->database->type(),
+ 'server_uuid' => $server->uuid,
+ ]);
+
$this->refresh();
$this->dispatch('success', 'SSL certificates regenerated. Restart database to apply changes.');
} catch (Exception $e) {
diff --git a/bootstrap/helpers/audit.php b/bootstrap/helpers/audit.php
index 2c8b7f4a8f..aea549a5be 100644
--- a/bootstrap/helpers/audit.php
+++ b/bootstrap/helpers/audit.php
@@ -1,6 +1,7 @@
<?php
use App\Models\AuditEvent;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
@@ -47,6 +48,24 @@ if (! function_exists('auditLog')) {
}
}
+if (! function_exists('auditChangedFields')) {
+ /**
+ * Names of the attributes that the next save() will really change, without timestamps.
+ * Call it before save(). Loosely equal values, such as `false` and `0` in an uncast
+ * boolean column, do not count as changes.
+ *
+ * @return array<int, string>
+ */
+ function auditChangedFields(Model $model): array
+ {
+ return collect(array_keys($model->getDirty()))
+ ->reject(fn (string $field): bool => in_array($field, ['created_at', 'updated_at'], true)
+ || $model->getOriginal($field) == $model->getAttribute($field))
+ ->values()
+ ->all();
+ }
+}
+
if (! function_exists('auditFailureDeduplicationWindow')) {
/**
* Seconds during which repeated unauthenticated failures from one source are recorded once.
diff --git a/tests/Feature/AccountAuditTest.php b/tests/Feature/AccountAuditTest.php
new file mode 100644
index 0000000000..0115a99656
--- /dev/null
+++ b/tests/Feature/AccountAuditTest.php
@@ -0,0 +1,284 @@
+<?php
+
+use App\Http\Middleware\CheckForcePasswordReset;
+use App\Http\Middleware\DecideWhatToDoWithUser;
+use App\Livewire\Admin\Index as AdminIndex;
+use App\Livewire\ForcePasswordReset;
+use App\Livewire\Team\AdminView;
+use App\Models\AuditEvent;
+use App\Models\InstanceSettings;
+use App\Models\OauthIdentity;
+use App\Models\OauthSetting;
+use App\Models\Team;
+use App\Models\TeamInvitation;
+use App\Models\User;
+use App\Services\Auth\OauthLoginService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Auth;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\Hash;
+use Illuminate\Support\Once;
+use Laravel\Fortify\Actions\ConfirmTwoFactorAuthentication;
+use Laravel\Fortify\Actions\DisableTwoFactorAuthentication;
+use Laravel\Fortify\Actions\EnableTwoFactorAuthentication;
+use Laravel\Fortify\Actions\GenerateNewRecoveryCodes;
+use Livewire\Livewire;
+use PragmaRX\Google2FA\Google2FA;
+use Visus\Cuid2\Cuid2;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->withoutDefer();
+
+ InstanceSettings::forceCreate(['id' => 0]);
+ Once::flush();
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+});
+
+function accountAuditRow(string $event): AuditEvent
+{
+ return AuditEvent::query()->where('event', $event)->sole();
+}
+
+function accountAuditSerialized(AuditEvent $event): string
+{
+ return json_encode($event->toArray());
+}
+
+function accountAuditOauthUser(string|int $id, string $email, array $rawClaims = []): object
+{
+ return (object) [
+ 'id' => $id,
+ 'email' => $email,
+ 'name' => 'Provider User',
+ 'user' => $rawClaims,
+ ];
+}
+
+test('records two factor lifecycle events without storing the secret or recovery codes', function () {
+ app(EnableTwoFactorAuthentication::class)($this->user);
+ $secret = decrypt($this->user->fresh()->two_factor_secret);
+ $initialCodes = $this->user->fresh()->recoveryCodes();
+
+ app(ConfirmTwoFactorAuthentication::class)($this->user, app(Google2FA::class)->getCurrentOtp($secret));
+ app(GenerateNewRecoveryCodes::class)($this->user);
+ $regeneratedCodes = $this->user->fresh()->recoveryCodes();
+ app(DisableTwoFactorAuthentication::class)($this->user);
+
+ foreach ([
+ 'auth.user.two_factor_enabled',
+ 'auth.user.two_factor_confirmed',
+ 'auth.user.recovery_codes_regenerated',
+ 'auth.user.two_factor_disabled',
+ ] as $eventName) {
+ $event = accountAuditRow($eventName);
+ $serialized = accountAuditSerialized($event);
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->actor_id)->toBe($this->user->id)
+ ->and($serialized)->not->toContain($secret);
+
+ foreach ([...$initialCodes, ...$regeneratedCodes] as $code) {
+ expect($serialized)->not->toContain($code);
+ }
+ }
+});
+
+test('records a forced password change without the password', function () {
+ $this->user->forceFill(['force_password_reset' => true])->save();
+ $newPassword = 'forced-new-password-value';
+
+ Livewire::test(ForcePasswordReset::class)
+ ->set('password', $newPassword)
+ ->set('password_confirmation', $newPassword)
+ ->call('submit')
+ ->assertRedirect(route('dashboard'));
+
+ $event = accountAuditRow('ui.user.password_changed');
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->actor_id)->toBe($this->user->id)
+ ->and(data_get($event->metadata, 'reason'))->toBe('forced_reset')
+ ->and(accountAuditSerialized($event))->not->toContain($newPassword);
+});
+
+test('does not record a forced password change when validation fails', function () {
+ $this->user->forceFill(['force_password_reset' => true])->save();
+
+ Livewire::test(ForcePasswordReset::class)
+ ->set('password', 'forced-new-password-value')
+ ->set('password_confirmation', 'different-password-value')
+ ->call('submit');
+
+ expect(AuditEvent::query()->where('event', 'ui.user.password_changed')->exists())->toBeFalse();
+});
+
+test('records an accepted team invitation', function () {
+ $this->withoutMiddleware([DecideWhatToDoWithUser::class, CheckForcePasswordReset::class]);
+ $invitedTeam = Team::factory()->create();
+ TeamInvitation::create([
+ 'team_id' => $invitedTeam->id,
+ 'uuid' => 'account-audit-invitation',
+ 'email' => $this->user->email,
+ 'role' => 'admin',
+ 'link' => url('/invitations/account-audit-invitation'),
+ 'via' => 'link',
+ ]);
+
+ $this->post('/invitations/account-audit-invitation')
+ ->assertRedirect(route('team.index'));
+
+ $event = accountAuditRow('ui.team_invitation.accepted');
+
+ expect($event->team_id)->toBe($invitedTeam->id)
+ ->and($event->actor_id)->toBe($this->user->id)
+ ->and($event->resource_uuid)->toBe('account-audit-invitation')
+ ->and(data_get($event->metadata, 'role'))->toBe('admin')
+ ->and(data_get($event->metadata, 'member_email'))->toBe($this->user->email)
+ ->and(data_get($event->metadata, 'already_member'))->toBeFalse();
+});
+
+test('records an accepted magic link invitation without the temporary password', function () {
+ $this->withoutMiddleware([DecideWhatToDoWithUser::class, CheckForcePasswordReset::class]);
+ Auth::logout();
+
+ $invitedTeam = Team::factory()->create();
+ $temporaryPassword = 'temporary-password-123';
+ $invitee = User::factory()->create([
+ 'email' => '[email protected]',
+ 'password' => Hash::make($temporaryPassword),
+ 'force_password_reset' => true,
+ ]);
+ $uuid = (string) new Cuid2(32);
+ $token = Crypt::encryptString("{$invitee->email}@@@{$uuid}@@@{$temporaryPassword}");
+ TeamInvitation::create([
+ 'team_id' => $invitedTeam->id,
+ 'uuid' => $uuid,
+ 'email' => $invitee->email,
+ 'role' => 'member',
+ 'link' => route('auth.link', ['token' => $token]),
+ 'via' => 'link',
+ ]);
+
+ $this->post(route('auth.link.accept'), ['token' => $token])
+ ->assertRedirect(route('dashboard'));
+
+ $event = accountAuditRow('ui.team_invitation.accepted');
+ $serialized = accountAuditSerialized($event);
+
+ expect($event->team_id)->toBe($invitedTeam->id)
+ ->and($event->actor_id)->toBe($invitee->id)
+ ->and($event->actor_email)->toBe($invitee->email)
+ ->and(data_get($event->metadata, 'role'))->toBe('member')
+ ->and($serialized)->not->toContain($temporaryPassword)
+ ->and($serialized)->not->toContain($token);
+});
+
+test('records a user deleted by an instance admin', function () {
+ $rootTeam = Team::factory()->create(['id' => 0]);
+ $rootTeam->members()->attach($this->user->id, ['role' => 'admin']);
+ $deletedUser = User::factory()->create(['email' => '[email protected]']);
+
+ Livewire::test(AdminView::class)
+ ->call('delete', $deletedUser->id, 'password')
+ ->assertReturned(true);
+
+ $event = accountAuditRow('ui.user.deleted');
+
+ expect(User::find($deletedUser->id))->toBeNull()
+ ->and($event->team_id)->toBe($this->team->id)
+ ->and($event->actor_id)->toBe($this->user->id)
+ ->and(data_get($event->metadata, 'deleted_user_id'))->toBe($deletedUser->id)
+ ->and(data_get($event->metadata, 'deleted_user_email'))->toBe('[email protected]');
+});
+
+test('does not record a user deletion when the password is wrong', function () {
+ $rootTeam = Team::factory()->create(['id' => 0]);
+ $rootTeam->members()->attach($this->user->id, ['role' => 'admin']);
+ $targetUser = User::factory()->create();
+
+ Livewire::test(AdminView::class)
+ ->call('delete', $targetUser->id, 'wrong-password');
+
+ expect(User::find($targetUser->id))->not->toBeNull()
+ ->and(AuditEvent::query()->where('event', 'ui.user.deleted')->exists())->toBeFalse();
+});
+
+test('records impersonation with the impersonating root user as actor', function () {
+ config()->set('constants.coolify.self_hosted', false);
+
+ $rootUser = User::factory()->create(['id' => 0]);
+ $rootTeam = Team::find(0);
+ $targetUser = User::factory()->create(['email' => '[email protected]']);
+
+ $this->actingAs($rootUser);
+ session(['currentTeam' => $rootTeam]);
+
+ Livewire::test(AdminIndex::class)
+ ->call('switchUser', $targetUser->id)
+ ->assertRedirect(route('dashboard'));
+
+ $event = accountAuditRow('ui.user.impersonated');
+
+ expect($event->actor_id)->toBe(0)
+ ->and($event->team_id)->toBe(0)
+ ->and(data_get($event->metadata, 'target_user_id'))->toBe($targetUser->id)
+ ->and(data_get($event->metadata, 'target_user_email'))->toBe('[email protected]');
+});
+
+test('records an oauth identity linked to an existing user', function () {
+ Auth::logout();
+ $this->user->forceFill(['current_team_id' => $this->team->id])->save();
+ $setting = OauthSetting::create([
+ 'provider' => 'github',
+ 'client_id' => 'github-client-id',
+ 'client_secret' => 'github-client-secret',
+ 'enabled' => true,
+ ]);
+
+ app(OauthLoginService::class)->login('github', accountAuditOauthUser(4242, $this->user->email), $setting);
+
+ $event = accountAuditRow('auth.user.oauth_identity_linked');
+
+ expect(OauthIdentity::query()->where('user_id', $this->user->id)->exists())->toBeTrue()
+ ->and($event->team_id)->toBe($this->team->id)
+ ->and($event->actor_id)->toBe($this->user->id)
+ ->and($event->actor_email)->toBe($this->user->email)
+ ->and(data_get($event->metadata, 'provider'))->toBe('github')
+ ->and(accountAuditSerialized($event))->not->toContain('github-client-secret')
+ ->and(AuditEvent::query()->where('event', 'auth.user.registered')->exists())->toBeFalse();
+});
+
+test('records registration of a user created by oauth login', function (bool $autoJoinRootTeam) {
+ Auth::logout();
+ Team::factory()->create(['id' => 0]);
+ instanceSettings()->update(['is_registration_enabled' => true]);
+ Once::flush();
+ $setting = OauthSetting::create([
+ 'provider' => 'github',
+ 'client_id' => 'github-client-id',
+ 'client_secret' => 'github-client-secret',
+ 'enabled' => true,
+ 'auto_join_root_team' => $autoJoinRootTeam,
+ ]);
+
+ $user = app(OauthLoginService::class)->login('github', accountAuditOauthUser(5151, '[email protected]'), $setting);
+
+ $event = accountAuditRow('auth.user.registered');
+
+ expect($event->actor_id)->toBe($user->id)
+ ->and($event->actor_email)->toBe('[email protected]')
+ ->and($event->team_id)->toBe($user->teams()->first()->id)
+ ->and(data_get($event->metadata, 'provider'))->toBe('github')
+ ->and(data_get($event->metadata, 'via'))->toBe('oauth')
+ ->and(AuditEvent::query()->where('event', 'auth.user.oauth_identity_linked')->exists())->toBeFalse();
+})->with([
+ 'personal team' => [false],
+ 'root team only' => [true],
+]);
diff --git a/tests/Feature/ApplicationSettingsAuditTest.php b/tests/Feature/ApplicationSettingsAuditTest.php
new file mode 100644
index 0000000000..674518093f
--- /dev/null
+++ b/tests/Feature/ApplicationSettingsAuditTest.php
@@ -0,0 +1,212 @@
+<?php
+
+use App\Enums\ApplicationDeploymentStatus;
+use App\Livewire\Project\Application\DeploymentNavbar;
+use App\Livewire\Project\Application\Domains;
+use App\Livewire\Project\Application\General;
+use App\Livewire\Project\Application\PreviewDomains;
+use App\Livewire\Project\Application\Previews;
+use App\Livewire\Project\Application\Rollback;
+use App\Livewire\Project\Application\Swarm;
+use App\Livewire\Project\Shared\EnvironmentVariable\All;
+use App\Models\Application;
+use App\Models\ApplicationDeploymentQueue;
+use App\Models\ApplicationPreview;
+use App\Models\AuditEvent;
+use App\Models\Environment;
+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\Collection;
+use Illuminate\Support\Facades\Queue;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->withoutDefer();
+ $this->withoutVite();
+ Server::flushIdentityMap();
+ Queue::fake();
+ config(['app.maintenance.driver' => 'file']);
+
+ InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['id' => 0, 'is_dns_validation_enabled' => false],
+ ));
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ $this->server = Server::factory()->create(['team_id' => $this->team->id]);
+ $this->destination = StandaloneDocker::query()->where('server_id', $this->server->id)->firstOrFail();
+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
+
+ $this->application = Application::factory()->create([
+ 'name' => 'Audited App',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ 'fqdn' => null,
+ 'redirect' => 'both',
+ 'build_pack' => 'nixpacks',
+ 'static_image' => 'nginx:alpine',
+ 'base_directory' => '/',
+ 'is_http_basic_auth_enabled' => false,
+ 'git_repository' => 'coollabsio/coolify',
+ 'git_branch' => 'main',
+ 'ports_exposes' => '3000',
+ 'swarm_replicas' => 1,
+ ]);
+});
+
+function applicationSettingsAuditEvents(string $event): Collection
+{
+ return AuditEvent::query()->where('event', $event)->orderBy('id')->get();
+}
+
+function createAuditedApplicationPreview(Application $application, int $pullRequestId, array $attributes = []): ApplicationPreview
+{
+ return ApplicationPreview::create(array_merge([
+ 'application_id' => $application->id,
+ 'pull_request_id' => $pullRequestId,
+ 'pull_request_html_url' => "https://github.com/coollabsio/coolify/pull/{$pullRequestId}",
+ ], $attributes));
+}
+
+it('audits preview deployment settings and skips the audit when nothing changed', function () {
+ $component = Livewire::test(Previews::class, ['application' => $this->application])
+ ->set('isPreviewDeploymentsEnabled', true)
+ ->set('isPrDeploymentsPublicEnabled', true)
+ ->call('savePreviewSettings')
+ ->assertHasNoErrors();
+
+ $events = applicationSettingsAuditEvents('ui.application.settings_updated');
+ expect($events)->toHaveCount(1)
+ ->and($events->first()->team_id)->toBe($this->team->id)
+ ->and($events->first()->resource_uuid)->toBe($this->application->uuid)
+ ->and($events->first()->metadata['application_name'])->toBe('Audited App')
+ ->and($events->first()->metadata['changed_fields'])
+ ->toEqualCanonicalizing(['is_preview_deployments_enabled', 'is_pr_deployments_public_enabled']);
+
+ $component->call('savePreviewSettings')->assertHasNoErrors();
+
+ expect(applicationSettingsAuditEvents('ui.application.settings_updated'))->toHaveCount(1);
+});
+
+it('does not audit preview settings when the user cannot update the application', function () {
+ $this->team->members()->updateExistingPivot($this->user->id, ['role' => 'member']);
+
+ Livewire::test(Previews::class, ['application' => $this->application])
+ ->set('isPreviewDeploymentsEnabled', true)
+ ->call('savePreviewSettings')
+ ->assertForbidden();
+
+ expect(AuditEvent::query()->where('event', 'ui.application.settings_updated')->exists())->toBeFalse();
+});
+
+it('audits adding, retagging and deleting a preview', function () {
+ $component = Livewire::test(Previews::class, ['application' => $this->application])
+ ->set('parameters', [
+ 'project_uuid' => $this->project->uuid,
+ 'environment_uuid' => $this->environment->uuid,
+ 'application_uuid' => $this->application->uuid,
+ ])
+ ->call('add', 42, 'https://github.com/coollabsio/coolify/pull/42');
+
+ $created = applicationSettingsAuditEvents('ui.application.preview_created');
+ expect($created)->toHaveCount(1)
+ ->and($created->first()->metadata['pull_request_id'])->toBe(42)
+ ->and($created->first()->resource_uuid)->toBe($this->application->uuid);
+
+ $component->set('previewDockerTags.0', 'pr-42')
+ ->call('save_preview', ApplicationPreview::query()->where('pull_request_id', 42)->value('id'));
+
+ $updated = applicationSettingsAuditEvents('ui.application.preview_updated');
+ expect($updated)->toHaveCount(1)
+ ->and($updated->first()->metadata['pull_request_id'])->toBe(42)
+ ->and($updated->first()->metadata['changed_fields'])->toBe(['docker_registry_image_tag']);
+
+ $component->call('delete', 42);
+
+ $deleted = applicationSettingsAuditEvents('ui.application.preview_deleted');
+ expect($deleted)->toHaveCount(1)
+ ->and($deleted->first()->metadata['pull_request_id'])->toBe(42);
+});
+
+it('audits preview domain changes', function () {
+ $preview = createAuditedApplicationPreview($this->application, 7, [
+ 'fqdn' => 'https://one-pr-7.example.com,https://two-pr-7.example.com',
+ ]);
+
+ Livewire::test(PreviewDomains::class, ['preview' => $preview])
+ ->call('removeDomain', 1)
+ ->assertHasNoErrors();
+
+ $events = applicationSettingsAuditEvents('ui.application.preview_updated');
+ expect($preview->fresh()->fqdn)->toBe('https://one-pr-7.example.com')
+ ->and($events)->toHaveCount(1)
+ ->and($events->first()->metadata['pull_request_id'])->toBe(7)
+ ->and($events->first()->metadata['changed_fields'])->toBe(['fqdn']);
+});
+
+it('audits application setting changes from each settings control', function (Closure $change, string $field) {
+ $change->call($this);
+
+ $events = applicationSettingsAuditEvents('ui.application.settings_updated');
+ expect($events)->toHaveCount(1)
+ ->and($events->first()->resource_uuid)->toBe($this->application->uuid)
+ ->and($events->first()->metadata['changed_fields'])->toBe([$field]);
+})->with([
+ 'general settings' => [function () {
+ Livewire::test(General::class, ['application' => $this->application])
+ ->set('isPreserveRepositoryEnabled', true)
+ ->call('instantSave')
+ ->assertHasNoErrors();
+ }, 'is_preserve_repository_enabled'],
+ 'force https' => [function () {
+ $this->application->update(['fqdn' => 'https://app.example.com']);
+ Livewire::test(Domains::class, ['application' => $this->application->fresh()])
+ ->set('isForceHttpsEnabled', false)
+ ->call('updateForceHttps')
+ ->assertHasNoErrors();
+ }, 'is_force_https_enabled'],
+ 'swarm worker nodes' => [function () {
+ $current = (bool) $this->application->settings->is_swarm_only_worker_nodes;
+ Livewire::test(Swarm::class, ['application' => $this->application])
+ ->set('isSwarmOnlyWorkerNodes', ! $current)
+ ->call('instantSave')
+ ->assertHasNoErrors();
+ }, 'is_swarm_only_worker_nodes'],
+ 'deployment debug logs' => [function () {
+ $deployment = ApplicationDeploymentQueue::create([
+ 'application_id' => $this->application->id,
+ 'deployment_uuid' => 'audit-debug-toggle',
+ 'server_id' => $this->server->id,
+ 'destination_id' => $this->destination->id,
+ 'status' => ApplicationDeploymentStatus::FINISHED->value,
+ ]);
+ Livewire::test(DeploymentNavbar::class, ['application_deployment_queue' => $deployment])
+ ->call('show_debug');
+ }, 'is_debug_enabled'],
+ 'rollback image retention' => [function () {
+ Livewire::test(Rollback::class, ['application' => $this->application])
+ ->set('dockerImagesToKeep', 5)
+ ->call('saveSettings')
+ ->assertHasNoErrors();
+ }, 'docker_images_to_keep'],
+ 'build secrets' => [function () {
+ Livewire::test(All::class, ['resource' => $this->application])
+ ->set('use_build_secrets', true)
+ ->call('instantSave')
+ ->assertHasNoErrors();
+ }, 'use_build_secrets'],
+]);
diff --git a/tests/Feature/AuditChangedFieldsTest.php b/tests/Feature/AuditChangedFieldsTest.php
new file mode 100644
index 0000000000..6c55a7051c
--- /dev/null
+++ b/tests/Feature/AuditChangedFieldsTest.php
@@ -0,0 +1,58 @@
+<?php
+
+use Illuminate\Database\Eloquent\Model;
+use Illuminate\Support\Facades\Crypt;
+
+/**
+ * Builds an unsaved model whose stored state is the given raw attributes.
+ *
+ * @param array<string, mixed> $attributes
+ */
+function auditChangedFieldsModel(array $attributes): Model
+{
+ $model = new class extends Model
+ {
+ protected $casts = [
+ 'secret' => 'encrypted',
+ 'labels' => 'array',
+ ];
+ };
+ $model->setRawAttributes($attributes, true);
+
+ return $model;
+}
+
+it('ignores timestamps and loosely equal values', function () {
+ $model = auditChangedFieldsModel(['flag' => 0, 'name' => 'web', 'updated_at' => '2026-01-01 00:00:00']);
+
+ $model->flag = false;
+ $model->name = 'web';
+ $model->updated_at = '2026-02-01 00:00:00';
+
+ expect(auditChangedFields($model))->toBe([]);
+
+ $model->flag = true;
+ $model->name = 'api';
+
+ expect(auditChangedFields($model))->toBe(['flag', 'name']);
+});
+
+it('compares decrypted values of encrypted attributes', function () {
+ $model = auditChangedFieldsModel(['secret' => Crypt::encryptString('token')]);
+
+ $model->secret = 'token';
+ expect(auditChangedFields($model))->toBe([]);
+
+ $model->secret = 'other';
+ expect(auditChangedFields($model))->toBe(['secret']);
+});
+
+it('compares decoded values of array attributes', function () {
+ $model = auditChangedFieldsModel(['labels' => json_encode(['linux', 'x64'])]);
+
+ $model->labels = ['linux', 'x64'];
+ expect(auditChangedFields($model))->toBe([]);
+
+ $model->labels = ['linux', 'arm64'];
+ expect(auditChangedFields($model))->toBe(['labels']);
+});
diff --git a/tests/Feature/InstanceSettingsAuditTest.php b/tests/Feature/InstanceSettingsAuditTest.php
new file mode 100644
index 0000000000..09e4cc9358
--- /dev/null
+++ b/tests/Feature/InstanceSettingsAuditTest.php
@@ -0,0 +1,270 @@
+<?php
+
+use App\Actions\Stripe\RefundSubscription;
+use App\Livewire\Settings\Advanced;
+use App\Livewire\Settings\Index as SettingsIndex;
+use App\Livewire\Settings\Updates;
+use App\Livewire\SettingsEmail;
+use App\Livewire\Subscription\Actions as SubscriptionActions;
+use App\Livewire\Upgrade;
+use App\Models\AuditEvent;
+use App\Models\InstanceSettings;
+use App\Models\Subscription;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Facades\Cache;
+use Illuminate\Support\Once;
+use Livewire\Livewire;
+use Stripe\Service\SubscriptionService;
+use Stripe\StripeClient;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->withoutDefer();
+ config()->set('constants.coolify.self_hosted', false);
+
+ InstanceSettings::forceCreate(['id' => 0]);
+ Once::flush();
+
+ $this->rootTeam = Team::factory()->create(['id' => 0]);
+ $this->user = User::factory()->create();
+ $this->rootTeam->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->rootTeam]);
+});
+
+function instanceSettingsAuditEvents(string $event)
+{
+ return AuditEvent::query()->where('event', $event)->get();
+}
+
+function mockInstanceSettingsAuditStripe(): SubscriptionService
+{
+ $stripe = Mockery::mock(StripeClient::class);
+ $subscriptions = Mockery::mock(SubscriptionService::class);
+ $stripe->subscriptions = $subscriptions;
+ app()->instance(StripeClient::class, $stripe);
+
+ return $subscriptions;
+}
+
+function createInstanceSettingsAuditSubscription(Team $team, array $attributes = []): Subscription
+{
+ return Subscription::create([
+ 'team_id' => $team->id,
+ 'stripe_subscription_id' => 'sub_audit_123',
+ 'stripe_customer_id' => 'cus_audit_123',
+ 'stripe_invoice_paid' => true,
+ 'stripe_plan_id' => 'price_audit_123',
+ 'stripe_cancel_at_period_end' => false,
+ 'stripe_past_due' => false,
+ ...$attributes,
+ ]);
+}
+
+test('advanced settings save records changed field names without the domain connect private key', function () {
+ Livewire::test(Advanced::class)
+ ->set('is_api_enabled', true)
+ ->set('domain_connect_private_key', 'super-secret-private-key-value')
+ ->call('submit');
+
+ $events = instanceSettingsAuditEvents('ui.instance.settings.updated');
+
+ expect($events)->toHaveCount(1)
+ ->and($events->first()->team_id)->toBeNull()
+ ->and($events->first()->resource_type)->toBe('instance')
+ ->and($events->first()->metadata['section'])->toBe('advanced')
+ ->and($events->first()->metadata['changed_fields'])->toContain('is_api_enabled', 'domain_connect_private_key')
+ ->and(json_encode($events->first()->getAttributes()))->not->toContain('super-secret-private-key-value');
+});
+
+test('update settings toggle without changes records no event', function () {
+ Livewire::test(Updates::class)->call('instantSave');
+ $countAfterFirstSave = AuditEvent::query()->count();
+
+ Livewire::test(Updates::class)->call('instantSave');
+
+ expect(AuditEvent::query()->count())->toBe($countAfterFirstSave);
+});
+
+test('clearing the domain connect private key is audited only when a key existed', function () {
+ instanceSettings()->update(['domain_connect_private_key' => 'existing-private-key-value']);
+ Once::flush();
+
+ Livewire::test(Advanced::class)->call('clearDomainConnectPrivateKey');
+ Livewire::test(Advanced::class)->call('clearDomainConnectPrivateKey');
+
+ $events = instanceSettingsAuditEvents('ui.instance.settings.updated');
+
+ expect($events)->toHaveCount(1)
+ ->and($events->first()->metadata['changed_fields'])->toBe(['domain_connect_private_key'])
+ ->and(json_encode($events->first()->getAttributes()))->not->toContain('existing-private-key-value');
+});
+
+test('general instance settings save is audited', function () {
+ Livewire::test(SettingsIndex::class)
+ ->set('instance_name', 'Audited Instance')
+ ->call('submit');
+
+ $event = instanceSettingsAuditEvents('ui.instance.settings.updated')->sole();
+
+ expect($event->team_id)->toBeNull()
+ ->and($event->metadata['section'])->toBe('general')
+ ->and($event->metadata['changed_fields'])->toBe(['instance_name']);
+});
+
+test('update settings save is audited', function () {
+ Livewire::test(Updates::class)
+ ->set('update_check_frequency', '0 */2 * * *')
+ ->call('instantSave');
+
+ $event = instanceSettingsAuditEvents('ui.instance.settings.updated')->sole();
+
+ expect($event->team_id)->toBeNull()
+ ->and($event->metadata['section'])->toBe('updates')
+ ->and($event->metadata['changed_fields'])->toBe(['update_check_frequency']);
+});
+
+test('smtp settings save is audited without the smtp password', function () {
+ Livewire::test(SettingsEmail::class)
+ ->set('smtpEnabled', true)
+ ->set('smtpHost', 'smtp.example.com')
+ ->set('smtpPort', '587')
+ ->set('smtpEncryption', 'starttls')
+ ->set('smtpFromAddress', '[email protected]')
+ ->set('smtpFromName', 'Coolify')
+ ->set('smtpPassword', 'smtp-secret-password')
+ ->call('submitSmtp');
+
+ $event = instanceSettingsAuditEvents('ui.settings.email.updated')->sole();
+
+ expect($event->team_id)->toBeNull()
+ ->and($event->metadata['changed_fields'])->toContain('smtp_enabled', 'smtp_host', 'smtp_password')
+ ->and(json_encode($event->getAttributes()))->not->toContain('smtp-secret-password');
+});
+
+test('resend settings save is audited without the api key', function () {
+ Livewire::test(SettingsEmail::class)
+ ->set('resendEnabled', true)
+ ->set('resendApiKey', 're_secret_api_key')
+ ->set('smtpFromAddress', '[email protected]')
+ ->set('smtpFromName', 'Coolify')
+ ->call('submitResend');
+
+ $event = instanceSettingsAuditEvents('ui.settings.email.updated')->sole();
+
+ expect($event->metadata['changed_fields'])->toContain('resend_enabled', 'resend_api_key')
+ ->and(json_encode($event->getAttributes()))->not->toContain('re_secret_api_key');
+});
+
+test('manual instance upgrade is audited', function () {
+ Bus::fake();
+ config()->set('constants.coolify.version', '4.0.0');
+ Cache::put('coolify:versions:all', ['coolify' => ['v4' => ['version' => '4.0.1']]], 3600);
+
+ Livewire::test(Upgrade::class)->call('upgrade');
+
+ $event = instanceSettingsAuditEvents('ui.instance.upgrade_started')->sole();
+
+ expect($event->team_id)->toBeNull()
+ ->and($event->resource_type)->toBe('instance')
+ ->and($event->metadata['from_version'])->toBe('4.0.0')
+ ->and($event->metadata['to_version'])->toBe('4.0.1');
+});
+
+test('non-admin upgrade attempt is not audited as started', function () {
+ Bus::fake();
+ $team = Team::factory()->create();
+ $member = User::factory()->create();
+ $team->members()->attach($member->id, ['role' => 'owner']);
+ $this->actingAs($member);
+ session(['currentTeam' => $team]);
+
+ Livewire::test(Upgrade::class)->call('upgrade');
+
+ expect(instanceSettingsAuditEvents('ui.instance.upgrade_started'))->toBeEmpty();
+});
+
+describe('subscription changes', function () {
+ beforeEach(function () {
+ config()->set('subscription.provider', 'stripe');
+ config()->set('subscription.stripe_api_key', 'sk_test_fake');
+
+ $this->team = Team::factory()->create(['name' => 'Billing Team']);
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ session(['currentTeam' => $this->team]);
+ });
+
+ test('scheduling cancellation at period end is audited', function () {
+ $subscription = createInstanceSettingsAuditSubscription($this->team);
+ mockInstanceSettingsAuditStripe()->shouldReceive('update')
+ ->with('sub_audit_123', ['cancel_at_period_end' => true])
+ ->once();
+
+ Livewire::test(SubscriptionActions::class)->call('cancelAtPeriodEnd', 'password');
+
+ $event = instanceSettingsAuditEvents('ui.subscription.cancellation_scheduled')->sole();
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->resource_type)->toBe('subscription')
+ ->and($event->resource_name)->toBe('Billing Team')
+ ->and($event->metadata['subscription_id'])->toBe($subscription->id);
+ });
+
+ test('resuming a subscription is audited', function () {
+ createInstanceSettingsAuditSubscription($this->team, ['stripe_cancel_at_period_end' => true]);
+ mockInstanceSettingsAuditStripe()->shouldReceive('update')
+ ->with('sub_audit_123', ['cancel_at_period_end' => false])
+ ->once();
+
+ Livewire::test(SubscriptionActions::class)->call('resumeSubscription');
+
+ expect(instanceSettingsAuditEvents('ui.subscription.resumed')->sole()->team_id)->toBe($this->team->id);
+ });
+
+ test('immediate cancellation is audited', function () {
+ createInstanceSettingsAuditSubscription($this->team);
+ mockInstanceSettingsAuditStripe()->shouldReceive('cancel')->with('sub_audit_123')->once();
+
+ Livewire::test(SubscriptionActions::class)->call('cancelImmediately', 'password');
+
+ expect(instanceSettingsAuditEvents('ui.subscription.cancelled')->sole()->team_id)->toBe($this->team->id);
+ });
+
+ test('refund is audited and an invalid password records nothing', function () {
+ createInstanceSettingsAuditSubscription($this->team);
+ $refund = Mockery::mock(RefundSubscription::class);
+ $refund->shouldReceive('execute')->once()->andReturn(['success' => true, 'error' => null]);
+ app()->instance(RefundSubscription::class, $refund);
+
+ Livewire::test(SubscriptionActions::class)->call('refundSubscription', 'wrong-password');
+ expect(instanceSettingsAuditEvents('ui.subscription.refunded'))->toBeEmpty();
+
+ Livewire::test(SubscriptionActions::class)->call('refundSubscription', 'password');
+ expect(instanceSettingsAuditEvents('ui.subscription.refunded')->sole()->team_id)->toBe($this->team->id);
+ });
+
+ test('server limit change is audited', function () {
+ Bus::fake();
+ createInstanceSettingsAuditSubscription($this->team);
+ $this->team->update(['custom_server_limit' => 2]);
+ $subscriptions = mockInstanceSettingsAuditStripe();
+ $subscriptions->shouldReceive('retrieve')->with('sub_audit_123')->andReturn((object) [
+ 'items' => (object) ['data' => [(object) ['id' => 'si_audit', 'quantity' => 2]]],
+ ]);
+ $subscriptions->shouldReceive('update')->once()->andReturn((object) ['latest_invoice' => null]);
+
+ Livewire::test(SubscriptionActions::class)
+ ->set('quantity', 5)
+ ->call('updateQuantity');
+
+ $event = instanceSettingsAuditEvents('ui.subscription.quantity_updated')->sole();
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->metadata['from_server_limit'])->toBe(2)
+ ->and($event->metadata['to_server_limit'])->toBe(5);
+ });
+});
diff --git a/tests/Feature/ScheduleAuditTest.php b/tests/Feature/ScheduleAuditTest.php
new file mode 100644
index 0000000000..281fdd42b4
--- /dev/null
+++ b/tests/Feature/ScheduleAuditTest.php
@@ -0,0 +1,424 @@
+<?php
+
+use App\Livewire\Project\Application\Backup\Create as CreateApplicationVolumeBackup;
+use App\Livewire\Project\Database\BackupEdit;
+use App\Livewire\Project\Database\CreateScheduledBackup;
+use App\Livewire\Project\Database\ScheduledBackups;
+use App\Livewire\Project\Service\VolumeBackup\Create as CreateServiceVolumeBackup;
+use App\Livewire\Project\Shared\ScheduledTask\Add as AddScheduledTask;
+use App\Livewire\Project\Shared\ScheduledTask\Show as ShowScheduledTask;
+use App\Livewire\Project\Shared\Storages\VolumeBackups;
+use App\Livewire\SettingsBackup;
+use App\Livewire\Storage\Resources as StorageResources;
+use App\Models\Application;
+use App\Models\AuditEvent;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\LocalPersistentVolume;
+use App\Models\PrivateKey;
+use App\Models\Project;
+use App\Models\S3Storage;
+use App\Models\ScheduledDatabaseBackup;
+use App\Models\ScheduledTask;
+use App\Models\ScheduledVolumeBackup;
+use App\Models\Server;
+use App\Models\Service;
+use App\Models\ServiceApplication;
+use App\Models\StandaloneDocker;
+use App\Models\StandalonePostgresql;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Routing\Events\RouteMatched;
+use Illuminate\Support\Facades\Event;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Once;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->withoutDefer();
+ $this->withoutVite();
+ Server::flushIdentityMap();
+
+ InstanceSettings::forceCreate(['id' => 0]);
+ Once::flush();
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ $privateKey = PrivateKey::factory()->create(['team_id' => $this->team->id]);
+ $this->server = Server::factory()->create([
+ 'team_id' => $this->team->id,
+ 'private_key_id' => $privateKey->id,
+ 'ip' => '203.0.113.20',
+ ]);
+ $this->destination = StandaloneDocker::where('server_id', $this->server->id)->firstOrFail();
+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
+ $this->application = Application::factory()->create([
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ ]);
+});
+
+afterEach(function () {
+ Event::forget(RouteMatched::class);
+});
+
+function bindScheduleAuditTaskRoute(Application $application, ScheduledTask $task): void
+{
+ $application->loadMissing('environment.project');
+
+ Event::listen(RouteMatched::class, function (RouteMatched $event) use ($application, $task): void {
+ $event->route->setParameter('task_uuid', $task->uuid);
+ $event->route->setParameter('project_uuid', $application->environment->project->uuid);
+ $event->route->setParameter('environment_uuid', $application->environment->uuid);
+ $event->route->setParameter('application_uuid', $application->uuid);
+ });
+}
+
+function createScheduleAuditTask(Team $team, Application $application): ScheduledTask
+{
+ return ScheduledTask::factory()->create([
+ 'team_id' => $team->id,
+ 'application_id' => $application->id,
+ 'name' => 'nightly-job',
+ 'command' => 'echo nightly',
+ 'frequency' => '0 0 * * *',
+ 'container' => '',
+ 'timeout' => 300,
+ 'enabled' => true,
+ ]);
+}
+
+function createScheduleAuditPostgres(Environment $environment, StandaloneDocker $destination): StandalonePostgresql
+{
+ return StandalonePostgresql::create([
+ 'name' => 'schedule-audit-pg',
+ 'image' => 'postgres:16-alpine',
+ 'postgres_user' => 'postgres',
+ 'postgres_password' => 'password',
+ 'postgres_db' => 'postgres',
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => $destination->getMorphClass(),
+ ]);
+}
+
+function createScheduleAuditDatabaseBackup(Team $team, StandalonePostgresql $database, array $overrides = []): ScheduledDatabaseBackup
+{
+ return ScheduledDatabaseBackup::create(array_merge([
+ 'frequency' => '0 0 * * *',
+ 'save_s3' => false,
+ 's3_storage_id' => null,
+ 'database_type' => $database->getMorphClass(),
+ 'database_id' => $database->id,
+ 'team_id' => $team->id,
+ ], $overrides));
+}
+
+function createScheduleAuditS3(Team $team, string $name): S3Storage
+{
+ return S3Storage::create([
+ 'name' => $name,
+ 'region' => 'us-east-1',
+ 'key' => 'test-key',
+ 'secret' => 'test-secret',
+ 'bucket' => 'test-bucket',
+ 'endpoint' => 'https://s3.example.com',
+ 'is_usable' => true,
+ 'team_id' => $team->id,
+ ]);
+}
+
+function createScheduleAuditVolume(Application $application): LocalPersistentVolume
+{
+ return LocalPersistentVolume::create([
+ 'name' => 'schedule-audit-data',
+ 'mount_path' => '/data',
+ 'resource_id' => $application->id,
+ 'resource_type' => $application->getMorphClass(),
+ ]);
+}
+
+function scheduleAuditEvent(string $event): AuditEvent
+{
+ return AuditEvent::query()->where('event', $event)->sole();
+}
+
+test('creating a scheduled task records an audit event without the command', function () {
+ Livewire::test(AddScheduledTask::class, [
+ 'id' => (string) $this->application->id,
+ 'type' => 'application',
+ 'containerNames' => collect(),
+ ])
+ ->set('name', 'backup-job')
+ ->set('command', 'curl -H "Authorization: Bearer super-secret" https://example.com')
+ ->set('frequency', '0 0 * * *')
+ ->set('timeout', 300)
+ ->call('submit')
+ ->assertHasNoErrors();
+
+ $task = ScheduledTask::query()->sole();
+ $event = scheduleAuditEvent('ui.scheduled_task.created');
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->resource_uuid)->toBe($task->uuid)
+ ->and($event->metadata['resource_type'])->toBe('application')
+ ->and($event->metadata['resource_uuid'])->toBe($this->application->uuid)
+ ->and(json_encode($event->metadata))->not->toContain('super-secret');
+});
+
+test('updating a scheduled task records changed field names only', function () {
+ $task = createScheduleAuditTask($this->team, $this->application);
+ bindScheduleAuditTaskRoute($this->application, $task);
+
+ Livewire::test(ShowScheduledTask::class)
+ ->set('command', 'echo token=super-secret')
+ ->set('timeout', 600)
+ ->call('submit');
+
+ $event = scheduleAuditEvent('ui.scheduled_task.updated');
+
+ expect($event->resource_uuid)->toBe($task->uuid)
+ ->and($event->metadata['changed_fields'])->toEqualCanonicalizing(['command', 'timeout'])
+ ->and(json_encode($event->metadata))->not->toContain('super-secret');
+});
+
+test('saving a scheduled task without changes records no audit event', function () {
+ $task = createScheduleAuditTask($this->team, $this->application);
+ bindScheduleAuditTaskRoute($this->application, $task);
+
+ Livewire::test(ShowScheduledTask::class)
+ ->call('submit')
+ ->call('instantSave');
+
+ expect(AuditEvent::query()->where('event', 'ui.scheduled_task.updated')->exists())->toBeFalse();
+});
+
+test('toggling and deleting a scheduled task record audit events', function () {
+ $task = createScheduleAuditTask($this->team, $this->application);
+ bindScheduleAuditTaskRoute($this->application, $task);
+
+ Livewire::test(ShowScheduledTask::class)
+ ->call('toggleEnabled')
+ ->call('delete');
+
+ expect(scheduleAuditEvent('ui.scheduled_task.updated')->metadata['changed_fields'])->toBe(['enabled'])
+ ->and(scheduleAuditEvent('ui.scheduled_task.deleted')->resource_uuid)->toBe($task->uuid)
+ ->and($task->fresh())->toBeNull();
+});
+
+test('creating a database backup schedule records an audit event', function () {
+ $database = createScheduleAuditPostgres($this->environment, $this->destination);
+
+ Livewire::test(CreateScheduledBackup::class, ['database' => $database])
+ ->set('frequency', 'daily')
+ ->call('submit');
+
+ $backup = ScheduledDatabaseBackup::query()->sole();
+ $event = scheduleAuditEvent('ui.database.backup_schedule_created');
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->resource_uuid)->toBe($database->uuid)
+ ->and($event->metadata['backup_uuid'])->toBe($backup->uuid)
+ ->and($event->metadata['save_s3'])->toBeFalse();
+});
+
+test('updating a database backup schedule records changed fields and skips unchanged saves', function () {
+ $database = createScheduleAuditPostgres($this->environment, $this->destination);
+ $backup = createScheduleAuditDatabaseBackup($this->team, $database);
+
+ $component = Livewire::test(BackupEdit::class, [
+ 'backup' => $backup->fresh(),
+ 'availableS3Storages' => $this->team->s3s,
+ ]);
+
+ $component->call('submit');
+ expect(AuditEvent::query()->where('event', 'ui.database.backup_schedule_updated')->exists())->toBeFalse();
+
+ $component->set('frequency', '0 3 * * *')->call('submit');
+ $component->call('toggleEnabled');
+
+ $events = AuditEvent::query()->where('event', 'ui.database.backup_schedule_updated')->oldest('id')->get();
+
+ expect($events)->toHaveCount(2)
+ ->and($events[0]->resource_uuid)->toBe($database->uuid)
+ ->and($events[0]->metadata['backup_uuid'])->toBe($backup->uuid)
+ ->and($events[0]->metadata['changed_fields'])->toBe(['frequency'])
+ ->and($events[1]->metadata['changed_fields'])->toBe(['enabled']);
+});
+
+test('deleting a backup schedule from the backup list records an audit event', function () {
+ $database = createScheduleAuditPostgres($this->environment, $this->destination);
+ $backup = createScheduleAuditDatabaseBackup($this->team, $database);
+
+ Event::listen(RouteMatched::class, function (RouteMatched $event) use ($database): void {
+ $event->route->setParameter('project_uuid', $this->project->uuid);
+ $event->route->setParameter('environment_uuid', $this->environment->uuid);
+ $event->route->setParameter('database_uuid', $database->uuid);
+ });
+
+ Livewire::test(ScheduledBackups::class, ['database' => $database])
+ ->call('delete', $backup->id);
+
+ $event = scheduleAuditEvent('ui.database.backup_schedule_deleted');
+
+ expect($backup->fresh())->toBeNull()
+ ->and($event->resource_uuid)->toBe($database->uuid)
+ ->and($event->metadata['backup_uuid'])->toBe($backup->uuid);
+});
+
+test('disabling or moving S3 storage for backups records audit events', function () {
+ $source = createScheduleAuditS3($this->team, 'Source S3');
+ $destination = createScheduleAuditS3($this->team, 'Destination S3');
+ $database = createScheduleAuditPostgres($this->environment, $this->destination);
+ $databaseBackup = createScheduleAuditDatabaseBackup($this->team, $database, [
+ 'save_s3' => true,
+ 's3_storage_id' => $source->id,
+ ]);
+ $volume = createScheduleAuditVolume($this->application);
+ $volumeBackup = $volume->scheduledBackups()->create([
+ 'team_id' => $this->team->id,
+ 'frequency' => 'daily',
+ 'save_s3' => true,
+ 's3_storage_id' => $source->id,
+ ]);
+
+ Livewire::test(StorageResources::class, ['storage' => $source])
+ ->call('disableS3', $databaseBackup->id)
+ ->set("selectedVolumeStorages.{$volumeBackup->id}", $destination->id)
+ ->call('moveVolumeBackup', $volumeBackup->id);
+
+ $databaseEvent = scheduleAuditEvent('ui.database.backup_schedule_updated');
+ $volumeEvent = scheduleAuditEvent('ui.volume_backup.schedule_set');
+
+ expect($databaseEvent->resource_uuid)->toBe($database->uuid)
+ ->and($databaseEvent->metadata['changed_fields'])->toEqualCanonicalizing(['save_s3', 's3_storage_id'])
+ ->and($volumeEvent->metadata['resource_type'])->toBe('application')
+ ->and($volumeEvent->metadata['resource_uuid'])->toBe($this->application->uuid)
+ ->and($volumeEvent->metadata['storage_uuid'])->toBe($volume->uuid)
+ ->and($volumeEvent->metadata['backup_uuid'])->toBe($volumeBackup->uuid)
+ ->and($volumeEvent->metadata['changed_fields'])->toBe(['s3_storage_id']);
+});
+
+test('configuring the instance database backup records an audit event', function () {
+ $rootTeam = Team::find(0) ?? Team::factory()->create(['id' => 0]);
+ $privateKey = PrivateKey::factory()->create(['team_id' => $rootTeam->id]);
+ $server = Server::factory()->create([
+ 'id' => 0,
+ 'team_id' => $rootTeam->id,
+ 'private_key_id' => $privateKey->id,
+ 'ip' => '127.0.0.1',
+ ]);
+ StandaloneDocker::query()->where('server_id', $server->id)->firstOrFail()->forceFill(['id' => 0])->save();
+
+ $admin = User::factory()->create();
+ $rootTeam->members()->attach($admin->id, ['role' => 'admin']);
+ $this->actingAs($admin);
+ session(['currentTeam' => $rootTeam]);
+
+ Process::fake([
+ '*' => Process::result(output: json_encode([[
+ 'Config' => ['Env' => ['POSTGRES_PASSWORD=instance-secret', 'POSTGRES_USER=coolify', 'POSTGRES_DB=coolify']],
+ ]])),
+ ]);
+
+ Livewire::test(SettingsBackup::class)
+ ->call('addCoolifyDatabase')
+ ->assertHasNoErrors();
+
+ $database = StandalonePostgresql::query()->where('name', 'coolify-db')->sole();
+ $event = scheduleAuditEvent('ui.database.backup_schedule_created');
+
+ expect($event->team_id)->toBe(0)
+ ->and($event->resource_uuid)->toBe($database->uuid)
+ ->and(json_encode($event->metadata))->not->toContain('instance-secret');
+});
+
+test('creating an application storage backup schedule records an audit event', function () {
+ $volume = createScheduleAuditVolume($this->application);
+
+ Livewire::test(CreateApplicationVolumeBackup::class, [
+ 'application' => $this->application,
+ 'selectedTargetKey' => 'volume:'.$volume->id,
+ ])
+ ->set('frequency', 'daily')
+ ->call('submit');
+
+ $backup = ScheduledVolumeBackup::query()->sole();
+ $event = scheduleAuditEvent('ui.volume_backup.schedule_set');
+
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->metadata['resource_type'])->toBe('application')
+ ->and($event->metadata['resource_uuid'])->toBe($this->application->uuid)
+ ->and($event->metadata['storage_uuid'])->toBe($volume->uuid)
+ ->and($event->metadata['backup_uuid'])->toBe($backup->uuid)
+ ->and($event->metadata['created'])->toBeTrue();
+});
+
+test('creating a service storage backup schedule records an audit event', function () {
+ $service = Service::factory()->create([
+ 'server_id' => $this->server->id,
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ ]);
+ $serviceApplication = ServiceApplication::create([
+ 'uuid' => new_public_id(),
+ 'name' => 'directus',
+ 'service_id' => $service->id,
+ ]);
+ $volume = LocalPersistentVolume::create([
+ 'name' => $service->uuid.'_directus-uploads',
+ 'mount_path' => '/directus/uploads',
+ 'resource_id' => $serviceApplication->id,
+ 'resource_type' => $serviceApplication->getMorphClass(),
+ ]);
+
+ Livewire::test(CreateServiceVolumeBackup::class, ['service' => $service])
+ ->set('targetKey', 'volume:'.$volume->id)
+ ->set('frequency', 'daily')
+ ->call('submit');
+
+ $event = scheduleAuditEvent('ui.volume_backup.schedule_set');
+
+ expect($event->metadata['resource_type'])->toBe('service')
+ ->and($event->metadata['resource_uuid'])->toBe($service->uuid)
+ ->and($event->metadata['storage_uuid'])->toBe($volume->uuid);
+});
+
+test('updating, toggling, and deleting a storage backup schedule record audit events', function () {
+ $volume = createScheduleAuditVolume($this->application);
+ $backup = $volume->scheduledBackups()->create([
+ 'team_id' => $this->team->id,
+ 'frequency' => 'daily',
+ 'enabled' => true,
+ ]);
+
+ $component = Livewire::test(VolumeBackups::class, ['storage' => $volume, 'resource' => $this->application]);
+
+ $component->call('save');
+ expect(AuditEvent::query()->where('event', 'ui.volume_backup.schedule_set')->exists())->toBeFalse();
+
+ $component->set('frequency', 'hourly')->call('save');
+ $component->call('toggleEnabled');
+ $component->call('delete', 'password');
+
+ $setEvents = AuditEvent::query()->where('event', 'ui.volume_backup.schedule_set')->oldest('id')->get();
+ $deleteEvent = scheduleAuditEvent('ui.volume_backup.schedule_deleted');
+
+ expect($setEvents)->toHaveCount(2)
+ ->and($setEvents[0]->metadata['changed_fields'])->toBe(['frequency'])
+ ->and($setEvents[0]->metadata['created'])->toBeFalse()
+ ->and($setEvents[1]->metadata['changed_fields'])->toBe(['enabled'])
+ ->and($deleteEvent->metadata['backup_uuid'])->toBe($backup->uuid)
+ ->and($deleteEvent->metadata['storage_uuid'])->toBe($volume->uuid)
+ ->and($backup->fresh())->toBeNull();
+});
diff --git a/tests/Feature/Security/AuditLogTest.php b/tests/Feature/Security/AuditLogTest.php
index fae6cae832..ebf6f13d8d 100644
--- a/tests/Feature/Security/AuditLogTest.php
+++ b/tests/Feature/Security/AuditLogTest.php
@@ -5,6 +5,7 @@ use App\Livewire\Security\CloudInitScripts;
use App\Livewire\Security\CloudProviderTokenForm;
use App\Livewire\Security\CloudProviderTokens;
use App\Models\Application;
+use App\Models\AuditEvent;
use App\Models\CloudInitScript;
use App\Models\CloudProviderToken;
use App\Models\Environment;
@@ -398,26 +399,11 @@ describe('API mutation audit logging', function () {
$response->assertStatus(403);
});
- test('project creation emits api.project.created audit event', function () {
+ test('project creation records api.project.created audit event', function () {
[$team, $user] = makeAuditTeamUser();
$token = makeAuditApiToken($user, $team);
auth()->forgetGuards();
- $auditChannel = Mockery::mock();
- $auditChannel->shouldReceive('info')
- ->atLeast()
- ->once()
- ->with('api.project.created', Mockery::on(function ($context) {
- return $context['event'] === 'api.project.created'
- && ! empty($context['project_uuid'])
- && $context['project_name'] === 'audit-project';
- }));
-
- Log::shouldReceive('channel')->with('audit')->andReturn($auditChannel);
- Log::shouldReceive('warning')->andReturnNull();
- Log::shouldReceive('info')->andReturnNull();
- Log::shouldReceive('error')->andReturnNull();
-
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$token,
'Content-Type' => 'application/json',
@@ -427,6 +413,11 @@ describe('API mutation audit logging', function () {
]);
$response->assertStatus(201);
+
+ $event = AuditEvent::query()->where('event', 'api.project.created')->sole();
+ expect($event->team_id)->toBe($team->id)
+ ->and($event->resource_uuid)->toBe($response->json('uuid'))
+ ->and($event->resource_name)->toBe('audit-project');
});
});
diff --git a/tests/Feature/SentinelPushDeduplicationTest.php b/tests/Feature/SentinelPushDeduplicationTest.php
index b319d97aee..349c245030 100644
--- a/tests/Feature/SentinelPushDeduplicationTest.php
+++ b/tests/Feature/SentinelPushDeduplicationTest.php
@@ -3,6 +3,7 @@
use App\Events\SentinelSynchronized;
use App\Http\Controllers\Api\SentinelController;
use App\Jobs\PushServerUpdateJob;
+use App\Models\AuditEvent;
use App\Models\Server;
use App\Models\User;
use Illuminate\Contracts\Cache\LockTimeoutException;
@@ -90,6 +91,7 @@ it('does not audit successful sentinel pushes', function () use ($running) {
pushSentinel($this->token, sentinelPayload($running()))->assertOk();
Queue::assertPushed(PushServerUpdateJob::class, 1);
+ expect(AuditEvent::query()->count())->toBe(0);
});
it('updates the heartbeat even when the job is skipped', function () use ($running) {
diff --git a/tests/Feature/ServerSettingsAuditTest.php b/tests/Feature/ServerSettingsAuditTest.php
new file mode 100644
index 0000000000..c9976c6657
--- /dev/null
+++ b/tests/Feature/ServerSettingsAuditTest.php
@@ -0,0 +1,397 @@
+<?php
+
+use App\Actions\Proxy\SaveProxyConfiguration;
+use App\Actions\Server\StartSentinel;
+use App\Helpers\SslHelper;
+use App\Livewire\Destination\New\Docker as NewDockerDestination;
+use App\Livewire\Destination\Show as DestinationShow;
+use App\Livewire\Project\Database\Postgresql\StatusInfo as PostgresqlStatusInfo;
+use App\Livewire\Server\Advanced;
+use App\Livewire\Server\CaCertificate\Show as CaCertificateShow;
+use App\Livewire\Server\Charts;
+use App\Livewire\Server\CloudflareTunnel;
+use App\Livewire\Server\Destinations;
+use App\Livewire\Server\DockerCleanup;
+use App\Livewire\Server\GithubRunners;
+use App\Livewire\Server\New\ByVultr;
+use App\Livewire\Server\Proxy;
+use App\Livewire\Server\Security\TerminalAccess;
+use App\Livewire\Server\Sentinel;
+use App\Livewire\Server\Show as ServerShow;
+use App\Livewire\Server\Swarm;
+use App\Models\AuditEvent;
+use App\Models\CloudInitScript;
+use App\Models\CloudProviderToken;
+use App\Models\Environment;
+use App\Models\GithubApp;
+use App\Models\GithubRunnerConfig;
+use App\Models\InstanceSettings;
+use App\Models\PrivateKey;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\StandaloneDocker;
+use App\Models\StandalonePostgresql;
+use App\Models\SwarmDocker;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Once;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->withoutDefer();
+ Server::flushIdentityMap();
+ Queue::fake();
+ config(['constants.ssh.mux_enabled' => false]);
+
+ InstanceSettings::forceCreate(['id' => 0]);
+ Once::flush();
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ $this->server = Server::factory()->create(['team_id' => $this->team->id]);
+});
+
+afterEach(function () {
+ Server::flushIdentityMap();
+});
+
+/**
+ * @return Collection<int, AuditEvent>
+ */
+function serverSettingsAuditRows(string $event): Collection
+{
+ return AuditEvent::query()->where('event', $event)->get();
+}
+
+function serverSettingsAuditVultrPrivateKey(): string
+{
+ return <<<'KEY'
+-----BEGIN OPENSSH PRIVATE KEY-----
+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
+QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
+hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
+AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
+uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
+-----END OPENSSH PRIVATE KEY-----
+KEY;
+}
+
+function serverSettingsAuditGithubApp(Team $team): GithubApp
+{
+ $rsaKey = openssl_pkey_new(['private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA]);
+ openssl_pkey_export($rsaKey, $pemKey);
+ $privateKey = PrivateKey::create(['name' => 'Runner key', 'private_key' => $pemKey, 'team_id' => $team->id]);
+
+ // Missing runner permissions, so saving does not call the GitHub API.
+ return GithubApp::create([
+ 'name' => 'audit-runner-app',
+ 'organization' => 'acme',
+ 'api_url' => 'https://api.github.com',
+ 'html_url' => 'https://github.com',
+ 'custom_user' => 'git',
+ 'custom_port' => 22,
+ 'app_id' => 4444,
+ 'installation_id' => 4445,
+ 'webhook_secret' => 'secret',
+ 'private_key_id' => $privateKey->id,
+ 'team_id' => $team->id,
+ 'is_system_wide' => false,
+ 'organization_self_hosted_runners' => null,
+ 'actions' => null,
+ 'webhook_events' => ['push'],
+ ]);
+}
+
+test('toggling terminal access records enabled and disabled events', function () {
+ $this->server->settings->update(['is_terminal_enabled' => false]);
+
+ $component = Livewire::test(TerminalAccess::class, ['server_uuid' => $this->server->uuid]);
+ $component->call('toggleTerminal', 'password');
+ $component->call('toggleTerminal', 'password');
+
+ $enabled = serverSettingsAuditRows('ui.server.terminal_access.enabled');
+ expect($enabled)->toHaveCount(1)
+ ->and($enabled->first()->team_id)->toBe($this->team->id)
+ ->and($enabled->first()->metadata['server_uuid'])->toBe($this->server->uuid)
+ ->and(serverSettingsAuditRows('ui.server.terminal_access.disabled'))->toHaveCount(1);
+});
+
+test('server settings saves record changed setting names without the sentinel token', function () {
+ $newToken = 'audit-secret-sentinel-token-123';
+
+ Livewire::test(ServerShow::class, ['server_uuid' => $this->server->uuid])
+ ->set('wildcardDomain', 'https://apps.example.com')
+ ->set('sentinelToken', $newToken)
+ ->call('submit')
+ ->assertHasNoErrors();
+
+ $rows = serverSettingsAuditRows('ui.server.settings_updated');
+ expect($rows)->toHaveCount(1)
+ ->and($rows->first()->team_id)->toBe($this->team->id)
+ ->and($rows->first()->metadata['changed_fields'])->toEqualCanonicalizing(['wildcard_domain', 'sentinel_token'])
+ ->and(AuditEvent::query()->where('metadata', 'like', "%{$newToken}%")->exists())->toBeFalse();
+});
+
+test('saving server settings without changes records no event', function () {
+ Livewire::test(ServerShow::class, ['server_uuid' => $this->server->uuid])
+ ->call('submit')
+ ->assertHasNoErrors();
+
+ expect(serverSettingsAuditRows('ui.server.settings_updated'))->toBeEmpty();
+});
+
+test('cloudflare tunnel enable, disable and configuration record events without the tunnel token', function () {
+ $component = Livewire::test(CloudflareTunnel::class, ['server_uuid' => $this->server->uuid]);
+
+ $component->call('manualCloudflareConfig');
+ expect(serverSettingsAuditRows('ui.server.cloudflare_tunnel.enabled'))->toHaveCount(1);
+
+ $component->call('toggleCloudflareTunnels');
+ expect(serverSettingsAuditRows('ui.server.cloudflare_tunnel.disabled'))->toHaveCount(1)
+ ->and($this->server->settings->fresh()->is_cloudflare_tunnel)->toBeFalsy();
+
+ $component->set('cloudflare_token', 'cf-audit-secret-token')
+ ->set('ssh_domain', 'ssh.example.com')
+ ->call('automatedCloudflareConfig');
+
+ $configured = serverSettingsAuditRows('ui.server.cloudflare_tunnel.configuration_started');
+ expect($configured)->toHaveCount(1)
+ ->and($configured->first()->metadata['ssh_domain'])->toBe('ssh.example.com')
+ ->and(AuditEvent::query()->where('metadata', 'like', '%cf-audit-secret-token%')->exists())->toBeFalse();
+});
+
+test('docker cleanup settings record changed fields once and skip unchanged saves', function () {
+ $component = Livewire::test(DockerCleanup::class, ['server_uuid' => $this->server->uuid])
+ ->set('deleteUnusedVolumes', true)
+ ->call('instantSave');
+
+ $component->call('instantSave');
+
+ $rows = serverSettingsAuditRows('ui.server.docker_cleanup.updated');
+ expect($rows)->toHaveCount(1)
+ ->and($rows->first()->metadata['changed_fields'])->toBe(['delete_unused_volumes']);
+});
+
+test('sentinel instant save records the changed settings', function () {
+ Livewire::test(Sentinel::class, ['server' => $this->server])
+ ->set('isSentinelDebugEnabled', true)
+ ->call('instantSave');
+
+ $rows = serverSettingsAuditRows('ui.server.sentinel.updated');
+ expect($rows)->toHaveCount(1)
+ ->and($rows->first()->metadata['changed_fields'])->toBe(['is_sentinel_debug_enabled']);
+});
+
+test('metrics settings and the metrics toggle record sentinel updates', function () {
+ StartSentinel::shouldRun();
+
+ Livewire::test(Charts::class, ['server_uuid' => $this->server->uuid])
+ ->set('sentinelMetricsHistoryDays', 30)
+ ->call('saveMetricsSettings')
+ ->call('toggleMetrics');
+
+ $changedFields = serverSettingsAuditRows('ui.server.sentinel.updated')->pluck('metadata.changed_fields')->all();
+ expect($changedFields)->toBe([['sentinel_metrics_history_days'], ['is_metrics_enabled']]);
+});
+
+test('advanced and swarm settings record server settings updates', function () {
+ Livewire::test(Advanced::class, ['server_uuid' => $this->server->uuid])
+ ->set('concurrentBuilds', 4)
+ ->call('instantSave');
+
+ $swarmServer = Server::factory()->create(['team_id' => $this->team->id]);
+ $swarmServer->settings()->update(['is_swarm_manager' => true]);
+
+ Livewire::test(Swarm::class, ['server_uuid' => $this->server->uuid])
+ ->set('isSwarmWorker', true)
+ ->call('instantSave');
+
+ $changedFields = serverSettingsAuditRows('ui.server.settings_updated')->pluck('metadata.changed_fields')->all();
+ expect($changedFields)->toBe([['concurrent_builds'], ['is_swarm_worker']]);
+});
+
+test('proxy settings and configuration saves record proxy events', function () {
+ SaveProxyConfiguration::shouldRun();
+
+ Livewire::test(Proxy::class, ['server' => $this->server])
+ ->set('generateExactLabels', true)
+ ->call('instantSave')
+ ->set('proxySettings', "services:\n traefik:\n image: traefik:v3.6\n")
+ ->call('submit');
+
+ $updated = serverSettingsAuditRows('ui.server.proxy.updated');
+ expect($updated)->toHaveCount(1)
+ ->and($updated->first()->metadata['changed_fields'])->toBe(['generate_exact_labels'])
+ ->and(serverSettingsAuditRows('ui.server.proxy.configuration_saved'))->toHaveCount(1);
+});
+
+test('github runner settings record created, updated and disabled events', function () {
+ $this->server->settings()->update(['server_role' => 'build', 'is_build_server' => true]);
+ Server::flushIdentityMap();
+ $githubApp = serverSettingsAuditGithubApp($this->team);
+
+ $component = Livewire::test(GithubRunners::class, ['server_uuid' => $this->server->uuid])
+ ->set('githubAppId', $githubApp->id)
+ ->call('submit')
+ ->assertHasNoErrors();
+
+ $component->set('maxRunners', 5)->call('submit');
+ $component->call('submit');
+
+ GithubRunnerConfig::query()->update(['is_enabled' => true]);
+ $component->call('toggleEnabled');
+
+ $created = serverSettingsAuditRows('ui.server.github_runners.created');
+ $updated = serverSettingsAuditRows('ui.server.github_runners.updated');
+ expect($created)->toHaveCount(1)
+ ->and($created->first()->metadata['github_app_uuid'])->toBe($githubApp->uuid)
+ ->and($updated)->toHaveCount(1)
+ ->and($updated->first()->metadata['changed_fields'])->toBe(['max_runners'])
+ ->and(serverSettingsAuditRows('ui.server.github_runners.disabled'))->toHaveCount(1);
+});
+
+test('CA certificate save and regeneration record events without certificate contents', function () {
+ Livewire::test(CaCertificateShow::class, ['server_uuid' => $this->server->uuid])
+ ->call('regenerateCaCertificate')
+ ->assertDispatched('success');
+
+ $caCertificate = $this->server->sslCertificates()->where('is_ca_certificate', true)->firstOrFail();
+
+ Livewire::test(CaCertificateShow::class, ['server_uuid' => $this->server->uuid])
+ ->set('certificateContent', $caCertificate->ssl_certificate)
+ ->call('saveCaCertificate')
+ ->assertDispatched('success');
+
+ expect(serverSettingsAuditRows('ui.server.ca_certificate.regenerated'))->toHaveCount(1)
+ ->and(serverSettingsAuditRows('ui.server.ca_certificate.updated'))->toHaveCount(1)
+ ->and(AuditEvent::query()->where('metadata', 'like', '%PRIVATE KEY%')->exists())->toBeFalse()
+ ->and(AuditEvent::query()->where('metadata', 'like', '%BEGIN CERTIFICATE%')->exists())->toBeFalse();
+});
+
+test('regenerating a database SSL certificate records an event', function () {
+ $this->server->generateCaCertificate();
+ $caCertificate = $this->server->sslCertificates()->where('is_ca_certificate', true)->firstOrFail();
+ $destination = StandaloneDocker::where('server_id', $this->server->id)->firstOrFail();
+ $project = Project::factory()->create(['team_id' => $this->team->id]);
+ $environment = Environment::factory()->create(['project_id' => $project->id]);
+
+ $database = StandalonePostgresql::create([
+ 'name' => 'audit-ssl-db',
+ 'status' => 'exited:unhealthy',
+ 'enable_ssl' => true,
+ 'environment_id' => $environment->id,
+ 'destination_id' => $destination->id,
+ 'destination_type' => $destination->getMorphClass(),
+ 'postgres_user' => 'postgres',
+ 'postgres_password' => 'password',
+ 'postgres_db' => 'postgres',
+ 'image' => 'postgres:16-alpine',
+ ]);
+
+ SslHelper::generateSslCertificate(
+ commonName: $database->uuid,
+ resourceType: $database->getMorphClass(),
+ resourceId: $database->id,
+ serverId: $this->server->id,
+ caCert: $caCertificate->ssl_certificate,
+ caKey: $caCertificate->ssl_private_key,
+ configurationDir: '/data/coolify/databases/'.$database->uuid,
+ mountPath: '/var/lib/postgresql/certs',
+ );
+
+ Livewire::test(PostgresqlStatusInfo::class, ['database' => $database])
+ ->call('regenerateSslCertificate')
+ ->assertDispatched('success');
+
+ $rows = serverSettingsAuditRows('ui.database.ssl_certificate_regenerated');
+ expect($rows)->toHaveCount(1)
+ ->and($rows->first()->team_id)->toBe($this->team->id)
+ ->and($rows->first()->metadata['database_uuid'])->toBe($database->uuid)
+ ->and(AuditEvent::query()->where('metadata', 'like', '%PRIVATE KEY%')->exists())->toBeFalse();
+});
+
+test('destination create, rename and delete record destination events', function () {
+ Livewire::test(NewDockerDestination::class, ['server_id' => (string) $this->server->id])
+ ->set('network', 'audit-network')
+ ->call('submit');
+
+ Livewire::test(Destinations::class, ['server_uuid' => $this->server->uuid])
+ ->call('add', 'scanned-network');
+
+ $created = serverSettingsAuditRows('ui.destination.created');
+ expect($created)->toHaveCount(2)
+ ->and($created->pluck('metadata.destination_type')->unique()->all())->toBe(['standalone'])
+ ->and($created->first()->team_id)->toBe($this->team->id);
+
+ $swarmDestination = SwarmDocker::create([
+ 'name' => 'audit-swarm',
+ 'network' => 'audit-swarm-network',
+ 'server_id' => $this->server->id,
+ ]);
+
+ $component = Livewire::test(DestinationShow::class, ['destination_uuid' => $swarmDestination->uuid])
+ ->call('submit');
+ expect(serverSettingsAuditRows('ui.destination.updated'))->toBeEmpty();
+
+ $component->set('name', 'audit-swarm-renamed')->call('submit');
+ $component->call('delete');
+
+ $updated = serverSettingsAuditRows('ui.destination.updated');
+ $deleted = serverSettingsAuditRows('ui.destination.deleted');
+ expect($updated)->toHaveCount(1)
+ ->and($updated->first()->metadata['changed_fields'])->toBe(['name'])
+ ->and($deleted)->toHaveCount(1)
+ ->and($deleted->first()->metadata['destination_uuid'])->toBe($swarmDestination->uuid)
+ ->and($deleted->first()->metadata['destination_type'])->toBe('swarm');
+});
+
+test('saving a cloud-init script from the server wizard records an event without the script', function () {
+ $token = CloudProviderToken::create([
+ 'team_id' => $this->team->id,
+ 'provider' => 'vultr',
+ 'token' => 'test-vultr-token',
+ 'name' => 'Test Vultr Token',
+ ]);
+ $privateKey = PrivateKey::create([
+ 'team_id' => $this->team->id,
+ 'name' => 'Test Private Key',
+ 'private_key' => serverSettingsAuditVultrPrivateKey(),
+ ]);
+
+ Http::fake([
+ 'https://api.vultr.com/v2/regions*' => Http::response(['regions' => [['id' => 'ewr', 'city' => 'New Jersey', 'country' => 'US']], 'meta' => ['links' => ['next' => null]]], 200),
+ 'https://api.vultr.com/v2/plans*' => Http::response(['plans' => [['id' => 'vc2-1c-1gb', 'vcpu_count' => 1, 'ram' => 1024, 'disk' => 25, 'monthly_cost' => 6, 'locations' => ['ewr']]], 'meta' => ['links' => ['next' => null]]], 200),
+ 'https://api.vultr.com/v2/os*' => Http::response(['os' => [['id' => 2284, 'name' => 'Ubuntu 24.04 LTS x64']], 'meta' => ['links' => ['next' => null]]], 200),
+ 'https://api.vultr.com/v2/ssh-keys*' => Http::response(['ssh_keys' => [], 'meta' => ['links' => ['next' => null]]], 200),
+ '*' => Http::response(['error' => 'unavailable'], 500),
+ ]);
+
+ $script = "#cloud-config\npackages:\n - audit-secret-package";
+
+ Livewire::test(ByVultr::class, ['selectedTokenUuid' => $token->uuid])
+ ->set('server_name', 'audit-vultr-server')
+ ->set('selected_region', 'ewr')
+ ->set('selected_plan', 'vc2-1c-1gb')
+ ->set('selected_os_id', 2284)
+ ->set('private_key_id', $privateKey->id)
+ ->set('cloud_init_script', $script)
+ ->set('save_cloud_init_script', true)
+ ->set('cloud_init_script_name', 'Audit script')
+ ->call('submit');
+
+ $savedScript = CloudInitScript::query()->where('name', 'Audit script')->firstOrFail();
+ $rows = serverSettingsAuditRows('ui.cloud_init_script.created');
+ expect($rows)->toHaveCount(1)
+ ->and($rows->first()->metadata['cloud_init_script_id'])->toBe($savedScript->id)
+ ->and(AuditEvent::query()->where('metadata', 'like', '%audit-secret-package%')->exists())->toBeFalse();
+});
diff --git a/tests/Feature/StorageAndServiceAuditTest.php b/tests/Feature/StorageAndServiceAuditTest.php
new file mode 100644
index 0000000000..0ec3dcee9a
--- /dev/null
+++ b/tests/Feature/StorageAndServiceAuditTest.php
@@ -0,0 +1,481 @@
+<?php
+
+use App\Actions\Database\StopDatabaseProxy;
+use App\Livewire\Project\Database\Sqlite\ConnectApplication;
+use App\Livewire\Project\Service\Domains;
+use App\Livewire\Project\Service\FileStorage;
+use App\Livewire\Project\Service\Index;
+use App\Livewire\Project\Service\Storage;
+use App\Livewire\Project\Shared\Storages\All;
+use App\Models\Application;
+use App\Models\AuditEvent;
+use App\Models\DnsProviderZone;
+use App\Models\Environment;
+use App\Models\InstanceSettings;
+use App\Models\IntegrationToken;
+use App\Models\LocalFileVolume;
+use App\Models\LocalPersistentVolume;
+use App\Models\ManagedDnsRecord;
+use App\Models\Project;
+use App\Models\Server;
+use App\Models\Service;
+use App\Models\ServiceApplication;
+use App\Models\ServiceDatabase;
+use App\Models\StandaloneDocker;
+use App\Models\StandalonePostgresql;
+use App\Models\StandaloneSqlite;
+use App\Models\Team;
+use App\Models\User;
+use App\Services\Dns\CloudflareDnsProvider;
+use App\Services\Dns\ManagedDnsRecordCleanup;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Facades\Crypt;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Process;
+use Illuminate\Support\Facades\Queue;
+use Illuminate\Support\Str;
+use Livewire\Livewire;
+
+uses(RefreshDatabase::class);
+
+beforeEach(function () {
+ $this->withoutVite();
+ $this->withoutDefer();
+ config()->set('app.maintenance.store', 'array');
+ Bus::fake();
+ // Remote `test -f` / `test -d` probes report a missing path; path confinement checks pass.
+ Process::fake(fn ($process) => Process::result(
+ output: str_contains(implode(' ', (array) $process->command), '&& echo OK || echo NOK') ? 'NOK' : 'OK'
+ ));
+ Server::flushIdentityMap();
+
+ InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(
+ ['id' => 0],
+ ['id' => 0, 'is_dns_validation_enabled' => false, 'is_api_enabled' => true],
+ ));
+
+ $this->team = Team::factory()->create();
+ $this->user = User::factory()->create();
+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);
+ $this->actingAs($this->user);
+ session(['currentTeam' => $this->team]);
+
+ $keyId = DB::table('private_keys')->insertGetId([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'Test Key',
+ 'private_key' => Crypt::encryptString('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,
+ 'ip' => '203.0.113.10',
+ ]);
+ $this->destination = StandaloneDocker::withoutEvents(fn () => StandaloneDocker::firstOrCreate(
+ ['server_id' => $this->server->id, 'network' => 'coolify'],
+ ['uuid' => (string) Str::uuid(), 'name' => 'test-docker'],
+ ));
+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);
+ $this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
+
+ $this->application = Application::factory()->create([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'Audit App',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ 'build_pack' => 'dockerimage',
+ 'docker_registry_image_name' => 'nginx',
+ ]);
+
+ $this->service = Service::factory()->create([
+ 'environment_id' => $this->environment->id,
+ 'server_id' => $this->server->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ 'docker_compose_raw' => "services:\n web:\n image: nginx:alpine\n postgres:\n image: postgres:17\n",
+ ]);
+ $this->serviceApplication = ServiceApplication::create([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'web',
+ 'service_id' => $this->service->id,
+ 'image' => 'nginx:alpine',
+ 'fqdn' => 'https://web.example.com',
+ ]);
+ $this->serviceDatabase = ServiceDatabase::create([
+ 'uuid' => (string) Str::uuid(),
+ 'name' => 'postgres',
+ 'service_id' => $this->service->id,
+ 'image' => 'postgres:17',
+ ]);
+});
+
+function storageServiceAuditEvent(string $event): ?AuditEvent
+{
+ return AuditEvent::query()->where('event', $event)->latest('id')->first();
+}
+
+function storageServiceAuditFileVolume(Application $application, array $attributes = []): LocalFileVolume
+{
+ return LocalFileVolume::create([
+ 'fs_path' => application_configuration_dir().'/'.$application->uuid.'/app.conf',
+ 'mount_path' => '/etc/app.conf',
+ 'content' => 'original-file-body',
+ 'is_directory' => false,
+ 'is_based_on_git' => false,
+ 'is_preview_suffix_enabled' => true,
+ 'resource_id' => $application->id,
+ 'resource_type' => $application->getMorphClass(),
+ ...$attributes,
+ ]);
+}
+
+test('creating storages records storage_created for the parent resource type without file content', function () {
+ Livewire::test(Storage::class, ['resource' => $this->application])
+ ->set('name', 'data')
+ ->set('mount_path', '/app/data')
+ ->call('submitPersistentVolume')
+ ->assertDispatched('success');
+
+ Livewire::test(Storage::class, ['resource' => $this->application])
+ ->set('file_storage_path', '/etc/nginx/nginx.conf')
+ ->set('file_storage_content', 'super-secret-file-body')
+ ->call('submitFileStorage')
+ ->assertDispatched('success');
+
+ Livewire::test(Storage::class, ['resource' => $this->serviceApplication])
+ ->set('host_file_storage_source', '/etc/hosts')
+ ->set('host_file_storage_destination', '/etc/hosts')
+ ->call('submitHostFileStorage')
+ ->assertDispatched('success');
+
+ $events = AuditEvent::query()->where('event', 'ui.application.storage_created')->orderBy('id')->get();
+ expect($events)->toHaveCount(2)
+ ->and($events[0]->team_id)->toBe($this->team->id)
+ ->and($events[0]->resource_uuid)->toBe($this->application->uuid)
+ ->and($events[0]->metadata)->toMatchArray([
+ 'application_uuid' => $this->application->uuid,
+ 'storage_type' => 'persistent',
+ 'storage_name' => $this->application->uuid.'-data',
+ 'mount_path' => '/app/data',
+ ])
+ ->and($events[1]->metadata)->toMatchArray(['storage_type' => 'file', 'mount_path' => '/etc/nginx/nginx.conf']);
+
+ $serviceEvent = storageServiceAuditEvent('ui.service.storage_created');
+ expect($serviceEvent->resource_uuid)->toBe($this->service->uuid)
+ ->and($serviceEvent->metadata)->toMatchArray([
+ 'service_application_uuid' => $this->serviceApplication->uuid,
+ 'storage_type' => 'host_file',
+ 'host_path' => '/etc/hosts',
+ ]);
+
+ expect(AuditEvent::query()->get()->toJson())->not->toContain('super-secret-file-body');
+});
+
+test('creating a database volume records database storage_created', function () {
+ $database = StandalonePostgresql::create([
+ 'name' => 'audit-postgres',
+ 'image' => 'postgres:15-alpine',
+ 'postgres_user' => 'postgres',
+ 'postgres_password' => 'password',
+ 'postgres_db' => 'postgres',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ ]);
+
+ Livewire::test(Storage::class, ['resource' => $database])
+ ->set('name', 'extra')
+ ->set('mount_path', '/extra')
+ ->call('submitPersistentVolume')
+ ->assertDispatched('success');
+
+ expect(storageServiceAuditEvent('ui.database.storage_created')->metadata)->toMatchArray([
+ 'database_uuid' => $database->uuid,
+ 'storage_type' => 'persistent',
+ 'mount_path' => '/extra',
+ ]);
+});
+
+test('updating file content records changed field names without the content', function () {
+ $file = storageServiceAuditFileVolume($this->application);
+
+ Livewire::test(FileStorage::class, ['fileStorage' => $file])
+ ->set('content', 'new-secret-file-body')
+ ->call('submit')
+ ->assertDispatched('success');
+
+ $event = storageServiceAuditEvent('ui.application.storage_updated');
+ expect($event->metadata)->toMatchArray([
+ 'storage_uuid' => $file->uuid,
+ 'storage_type' => 'file',
+ 'changed_fields' => ['content'],
+ ]);
+ expect(AuditEvent::query()->get()->toJson())
+ ->not->toContain('new-secret-file-body')
+ ->not->toContain('original-file-body');
+});
+
+test('saving a file storage without changes records no audit event', function () {
+ $file = storageServiceAuditFileVolume($this->application);
+
+ Livewire::test(FileStorage::class, ['fileStorage' => $file])
+ ->call('instantSave')
+ ->assertDispatched('success');
+
+ expect(AuditEvent::query()->where('event', 'like', '%.storage_updated')->exists())->toBeFalse();
+});
+
+test('converting and deleting a file storage records storage events', function () {
+ $file = storageServiceAuditFileVolume($this->application);
+
+ $component = Livewire::test(FileStorage::class, ['fileStorage' => $file])
+ ->call('convertToDirectory');
+
+ expect(storageServiceAuditEvent('ui.application.storage_updated')->metadata)->toMatchArray([
+ 'operation' => 'converted_to_directory',
+ 'storage_type' => 'directory',
+ ])->and(storageServiceAuditEvent('ui.application.storage_updated')->metadata['changed_fields'])->toContain('is_directory');
+
+ $component->call('convertToFile');
+ expect(storageServiceAuditEvent('ui.application.storage_updated')->metadata)->toMatchArray([
+ 'operation' => 'converted_to_file',
+ 'storage_type' => 'file',
+ ]);
+
+ Livewire::test(FileStorage::class, ['fileStorage' => $file->fresh()])
+ ->call('delete', 'password')
+ ->assertDispatched('success');
+
+ expect($file->fresh())->toBeNull()
+ ->and(storageServiceAuditEvent('ui.application.storage_deleted')->metadata)->toMatchArray([
+ 'storage_uuid' => $file->uuid,
+ 'mount_path' => '/etc/app.conf',
+ 'deleted_from_server' => true,
+ ]);
+});
+
+test('updating and deleting a persistent volume records storage events and skips unchanged saves', function () {
+ $volume = LocalPersistentVolume::create([
+ 'name' => $this->application->uuid.'-data',
+ 'mount_path' => '/app/data',
+ 'resource_id' => $this->application->id,
+ 'resource_type' => $this->application->getMorphClass(),
+ ]);
+
+ $component = Livewire::test(All::class, ['resource' => $this->application])
+ ->call('submit', $volume->id);
+
+ expect(AuditEvent::query()->where('event', 'ui.application.storage_updated')->exists())->toBeFalse();
+
+ $component->set("forms.{$volume->id}.mountPath", '/app/other')
+ ->call('submit', $volume->id)
+ ->assertDispatched('success');
+
+ expect(storageServiceAuditEvent('ui.application.storage_updated')->metadata)->toMatchArray([
+ 'storage_id' => $volume->id,
+ 'mount_path' => '/app/other',
+ 'changed_fields' => ['mount_path'],
+ ]);
+
+ $component->call('delete', $volume->id, 'password');
+
+ expect($volume->fresh())->toBeNull()
+ ->and(storageServiceAuditEvent('ui.application.storage_deleted')->metadata)->toMatchArray([
+ 'storage_id' => $volume->id,
+ 'storage_type' => 'persistent',
+ 'docker_volume_deleted' => false,
+ ]);
+});
+
+test('connecting and unlinking a sqlite volume records application storage events', function () {
+ $this->server->settings()->update(['is_reachable' => true, 'is_usable' => true]);
+ $sqlite = StandaloneSqlite::create([
+ 'name' => 'app-sqlite',
+ 'environment_id' => $this->environment->id,
+ 'destination_id' => $this->destination->id,
+ 'destination_type' => $this->destination->getMorphClass(),
+ ]);
+
+ Livewire::test(ConnectApplication::class, ['database' => $sqlite])
+ ->set('applicationUuid', $this->application->uuid)
+ ->set('mountPath', '/app/database')
+ ->call('connect')
+ ->assertHasNoErrors();
+
+ $volume = $this->application->persistentStorages()->sole();
+ expect(storageServiceAuditEvent('ui.application.storage_created')->metadata)->toMatchArray([
+ 'application_uuid' => $this->application->uuid,
+ 'standalone_sqlite_uuid' => $sqlite->uuid,
+ 'storage_id' => $volume->id,
+ 'mount_path' => '/app/database',
+ ]);
+
+ Livewire::test(ConnectApplication::class, ['database' => $sqlite])
+ ->call('unlink', $volume->id);
+
+ expect(storageServiceAuditEvent('ui.application.storage_deleted')->metadata)->toMatchArray([
+ 'standalone_sqlite_uuid' => $sqlite->uuid,
+ 'storage_id' => $volume->id,
+ ]);
+});
+
+test('updating a service database records changed fields and skips unchanged saves', function () {
+ $component = Livewire::test(Index::class, ['serviceApplication' => $this->serviceDatabase->fresh(), 'embedded' => true])
+ ->call('submitDatabase');
+
+ expect(AuditEvent::query()->where('event', 'ui.service_database.updated')->exists())->toBeFalse();
+
+ $component->set('humanName', 'Primary DB')
+ ->call('submitDatabase')
+ ->assertDispatched('success', 'Database saved.');
+
+ $event = storageServiceAuditEvent('ui.service_database.updated');
+ expect($event->resource_uuid)->toBe($this->serviceDatabase->uuid)
+ ->and($event->team_id)->toBe($this->team->id)
+ ->and($event->metadata)->toMatchArray([
+ 'service_uuid' => $this->service->uuid,
+ 'changed_fields' => ['human_name'],
+ ]);
+});
+
+test('disabling public access of a service database records is_public and public_port', function () {
+ StopDatabaseProxy::shouldRun()->once();
+ $this->serviceDatabase->update(['is_public' => true, 'public_port' => 15432]);
+
+ Livewire::test(Index::class, ['serviceApplication' => $this->serviceDatabase->fresh(), 'embedded' => true])
+ ->call('disablePublicAccess')
+ ->assertDispatched('success');
+
+ expect(storageServiceAuditEvent('ui.service_database.updated')->metadata)->toMatchArray([
+ 'service_database_uuid' => $this->serviceDatabase->uuid,
+ 'changed_fields' => ['is_public'],
+ 'is_public' => false,
+ 'public_port' => 15432,
+ ]);
+});
+
+test('updating, converting and deleting service applications records service application events', function () {
+ $component = Livewire::test(Index::class, ['serviceApplication' => $this->serviceApplication->fresh(), 'embedded' => true])
+ ->set('isGzipEnabled', false)
+ ->call('instantSaveApplicationSettings')
+ ->assertDispatched('success');
+
+ expect(storageServiceAuditEvent('ui.service_application.updated')->metadata)->toMatchArray([
+ 'service_application_uuid' => $this->serviceApplication->uuid,
+ ])->and(storageServiceAuditEvent('ui.service_application.updated')->metadata['changed_fields'])->toContain('is_gzip_enabled');
+
+ $component->set('maxRestartCount', 7)->call('saveMaxRestartCount');
+ expect(storageServiceAuditEvent('ui.service_application.updated')->metadata['changed_fields'])->toContain('max_restart_count');
+
+ $component->call('convertToDatabase');
+ $convertedDatabase = $this->service->databases()->where('name', 'web')->sole();
+ expect(storageServiceAuditEvent('ui.service_application.converted_to_database')->metadata)->toMatchArray([
+ 'service_application_uuid' => $this->serviceApplication->uuid,
+ 'service_database_uuid' => $convertedDatabase->uuid,
+ ]);
+
+ Livewire::test(Index::class, ['serviceApplication' => $convertedDatabase, 'embedded' => true])
+ ->call('convertToApplication');
+ $convertedApplication = $this->service->applications()->where('name', 'web')->sole();
+ expect(storageServiceAuditEvent('ui.service_database.converted_to_application')->metadata)->toMatchArray([
+ 'service_database_uuid' => $convertedDatabase->uuid,
+ 'service_application_uuid' => $convertedApplication->uuid,
+ ]);
+
+ Livewire::test(Index::class, ['serviceApplication' => $convertedApplication, 'embedded' => true])
+ ->call('deleteApplication', 'password');
+ Livewire::test(Index::class, ['serviceApplication' => $this->serviceDatabase->fresh(), 'embedded' => true])
+ ->call('deleteDatabase', 'password');
+
+ expect(storageServiceAuditEvent('ui.service_application.deleted')->resource_uuid)->toBe($convertedApplication->uuid)
+ ->and(storageServiceAuditEvent('ui.service_database.deleted')->resource_uuid)->toBe($this->serviceDatabase->uuid);
+});
+
+test('saving service application domains records service application updates', function () {
+ Queue::fake();
+
+ $component = Livewire::test(Domains::class, ['service' => $this->service->fresh(['applications', 'server'])])
+ ->call('updateForceHttps', $this->serviceApplication->id, false)
+ ->assertHasNoErrors();
+
+ expect(storageServiceAuditEvent('ui.service_application.updated')->metadata)->toMatchArray([
+ 'service_uuid' => $this->service->uuid,
+ 'service_application_uuid' => $this->serviceApplication->uuid,
+ 'changed_fields' => ['is_force_https_enabled'],
+ ]);
+
+ $component->set('newServiceApplicationId', $this->serviceApplication->id)
+ ->set('newDomain', 'https://second.example.com')
+ ->call('addDomain')
+ ->assertHasNoErrors();
+
+ expect($this->serviceApplication->fresh()->fqdn)->toContain('https://second.example.com')
+ ->and(storageServiceAuditEvent('ui.service_application.updated')->metadata['changed_fields'])->toContain('fqdn');
+});
+
+test('the service application API update records changed fields', function () {
+ auth()->forgetGuards();
+ $plainTextToken = Str::random(40);
+ $token = $this->user->tokens()->create([
+ 'name' => 'audit-token',
+ 'token' => hash('sha256', $plainTextToken),
+ 'abilities' => ['*'],
+ 'team_id' => $this->team->id,
+ ]);
+
+ $this->withToken($token->getKey().'|'.$plainTextToken)
+ ->patchJson("/api/v1/services/{$this->service->uuid}/applications/{$this->serviceApplication->uuid}", [
+ 'human_name' => 'Web UI',
+ ])
+ ->assertOk();
+
+ $event = storageServiceAuditEvent('api.service_application.updated');
+ expect($event->team_id)->toBe($this->team->id)
+ ->and($event->metadata)->toMatchArray([
+ 'service_uuid' => $this->service->uuid,
+ 'service_application_uuid' => $this->serviceApplication->uuid,
+ 'changed_fields' => ['human_name'],
+ ]);
+});
+
+test('forgetting a managed dns record without touching the provider is audited', function () {
+ $integrationToken = IntegrationToken::factory()->for($this->team)->create(['provider' => 'cloudflare', 'token' => 'secret']);
+ $zone = DnsProviderZone::factory()->for($integrationToken)->create(['provider_zone_id' => 'zone-1', 'name' => 'example.com']);
+ $notOwned = ManagedDnsRecord::factory()->for($zone, 'zone')->create(['name' => 'hand.example.com']);
+ $kept = ManagedDnsRecord::factory()->owned()->for($zone, 'zone')->create(['name' => 'kept.example.com']);
+ Http::fake();
+
+ $cleanup = app(ManagedDnsRecordCleanup::class);
+ $cleanup->release($notOwned, [], true);
+ $cleanup->release($kept, [], false);
+
+ $events = AuditEvent::query()->where('event', 'ui.dns_record.delete_skipped')->orderBy('id')->get();
+ expect($notOwned->fresh())->toBeNull()
+ ->and($kept->fresh())->toBeNull()
+ ->and($events->map(fn (AuditEvent $event) => [$event->metadata['hostname'], $event->metadata['reason']])->all())->toBe([
+ ['hand.example.com', 'not_owned'],
+ ['kept.example.com', 'kept_by_user'],
+ ]);
+ Http::assertNothingSent();
+});
+
+test('forgetting an owned dns record that is already gone at the provider is audited', function () {
+ $integrationToken = IntegrationToken::factory()->for($this->team)->create(['provider' => 'cloudflare', 'token' => 'secret']);
+ $zone = DnsProviderZone::factory()->for($integrationToken)->create(['provider_zone_id' => 'zone-1', 'name' => 'example.com']);
+ $record = ManagedDnsRecord::factory()->owned()->for($zone, 'zone')->create(['name' => 'gone.example.com']);
+ Http::fake(['api.cloudflare.com/*' => Http::response(['success' => false], 404)]);
+
+ app(CloudflareDnsProvider::class)->deleteRecord($record);
+
+ expect($record->fresh())->toBeNull()
+ ->and(storageServiceAuditEvent('ui.dns_record.already_deleted')->metadata)->toMatchArray([
+ 'hostname' => 'gone.example.com',
+ 'provider' => 'cloudflare',
+ 'zone' => 'example.com',
+ ]);
+});