repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Modal.php | app/View/Components/Modal.php | <?php
namespace App\View\Components;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Modal extends Component
{
/**
* Create a new component instance.
*/
public function __construct(
public string $modalId,
public ?string $submitWireAction = null,
public ?string $modalTitle = null,
public ?string $modalBody = null,
public ?string $modalSubmit = null,
public bool $noSubmit = false,
public bool $yesOrNo = false,
public string $action = 'delete'
) {
//
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.modal');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Services/Advanced.php | app/View/Components/Services/Advanced.php | <?php
namespace App\View\Components\Services;
use App\Models\Service;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Advanced extends Component
{
/**
* Create a new component instance.
*/
public function __construct(
public ?Service $service = null
) {}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.services.advanced');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Services/Links.php | app/View/Components/Services/Links.php | <?php
namespace App\View\Components\Services;
use App\Models\Service;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Collection;
use Illuminate\View\Component;
class Links extends Component
{
public Collection $links;
public function __construct(public Service $service)
{
$this->links = collect([]);
$service->applications()->get()->map(function ($application) {
$type = $application->serviceType();
if ($type) {
$links = generateServiceSpecificFqdns($application);
$links = $links->map(function ($link) {
return getFqdnWithoutPort($link);
});
$this->links = $this->links->merge($links);
} else {
if ($application->fqdn) {
$fqdns = collect(str($application->fqdn)->explode(','));
$fqdns->map(function ($fqdn) {
$this->links->push(getFqdnWithoutPort($fqdn));
});
}
if ($application->ports) {
$portsCollection = collect(str($application->ports)->explode(','));
$portsCollection->map(function ($port) {
if (str($port)->contains(':')) {
$hostPort = str($port)->before(':');
} else {
$hostPort = $port;
}
$this->links->push(base_url(withPort: false).":{$hostPort}");
});
}
}
});
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.services.links');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Services/Explanation.php | app/View/Components/Services/Explanation.php | <?php
namespace App\View\Components\Services;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Explanation extends Component
{
/**
* Create a new component instance.
*/
public function __construct()
{
//
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.services.explanation');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/Input.php | app/View/Components/Forms/Input.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class Input extends Component
{
public ?string $modelBinding = null;
public ?string $htmlId = null;
public function __construct(
public ?string $id = null,
public ?string $name = null,
public ?string $type = 'text',
public ?string $value = null,
public ?string $label = null,
public bool $required = false,
public bool $disabled = false,
public bool $readonly = false,
public ?string $helper = null,
public bool $allowToPeak = true,
public bool $isMultiline = false,
public string $defaultClass = 'input',
public string $autocomplete = 'off',
public ?int $minlength = null,
public ?int $maxlength = null,
public bool $autofocus = false,
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
}
}
}
public function render(): View|Closure|string
{
// Store original ID for wire:model binding (property name)
$this->modelBinding = $this->id;
if (is_null($this->id)) {
$this->id = new Cuid2;
// Don't create wire:model binding for auto-generated IDs
$this->modelBinding = 'null';
}
// Generate unique HTML ID by adding random suffix
// This prevents duplicate IDs when multiple forms are on the same page
if ($this->modelBinding && $this->modelBinding !== 'null') {
// Use original ID with random suffix for uniqueness
$uniqueSuffix = new Cuid2;
$this->htmlId = $this->modelBinding.'-'.$uniqueSuffix;
} else {
$this->htmlId = (string) $this->id;
}
if (is_null($this->name)) {
$this->name = $this->modelBinding !== 'null' ? $this->modelBinding : (string) $this->id;
}
if ($this->type === 'password') {
$this->defaultClass = $this->defaultClass.' pr-[2.8rem]';
}
// $this->label = Str::title($this->label);
return view('components.forms.input');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/Checkbox.php | app/View/Components/Forms/Checkbox.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class Checkbox extends Component
{
public ?string $modelBinding = null;
public ?string $htmlId = null;
/**
* Create a new component instance.
*/
public function __construct(
public ?string $id = null,
public ?string $name = null,
public ?string $value = null,
public ?string $domValue = null,
public ?string $label = null,
public ?string $helper = null,
public string|bool|null $checked = false,
public string|bool $instantSave = false,
public bool $disabled = false,
public string $defaultClass = 'dark:border-neutral-700 text-coolgray-400 dark:bg-coolgray-100 rounded-sm cursor-pointer dark:disabled:bg-base dark:disabled:cursor-not-allowed focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-coollabs dark:focus-visible:ring-warning focus-visible:ring-offset-2 dark:focus-visible:ring-offset-base',
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
$this->instantSave = false; // Disable instant save for unauthorized users
}
}
if ($this->disabled) {
$this->defaultClass .= ' opacity-40';
}
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
// Store original ID for wire:model binding (property name)
$this->modelBinding = $this->id;
// Generate unique HTML ID by adding random suffix
// This prevents duplicate IDs when multiple forms are on the same page
if ($this->id) {
$uniqueSuffix = new Cuid2;
$this->htmlId = $this->id.'-'.$uniqueSuffix;
} else {
$this->htmlId = $this->id;
}
return view('components.forms.checkbox');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/Textarea.php | app/View/Components/Forms/Textarea.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class Textarea extends Component
{
public ?string $modelBinding = null;
public ?string $htmlId = null;
/**
* Create a new component instance.
*/
public function __construct(
public ?string $id = null,
public ?string $name = null,
public ?string $type = 'text',
public ?string $value = null,
public ?string $label = null,
public ?string $placeholder = null,
public ?string $monacoEditorLanguage = '',
public bool $useMonacoEditor = false,
public bool $required = false,
public bool $disabled = false,
public bool $readonly = false,
public bool $allowTab = false,
public bool $spellcheck = false,
public bool $autofocus = false,
public ?string $helper = null,
public bool $realtimeValidation = false,
public bool $allowToPeak = true,
public string $defaultClass = 'input scrollbar font-mono',
public string $defaultClassInput = 'input',
public ?int $minlength = null,
public ?int $maxlength = null,
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
}
}
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
// Store original ID for wire:model binding (property name)
$this->modelBinding = $this->id;
if (is_null($this->id)) {
$this->id = new Cuid2;
// Don't create wire:model binding for auto-generated IDs
$this->modelBinding = 'null';
}
// Generate unique HTML ID by adding random suffix
// This prevents duplicate IDs when multiple forms are on the same page
if ($this->modelBinding && $this->modelBinding !== 'null') {
// Use original ID with random suffix for uniqueness
$uniqueSuffix = new Cuid2;
$this->htmlId = $this->modelBinding.'-'.$uniqueSuffix;
} else {
$this->htmlId = (string) $this->id;
}
if (is_null($this->name)) {
$this->name = $this->modelBinding !== 'null' ? $this->modelBinding : (string) $this->id;
}
// $this->label = Str::title($this->label);
return view('components.forms.textarea');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/Datalist.php | app/View/Components/Forms/Datalist.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class Datalist extends Component
{
public ?string $modelBinding = null;
public ?string $htmlId = null;
/**
* Create a new component instance.
*/
public function __construct(
public ?string $id = null,
public ?string $name = null,
public ?string $label = null,
public ?string $helper = null,
public bool $required = false,
public bool $disabled = false,
public bool $readonly = false,
public bool $multiple = false,
public string|bool $instantSave = false,
public ?string $value = null,
public ?string $placeholder = null,
public bool $autofocus = false,
public string $defaultClass = 'input',
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
$this->instantSave = false; // Disable instant save for unauthorized users
}
}
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
// Store original ID for wire:model binding (property name)
$this->modelBinding = $this->id;
if (is_null($this->id)) {
$this->id = new Cuid2;
// Don't create wire:model binding for auto-generated IDs
$this->modelBinding = 'null';
}
// Generate unique HTML ID by adding random suffix
// This prevents duplicate IDs when multiple forms are on the same page
if ($this->modelBinding && $this->modelBinding !== 'null') {
// Use original ID with random suffix for uniqueness
$uniqueSuffix = new Cuid2;
$this->htmlId = $this->modelBinding.'-'.$uniqueSuffix;
} else {
$this->htmlId = (string) $this->id;
}
if (is_null($this->name)) {
$this->name = $this->modelBinding !== 'null' ? $this->modelBinding : (string) $this->id;
}
return view('components.forms.datalist');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/Button.php | app/View/Components/Forms/Button.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
class Button extends Component
{
/**
* Create a new component instance.
*/
public function __construct(
public bool $disabled = false,
public bool $noStyle = false,
public ?string $modalId = null,
public string $defaultClass = 'button',
public bool $showLoadingIndicator = true,
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
}
}
if ($this->noStyle) {
$this->defaultClass = '';
}
}
public function render(): View|Closure|string
{
return view('components.forms.button');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/EnvVarInput.php | app/View/Components/Forms/EnvVarInput.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class EnvVarInput extends Component
{
public ?string $modelBinding = null;
public ?string $htmlId = null;
public array $scopeUrls = [];
public function __construct(
public ?string $id = null,
public ?string $name = null,
public ?string $type = 'text',
public ?string $value = null,
public ?string $label = null,
public bool $required = false,
public bool $disabled = false,
public bool $readonly = false,
public ?string $helper = null,
public bool $allowToPeak = true,
public string $defaultClass = 'input',
public string $autocomplete = 'off',
public ?int $minlength = null,
public ?int $maxlength = null,
public bool $autofocus = false,
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
public array $availableVars = [],
public ?string $projectUuid = null,
public ?string $environmentUuid = null,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
}
}
}
public function render(): View|Closure|string
{
// Store original ID for wire:model binding (property name)
$this->modelBinding = $this->id;
if (is_null($this->id)) {
$this->id = new Cuid2;
// Don't create wire:model binding for auto-generated IDs
$this->modelBinding = 'null';
}
// Generate unique HTML ID by adding random suffix
// This prevents duplicate IDs when multiple forms are on the same page
if ($this->modelBinding && $this->modelBinding !== 'null') {
// Use original ID with random suffix for uniqueness
$uniqueSuffix = new Cuid2;
$this->htmlId = $this->modelBinding.'-'.$uniqueSuffix;
} else {
$this->htmlId = (string) $this->id;
}
if (is_null($this->name)) {
$this->name = $this->modelBinding !== 'null' ? $this->modelBinding : (string) $this->id;
}
if ($this->type === 'password') {
$this->defaultClass = $this->defaultClass.' pr-[2.8rem]';
}
$this->scopeUrls = [
'team' => route('shared-variables.team.index'),
'project' => route('shared-variables.project.index'),
'environment' => $this->projectUuid && $this->environmentUuid
? route('shared-variables.environment.show', [
'project_uuid' => $this->projectUuid,
'environment_uuid' => $this->environmentUuid,
])
: route('shared-variables.environment.index'),
'default' => route('shared-variables.index'),
];
return view('components.forms.env-var-input');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Forms/Select.php | app/View/Components/Forms/Select.php | <?php
namespace App\View\Components\Forms;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Gate;
use Illuminate\View\Component;
use Visus\Cuid2\Cuid2;
class Select extends Component
{
public ?string $modelBinding = null;
public ?string $htmlId = null;
/**
* Create a new component instance.
*/
public function __construct(
public ?string $id = null,
public ?string $name = null,
public ?string $label = null,
public ?string $helper = null,
public bool $required = false,
public bool $disabled = false,
public string $defaultClass = 'select w-full',
public ?string $canGate = null,
public mixed $canResource = null,
public bool $autoDisable = true,
) {
// Handle authorization-based disabling
if ($this->canGate && $this->canResource && $this->autoDisable) {
$hasPermission = Gate::allows($this->canGate, $this->canResource);
if (! $hasPermission) {
$this->disabled = true;
}
}
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
// Store original ID for wire:model binding (property name)
$this->modelBinding = $this->id;
if (is_null($this->id)) {
$this->id = new Cuid2;
// Don't create wire:model binding for auto-generated IDs
$this->modelBinding = 'null';
}
// Generate unique HTML ID by adding random suffix
// This prevents duplicate IDs when multiple forms are on the same page
if ($this->modelBinding && $this->modelBinding !== 'null') {
// Use original ID with random suffix for uniqueness
$uniqueSuffix = new Cuid2;
$this->htmlId = $this->modelBinding.'-'.$uniqueSuffix;
} else {
$this->htmlId = (string) $this->id;
}
if (is_null($this->name)) {
$this->name = $this->modelBinding !== 'null' ? $this->modelBinding : (string) $this->id;
}
return view('components.forms.select');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Status/Services.php | app/View/Components/Status/Services.php | <?php
namespace App\View\Components\Status;
use App\Models\Service;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Services extends Component
{
/**
* Create a new component instance.
*/
public function __construct(
public Service $service,
public string $complexStatus = 'exited',
public bool $showRefreshButton = true
) {
$this->complexStatus = $service->status;
}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.status.services');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/View/Components/Status/Index.php | app/View/Components/Status/Index.php | <?php
namespace App\View\Components\Status;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Index extends Component
{
/**
* Create a new component instance.
*/
public function __construct(
public $resource = null,
public bool $showRefreshButton = true,
) {}
/**
* Get the view / contents that represent the component.
*/
public function render(): View|Closure|string
{
return view('components.status.index');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/app.php | bootstrap/app.php | <?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/getRealtimeVersion.php | bootstrap/getRealtimeVersion.php | <?php
// To prevent github actions from failing
function env()
{
return null;
}
$version = include 'config/constants.php';
echo $version['coolify']['realtime_version'] ?: 'unknown';
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/includeHelpers.php | bootstrap/includeHelpers.php | <?php
$files = glob(__DIR__.'/helpers/*.php');
foreach ($files as $file) {
require $file;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/getHelperVersion.php | bootstrap/getHelperVersion.php | <?php
// To prevent github actions from failing
function env()
{
return null;
}
$version = include 'config/constants.php';
echo $version['coolify']['helper_version'] ?: 'unknown';
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/getVersion.php | bootstrap/getVersion.php | <?php
// To prevent github actions from failing
function env()
{
return null;
}
$version = include 'config/constants.php';
echo $version['coolify']['version'] ?: 'unknown';
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/remoteProcess.php | bootstrap/helpers/remoteProcess.php | <?php
use App\Actions\CoolifyTask\PrepareCoolifyTask;
use App\Data\CoolifyTaskArgs;
use App\Enums\ActivityTypes;
use App\Helpers\SshMultiplexingHelper;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\PrivateKey;
use App\Models\Server;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Str;
use Spatie\Activitylog\Contracts\Activity;
function remote_process(
Collection|array $command,
Server $server,
?string $type = null,
?string $type_uuid = null,
?Model $model = null,
bool $ignore_errors = false,
$callEventOnFinish = null,
$callEventData = null
): Activity {
$type = $type ?? ActivityTypes::INLINE->value;
$command = $command instanceof Collection ? $command->toArray() : $command;
if ($server->isNonRoot()) {
$command = parseCommandsByLineForSudo(collect($command), $server);
}
$command_string = implode("\n", $command);
if (Auth::check()) {
$teams = Auth::user()->teams->pluck('id');
if (! $teams->contains($server->team_id) && ! $teams->contains(0)) {
throw new \Exception('User is not part of the team that owns this server');
}
}
SshMultiplexingHelper::ensureMultiplexedConnection($server);
return resolve(PrepareCoolifyTask::class, [
'remoteProcessArgs' => new CoolifyTaskArgs(
server_uuid: $server->uuid,
command: $command_string,
type: $type,
type_uuid: $type_uuid,
model: $model,
ignore_errors: $ignore_errors,
call_event_on_finish: $callEventOnFinish,
call_event_data: $callEventData,
),
])();
}
function instant_scp(string $source, string $dest, Server $server, $throwError = true)
{
return \App\Helpers\SshRetryHandler::retry(
function () use ($source, $dest, $server) {
$scp_command = SshMultiplexingHelper::generateScpCommand($server, $source, $dest);
$process = Process::timeout(config('constants.ssh.command_timeout'))->run($scp_command);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
excludeCertainErrors($process->errorOutput(), $exitCode);
}
return $output === 'null' ? null : $output;
},
[
'server' => $server->ip,
'source' => $source,
'dest' => $dest,
'function' => 'instant_scp',
],
$throwError
);
}
function instant_remote_process_with_timeout(Collection|array $command, Server $server, bool $throwError = true, bool $no_sudo = false): ?string
{
$command = $command instanceof Collection ? $command->toArray() : $command;
if ($server->isNonRoot() && ! $no_sudo) {
$command = parseCommandsByLineForSudo(collect($command), $server);
}
$command_string = implode("\n", $command);
return \App\Helpers\SshRetryHandler::retry(
function () use ($server, $command_string) {
$sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string);
$process = Process::timeout(30)->run($sshCommand);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
excludeCertainErrors($process->errorOutput(), $exitCode);
}
// Sanitize output to ensure valid UTF-8 encoding
$output = $output === 'null' ? null : sanitize_utf8_text($output);
return $output;
},
[
'server' => $server->ip,
'command_preview' => substr($command_string, 0, 100),
'function' => 'instant_remote_process_with_timeout',
],
$throwError
);
}
function instant_remote_process(Collection|array $command, Server $server, bool $throwError = true, bool $no_sudo = false, ?int $timeout = null, bool $disableMultiplexing = false): ?string
{
$command = $command instanceof Collection ? $command->toArray() : $command;
if ($server->isNonRoot() && ! $no_sudo) {
$command = parseCommandsByLineForSudo(collect($command), $server);
}
$command_string = implode("\n", $command);
$effectiveTimeout = $timeout ?? config('constants.ssh.command_timeout');
return \App\Helpers\SshRetryHandler::retry(
function () use ($server, $command_string, $effectiveTimeout, $disableMultiplexing) {
$sshCommand = SshMultiplexingHelper::generateSshCommand($server, $command_string, $disableMultiplexing);
$process = Process::timeout($effectiveTimeout)->run($sshCommand);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
excludeCertainErrors($process->errorOutput(), $exitCode);
}
// Sanitize output to ensure valid UTF-8 encoding
$output = $output === 'null' ? null : sanitize_utf8_text($output);
return $output;
},
[
'server' => $server->ip,
'command_preview' => substr($command_string, 0, 100),
'function' => 'instant_remote_process',
],
$throwError
);
}
function excludeCertainErrors(string $errorOutput, ?int $exitCode = null)
{
$ignoredErrors = collect([
'Permission denied (publickey',
'Could not resolve hostname',
]);
$ignored = $ignoredErrors->contains(fn ($error) => Str::contains($errorOutput, $error));
// Ensure we always have a meaningful error message
$errorMessage = trim($errorOutput);
if (empty($errorMessage)) {
$errorMessage = "SSH command failed with exit code: $exitCode";
}
if ($ignored) {
// TODO: Create new exception and disable in sentry
throw new \RuntimeException($errorMessage, $exitCode);
}
throw new \RuntimeException($errorMessage, $exitCode);
}
function decode_remote_command_output(?ApplicationDeploymentQueue $application_deployment_queue = null): Collection
{
if (is_null($application_deployment_queue)) {
return collect([]);
}
$application = Application::find(data_get($application_deployment_queue, 'application_id'));
$is_debug_enabled = data_get($application, 'settings.is_debug_enabled');
$logs = data_get($application_deployment_queue, 'logs');
if (empty($logs)) {
return collect([]);
}
try {
$decoded = json_decode(
$logs,
associative: true,
flags: JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
// If JSON decoding fails, try to clean up the logs and retry
try {
// Ensure valid UTF-8 encoding
$cleaned_logs = sanitize_utf8_text($logs);
$decoded = json_decode(
$cleaned_logs,
associative: true,
flags: JSON_THROW_ON_ERROR
);
} catch (\JsonException $e) {
// If it still fails, return empty collection to prevent crashes
return collect([]);
}
}
if (! is_array($decoded)) {
return collect([]);
}
$seenCommands = collect();
$formatted = collect($decoded);
if (! $is_debug_enabled) {
$formatted = $formatted->filter(fn ($i) => $i['hidden'] === false ?? false);
}
return $formatted
->sortBy(fn ($i) => data_get($i, 'order'))
->map(function ($i) {
data_set($i, 'timestamp', Carbon::parse(data_get($i, 'timestamp'))->format('Y-M-d H:i:s.u'));
return $i;
})
->reduce(function ($deploymentLogLines, $logItem) use ($seenCommands) {
$command = data_get($logItem, 'command');
$isStderr = data_get($logItem, 'type') === 'stderr';
$isNewCommand = ! is_null($command) && ! $seenCommands->first(function ($seenCommand) use ($logItem) {
return data_get($seenCommand, 'command') === data_get($logItem, 'command') && data_get($seenCommand, 'batch') === data_get($logItem, 'batch');
});
if ($isNewCommand) {
$deploymentLogLines->push([
'line' => $command,
'timestamp' => data_get($logItem, 'timestamp'),
'stderr' => $isStderr,
'hidden' => data_get($logItem, 'hidden'),
'command' => true,
]);
$seenCommands->push([
'command' => $command,
'batch' => data_get($logItem, 'batch'),
]);
}
$lines = explode(PHP_EOL, data_get($logItem, 'output'));
foreach ($lines as $line) {
$deploymentLogLines->push([
'line' => $line,
'timestamp' => data_get($logItem, 'timestamp'),
'stderr' => $isStderr,
'hidden' => data_get($logItem, 'hidden'),
]);
}
return $deploymentLogLines;
}, collect());
}
function remove_iip($text)
{
// Ensure the input is valid UTF-8 before processing
$text = sanitize_utf8_text($text);
// Git access tokens
$text = preg_replace('/x-access-token:.*?(?=@)/', 'x-access-token:'.REDACTED, $text);
// ANSI color codes
$text = preg_replace('/\x1b\[[0-9;]*m/', '', $text);
// Generic URLs with passwords (covers database URLs, ftp, amqp, ssh, etc.)
// (protocol://user:password@host → protocol://user:<REDACTED>@host)
$text = preg_replace('/((?:postgres|mysql|mongodb|rediss?|mariadb|ftp|sftp|ssh|amqp|amqps|ldap|ldaps|s3):\/\/[^:]+:)[^@]+(@)/i', '$1'.REDACTED.'$2', $text);
// Email addresses
$text = preg_replace('/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/', REDACTED, $text);
// Bearer/JWT tokens
$text = preg_replace('/Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/i', 'Bearer '.REDACTED, $text);
// GitHub tokens (ghp_ = personal, gho_ = OAuth, ghu_ = user-to-server, ghs_ = server-to-server, ghr_ = refresh)
$text = preg_replace('/\b(gh[pousr]_[A-Za-z0-9_]{36,})\b/', REDACTED, $text);
// GitLab tokens (glpat- = personal access token, glcbt- = CI build token, glrt- = runner token)
$text = preg_replace('/\b(gl(?:pat|cbt|rt)-[A-Za-z0-9\-_]{20,})\b/', REDACTED, $text);
// AWS credentials (Access Key ID starts with AKIA, ABIA, ACCA, ASIA)
$text = preg_replace('/\b(A(?:KIA|BIA|CCA|SIA)[A-Z0-9]{16})\b/', REDACTED, $text);
// AWS Secret Access Key (40 character base64-ish string, typically follows access key)
$text = preg_replace('/(aws_secret_access_key|AWS_SECRET_ACCESS_KEY)[=:]\s*[\'"]?([A-Za-z0-9\/+=]{40})[\'"]?/i', '$1='.REDACTED, $text);
// API keys (common patterns)
$text = preg_replace('/(api[_-]?key|apikey|api[_-]?secret|secret[_-]?key)[=:]\s*[\'"]?[A-Za-z0-9\-_]{16,}[\'"]?/i', '$1='.REDACTED, $text);
// Private key blocks
$text = preg_replace('/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/', REDACTED, $text);
return $text;
}
/**
* Sanitizes text to ensure it contains valid UTF-8 encoding.
*
* This function is crucial for preventing "Malformed UTF-8 characters" errors
* that can occur when Docker build output contains binary data mixed with text,
* especially during image processing or builds with many assets.
*
* @param string|null $text The text to sanitize
* @return string Valid UTF-8 encoded text
*/
function sanitize_utf8_text(?string $text): string
{
if (empty($text)) {
return '';
}
// Convert to UTF-8, replacing invalid sequences
$sanitized = mb_convert_encoding($text, 'UTF-8', 'UTF-8');
// Additional fallback: use SUBSTITUTE flag to replace invalid sequences with substitution character
if (! mb_check_encoding($sanitized, 'UTF-8')) {
$sanitized = mb_convert_encoding($text, 'UTF-8', mb_detect_encoding($text, mb_detect_order(), true) ?: 'UTF-8');
}
return $sanitized;
}
function refresh_server_connection(?PrivateKey $private_key = null)
{
if (is_null($private_key)) {
return;
}
foreach ($private_key->servers as $server) {
SshMultiplexingHelper::removeMuxFile($server);
}
}
function checkRequiredCommands(Server $server)
{
$commands = collect(['jq', 'jc']);
foreach ($commands as $command) {
$commandFound = instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'command -v {$command}'"], $server, false);
if ($commandFound) {
continue;
}
try {
instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'apt update && apt install -y {$command}'"], $server);
} catch (\Throwable) {
break;
}
$commandFound = instant_remote_process(["docker run --rm --privileged --net=host --pid=host --ipc=host --volume /:/host busybox chroot /host bash -c 'command -v {$command}'"], $server, false);
if (! $commandFound) {
break;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/notifications.php | bootstrap/helpers/notifications.php | <?php
use App\Models\Team;
use App\Notifications\Internal\GeneralNotification;
use Illuminate\Mail\Message;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Facades\Mail;
function is_transactional_emails_enabled(): bool
{
$settings = instanceSettings();
return $settings->smtp_enabled || $settings->resend_enabled;
}
function send_internal_notification(string $message): void
{
try {
$team = Team::find(0);
$team?->notify(new GeneralNotification($message));
} catch (\Throwable $e) {
ray($e->getMessage());
}
}
function send_user_an_email(MailMessage $mail, string $email, ?string $cc = null): void
{
$settings = instanceSettings();
$type = set_transanctional_email_settings($settings);
if (blank($type)) {
throw new Exception('No email settings found.');
}
if ($cc) {
Mail::send(
[],
[],
fn (Message $message) => $message
->to($email)
->replyTo($email)
->cc($cc)
->subject($mail->subject)
->html((string) $mail->render())
);
} else {
Mail::send(
[],
[],
fn (Message $message) => $message
->to($email)
->subject($mail->subject)
->html((string) $mail->render())
);
}
}
function set_transanctional_email_settings($settings = null)
{
if (! $settings) {
$settings = instanceSettings();
}
if (! data_get($settings, 'smtp_enabled') && ! data_get($settings, 'resend_enabled')) {
return null;
}
$configRepository = app('App\Services\ConfigurationRepository'::class);
$configRepository->updateMailConfig($settings);
if (data_get($settings, 'resend_enabled')) {
return 'resend';
}
if (data_get($settings, 'smtp_enabled')) {
return 'smtp';
}
return null;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/versions.php | bootstrap/helpers/versions.php | <?php
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
/**
* Get cached versions data from versions.json.
*
* This function provides a centralized, cached access point for all
* version data in the application. Data is cached in Redis for 1 hour
* and shared across all servers in the cluster.
*
* @return array|null The versions data array, or null if file doesn't exist
*/
function get_versions_data(): ?array
{
return Cache::remember('coolify:versions:all', 3600, function () {
$versionsPath = base_path('versions.json');
if (! File::exists($versionsPath)) {
return null;
}
return json_decode(File::get($versionsPath), true);
});
}
/**
* Get Traefik versions from cached data.
*
* @return array|null Array of Traefik versions (e.g., ['v3.5' => '3.5.6'])
*/
function get_traefik_versions(): ?array
{
$versions = get_versions_data();
if (! $versions) {
return null;
}
$traefikVersions = data_get($versions, 'traefik');
return is_array($traefikVersions) ? $traefikVersions : null;
}
/**
* Invalidate the versions cache.
* Call this after updating versions.json to ensure fresh data is loaded.
*/
function invalidate_versions_cache(): void
{
Cache::forget('coolify:versions:all');
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/github.php | bootstrap/helpers/github.php | <?php
use App\Models\GithubApp;
use App\Models\GitlabApp;
use Carbon\Carbon;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Token\Builder;
function generateGithubToken(GithubApp $source, string $type)
{
$response = Http::get("{$source->api_url}/zen");
$serverTime = CarbonImmutable::now()->setTimezone('UTC');
$githubTime = Carbon::parse($response->header('date'));
$timeDiff = abs($serverTime->diffInSeconds($githubTime));
if ($timeDiff > 50) {
throw new \Exception(
'System time is out of sync with GitHub API time:<br>'.
'- System time: '.$serverTime->format('Y-m-d H:i:s').' UTC<br>'.
'- GitHub time: '.$githubTime->format('Y-m-d H:i:s').' UTC<br>'.
'- Difference: '.$timeDiff.' seconds<br>'.
'Please synchronize your system clock.'
);
}
$signingKey = InMemory::plainText($source->privateKey->private_key);
$algorithm = new Sha256;
$tokenBuilder = (new Builder(new JoseEncoder, ChainedFormatter::default()));
$now = CarbonImmutable::now()->setTimezone('UTC');
$now = $now->setTime($now->format('H'), $now->format('i'), $now->format('s'));
$jwt = $tokenBuilder
->issuedBy($source->app_id)
->issuedAt($now->modify('-1 minute'))
->expiresAt($now->modify('+8 minutes'))
->getToken($algorithm, $signingKey)
->toString();
return match ($type) {
'jwt' => $jwt,
'installation' => (function () use ($source, $jwt) {
$response = Http::withHeaders([
'Authorization' => "Bearer $jwt",
'Accept' => 'application/vnd.github.machine-man-preview+json',
])->post("{$source->api_url}/app/installations/{$source->installation_id}/access_tokens");
if (! $response->successful()) {
$error = data_get($response->json(), 'message', 'no error message found');
if ($error === 'Not Found') {
$error = 'Repository not found. Is it moved or deleted?';
}
throw new RuntimeException("Failed to get installation token for {$source->name} with error: ".$error);
}
return $response->json()['token'];
})(),
default => throw new \InvalidArgumentException("Unsupported token type: {$type}")
};
}
function generateGithubInstallationToken(GithubApp $source)
{
return generateGithubToken($source, 'installation');
}
function generateGithubJwt(GithubApp $source)
{
return generateGithubToken($source, 'jwt');
}
function githubApi(GithubApp|GitlabApp|null $source, string $endpoint, string $method = 'get', ?array $data = null, bool $throwError = true)
{
if (is_null($source)) {
throw new \Exception('Source is required for API calls');
}
if ($source->getMorphClass() !== GithubApp::class) {
throw new \InvalidArgumentException("Unsupported source type: {$source->getMorphClass()}");
}
if ($source->is_public) {
$response = Http::GitHub($source->api_url)->$method($endpoint);
} else {
$token = generateGithubInstallationToken($source);
if ($data && in_array(strtolower($method), ['post', 'patch', 'put'])) {
$response = Http::GitHub($source->api_url, $token)->$method($endpoint, $data);
} else {
$response = Http::GitHub($source->api_url, $token)->$method($endpoint);
}
}
if (! $response->successful() && $throwError) {
$resetTime = Carbon::parse((int) $response->header('X-RateLimit-Reset'))->format('Y-m-d H:i:s');
$errorMessage = data_get($response->json(), 'message', 'no error message found');
$remainingCalls = $response->header('X-RateLimit-Remaining', '0');
throw new \Exception(
'GitHub API call failed:<br>'.
"Error: {$errorMessage}<br>".
'Rate Limit Status:<br>'.
"- Remaining Calls: {$remainingCalls}<br>".
"- Reset Time: {$resetTime} UTC"
);
}
return [
'rate_limit_remaining' => $response->header('X-RateLimit-Remaining'),
'rate_limit_reset' => $response->header('X-RateLimit-Reset'),
'data' => collect($response->json()),
];
}
function getInstallationPath(GithubApp $source)
{
$github = GithubApp::where('uuid', $source->uuid)->first();
$name = str(Str::kebab($github->name));
$installation_path = $github->html_url === 'https://github.com' ? 'apps' : 'github-apps';
return "$github->html_url/$installation_path/$name/installations/new";
}
function getPermissionsPath(GithubApp $source)
{
$github = GithubApp::where('uuid', $source->uuid)->first();
$name = str(Str::kebab($github->name));
return "$github->html_url/settings/apps/$name/permissions";
}
function loadRepositoryByPage(GithubApp $source, string $token, int $page)
{
$response = Http::GitHub($source->api_url, $token)
->timeout(20)
->retry(3, 200, throw: false)
->get('/installation/repositories', [
'per_page' => 100,
'page' => $page,
]);
$json = $response->json();
if ($response->status() !== 200) {
return [
'total_count' => 0,
'repositories' => [],
];
}
if ($json['total_count'] === 0) {
return [
'total_count' => 0,
'repositories' => [],
];
}
return [
'total_count' => $json['total_count'],
'repositories' => $json['repositories'],
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/shared.php | bootstrap/helpers/shared.php | <?php
use App\Enums\ApplicationDeploymentStatus;
use App\Enums\ProxyTypes;
use App\Jobs\ServerFilesFromServerJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\ApplicationPreview;
use App\Models\EnvironmentVariable;
use App\Models\GithubApp;
use App\Models\InstanceSettings;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
use App\Models\Server;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\Team;
use App\Models\User;
use Carbon\CarbonImmutable;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Process\Pool;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Support\Stringable;
use Laravel\Horizon\Contracts\JobRepository;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\Builder;
use phpseclib3\Crypt\EC;
use phpseclib3\Crypt\RSA;
use Poliander\Cron\CronExpression;
use PurplePixie\PhpDns\DNSQuery;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
use Visus\Cuid2\Cuid2;
function base_configuration_dir(): string
{
return '/data/coolify';
}
function application_configuration_dir(): string
{
return base_configuration_dir().'/applications';
}
function service_configuration_dir(): string
{
return base_configuration_dir().'/services';
}
function database_configuration_dir(): string
{
return base_configuration_dir().'/databases';
}
function database_proxy_dir($uuid): string
{
return base_configuration_dir()."/databases/$uuid/proxy";
}
function backup_dir(): string
{
return base_configuration_dir().'/backups';
}
function metrics_dir(): string
{
return base_configuration_dir().'/metrics';
}
function sanitize_string(?string $input = null): ?string
{
if (is_null($input)) {
return null;
}
// Remove any HTML/PHP tags
$sanitized = strip_tags($input);
// Convert special characters to HTML entities
$sanitized = htmlspecialchars($sanitized, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Remove any control characters
$sanitized = preg_replace('/[\x00-\x1F\x7F]/u', '', $sanitized);
// Trim whitespace
$sanitized = trim($sanitized);
return $sanitized;
}
/**
* Validate that a path or identifier is safe for use in shell commands.
*
* This function prevents command injection by rejecting strings that contain
* shell metacharacters or command substitution patterns.
*
* @param string $input The path or identifier to validate
* @param string $context Descriptive name for error messages (e.g., 'volume source', 'service name')
* @return string The validated input (unchanged if valid)
*
* @throws \Exception If dangerous characters are detected
*/
function validateShellSafePath(string $input, string $context = 'path'): string
{
// List of dangerous shell metacharacters that enable command injection
$dangerousChars = [
'`' => 'backtick (command substitution)',
'$(' => 'command substitution',
'${' => 'variable substitution with potential command injection',
'|' => 'pipe operator',
'&' => 'background/AND operator',
';' => 'command separator',
"\n" => 'newline (command separator)',
"\r" => 'carriage return',
"\t" => 'tab (token separator)',
'>' => 'output redirection',
'<' => 'input redirection',
];
// Check for dangerous characters
foreach ($dangerousChars as $char => $description) {
if (str_contains($input, $char)) {
throw new \Exception(
"Invalid {$context}: contains forbidden character '{$char}' ({$description}). ".
'Shell metacharacters are not allowed for security reasons.'
);
}
}
return $input;
}
function generate_readme_file(string $name, string $updated_at): string
{
$name = sanitize_string($name);
$updated_at = sanitize_string($updated_at);
return "Resource name: $name\nLatest Deployment Date: $updated_at";
}
function isInstanceAdmin()
{
return auth()?->user()?->isInstanceAdmin() ?? false;
}
function currentTeam()
{
return Auth::user()?->currentTeam() ?? null;
}
function showBoarding(): bool
{
if (Auth::user()?->isMember()) {
return false;
}
return currentTeam()->show_boarding ?? false;
}
function refreshSession(?Team $team = null): void
{
if (! $team) {
if (Auth::user()->currentTeam()) {
$team = Team::find(Auth::user()->currentTeam()->id);
} else {
$team = User::find(Auth::id())->teams->first();
}
}
Cache::forget('team:'.Auth::id());
Cache::remember('team:'.Auth::id(), 3600, function () use ($team) {
return $team;
});
session(['currentTeam' => $team]);
}
function handleError(?Throwable $error = null, ?Livewire\Component $livewire = null, ?string $customErrorMessage = null)
{
if ($error instanceof TooManyRequestsException) {
if (isset($livewire)) {
return $livewire->dispatch('error', "Too many requests. Please try again in {$error->secondsUntilAvailable} seconds.");
}
return "Too many requests. Please try again in {$error->secondsUntilAvailable} seconds.";
}
if ($error instanceof UniqueConstraintViolationException) {
if (isset($livewire)) {
return $livewire->dispatch('error', 'Duplicate entry found. Please use a different name.');
}
return 'Duplicate entry found. Please use a different name.';
}
if ($error instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
abort(404);
}
if ($error instanceof Throwable) {
$message = $error->getMessage();
} else {
$message = null;
}
if ($customErrorMessage) {
$message = $customErrorMessage.' '.$message;
}
if (isset($livewire)) {
return $livewire->dispatch('error', $message);
}
throw new Exception($message);
}
function get_route_parameters(): array
{
return Route::current()->parameters();
}
function get_latest_sentinel_version(): string
{
try {
$response = Http::get(config('constants.coolify.versions_url'));
$versions = $response->json();
return data_get($versions, 'coolify.sentinel.version');
} catch (\Throwable) {
return '0.0.0';
}
}
function get_latest_version_of_coolify(): string
{
try {
$versions = get_versions_data();
return data_get($versions, 'coolify.v4.version', '0.0.0');
} catch (\Throwable $e) {
return '0.0.0';
}
}
function generate_random_name(?string $cuid = null): string
{
$generator = new \Nubs\RandomNameGenerator\All(
[
new \Nubs\RandomNameGenerator\Alliteration,
]
);
if (is_null($cuid)) {
$cuid = new Cuid2;
}
return Str::kebab("{$generator->getName()}-$cuid");
}
function generateSSHKey(string $type = 'rsa')
{
if ($type === 'rsa') {
$key = RSA::createKey();
return [
'private' => $key->toString('PKCS1'),
'public' => $key->getPublicKey()->toString('OpenSSH', ['comment' => 'coolify-generated-ssh-key']),
];
} elseif ($type === 'ed25519') {
$key = EC::createKey('Ed25519');
return [
'private' => $key->toString('OpenSSH'),
'public' => $key->getPublicKey()->toString('OpenSSH', ['comment' => 'coolify-generated-ssh-key']),
];
}
throw new Exception('Invalid key type');
}
function formatPrivateKey(string $privateKey)
{
$privateKey = trim($privateKey);
if (! str_ends_with($privateKey, "\n")) {
$privateKey .= "\n";
}
return $privateKey;
}
function generate_application_name(string $git_repository, string $git_branch, ?string $cuid = null): string
{
if (is_null($cuid)) {
$cuid = new Cuid2;
}
return Str::kebab("$git_repository:$git_branch-$cuid");
}
/**
* Sort branches by priority: main first, master second, then alphabetically.
*
* @param Collection $branches Collection of branch objects with 'name' key
*/
function sortBranchesByPriority(Collection $branches): Collection
{
return $branches->sortBy(function ($branch) {
$name = data_get($branch, 'name');
return match ($name) {
'main' => '0_main',
'master' => '1_master',
default => '2_'.$name,
};
})->values();
}
function base_ip(): string
{
if (isDev()) {
return 'localhost';
}
$settings = instanceSettings();
if ($settings->public_ipv4) {
return "$settings->public_ipv4";
}
if ($settings->public_ipv6) {
return "$settings->public_ipv6";
}
return 'localhost';
}
function getFqdnWithoutPort(string $fqdn)
{
try {
$url = Url::fromString($fqdn);
$host = $url->getHost();
$scheme = $url->getScheme();
$path = $url->getPath();
return "$scheme://$host$path";
} catch (\Throwable) {
return $fqdn;
}
}
/**
* If fqdn is set, return it, otherwise return public ip.
*/
function base_url(bool $withPort = true): string
{
$settings = instanceSettings();
if ($settings->fqdn) {
return $settings->fqdn;
}
$port = config('app.port');
if ($settings->public_ipv4) {
if ($withPort) {
if (isDev()) {
return "http://localhost:$port";
}
return "http://$settings->public_ipv4:$port";
}
if (isDev()) {
return 'http://localhost';
}
return "http://$settings->public_ipv4";
}
if ($settings->public_ipv6) {
if ($withPort) {
return "http://$settings->public_ipv6:$port";
}
return "http://$settings->public_ipv6";
}
return url('/');
}
function isSubscribed()
{
return isSubscriptionActive() || auth()->user()->isInstanceAdmin();
}
function isProduction(): bool
{
return ! isDev();
}
function isDev(): bool
{
return config('app.env') === 'local';
}
function isCloud(): bool
{
return ! config('constants.coolify.self_hosted');
}
function translate_cron_expression($expression_to_validate): string
{
if (isset(VALID_CRON_STRINGS[$expression_to_validate])) {
return VALID_CRON_STRINGS[$expression_to_validate];
}
return $expression_to_validate;
}
function validate_cron_expression($expression_to_validate): bool
{
if (empty($expression_to_validate)) {
return false;
}
$isValid = false;
$expression = new CronExpression($expression_to_validate);
$isValid = $expression->isValid();
if (isset(VALID_CRON_STRINGS[$expression_to_validate])) {
$isValid = true;
}
return $isValid;
}
function validate_timezone(string $timezone): bool
{
return in_array($timezone, timezone_identifiers_list());
}
function parseEnvFormatToArray($env_file_contents)
{
$env_array = [];
$lines = explode("\n", $env_file_contents);
foreach ($lines as $line) {
if ($line === '' || substr($line, 0, 1) === '#') {
continue;
}
$equals_pos = strpos($line, '=');
if ($equals_pos !== false) {
$key = substr($line, 0, $equals_pos);
$value = substr($line, $equals_pos + 1);
if (substr($value, 0, 1) === '"' && substr($value, -1) === '"') {
$value = substr($value, 1, -1);
} elseif (substr($value, 0, 1) === "'" && substr($value, -1) === "'") {
$value = substr($value, 1, -1);
}
$env_array[$key] = $value;
}
}
return $env_array;
}
function data_get_str($data, $key, $default = null): Stringable
{
$str = data_get($data, $key, $default) ?? $default;
return str($str);
}
function generateUrl(Server $server, string $random, bool $forceHttps = false): string
{
$wildcard = data_get($server, 'settings.wildcard_domain');
if (is_null($wildcard) || $wildcard === '') {
$wildcard = sslip($server);
}
$url = Url::fromString($wildcard);
$host = $url->getHost();
$path = $url->getPath() === '/' ? '' : $url->getPath();
$scheme = $url->getScheme();
if ($forceHttps) {
$scheme = 'https';
}
return "$scheme://{$random}.$host$path";
}
function generateFqdn(Server $server, string $random, bool $forceHttps = false, int $parserVersion = 5): string
{
$wildcard = data_get($server, 'settings.wildcard_domain');
if (is_null($wildcard) || $wildcard === '') {
$wildcard = sslip($server);
}
$url = Url::fromString($wildcard);
$host = $url->getHost();
$path = $url->getPath() === '/' ? '' : $url->getPath();
$scheme = $url->getScheme();
if ($forceHttps) {
$scheme = 'https';
}
if ($parserVersion >= 5 && version_compare(config('constants.coolify.version'), '4.0.0-beta.420.7', '>=')) {
return "{$random}.$host$path";
}
return "$scheme://{$random}.$host$path";
}
function sslip(Server $server)
{
if (isDev() && $server->id === 0) {
return 'http://127.0.0.1.sslip.io';
}
if ($server->ip === 'host.docker.internal') {
$baseIp = base_ip();
return "http://$baseIp.sslip.io";
}
// ipv6
if (str($server->ip)->contains(':')) {
$ipv6 = str($server->ip)->replace(':', '-');
return "http://{$ipv6}.sslip.io";
}
return "http://{$server->ip}.sslip.io";
}
function get_service_templates(bool $force = false): Collection
{
if ($force) {
try {
$response = Http::retry(3, 1000)->get(config('constants.services.official'));
if ($response->failed()) {
return collect([]);
}
$services = $response->json();
return collect($services);
} catch (\Throwable) {
$services = File::get(base_path('templates/'.config('constants.services.file_name')));
return collect(json_decode($services))->sortKeys();
}
} else {
$services = File::get(base_path('templates/'.config('constants.services.file_name')));
return collect(json_decode($services))->sortKeys();
}
}
function getResourceByUuid(string $uuid, ?int $teamId = null)
{
if (is_null($teamId)) {
return null;
}
$resource = queryResourcesByUuid($uuid);
if (! is_null($resource) && $resource->environment->project->team_id === $teamId) {
return $resource;
}
return null;
}
function queryDatabaseByUuidWithinTeam(string $uuid, string $teamId)
{
$postgresql = StandalonePostgresql::whereUuid($uuid)->first();
if ($postgresql && $postgresql->team()->id == $teamId) {
return $postgresql->unsetRelation('environment');
}
$redis = StandaloneRedis::whereUuid($uuid)->first();
if ($redis && $redis->team()->id == $teamId) {
return $redis->unsetRelation('environment');
}
$mongodb = StandaloneMongodb::whereUuid($uuid)->first();
if ($mongodb && $mongodb->team()->id == $teamId) {
return $mongodb->unsetRelation('environment');
}
$mysql = StandaloneMysql::whereUuid($uuid)->first();
if ($mysql && $mysql->team()->id == $teamId) {
return $mysql->unsetRelation('environment');
}
$mariadb = StandaloneMariadb::whereUuid($uuid)->first();
if ($mariadb && $mariadb->team()->id == $teamId) {
return $mariadb->unsetRelation('environment');
}
$keydb = StandaloneKeydb::whereUuid($uuid)->first();
if ($keydb && $keydb->team()->id == $teamId) {
return $keydb->unsetRelation('environment');
}
$dragonfly = StandaloneDragonfly::whereUuid($uuid)->first();
if ($dragonfly && $dragonfly->team()->id == $teamId) {
return $dragonfly->unsetRelation('environment');
}
$clickhouse = StandaloneClickhouse::whereUuid($uuid)->first();
if ($clickhouse && $clickhouse->team()->id == $teamId) {
return $clickhouse->unsetRelation('environment');
}
return null;
}
function queryResourcesByUuid(string $uuid)
{
$resource = null;
$application = Application::whereUuid($uuid)->first();
if ($application) {
return $application;
}
$service = Service::whereUuid($uuid)->first();
if ($service) {
return $service;
}
$postgresql = StandalonePostgresql::whereUuid($uuid)->first();
if ($postgresql) {
return $postgresql;
}
$redis = StandaloneRedis::whereUuid($uuid)->first();
if ($redis) {
return $redis;
}
$mongodb = StandaloneMongodb::whereUuid($uuid)->first();
if ($mongodb) {
return $mongodb;
}
$mysql = StandaloneMysql::whereUuid($uuid)->first();
if ($mysql) {
return $mysql;
}
$mariadb = StandaloneMariadb::whereUuid($uuid)->first();
if ($mariadb) {
return $mariadb;
}
$keydb = StandaloneKeydb::whereUuid($uuid)->first();
if ($keydb) {
return $keydb;
}
$dragonfly = StandaloneDragonfly::whereUuid($uuid)->first();
if ($dragonfly) {
return $dragonfly;
}
$clickhouse = StandaloneClickhouse::whereUuid($uuid)->first();
if ($clickhouse) {
return $clickhouse;
}
return $resource;
}
function generateTagDeployWebhook($tag_name)
{
$baseUrl = base_url();
$api = Url::fromString($baseUrl).'/api/v1';
$endpoint = "/deploy?tag=$tag_name";
return $api.$endpoint;
}
function generateDeployWebhook($resource)
{
$baseUrl = base_url();
$api = Url::fromString($baseUrl).'/api/v1';
$endpoint = '/deploy';
$uuid = data_get($resource, 'uuid');
return $api.$endpoint."?uuid=$uuid&force=false";
}
function generateGitManualWebhook($resource, $type)
{
if ($resource->source_id !== 0 && ! is_null($resource->source_id)) {
return null;
}
if ($resource->getMorphClass() === \App\Models\Application::class) {
$baseUrl = base_url();
return Url::fromString($baseUrl)."/webhooks/source/$type/events/manual";
}
return null;
}
function removeAnsiColors($text)
{
return preg_replace('/\e[[][A-Za-z0-9];?[0-9]*m?/', '', $text);
}
function sanitizeLogsForExport(string $text): string
{
// All sanitization is now handled by remove_iip()
return remove_iip($text);
}
function getTopLevelNetworks(Service|Application $resource)
{
if ($resource->getMorphClass() === \App\Models\Service::class) {
if ($resource->docker_compose_raw) {
try {
$yaml = Yaml::parse($resource->docker_compose_raw);
} catch (\Exception $e) {
// If the docker-compose.yml file is not valid, we will return the network name as the key
$topLevelNetworks = collect([
$resource->uuid => [
'name' => $resource->uuid,
'external' => true,
],
]);
return $topLevelNetworks->keys();
}
$services = data_get($yaml, 'services');
$topLevelNetworks = collect(data_get($yaml, 'networks', []));
$definedNetwork = collect([$resource->uuid]);
$services = collect($services)->map(function ($service, $_) use ($topLevelNetworks, $definedNetwork) {
$serviceNetworks = collect(data_get($service, 'networks', []));
$networkMode = data_get($service, 'network_mode');
$hasValidNetworkMode =
$networkMode === 'host' ||
(is_string($networkMode) && (str_starts_with($networkMode, 'service:') || str_starts_with($networkMode, 'container:')));
// Only add 'networks' key if 'network_mode' is not 'host' or does not start with 'service:' or 'container:'
if (! $hasValidNetworkMode) {
// Collect/create/update networks
if ($serviceNetworks->count() > 0) {
foreach ($serviceNetworks as $networkName => $networkDetails) {
if ($networkName === 'default') {
continue;
}
// ignore alias
if ($networkDetails['aliases'] ?? false) {
continue;
}
$networkExists = $topLevelNetworks->contains(function ($value, $key) use ($networkName) {
return $value == $networkName || $key == $networkName;
});
if (! $networkExists) {
if (is_string($networkDetails) || is_int($networkDetails)) {
$topLevelNetworks->put($networkDetails, null);
}
}
}
}
$definedNetworkExists = $topLevelNetworks->contains(function ($value, $_) use ($definedNetwork) {
return $value == $definedNetwork;
});
if (! $definedNetworkExists) {
foreach ($definedNetwork as $network) {
$topLevelNetworks->put($network, [
'name' => $network,
'external' => true,
]);
}
}
}
return $service;
});
return $topLevelNetworks->keys();
}
} elseif ($resource->getMorphClass() === \App\Models\Application::class) {
try {
$yaml = Yaml::parse($resource->docker_compose_raw);
} catch (\Exception $e) {
// If the docker-compose.yml file is not valid, we will return the network name as the key
$topLevelNetworks = collect([
$resource->uuid => [
'name' => $resource->uuid,
'external' => true,
],
]);
return $topLevelNetworks->keys();
}
$topLevelNetworks = collect(data_get($yaml, 'networks', []));
$services = data_get($yaml, 'services');
$definedNetwork = collect([$resource->uuid]);
$services = collect($services)->map(function ($service, $_) use ($topLevelNetworks, $definedNetwork) {
$serviceNetworks = collect(data_get($service, 'networks', []));
// Collect/create/update networks
if ($serviceNetworks->count() > 0) {
foreach ($serviceNetworks as $networkName => $networkDetails) {
if ($networkName === 'default') {
continue;
}
// ignore alias
if ($networkDetails['aliases'] ?? false) {
continue;
}
$networkExists = $topLevelNetworks->contains(function ($value, $key) use ($networkName) {
return $value == $networkName || $key == $networkName;
});
if (! $networkExists) {
if (is_string($networkDetails) || is_int($networkDetails)) {
$topLevelNetworks->put($networkDetails, null);
}
}
}
}
$definedNetworkExists = $topLevelNetworks->contains(function ($value, $_) use ($definedNetwork) {
return $value == $definedNetwork;
});
if (! $definedNetworkExists) {
foreach ($definedNetwork as $network) {
$topLevelNetworks->put($network, [
'name' => $network,
'external' => true,
]);
}
}
return $service;
});
return $topLevelNetworks->keys();
}
}
function sourceIsLocal(Stringable $source)
{
if ($source->startsWith('./') || $source->startsWith('/') || $source->startsWith('~') || $source->startsWith('..') || $source->startsWith('~/') || $source->startsWith('../')) {
return true;
}
return false;
}
function replaceLocalSource(Stringable $source, Stringable $replacedWith)
{
if ($source->startsWith('.')) {
$source = $source->replaceFirst('.', $replacedWith->value());
}
if ($source->startsWith('~')) {
$source = $source->replaceFirst('~', $replacedWith->value());
}
if ($source->startsWith('..')) {
$source = $source->replaceFirst('..', $replacedWith->value());
}
if ($source->endsWith('/') && $source->value() !== '/') {
$source = $source->replaceLast('/', '');
}
return $source;
}
function convertToArray($collection)
{
if ($collection instanceof Collection) {
return $collection->map(function ($item) {
return convertToArray($item);
})->toArray();
} elseif ($collection instanceof Stringable) {
return (string) $collection;
} elseif (is_array($collection)) {
return array_map(function ($item) {
return convertToArray($item);
}, $collection);
}
return $collection;
}
function parseCommandFromMagicEnvVariable(Str|string $key): Stringable
{
$value = str($key);
$count = substr_count($value->value(), '_');
$command = null;
if ($count === 2) {
if ($value->startsWith('SERVICE_FQDN') || $value->startsWith('SERVICE_URL')) {
// SERVICE_FQDN_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
} else {
// SERVICE_BASE64_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
}
}
if ($count === 3) {
if ($value->startsWith('SERVICE_FQDN') || $value->startsWith('SERVICE_URL')) {
// SERVICE_FQDN_UMAMI_1000
$command = $value->after('SERVICE_')->before('_');
} else {
// SERVICE_BASE64_64_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
}
}
return str($command);
}
function parseEnvVariable(Str|string $value)
{
$value = str($value);
$count = substr_count($value->value(), '_');
$command = null;
$forService = null;
$generatedValue = null;
$port = null;
if ($value->startsWith('SERVICE')) {
if ($count === 2) {
if ($value->startsWith('SERVICE_FQDN') || $value->startsWith('SERVICE_URL')) {
// SERVICE_FQDN_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
$forService = $value->afterLast('_');
} else {
// SERVICE_BASE64_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
}
}
if ($count === 3) {
if ($value->startsWith('SERVICE_FQDN') || $value->startsWith('SERVICE_URL')) {
// SERVICE_FQDN_UMAMI_1000
$command = $value->after('SERVICE_')->before('_');
$forService = $value->after('SERVICE_')->after('_')->before('_');
$port = $value->afterLast('_');
if (filter_var($port, FILTER_VALIDATE_INT) === false) {
$port = null;
}
} else {
// SERVICE_BASE64_64_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
}
}
}
return [
'command' => $command,
'forService' => $forService,
'generatedValue' => $generatedValue,
'port' => $port,
];
}
function generateEnvValue(string $command, Service|Application|null $service = null)
{
switch ($command) {
case 'PASSWORD':
$generatedValue = Str::password(symbols: false);
break;
case 'PASSWORD_64':
$generatedValue = Str::password(length: 64, symbols: false);
break;
case 'PASSWORDWITHSYMBOLS':
$generatedValue = Str::password(symbols: true);
break;
case 'PASSWORDWITHSYMBOLS_64':
$generatedValue = Str::password(length: 64, symbols: true);
break;
// This is not base64, it's just a random string
case 'BASE64_64':
$generatedValue = Str::random(64);
break;
case 'BASE64_128':
$generatedValue = Str::random(128);
break;
case 'BASE64':
case 'BASE64_32':
$generatedValue = Str::random(32);
break;
// This is base64,
case 'REALBASE64_64':
$generatedValue = base64_encode(Str::random(64));
break;
case 'REALBASE64_128':
$generatedValue = base64_encode(Str::random(128));
break;
case 'REALBASE64':
case 'REALBASE64_32':
$generatedValue = base64_encode(Str::random(32));
break;
case 'HEX_32':
$generatedValue = bin2hex(Str::random(32));
break;
case 'HEX_64':
$generatedValue = bin2hex(Str::random(64));
break;
case 'HEX_128':
$generatedValue = bin2hex(Str::random(128));
break;
case 'USER':
$generatedValue = Str::random(16);
break;
case 'SUPABASEANON':
$signingKey = $service->environment_variables()->where('key', 'SERVICE_PASSWORD_JWT')->first();
if (is_null($signingKey)) {
return;
} else {
$signingKey = $signingKey->value;
}
$key = InMemory::plainText($signingKey);
$algorithm = new Sha256;
$tokenBuilder = (new Builder(new JoseEncoder, ChainedFormatter::default()));
$now = CarbonImmutable::now();
$now = $now->setTime($now->format('H'), $now->format('i'));
$token = $tokenBuilder
->issuedBy('supabase')
->issuedAt($now)
->expiresAt($now->modify('+100 year'))
->withClaim('role', 'anon')
->getToken($algorithm, $key);
$generatedValue = $token->toString();
break;
case 'SUPABASESERVICE':
$signingKey = $service->environment_variables()->where('key', 'SERVICE_PASSWORD_JWT')->first();
if (is_null($signingKey)) {
return;
} else {
$signingKey = $signingKey->value;
}
$key = InMemory::plainText($signingKey);
$algorithm = new Sha256;
$tokenBuilder = (new Builder(new JoseEncoder, ChainedFormatter::default()));
$now = CarbonImmutable::now();
$now = $now->setTime($now->format('H'), $now->format('i'));
$token = $tokenBuilder
->issuedBy('supabase')
->issuedAt($now)
->expiresAt($now->modify('+100 year'))
->withClaim('role', 'service_role')
->getToken($algorithm, $key);
$generatedValue = $token->toString();
break;
default:
// $generatedValue = Str::random(16);
$generatedValue = null;
break;
}
return $generatedValue;
}
function getRealtime()
{
$envDefined = config('constants.pusher.port');
if (empty($envDefined)) {
$url = Url::fromString(Request::getSchemeAndHttpHost());
$port = $url->getPort();
if ($port) {
return '6001';
} else {
return null;
}
} else {
return $envDefined;
}
}
function validateDNSEntry(string $fqdn, Server $server)
{
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/domains.php | bootstrap/helpers/domains.php | <?php
use App\Models\Application;
use App\Models\ServiceApplication;
use Illuminate\Support\Collection;
function checkDomainUsage(ServiceApplication|Application|null $resource = null, ?string $domain = null)
{
$conflicts = [];
// Get the current team for filtering
$currentTeam = null;
if ($resource) {
$currentTeam = $resource->team();
}
if ($resource) {
if ($resource->getMorphClass() === Application::class && $resource->build_pack === 'dockercompose') {
$domains = data_get(json_decode($resource->docker_compose_domains, true), '*.domain');
$domains = collect($domains);
} else {
$domains = collect($resource->fqdns);
}
} elseif ($domain) {
$domains = collect([$domain]);
} else {
return ['conflicts' => [], 'hasConflicts' => false];
}
$domains = $domains->map(function ($domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
return str($domain);
});
// Filter applications by team if we have a current team
$appsQuery = Application::query();
if ($currentTeam) {
$appsQuery = $appsQuery->whereHas('environment.project', function ($query) use ($currentTeam) {
$query->where('team_id', $currentTeam->id);
});
}
$apps = $appsQuery->get();
foreach ($apps as $app) {
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
if (data_get($resource, 'uuid')) {
if ($resource->uuid !== $app->uuid) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => $app->name,
'resource_link' => $app->link(),
'resource_type' => 'application',
'message' => "Domain $naked_domain is already in use by application '{$app->name}'",
];
}
} elseif ($domain) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => $app->name,
'resource_link' => $app->link(),
'resource_type' => 'application',
'message' => "Domain $naked_domain is already in use by application '{$app->name}'",
];
}
}
}
}
// Filter service applications by team if we have a current team
$serviceAppsQuery = ServiceApplication::query();
if ($currentTeam) {
$serviceAppsQuery = $serviceAppsQuery->whereHas('service.environment.project', function ($query) use ($currentTeam) {
$query->where('team_id', $currentTeam->id);
});
}
$apps = $serviceAppsQuery->get();
foreach ($apps as $app) {
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
if (data_get($resource, 'uuid')) {
if ($resource->uuid !== $app->uuid) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => $app->service->name,
'resource_link' => $app->service->link(),
'resource_type' => 'service',
'message' => "Domain $naked_domain is already in use by service '{$app->service->name}'",
];
}
} elseif ($domain) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => $app->service->name,
'resource_link' => $app->service->link(),
'resource_type' => 'service',
'message' => "Domain $naked_domain is already in use by service '{$app->service->name}'",
];
}
}
}
}
if ($resource) {
$settings = instanceSettings();
if (data_get($settings, 'fqdn')) {
$domain = data_get($settings, 'fqdn');
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => 'Coolify Instance',
'resource_link' => '#',
'resource_type' => 'instance',
'message' => "Domain $naked_domain is already in use by this Coolify instance",
];
}
}
}
return [
'conflicts' => $conflicts,
'hasConflicts' => count($conflicts) > 0,
];
}
function checkIfDomainIsAlreadyUsedViaAPI(Collection|array $domains, ?string $teamId = null, ?string $uuid = null)
{
$conflicts = [];
if (is_null($teamId)) {
return ['error' => 'Team ID is required.'];
}
if (is_array($domains)) {
$domains = collect($domains);
}
$domains = $domains->map(function ($domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
return str($domain);
});
// Check applications within the same team
$applications = Application::ownedByCurrentTeamAPI($teamId)->get(['fqdn', 'uuid', 'name', 'id']);
$serviceApplications = ServiceApplication::ownedByCurrentTeamAPI($teamId)->with('service:id,name')->get(['fqdn', 'uuid', 'id', 'service_id']);
if ($uuid) {
$applications = $applications->filter(fn ($app) => $app->uuid !== $uuid);
$serviceApplications = $serviceApplications->filter(fn ($app) => $app->uuid !== $uuid);
}
foreach ($applications as $app) {
if (is_null($app->fqdn)) {
continue;
}
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => $app->name,
'resource_uuid' => $app->uuid,
'resource_type' => 'application',
'message' => "Domain $naked_domain is already in use by application '{$app->name}'",
];
}
}
}
foreach ($serviceApplications as $app) {
if (str($app->fqdn)->isEmpty()) {
continue;
}
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => $app->service->name ?? 'Unknown Service',
'resource_uuid' => $app->uuid,
'resource_type' => 'service',
'message' => "Domain $naked_domain is already in use by service '{$app->service->name}'",
];
}
}
}
// Check instance-level domain
$settings = instanceSettings();
if (data_get($settings, 'fqdn')) {
$domain = data_get($settings, 'fqdn');
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
$conflicts[] = [
'domain' => $naked_domain,
'resource_name' => 'Coolify Instance',
'resource_uuid' => null,
'resource_type' => 'instance',
'message' => "Domain $naked_domain is already in use by this Coolify instance",
];
}
}
return [
'conflicts' => $conflicts,
'hasConflicts' => count($conflicts) > 0,
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/socialite.php | bootstrap/helpers/socialite.php | <?php
use App\Models\OauthSetting;
use Laravel\Socialite\Facades\Socialite;
function get_socialite_provider(string $provider)
{
$oauth_setting = OauthSetting::firstWhere('provider', $provider);
if (! filled($oauth_setting->redirect_uri)) {
$oauth_setting->update(['redirect_uri' => route('auth.callback', $provider)]);
}
if ($provider === 'azure') {
$azure_config = new \SocialiteProviders\Manager\Config(
$oauth_setting->client_id,
$oauth_setting->client_secret,
$oauth_setting->redirect_uri,
['tenant' => $oauth_setting->tenant],
);
return Socialite::driver('azure')->setConfig($azure_config);
}
if ($provider == 'authentik' || $provider == 'clerk') {
$authentik_clerk_config = new \SocialiteProviders\Manager\Config(
$oauth_setting->client_id,
$oauth_setting->client_secret,
$oauth_setting->redirect_uri,
['base_url' => $oauth_setting->base_url],
);
return Socialite::driver($provider)->setConfig($authentik_clerk_config);
}
if ($provider == 'zitadel') {
$zitadel_config = new \SocialiteProviders\Manager\Config(
$oauth_setting->client_id,
$oauth_setting->client_secret,
$oauth_setting->redirect_uri,
['base_url' => $oauth_setting->base_url],
);
return Socialite::driver('zitadel')->setConfig($zitadel_config);
}
if ($provider == 'google') {
$google_config = new \SocialiteProviders\Manager\Config(
$oauth_setting->client_id,
$oauth_setting->client_secret,
$oauth_setting->redirect_uri
);
return Socialite::driver('google')
->setConfig($google_config)
->with(['hd' => $oauth_setting->tenant]);
}
$config = [
'client_id' => $oauth_setting->client_id,
'client_secret' => $oauth_setting->client_secret,
'redirect' => $oauth_setting->redirect_uri,
];
$provider_class_map = [
'bitbucket' => \Laravel\Socialite\Two\BitbucketProvider::class,
'discord' => \SocialiteProviders\Discord\Provider::class,
'github' => \Laravel\Socialite\Two\GithubProvider::class,
'gitlab' => \Laravel\Socialite\Two\GitlabProvider::class,
'infomaniak' => \SocialiteProviders\Infomaniak\Provider::class,
];
$socialite = Socialite::buildProvider(
$provider_class_map[$provider],
$config
);
if ($provider == 'gitlab' && ! empty($oauth_setting->base_url)) {
$socialite->setHost($oauth_setting->base_url);
}
return $socialite;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/parsers.php | bootstrap/helpers/parsers.php | <?php
use App\Enums\ProxyTypes;
use App\Jobs\ServerFilesFromServerJob;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
use Visus\Cuid2\Cuid2;
/**
* Validates a Docker Compose YAML string for command injection vulnerabilities.
* This should be called BEFORE saving to database to prevent malicious data from being stored.
*
* @param string $composeYaml The raw Docker Compose YAML content
*
* @throws \Exception If the compose file contains command injection attempts
*/
function validateDockerComposeForInjection(string $composeYaml): void
{
try {
$parsed = Yaml::parse($composeYaml);
} catch (\Exception $e) {
throw new \Exception('Invalid YAML format: '.$e->getMessage(), 0, $e);
}
if (! is_array($parsed) || ! isset($parsed['services']) || ! is_array($parsed['services'])) {
throw new \Exception('Docker Compose file must contain a "services" section');
}
// Validate service names
foreach ($parsed['services'] as $serviceName => $serviceConfig) {
try {
validateShellSafePath($serviceName, 'service name');
} catch (\Exception $e) {
throw new \Exception(
'Invalid Docker Compose service name: '.$e->getMessage().
' Service names must not contain shell metacharacters.',
0,
$e
);
}
// Validate volumes in this service (both string and array formats)
if (isset($serviceConfig['volumes']) && is_array($serviceConfig['volumes'])) {
foreach ($serviceConfig['volumes'] as $volume) {
if (is_string($volume)) {
// String format: "source:target" or "source:target:mode"
validateVolumeStringForInjection($volume);
} elseif (is_array($volume)) {
// Array format: {type: bind, source: ..., target: ...}
if (isset($volume['source'])) {
$source = $volume['source'];
if (is_string($source)) {
// Allow env vars and env vars with defaults (validated in parseDockerVolumeString)
// Also allow env vars followed by safe path concatenation (e.g., ${VAR}/path)
$isSimpleEnvVar = preg_match('/^\$\{[a-zA-Z_][a-zA-Z0-9_]*\}$/', $source);
$isEnvVarWithDefault = preg_match('/^\$\{[^}]+:-[^}]*\}$/', $source);
$isEnvVarWithPath = preg_match('/^\$\{[a-zA-Z_][a-zA-Z0-9_]*\}[\/\w\.\-]*$/', $source);
if (! $isSimpleEnvVar && ! $isEnvVarWithDefault && ! $isEnvVarWithPath) {
try {
validateShellSafePath($source, 'volume source');
} catch (\Exception $e) {
throw new \Exception(
'Invalid Docker volume definition (array syntax): '.$e->getMessage().
' Please use safe path names without shell metacharacters.',
0,
$e
);
}
}
}
}
if (isset($volume['target'])) {
$target = $volume['target'];
if (is_string($target)) {
try {
validateShellSafePath($target, 'volume target');
} catch (\Exception $e) {
throw new \Exception(
'Invalid Docker volume definition (array syntax): '.$e->getMessage().
' Please use safe path names without shell metacharacters.',
0,
$e
);
}
}
}
}
}
}
}
}
/**
* Validates a Docker volume string (format: "source:target" or "source:target:mode")
*
* @param string $volumeString The volume string to validate
*
* @throws \Exception If the volume string contains command injection attempts
*/
function validateVolumeStringForInjection(string $volumeString): void
{
// Canonical parsing also validates and throws on unsafe input
parseDockerVolumeString($volumeString);
}
function parseDockerVolumeString(string $volumeString): array
{
$volumeString = trim($volumeString);
$source = null;
$target = null;
$mode = null;
// First, check if the source contains an environment variable with default value
// This needs to be done before counting colons because ${VAR:-value} contains a colon
$envVarPattern = '/^\$\{[^}]+:-[^}]*\}/';
$hasEnvVarWithDefault = false;
$envVarEndPos = 0;
if (preg_match($envVarPattern, $volumeString, $matches)) {
$hasEnvVarWithDefault = true;
$envVarEndPos = strlen($matches[0]);
}
// Count colons, but exclude those inside environment variables
$effectiveVolumeString = $volumeString;
if ($hasEnvVarWithDefault) {
// Temporarily replace the env var to count colons correctly
$effectiveVolumeString = substr($volumeString, $envVarEndPos);
$colonCount = substr_count($effectiveVolumeString, ':');
} else {
$colonCount = substr_count($volumeString, ':');
}
if ($colonCount === 0) {
// Named volume without target (unusual but valid)
// Example: "myvolume"
$source = $volumeString;
$target = $volumeString;
} elseif ($colonCount === 1) {
// Simple volume mapping
// Examples: "gitea:/data" or "./data:/app/data" or "${VAR:-default}:/data"
if ($hasEnvVarWithDefault) {
$source = substr($volumeString, 0, $envVarEndPos);
$remaining = substr($volumeString, $envVarEndPos);
if (strlen($remaining) > 0 && $remaining[0] === ':') {
$target = substr($remaining, 1);
} else {
$target = $remaining;
}
} else {
$parts = explode(':', $volumeString);
$source = $parts[0];
$target = $parts[1];
}
} elseif ($colonCount === 2) {
// Volume with mode OR Windows path OR env var with mode
// Handle env var with mode first
if ($hasEnvVarWithDefault) {
// ${VAR:-default}:/path:mode
$source = substr($volumeString, 0, $envVarEndPos);
$remaining = substr($volumeString, $envVarEndPos);
if (strlen($remaining) > 0 && $remaining[0] === ':') {
$remaining = substr($remaining, 1);
$lastColon = strrpos($remaining, ':');
if ($lastColon !== false) {
$possibleMode = substr($remaining, $lastColon + 1);
$validModes = ['ro', 'rw', 'z', 'Z', 'rslave', 'rprivate', 'rshared', 'slave', 'private', 'shared', 'cached', 'delegated', 'consistent'];
if (in_array($possibleMode, $validModes)) {
$mode = $possibleMode;
$target = substr($remaining, 0, $lastColon);
} else {
$target = $remaining;
}
} else {
$target = $remaining;
}
}
} elseif (preg_match('/^[A-Za-z]:/', $volumeString)) {
// Windows path as source (C:/, D:/, etc.)
// Find the second colon which is the real separator
$secondColon = strpos($volumeString, ':', 2);
if ($secondColon !== false) {
$source = substr($volumeString, 0, $secondColon);
$target = substr($volumeString, $secondColon + 1);
} else {
// Malformed, treat as is
$source = $volumeString;
$target = $volumeString;
}
} else {
// Not a Windows path, check for mode
$lastColon = strrpos($volumeString, ':');
$possibleMode = substr($volumeString, $lastColon + 1);
// Check if the last part is a valid Docker volume mode
$validModes = ['ro', 'rw', 'z', 'Z', 'rslave', 'rprivate', 'rshared', 'slave', 'private', 'shared', 'cached', 'delegated', 'consistent'];
if (in_array($possibleMode, $validModes)) {
// It's a mode
// Examples: "gitea:/data:ro" or "./data:/app/data:rw"
$mode = $possibleMode;
$volumeWithoutMode = substr($volumeString, 0, $lastColon);
$colonPos = strpos($volumeWithoutMode, ':');
if ($colonPos !== false) {
$source = substr($volumeWithoutMode, 0, $colonPos);
$target = substr($volumeWithoutMode, $colonPos + 1);
} else {
// Shouldn't happen for valid volume strings
$source = $volumeWithoutMode;
$target = $volumeWithoutMode;
}
} else {
// The last colon is part of the path
// For now, treat the first occurrence of : as the separator
$firstColon = strpos($volumeString, ':');
$source = substr($volumeString, 0, $firstColon);
$target = substr($volumeString, $firstColon + 1);
}
}
} else {
// More than 2 colons - likely Windows paths or complex cases
// Use a heuristic: find the most likely separator colon
// Look for patterns like "C:" at the beginning (Windows drive)
if (preg_match('/^[A-Za-z]:/', $volumeString)) {
// Windows path as source
// Find the next colon after the drive letter
$secondColon = strpos($volumeString, ':', 2);
if ($secondColon !== false) {
$source = substr($volumeString, 0, $secondColon);
$remaining = substr($volumeString, $secondColon + 1);
// Check if there's a mode at the end
$lastColon = strrpos($remaining, ':');
if ($lastColon !== false) {
$possibleMode = substr($remaining, $lastColon + 1);
$validModes = ['ro', 'rw', 'z', 'Z', 'rslave', 'rprivate', 'rshared', 'slave', 'private', 'shared', 'cached', 'delegated', 'consistent'];
if (in_array($possibleMode, $validModes)) {
$mode = $possibleMode;
$target = substr($remaining, 0, $lastColon);
} else {
$target = $remaining;
}
} else {
$target = $remaining;
}
} else {
// Malformed, treat as is
$source = $volumeString;
$target = $volumeString;
}
} else {
// Try to parse normally, treating first : as separator
$firstColon = strpos($volumeString, ':');
$source = substr($volumeString, 0, $firstColon);
$remaining = substr($volumeString, $firstColon + 1);
// Check for mode at the end
$lastColon = strrpos($remaining, ':');
if ($lastColon !== false) {
$possibleMode = substr($remaining, $lastColon + 1);
$validModes = ['ro', 'rw', 'z', 'Z', 'rslave', 'rprivate', 'rshared', 'slave', 'private', 'shared', 'cached', 'delegated', 'consistent'];
if (in_array($possibleMode, $validModes)) {
$mode = $possibleMode;
$target = substr($remaining, 0, $lastColon);
} else {
$target = $remaining;
}
} else {
$target = $remaining;
}
}
}
// Handle environment variable expansion in source
// Example: ${VOLUME_DB_PATH:-db} should extract default value if present
if ($source && preg_match('/^\$\{([^}]+)\}$/', $source, $matches)) {
$varContent = $matches[1];
// Check if there's a default value with :-
if (strpos($varContent, ':-') !== false) {
$parts = explode(':-', $varContent, 2);
$varName = $parts[0];
$defaultValue = isset($parts[1]) ? $parts[1] : '';
// If there's a non-empty default value, use it for source
if ($defaultValue !== '') {
$source = $defaultValue;
} else {
// Empty default value, keep the variable reference for env resolution
$source = '${'.$varName.'}';
}
}
// Otherwise keep the variable as-is for later expansion (no default value)
}
// Validate source path for command injection attempts
// We validate the final source value after environment variable processing
if ($source !== null) {
// Allow environment variables like ${VAR_NAME} or ${VAR}
// Also allow env vars followed by safe path concatenation (e.g., ${VAR}/path)
$sourceStr = is_string($source) ? $source : $source;
// Skip validation for simple environment variable references
// Pattern 1: ${WORD_CHARS} with no special characters inside
// Pattern 2: ${WORD_CHARS}/path/to/file (env var with path concatenation)
$isSimpleEnvVar = preg_match('/^\$\{[a-zA-Z_][a-zA-Z0-9_]*\}$/', $sourceStr);
$isEnvVarWithPath = preg_match('/^\$\{[a-zA-Z_][a-zA-Z0-9_]*\}[\/\w\.\-]*$/', $sourceStr);
if (! $isSimpleEnvVar && ! $isEnvVarWithPath) {
try {
validateShellSafePath($sourceStr, 'volume source');
} catch (\Exception $e) {
// Re-throw with more context about the volume string
throw new \Exception(
'Invalid Docker volume definition: '.$e->getMessage().
' Please use safe path names without shell metacharacters.'
);
}
}
}
// Also validate target path
if ($target !== null) {
$targetStr = is_string($target) ? $target : $target;
// Target paths in containers are typically absolute paths, so we validate them too
// but they're less likely to be dangerous since they're not used in host commands
// Still, defense in depth is important
try {
validateShellSafePath($targetStr, 'volume target');
} catch (\Exception $e) {
throw new \Exception(
'Invalid Docker volume definition: '.$e->getMessage().
' Please use safe path names without shell metacharacters.'
);
}
}
return [
'source' => $source !== null ? str($source) : null,
'target' => $target !== null ? str($target) : null,
'mode' => $mode !== null ? str($mode) : null,
];
}
function applicationParser(Application $resource, int $pull_request_id = 0, ?int $preview_id = null, ?string $commit = null): Collection
{
$uuid = data_get($resource, 'uuid');
$compose = data_get($resource, 'docker_compose_raw');
// Store original compose for later use to update docker_compose_raw with content removed
$originalCompose = $compose;
if (! $compose) {
return collect([]);
}
$pullRequestId = $pull_request_id;
$isPullRequest = $pullRequestId == 0 ? false : true;
$server = data_get($resource, 'destination.server');
$fileStorages = $resource->fileStorages();
try {
$yaml = Yaml::parse($compose);
} catch (\Exception) {
return collect([]);
}
$services = data_get($yaml, 'services', collect([]));
$topLevel = collect([
'volumes' => collect(data_get($yaml, 'volumes', [])),
'networks' => collect(data_get($yaml, 'networks', [])),
'configs' => collect(data_get($yaml, 'configs', [])),
'secrets' => collect(data_get($yaml, 'secrets', [])),
]);
// If there are predefined volumes, make sure they are not null
if ($topLevel->get('volumes')->count() > 0) {
$temp = collect([]);
foreach ($topLevel['volumes'] as $volumeName => $volume) {
if (is_null($volume)) {
continue;
}
$temp->put($volumeName, $volume);
}
$topLevel['volumes'] = $temp;
}
// Get the base docker network
$baseNetwork = collect([$uuid]);
if ($isPullRequest) {
$baseNetwork = collect(["{$uuid}-{$pullRequestId}"]);
}
$parsedServices = collect([]);
$allMagicEnvironments = collect([]);
foreach ($services as $serviceName => $service) {
// Validate service name for command injection
try {
validateShellSafePath($serviceName, 'service name');
} catch (\Exception $e) {
throw new \Exception(
'Invalid Docker Compose service name: '.$e->getMessage().
' Service names must not contain shell metacharacters.'
);
}
$magicEnvironments = collect([]);
$image = data_get_str($service, 'image');
$environment = collect(data_get($service, 'environment', []));
$buildArgs = collect(data_get($service, 'build.args', []));
$environment = $environment->merge($buildArgs);
$environment = collect(data_get($service, 'environment', []));
$buildArgs = collect(data_get($service, 'build.args', []));
$environment = $environment->merge($buildArgs);
// convert environment variables to one format
$environment = convertToKeyValueCollection($environment);
// Add Coolify defined environments
$allEnvironments = $resource->environment_variables()->get(['key', 'value']);
$allEnvironments = $allEnvironments->mapWithKeys(function ($item) {
return [$item['key'] => $item['value']];
});
// filter and add magic environments
foreach ($environment as $key => $value) {
// Get all SERVICE_ variables from keys and values
$key = str($key);
$value = str($value);
$regex = '/\$(\{?([a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)\}?)/';
preg_match_all($regex, $value, $valueMatches);
if (count($valueMatches[1]) > 0) {
foreach ($valueMatches[1] as $match) {
$match = replaceVariables($match);
if ($match->startsWith('SERVICE_')) {
if ($magicEnvironments->has($match->value())) {
continue;
}
$magicEnvironments->put($match->value(), '');
}
}
}
// Get magic environments where we need to preset the FQDN
// for example SERVICE_FQDN_APP_3000 (without a value)
if ($key->startsWith('SERVICE_FQDN_')) {
// SERVICE_FQDN_APP or SERVICE_FQDN_APP_3000
$parsed = parseServiceEnvironmentVariable($key->value());
$fqdnFor = $parsed['service_name'];
$port = $parsed['port'];
$fqdn = $resource->fqdn;
if (blank($resource->fqdn)) {
$fqdn = generateFqdn(server: $server, random: "$uuid", parserVersion: $resource->compose_parsing_version);
}
if ($value && get_class($value) === \Illuminate\Support\Stringable::class && $value->startsWith('/')) {
$path = $value->value();
if ($path !== '/') {
$fqdn = "$fqdn$path";
}
}
$fqdnWithPort = $fqdn;
if ($port) {
$fqdnWithPort = "$fqdn:$port";
}
if (is_null($resource->fqdn)) {
data_forget($resource, 'environment_variables');
data_forget($resource, 'environment_variables_preview');
$resource->fqdn = $fqdnWithPort;
$resource->save();
}
if (! $parsed['has_port']) {
$resource->environment_variables()->updateOrCreate([
'key' => $key->value(),
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $fqdn,
'is_preview' => false,
]);
}
if ($parsed['has_port']) {
$newKey = str($key)->beforeLast('_');
$resource->environment_variables()->updateOrCreate([
'key' => $newKey->value(),
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $fqdn,
'is_preview' => false,
]);
}
}
}
$allMagicEnvironments = $allMagicEnvironments->merge($magicEnvironments);
if ($magicEnvironments->count() > 0) {
// Generate Coolify environment variables
foreach ($magicEnvironments as $key => $value) {
$key = str($key);
$value = replaceVariables($value);
$command = parseCommandFromMagicEnvVariable($key);
if ($command->value() === 'FQDN' || $command->value() === 'URL') {
// ALWAYS create BOTH SERVICE_URL and SERVICE_FQDN pairs regardless of which one is in template
$parsed = parseServiceEnvironmentVariable($key->value());
$serviceName = $parsed['service_name'];
$port = $parsed['port'];
// Extract case-preserved service name from template
$strKey = str($key->value());
if ($parsed['has_port']) {
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceNamePreserved = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
} else {
$serviceNamePreserved = $strKey->after('SERVICE_FQDN_')->beforeLast('_')->value();
}
} else {
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceNamePreserved = $strKey->after('SERVICE_URL_')->value();
} else {
$serviceNamePreserved = $strKey->after('SERVICE_FQDN_')->value();
}
}
$originalServiceName = str($serviceName)->replace('_', '-')->value();
// Always normalize service names to match docker_compose_domains lookup
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
// Generate BOTH FQDN & URL
$fqdn = generateFqdn(server: $server, random: "$originalServiceName-$uuid", parserVersion: $resource->compose_parsing_version);
$url = generateUrl(server: $server, random: "$originalServiceName-$uuid");
// IMPORTANT: SERVICE_FQDN env vars should NOT contain scheme (host only)
// But $fqdn variable itself may contain scheme (used for database domain field)
// Strip scheme for environment variable values
$fqdnValueForEnv = str($fqdn)->after('://')->value();
// Append port if specified
$urlWithPort = $url;
$fqdnValueForEnvWithPort = $fqdnValueForEnv;
if ($port && is_numeric($port)) {
$urlWithPort = "$url:$port";
$fqdnValueForEnvWithPort = "$fqdnValueForEnv:$port";
}
// ALWAYS create base SERVICE_FQDN variable (host only, no scheme)
$resource->environment_variables()->firstOrCreate([
'key' => "SERVICE_FQDN_{$serviceNamePreserved}",
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $fqdnValueForEnv,
'is_preview' => false,
]);
// ALWAYS create base SERVICE_URL variable (with scheme)
$resource->environment_variables()->firstOrCreate([
'key' => "SERVICE_URL_{$serviceNamePreserved}",
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $url,
'is_preview' => false,
]);
// If port-specific, ALSO create port-specific pairs
if ($parsed['has_port'] && $port) {
$resource->environment_variables()->firstOrCreate([
'key' => "SERVICE_FQDN_{$serviceNamePreserved}_{$port}",
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $fqdnValueForEnvWithPort,
'is_preview' => false,
]);
$resource->environment_variables()->firstOrCreate([
'key' => "SERVICE_URL_{$serviceNamePreserved}_{$port}",
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $urlWithPort,
'is_preview' => false,
]);
}
if ($resource->build_pack === 'dockercompose') {
// Check if a service with this name actually exists
$serviceExists = false;
foreach ($services as $serviceNameKey => $service) {
$transformedServiceName = str($serviceNameKey)->replace('-', '_')->replace('.', '_')->value();
if ($transformedServiceName === $serviceName) {
$serviceExists = true;
break;
}
}
// Only add domain if the service exists
if ($serviceExists) {
$domains = collect(json_decode(data_get($resource, 'docker_compose_domains'))) ?? collect([]);
$domainExists = data_get($domains->get($serviceName), 'domain');
// Update domain using URL with port if applicable
$domainValue = $port ? $urlWithPort : $url;
if (is_null($domainExists)) {
$domains->put($serviceName, [
'domain' => $domainValue,
]);
$resource->docker_compose_domains = $domains->toJson();
$resource->save();
}
}
}
} else {
$value = generateEnvValue($command, $resource);
$resource->environment_variables()->firstOrCreate([
'key' => $key->value(),
'resourceable_type' => get_class($resource),
'resourceable_id' => $resource->id,
], [
'value' => $value,
'is_preview' => false,
]);
}
}
}
}
// generate SERVICE_NAME variables for docker compose services
$serviceNameEnvironments = collect([]);
if ($resource->build_pack === 'dockercompose') {
$serviceNameEnvironments = generateDockerComposeServiceName($services, $pullRequestId);
}
// Parse the rest of the services
foreach ($services as $serviceName => $service) {
$image = data_get_str($service, 'image');
$restart = data_get_str($service, 'restart', RESTART_MODE);
$logging = data_get($service, 'logging');
if ($server->isLogDrainEnabled()) {
if ($resource->isLogDrainEnabled()) {
$logging = generate_fluentd_configuration();
}
}
$volumes = collect(data_get($service, 'volumes', []));
$networks = collect(data_get($service, 'networks', []));
$use_network_mode = data_get($service, 'network_mode') !== null;
$depends_on = collect(data_get($service, 'depends_on', []));
$labels = collect(data_get($service, 'labels', []));
if ($labels->count() > 0) {
if (isAssociativeArray($labels)) {
$newLabels = collect([]);
$labels->each(function ($value, $key) use ($newLabels) {
$newLabels->push("$key=$value");
});
$labels = $newLabels;
}
}
$environment = collect(data_get($service, 'environment', []));
$ports = collect(data_get($service, 'ports', []));
$buildArgs = collect(data_get($service, 'build.args', []));
$environment = $environment->merge($buildArgs);
$environment = convertToKeyValueCollection($environment);
$coolifyEnvironments = collect([]);
$isDatabase = isDatabaseImage($image, $service);
$volumesParsed = collect([]);
$baseName = generateApplicationContainerName(
application: $resource,
pull_request_id: $pullRequestId
);
$containerName = "$serviceName-$baseName";
$predefinedPort = null;
$originalResource = $resource;
if ($volumes->count() > 0) {
foreach ($volumes as $index => $volume) {
$type = null;
$source = null;
$target = null;
$content = null;
$isDirectory = false;
if (is_string($volume)) {
$parsed = parseDockerVolumeString($volume);
$source = $parsed['source'];
$target = $parsed['target'];
// Mode is available in $parsed['mode'] if needed
$foundConfig = $fileStorages->whereMountPath($target)->first();
if (sourceIsLocal($source)) {
$type = str('bind');
if ($foundConfig) {
$contentNotNull_temp = data_get($foundConfig, 'content');
if ($contentNotNull_temp) {
$content = $contentNotNull_temp;
}
$isDirectory = data_get($foundConfig, 'is_directory');
} else {
// By default, we cannot determine if the bind is a directory or not, so we set it to directory
$isDirectory = true;
}
} else {
$type = str('volume');
}
} elseif (is_array($volume)) {
$type = data_get_str($volume, 'type');
$source = data_get_str($volume, 'source');
$target = data_get_str($volume, 'target');
$content = data_get($volume, 'content');
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/docker.php | bootstrap/helpers/docker.php | <?php
use App\Enums\ProxyTypes;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\Server;
use App\Models\ServiceApplication;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
use Visus\Cuid2\Cuid2;
function getCurrentApplicationContainerStatus(Server $server, int $id, ?int $pullRequestId = null, ?bool $includePullrequests = false): Collection
{
$containers = collect([]);
if (! $server->isSwarm()) {
$containers = instant_remote_process(["docker ps -a --filter='label=coolify.applicationId={$id}' --format '{{json .}}' "], $server);
$containers = format_docker_command_output_to_json($containers);
$containers = $containers->map(function ($container) use ($pullRequestId, $includePullrequests) {
$labels = data_get($container, 'Labels');
$containerName = data_get($container, 'Names');
$hasPrLabel = str($labels)->contains('coolify.pullRequestId=');
$prLabelValue = null;
if ($hasPrLabel) {
preg_match('/coolify\.pullRequestId=(\d+)/', $labels, $matches);
$prLabelValue = $matches[1] ?? null;
}
// Treat pullRequestId=0 or missing label as base deployment (convention: 0 = no PR)
$isBaseDeploy = ! $hasPrLabel || (int) $prLabelValue === 0;
// If we're looking for a specific PR and this is a base deployment, exclude it
if ($pullRequestId !== null && $pullRequestId !== 0 && $isBaseDeploy) {
return null;
}
// If this is a base deployment, include it when not filtering for PRs
if ($isBaseDeploy) {
return $container;
}
if ($includePullrequests) {
return $container;
}
if ($pullRequestId !== null && $pullRequestId !== 0 && str($labels)->contains("coolify.pullRequestId={$pullRequestId}")) {
return $container;
}
return null;
});
$filtered = $containers->filter();
return $filtered;
}
return $containers;
}
function getCurrentServiceContainerStatus(Server $server, int $id): Collection
{
$containers = collect([]);
if (! $server->isSwarm()) {
$containers = instant_remote_process(["docker ps -a --filter='label=coolify.serviceId={$id}' --format '{{json .}}' "], $server);
$containers = format_docker_command_output_to_json($containers);
return $containers->filter();
}
return $containers;
}
function format_docker_command_output_to_json($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
if (count($outputLines) === 1) {
$outputLines = collect($outputLines[0]);
} else {
$outputLines = collect($outputLines);
}
try {
return $outputLines
->reject(fn ($line) => empty($line))
->map(fn ($outputLine) => json_decode($outputLine, true, flags: JSON_THROW_ON_ERROR));
} catch (\Throwable) {
return collect([]);
}
}
function format_docker_labels_to_json(string|array $rawOutput): Collection
{
if (is_array($rawOutput)) {
return collect($rawOutput);
}
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->map(function ($outputLine) {
$outputArray = explode(',', $outputLine);
return collect($outputArray)
->map(function ($outputLine) {
return explode('=', $outputLine);
})
->mapWithKeys(function ($outputLine) {
return [$outputLine[0] => $outputLine[1]];
});
})[0];
}
function format_docker_envs_to_json($rawOutput)
{
try {
$outputLines = json_decode($rawOutput, true, flags: JSON_THROW_ON_ERROR);
return collect(data_get($outputLines[0], 'Config.Env', []))->mapWithKeys(function ($env) {
$env = explode('=', $env, 2);
return [$env[0] => $env[1]];
});
} catch (\Throwable) {
return collect([]);
}
}
function checkMinimumDockerEngineVersion($dockerVersion)
{
$majorDockerVersion = str($dockerVersion)->before('.')->value();
$requiredDockerVersion = str(config('constants.docker.minimum_required_version'))->before('.')->value();
if ($majorDockerVersion < $requiredDockerVersion) {
$dockerVersion = null;
}
return $dockerVersion;
}
function executeInDocker(string $containerId, string $command)
{
return "docker exec {$containerId} bash -c '{$command}'";
// return "docker exec {$this->deployment_uuid} bash -c '{$command} |& tee -a /proc/1/fd/1; [ \$PIPESTATUS -eq 0 ] || exit \$PIPESTATUS'";
}
function getContainerStatus(Server $server, string $container_id, bool $all_data = false, bool $throwError = false)
{
if ($server->isSwarm()) {
$container = instant_remote_process(["docker service ls --filter 'name={$container_id}' --format '{{json .}}' "], $server, $throwError);
} else {
$container = instant_remote_process(["docker inspect --format '{{json .}}' {$container_id}"], $server, $throwError);
}
if (! $container) {
return 'exited';
}
$container = format_docker_command_output_to_json($container);
if ($container->isEmpty()) {
return 'exited';
}
if ($all_data) {
return $container[0];
}
if ($server->isSwarm()) {
$replicas = data_get($container[0], 'Replicas');
$replicas = explode('/', $replicas);
$active = (int) $replicas[0];
$total = (int) $replicas[1];
if ($active === $total) {
return 'running';
} else {
return 'starting';
}
} else {
return data_get($container[0], 'State.Status', 'exited');
}
}
function generateApplicationContainerName(Application $application, $pull_request_id = 0)
{
// TODO: refactor generateApplicationContainerName, we do not need $application and $pull_request_id
$consistent_container_name = $application->settings->is_consistent_container_name_enabled;
$now = now()->format('Hisu');
if ($pull_request_id !== 0 && $pull_request_id !== null) {
return $application->uuid.'-pr-'.$pull_request_id;
} else {
if ($consistent_container_name) {
return $application->uuid;
}
return $application->uuid.'-'.$now;
}
}
function get_port_from_dockerfile($dockerfile): ?int
{
$dockerfile_array = explode("\n", $dockerfile);
$found_exposed_port = null;
foreach ($dockerfile_array as $line) {
$line_str = str($line)->trim();
if ($line_str->startsWith('EXPOSE')) {
$found_exposed_port = $line_str->replace('EXPOSE', '')->trim();
break;
}
}
if ($found_exposed_port) {
return (int) $found_exposed_port->value();
}
return null;
}
function defaultDatabaseLabels($database)
{
$labels = collect([]);
$labels->push('coolify.managed=true');
$labels->push('coolify.type=database');
$labels->push('coolify.databaseId='.$database->id);
$labels->push('coolify.resourceName='.Str::slug($database->name));
$labels->push('coolify.serviceName='.Str::slug($database->name));
$labels->push('coolify.projectName='.Str::slug($database->project()->name));
$labels->push('coolify.environmentName='.Str::slug($database->environment->name));
$labels->push('coolify.database.subType='.$database->type());
return $labels;
}
function defaultLabels($id, $name, string $projectName, string $resourceName, string $environment, $pull_request_id = 0, string $type = 'application', $subType = null, $subId = null, $subName = null)
{
$labels = collect([]);
$labels->push('coolify.managed=true');
$labels->push('coolify.version='.config('constants.coolify.version'));
$labels->push('coolify.'.$type.'Id='.$id);
$labels->push("coolify.type=$type");
$labels->push('coolify.name='.$name);
$labels->push('coolify.resourceName='.Str::slug($resourceName));
$labels->push('coolify.projectName='.Str::slug($projectName));
$labels->push('coolify.serviceName='.Str::slug($subName ?? $resourceName));
$labels->push('coolify.environmentName='.Str::slug($environment));
$labels->push('coolify.pullRequestId='.$pull_request_id);
if ($type === 'service') {
$subId && $labels->push('coolify.service.subId='.$subId);
$subType && $labels->push('coolify.service.subType='.$subType);
$subName && $labels->push('coolify.service.subName='.Str::slug($subName));
}
return $labels;
}
function generateServiceSpecificFqdns(ServiceApplication|Application $resource)
{
if ($resource->getMorphClass() === \App\Models\ServiceApplication::class) {
$uuid = data_get($resource, 'uuid');
$server = data_get($resource, 'service.server');
$environment_variables = data_get($resource, 'service.environment_variables');
$type = $resource->serviceType();
} elseif ($resource->getMorphClass() === \App\Models\Application::class) {
$uuid = data_get($resource, 'uuid');
$server = data_get($resource, 'destination.server');
$environment_variables = data_get($resource, 'environment_variables');
$type = $resource->serviceType();
}
if (is_null($server) || is_null($type)) {
return collect([]);
}
$variables = collect($environment_variables);
$payload = collect([]);
switch ($type) {
case $type?->contains('minio'):
$MINIO_BROWSER_REDIRECT_URL = $variables->where('key', 'MINIO_BROWSER_REDIRECT_URL')->first();
$MINIO_SERVER_URL = $variables->where('key', 'MINIO_SERVER_URL')->first();
if (is_null($MINIO_BROWSER_REDIRECT_URL) || is_null($MINIO_SERVER_URL)) {
return collect([]);
}
if (str($MINIO_BROWSER_REDIRECT_URL->value ?? '')->isEmpty()) {
$MINIO_BROWSER_REDIRECT_URL->update([
'value' => generateUrl(server: $server, random: 'console-'.$uuid, forceHttps: true),
]);
}
if (str($MINIO_SERVER_URL->value ?? '')->isEmpty()) {
$MINIO_SERVER_URL->update([
'value' => generateUrl(server: $server, random: 'minio-'.$uuid, forceHttps: true),
]);
}
$payload = collect([
$MINIO_BROWSER_REDIRECT_URL->value.':9001',
$MINIO_SERVER_URL->value.':9000',
]);
break;
case $type?->contains('logto'):
$LOGTO_ENDPOINT = $variables->where('key', 'LOGTO_ENDPOINT')->first();
$LOGTO_ADMIN_ENDPOINT = $variables->where('key', 'LOGTO_ADMIN_ENDPOINT')->first();
if (is_null($LOGTO_ENDPOINT) || is_null($LOGTO_ADMIN_ENDPOINT)) {
return collect([]);
}
if (str($LOGTO_ENDPOINT->value ?? '')->isEmpty()) {
$LOGTO_ENDPOINT->update([
'value' => generateUrl(server: $server, random: 'logto-'.$uuid),
]);
}
if (str($LOGTO_ADMIN_ENDPOINT->value ?? '')->isEmpty()) {
$LOGTO_ADMIN_ENDPOINT->update([
'value' => generateUrl(server: $server, random: 'logto-admin-'.$uuid),
]);
}
$payload = collect([
$LOGTO_ENDPOINT->value.':3001',
$LOGTO_ADMIN_ENDPOINT->value.':3002',
]);
break;
case $type?->contains('garage'):
$GARAGE_S3_API_URL = $variables->where('key', 'GARAGE_S3_API_URL')->first();
$GARAGE_WEB_URL = $variables->where('key', 'GARAGE_WEB_URL')->first();
$GARAGE_ADMIN_URL = $variables->where('key', 'GARAGE_ADMIN_URL')->first();
if (is_null($GARAGE_S3_API_URL) || is_null($GARAGE_WEB_URL) || is_null($GARAGE_ADMIN_URL)) {
return collect([]);
}
if (str($GARAGE_S3_API_URL->value ?? '')->isEmpty()) {
$GARAGE_S3_API_URL->update([
'value' => generateUrl(server: $server, random: 's3-'.$uuid, forceHttps: true),
]);
}
if (str($GARAGE_WEB_URL->value ?? '')->isEmpty()) {
$GARAGE_WEB_URL->update([
'value' => generateUrl(server: $server, random: 'web-'.$uuid, forceHttps: true),
]);
}
if (str($GARAGE_ADMIN_URL->value ?? '')->isEmpty()) {
$GARAGE_ADMIN_URL->update([
'value' => generateUrl(server: $server, random: 'admin-'.$uuid, forceHttps: true),
]);
}
$payload = collect([
$GARAGE_S3_API_URL->value.':3900',
$GARAGE_WEB_URL->value.':3902',
$GARAGE_ADMIN_URL->value.':3903',
]);
break;
}
return $payload;
}
function fqdnLabelsForCaddy(string $network, string $uuid, Collection $domains, bool $is_force_https_enabled = false, $onlyPort = null, ?Collection $serviceLabels = null, ?bool $is_gzip_enabled = true, ?bool $is_stripprefix_enabled = true, ?string $service_name = null, ?string $image = null, string $redirect_direction = 'both', ?string $predefinedPort = null, bool $is_http_basic_auth_enabled = false, ?string $http_basic_auth_username = null, ?string $http_basic_auth_password = null)
{
$labels = collect([]);
if ($serviceLabels) {
$labels->push("caddy_ingress_network={$uuid}");
} else {
$labels->push("caddy_ingress_network={$network}");
}
$is_http_basic_auth_enabled = $is_http_basic_auth_enabled && $http_basic_auth_username !== null && $http_basic_auth_password !== null;
if ($is_http_basic_auth_enabled) {
$hashedPassword = password_hash($http_basic_auth_password, PASSWORD_BCRYPT, ['cost' => 10]);
}
foreach ($domains as $loop => $domain) {
$url = Url::fromString($domain);
$host = $url->getHost();
$path = $url->getPath();
$host_without_www = str($host)->replace('www.', '');
$schema = $url->getScheme();
$port = $url->getPort();
$handle = 'handle_path';
if (! $is_stripprefix_enabled) {
$handle = 'handle';
}
if (is_null($port) && ! is_null($onlyPort)) {
$port = $onlyPort;
}
if (is_null($port) && $predefinedPort) {
$port = $predefinedPort;
}
$labels->push("caddy_{$loop}={$schema}://{$host}");
$labels->push("caddy_{$loop}.header=-Server");
$labels->push("caddy_{$loop}.try_files={path} /index.html /index.php");
if ($port) {
$labels->push("caddy_{$loop}.{$handle}.{$loop}_reverse_proxy={{upstreams $port}}");
} else {
$labels->push("caddy_{$loop}.{$handle}.{$loop}_reverse_proxy={{upstreams}}");
}
$labels->push("caddy_{$loop}.{$handle}={$path}*");
if ($is_gzip_enabled) {
$labels->push("caddy_{$loop}.encode=zstd gzip");
}
if ($redirect_direction === 'www' && ! str($host)->startsWith('www.')) {
$labels->push("caddy_{$loop}.redir={$schema}://www.{$host}{uri}");
}
if ($redirect_direction === 'non-www' && str($host)->startsWith('www.')) {
$labels->push("caddy_{$loop}.redir={$schema}://{$host_without_www}{uri}");
}
if ($is_http_basic_auth_enabled) {
$labels->push("caddy_{$loop}.basicauth.{$http_basic_auth_username}=\"{$hashedPassword}\"");
}
}
return $labels->sort();
}
function fqdnLabelsForTraefik(string $uuid, Collection $domains, bool $is_force_https_enabled = false, $onlyPort = null, ?Collection $serviceLabels = null, ?bool $is_gzip_enabled = true, ?bool $is_stripprefix_enabled = true, ?string $service_name = null, bool $generate_unique_uuid = false, ?string $image = null, string $redirect_direction = 'both', bool $is_http_basic_auth_enabled = false, ?string $http_basic_auth_username = null, ?string $http_basic_auth_password = null)
{
$labels = collect([]);
$labels->push('traefik.enable=true');
if ($is_gzip_enabled) {
$labels->push('traefik.http.middlewares.gzip.compress=true');
}
$labels->push('traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https');
$is_http_basic_auth_enabled = $is_http_basic_auth_enabled && $http_basic_auth_username !== null && $http_basic_auth_password !== null;
$http_basic_auth_label = "http-basic-auth-{$uuid}";
if ($is_http_basic_auth_enabled) {
$hashedPassword = password_hash($http_basic_auth_password, PASSWORD_BCRYPT, ['cost' => 10]);
}
if ($is_http_basic_auth_enabled) {
$labels->push("traefik.http.middlewares.{$http_basic_auth_label}.basicauth.users={$http_basic_auth_username}:{$hashedPassword}");
}
$middlewares_from_labels = collect([]);
if ($serviceLabels) {
$middlewares_from_labels = $serviceLabels->map(function ($item) {
// Handle array values from YAML parsing (e.g., "traefik.enable: true" becomes an array)
if (is_array($item)) {
// Convert array to string format "key=value"
$key = collect($item)->keys()->first();
$value = collect($item)->values()->first();
$item = "$key=$value";
}
if (! is_string($item)) {
return null;
}
if (preg_match('/traefik\.http\.middlewares\.(.*?)(\.|$)/', $item, $matches)) {
return $matches[1];
}
if (preg_match('/coolify\.traefik\.middlewares=(.*)/', $item, $matches)) {
return explode(',', $matches[1]);
}
return null;
})->flatten()
->filter()
->unique();
}
foreach ($domains as $loop => $domain) {
try {
if ($generate_unique_uuid) {
$uuid = new Cuid2;
}
$url = Url::fromString($domain);
$host = $url->getHost();
$path = $url->getPath();
$schema = $url->getScheme();
$port = $url->getPort();
if (is_null($port) && ! is_null($onlyPort)) {
$port = $onlyPort;
}
$http_label = "http-{$loop}-{$uuid}";
$https_label = "https-{$loop}-{$uuid}";
if ($service_name) {
$http_label = "http-{$loop}-{$uuid}-{$service_name}";
$https_label = "https-{$loop}-{$uuid}-{$service_name}";
}
if (str($image)->contains('ghost')) {
$labels->push("traefik.http.middlewares.redir-ghost-{$uuid}.redirectregex.regex=^{$path}/(.*)");
$labels->push("traefik.http.middlewares.redir-ghost-{$uuid}.redirectregex.replacement=/$1");
$labels->push("caddy_{$loop}.handle_path.{$loop}_redir-ghost-{$uuid}.handler=rewrite");
$labels->push("caddy_{$loop}.handle_path.{$loop}_redir-ghost-{$uuid}.rewrite.regexp=^{$path}/(.*)");
$labels->push("caddy_{$loop}.handle_path.{$loop}_redir-ghost-{$uuid}.rewrite.replacement=/$1");
}
$to_www_name = "{$loop}-{$uuid}-to-www";
$to_non_www_name = "{$loop}-{$uuid}-to-non-www";
$redirect_to_non_www = [
"traefik.http.middlewares.{$to_non_www_name}.redirectregex.regex=^(http|https)://www\.(.+)",
"traefik.http.middlewares.{$to_non_www_name}.redirectregex.replacement=\${1}://\${2}",
"traefik.http.middlewares.{$to_non_www_name}.redirectregex.permanent=false",
];
$redirect_to_www = [
"traefik.http.middlewares.{$to_www_name}.redirectregex.regex=^(http|https)://(?:www\.)?(.+)",
"traefik.http.middlewares.{$to_www_name}.redirectregex.replacement=\${1}://www.\${2}",
"traefik.http.middlewares.{$to_www_name}.redirectregex.permanent=false",
];
if ($schema === 'https') {
// Set labels for https
$labels->push("traefik.http.routers.{$https_label}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)");
$labels->push("traefik.http.routers.{$https_label}.entryPoints=https");
if ($port) {
$labels->push("traefik.http.routers.{$https_label}.service={$https_label}");
$labels->push("traefik.http.services.{$https_label}.loadbalancer.server.port=$port");
}
if ($path !== '/') {
// Middleware handling
$middlewares = collect([]);
if ($is_stripprefix_enabled && ! str($image)->contains('ghost')) {
$labels->push("traefik.http.middlewares.{$https_label}-stripprefix.stripprefix.prefixes={$path}");
$middlewares->push("{$https_label}-stripprefix");
}
if ($is_gzip_enabled) {
$middlewares->push('gzip');
}
if (str($image)->contains('ghost')) {
$middlewares->push("redir-ghost-{$uuid}");
}
if ($redirect_direction === 'non-www' && str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_non_www);
$middlewares->push($to_non_www_name);
}
if ($redirect_direction === 'www' && ! str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_www);
$middlewares->push($to_www_name);
}
if ($is_http_basic_auth_enabled) {
$middlewares->push($http_basic_auth_label);
}
$middlewares_from_labels->each(function ($middleware_name) use ($middlewares) {
$middlewares->push($middleware_name);
});
if ($middlewares->isNotEmpty()) {
$middlewares = $middlewares->join(',');
$labels->push("traefik.http.routers.{$https_label}.middlewares={$middlewares}");
}
} else {
$middlewares = collect([]);
if ($is_gzip_enabled) {
$middlewares->push('gzip');
}
if (str($image)->contains('ghost')) {
$middlewares->push("redir-ghost-{$uuid}");
}
if ($redirect_direction === 'non-www' && str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_non_www);
$middlewares->push($to_non_www_name);
}
if ($redirect_direction === 'www' && ! str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_www);
$middlewares->push($to_www_name);
}
if ($is_http_basic_auth_enabled) {
$middlewares->push($http_basic_auth_label);
}
$middlewares_from_labels->each(function ($middleware_name) use ($middlewares) {
$middlewares->push($middleware_name);
});
if ($middlewares->isNotEmpty()) {
$middlewares = $middlewares->join(',');
$labels->push("traefik.http.routers.{$https_label}.middlewares={$middlewares}");
}
}
$labels->push("traefik.http.routers.{$https_label}.tls=true");
$labels->push("traefik.http.routers.{$https_label}.tls.certresolver=letsencrypt");
// Set labels for http (redirect to https)
$labels->push("traefik.http.routers.{$http_label}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)");
$labels->push("traefik.http.routers.{$http_label}.entryPoints=http");
if ($port) {
$labels->push("traefik.http.services.{$http_label}.loadbalancer.server.port=$port");
$labels->push("traefik.http.routers.{$http_label}.service={$http_label}");
}
if ($is_force_https_enabled) {
$labels->push("traefik.http.routers.{$http_label}.middlewares=redirect-to-https");
}
} else {
// Set labels for http
$labels->push("traefik.http.routers.{$http_label}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)");
$labels->push("traefik.http.routers.{$http_label}.entryPoints=http");
if ($port) {
$labels->push("traefik.http.services.{$http_label}.loadbalancer.server.port=$port");
$labels->push("traefik.http.routers.{$http_label}.service={$http_label}");
}
if ($path !== '/') {
$middlewares = collect([]);
if ($is_stripprefix_enabled && ! str($image)->contains('ghost')) {
$labels->push("traefik.http.middlewares.{$http_label}-stripprefix.stripprefix.prefixes={$path}");
$middlewares->push("{$http_label}-stripprefix");
}
if ($is_gzip_enabled) {
$middlewares->push('gzip');
}
if (str($image)->contains('ghost')) {
$middlewares->push("redir-ghost-{$uuid}");
}
if ($redirect_direction === 'non-www' && str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_non_www);
$middlewares->push($to_non_www_name);
}
if ($redirect_direction === 'www' && ! str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_www);
$middlewares->push($to_www_name);
}
if ($is_http_basic_auth_enabled) {
$middlewares->push($http_basic_auth_label);
}
$middlewares_from_labels->each(function ($middleware_name) use ($middlewares) {
$middlewares->push($middleware_name);
});
if ($middlewares->isNotEmpty()) {
$middlewares = $middlewares->join(',');
$labels->push("traefik.http.routers.{$http_label}.middlewares={$middlewares}");
}
} else {
$middlewares = collect([]);
if ($is_gzip_enabled) {
$middlewares->push('gzip');
}
if (str($image)->contains('ghost')) {
$middlewares->push("redir-ghost-{$uuid}");
}
if ($redirect_direction === 'non-www' && str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_non_www);
$middlewares->push($to_non_www_name);
}
if ($redirect_direction === 'www' && ! str($host)->startsWith('www.')) {
$labels = $labels->merge($redirect_to_www);
$middlewares->push($to_www_name);
}
if ($is_http_basic_auth_enabled) {
$middlewares->push($http_basic_auth_label);
}
$middlewares_from_labels->each(function ($middleware_name) use ($middlewares) {
$middlewares->push($middleware_name);
});
if ($middlewares->isNotEmpty()) {
$middlewares = $middlewares->join(',');
$labels->push("traefik.http.routers.{$http_label}.middlewares={$middlewares}");
}
}
}
} catch (\Throwable) {
continue;
}
}
return $labels->sort();
}
function generateLabelsApplication(Application $application, ?ApplicationPreview $preview = null): array
{
$ports = $application->settings->is_static ? [80] : $application->ports_exposes_array;
$onlyPort = null;
if (count($ports) > 0) {
$onlyPort = $ports[0];
}
$pull_request_id = data_get($preview, 'pull_request_id', 0);
$appUuid = $application->uuid;
if ($pull_request_id !== 0) {
$appUuid = $appUuid.'-pr-'.$pull_request_id;
}
$labels = collect([]);
if ($pull_request_id === 0) {
if ($application->fqdn) {
$domains = str(data_get($application, 'fqdn'))->explode(',');
$shouldGenerateLabelsExactly = $application->destination->server->settings->generate_exact_labels;
if ($shouldGenerateLabelsExactly) {
switch ($application->destination->server->proxyType()) {
case ProxyTypes::TRAEFIK->value:
$labels = $labels->merge(fqdnLabelsForTraefik(
uuid: $appUuid,
domains: $domains,
onlyPort: $onlyPort,
is_force_https_enabled: $application->isForceHttpsEnabled(),
is_gzip_enabled: $application->isGzipEnabled(),
is_stripprefix_enabled: $application->isStripprefixEnabled(),
redirect_direction: $application->redirect,
is_http_basic_auth_enabled: $application->is_http_basic_auth_enabled,
http_basic_auth_username: $application->http_basic_auth_username,
http_basic_auth_password: $application->http_basic_auth_password,
));
break;
case ProxyTypes::CADDY->value:
$labels = $labels->merge(fqdnLabelsForCaddy(
network: $application->destination->network,
uuid: $appUuid,
domains: $domains,
onlyPort: $onlyPort,
is_force_https_enabled: $application->isForceHttpsEnabled(),
is_gzip_enabled: $application->isGzipEnabled(),
is_stripprefix_enabled: $application->isStripprefixEnabled(),
redirect_direction: $application->redirect,
is_http_basic_auth_enabled: $application->is_http_basic_auth_enabled,
http_basic_auth_username: $application->http_basic_auth_username,
http_basic_auth_password: $application->http_basic_auth_password,
));
break;
}
} else {
$labels = $labels->merge(fqdnLabelsForTraefik(
uuid: $appUuid,
domains: $domains,
onlyPort: $onlyPort,
is_force_https_enabled: $application->isForceHttpsEnabled(),
is_gzip_enabled: $application->isGzipEnabled(),
is_stripprefix_enabled: $application->isStripprefixEnabled(),
redirect_direction: $application->redirect,
is_http_basic_auth_enabled: $application->is_http_basic_auth_enabled,
http_basic_auth_username: $application->http_basic_auth_username,
http_basic_auth_password: $application->http_basic_auth_password,
));
$labels = $labels->merge(fqdnLabelsForCaddy(
network: $application->destination->network,
uuid: $appUuid,
domains: $domains,
onlyPort: $onlyPort,
is_force_https_enabled: $application->isForceHttpsEnabled(),
is_gzip_enabled: $application->isGzipEnabled(),
is_stripprefix_enabled: $application->isStripprefixEnabled(),
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/proxy.php | bootstrap/helpers/proxy.php | <?php
use App\Actions\Proxy\SaveProxyConfiguration;
use App\Enums\ProxyTypes;
use App\Models\Application;
use App\Models\Server;
use Symfony\Component\Yaml\Yaml;
/**
* Check if a network name is a Docker predefined system network.
* These networks cannot be created, modified, or managed by docker network commands.
*
* @param string $network Network name to check
* @return bool True if it's a predefined network that should be skipped
*/
function isDockerPredefinedNetwork(string $network): bool
{
// Only filter 'default' and 'host' to match existing codebase patterns
// See: bootstrap/helpers/parsers.php:891, bootstrap/helpers/shared.php:689,748
return in_array($network, ['default', 'host'], true);
}
function collectProxyDockerNetworksByServer(Server $server)
{
if (! $server->isFunctional()) {
return collect();
}
$proxyType = $server->proxyType();
if (is_null($proxyType) || $proxyType === 'NONE') {
return collect();
}
$networks = instant_remote_process(['docker inspect --format="{{json .NetworkSettings.Networks }}" coolify-proxy'], $server, false);
return collect($networks)->map(function ($network) {
return collect(json_decode($network))->keys();
})->flatten()->unique();
}
function collectDockerNetworksByServer(Server $server)
{
$allNetworks = collect([]);
if ($server->isSwarm()) {
$networks = collect($server->swarmDockers)->map(function ($docker) {
return $docker['network'];
});
} else {
// Standalone networks
$networks = collect($server->standaloneDockers)->map(function ($docker) {
return $docker['network'];
});
}
$allNetworks = $allNetworks->merge($networks);
// Service networks
foreach ($server->services()->get() as $service) {
if ($service->isRunning()) {
$networks->push($service->networks());
}
$allNetworks->push($service->networks());
}
// Docker compose based apps
$docker_compose_apps = $server->dockerComposeBasedApplications();
foreach ($docker_compose_apps as $app) {
if ($app->isRunning()) {
$networks->push($app->uuid);
}
$allNetworks->push($app->uuid);
}
// Docker compose based preview deployments
$docker_compose_previews = $server->dockerComposeBasedPreviewDeployments();
foreach ($docker_compose_previews as $preview) {
if (! $preview->isRunning()) {
continue;
}
$pullRequestId = $preview->pull_request_id;
$applicationId = $preview->application_id;
$application = Application::find($applicationId);
if (! $application) {
continue;
}
$network = "{$application->uuid}-{$pullRequestId}";
$networks->push($network);
$allNetworks->push($network);
}
$networks = collect($networks)->flatten()->unique()->filter(function ($network) {
return ! isDockerPredefinedNetwork($network);
});
$allNetworks = $allNetworks->flatten()->unique()->filter(function ($network) {
return ! isDockerPredefinedNetwork($network);
});
if ($server->isSwarm()) {
if ($networks->count() === 0) {
$networks = collect(['coolify-overlay']);
$allNetworks = collect(['coolify-overlay']);
}
} else {
if ($networks->count() === 0) {
$networks = collect(['coolify']);
$allNetworks = collect(['coolify']);
}
}
return [
'networks' => $networks,
'allNetworks' => $allNetworks,
];
}
function connectProxyToNetworks(Server $server)
{
['networks' => $networks] = collectDockerNetworksByServer($server);
if ($server->isSwarm()) {
$commands = $networks->map(function ($network) {
return [
"docker network ls --format '{{.Name}}' | grep '^$network$' >/dev/null || docker network create --driver overlay --attachable $network >/dev/null",
"docker network connect $network coolify-proxy >/dev/null 2>&1 || true",
"echo 'Successfully connected coolify-proxy to $network network.'",
];
});
} else {
$commands = $networks->map(function ($network) {
return [
"docker network ls --format '{{.Name}}' | grep '^$network$' >/dev/null || docker network create --attachable $network >/dev/null",
"docker network connect $network coolify-proxy >/dev/null 2>&1 || true",
"echo 'Successfully connected coolify-proxy to $network network.'",
];
});
}
return $commands->flatten();
}
/**
* Ensures all required networks exist before docker compose up.
* This must be called BEFORE docker compose up since the compose file declares networks as external.
*
* @param Server $server The server to ensure networks on
* @return \Illuminate\Support\Collection Commands to create networks if they don't exist
*/
function ensureProxyNetworksExist(Server $server)
{
['allNetworks' => $networks] = collectDockerNetworksByServer($server);
if ($server->isSwarm()) {
$commands = $networks->map(function ($network) {
return [
"echo 'Ensuring network $network exists...'",
"docker network ls --format '{{.Name}}' | grep -q '^{$network}$' || docker network create --driver overlay --attachable $network",
];
});
} else {
$commands = $networks->map(function ($network) {
return [
"echo 'Ensuring network $network exists...'",
"docker network ls --format '{{.Name}}' | grep -q '^{$network}$' || docker network create --attachable $network",
];
});
}
return $commands->flatten();
}
function extractCustomProxyCommands(Server $server, string $existing_config): array
{
$custom_commands = [];
$proxy_type = $server->proxyType();
if ($proxy_type !== ProxyTypes::TRAEFIK->value || empty($existing_config)) {
return $custom_commands;
}
try {
$yaml = Yaml::parse($existing_config);
$existing_commands = data_get($yaml, 'services.traefik.command', []);
if (empty($existing_commands)) {
return $custom_commands;
}
// Define default commands that Coolify generates
$default_command_prefixes = [
'--ping=',
'--api.',
'--entrypoints.http.address=',
'--entrypoints.https.address=',
'--entrypoints.http.http.encodequerysemicolons=',
'--entryPoints.http.http2.maxConcurrentStreams=',
'--entrypoints.https.http.encodequerysemicolons=',
'--entryPoints.https.http2.maxConcurrentStreams=',
'--entrypoints.https.http3',
'--providers.file.',
'--certificatesresolvers.',
'--providers.docker',
'--providers.swarm',
'--log.level=',
'--accesslog.',
];
// Extract commands that don't match default prefixes (these are custom)
foreach ($existing_commands as $command) {
$is_default = false;
foreach ($default_command_prefixes as $prefix) {
if (str_starts_with($command, $prefix)) {
$is_default = true;
break;
}
}
if (! $is_default) {
$custom_commands[] = $command;
}
}
} catch (\Exception $e) {
// If we can't parse the config, return empty array
// Silently fail to avoid breaking the proxy regeneration
}
return $custom_commands;
}
function generateDefaultProxyConfiguration(Server $server, array $custom_commands = [])
{
$proxy_path = $server->proxyPath();
$proxy_type = $server->proxyType();
if ($server->isSwarm()) {
$networks = collect($server->swarmDockers)->map(function ($docker) {
return $docker['network'];
})->unique();
if ($networks->count() === 0) {
$networks = collect(['coolify-overlay']);
}
} else {
$networks = collect($server->standaloneDockers)->map(function ($docker) {
return $docker['network'];
})->unique();
if ($networks->count() === 0) {
$networks = collect(['coolify']);
}
}
$array_of_networks = collect([]);
$filtered_networks = collect([]);
$networks->map(function ($network) use ($array_of_networks, $filtered_networks) {
if (isDockerPredefinedNetwork($network)) {
return; // Predefined networks cannot be used in network configuration
}
$array_of_networks[$network] = [
'external' => true,
];
$filtered_networks->push($network);
});
if ($proxy_type === ProxyTypes::TRAEFIK->value) {
$labels = [
'traefik.enable=true',
'traefik.http.routers.traefik.entrypoints=http',
'traefik.http.routers.traefik.service=api@internal',
'traefik.http.services.traefik.loadbalancer.server.port=8080',
'coolify.managed=true',
'coolify.proxy=true',
];
$config = [
'name' => 'coolify-proxy',
'networks' => $array_of_networks->toArray(),
'services' => [
'traefik' => [
'container_name' => 'coolify-proxy',
'image' => 'traefik:v3.6',
'restart' => RESTART_MODE,
'extra_hosts' => [
'host.docker.internal:host-gateway',
],
'networks' => $filtered_networks->toArray(),
'ports' => [
'80:80',
'443:443',
'443:443/udp',
'8080:8080',
],
'healthcheck' => [
'test' => 'wget -qO- http://localhost:80/ping || exit 1',
'interval' => '4s',
'timeout' => '2s',
'retries' => 5,
],
'volumes' => [
'/var/run/docker.sock:/var/run/docker.sock:ro',
],
'command' => [
'--ping=true',
'--ping.entrypoint=http',
'--api.dashboard=true',
'--entrypoints.http.address=:80',
'--entrypoints.https.address=:443',
'--entrypoints.http.http.encodequerysemicolons=true',
'--entryPoints.http.http2.maxConcurrentStreams=250',
'--entrypoints.https.http.encodequerysemicolons=true',
'--entryPoints.https.http2.maxConcurrentStreams=250',
'--entrypoints.https.http3',
'--providers.file.directory=/traefik/dynamic/',
'--providers.file.watch=true',
'--certificatesresolvers.letsencrypt.acme.httpchallenge=true',
'--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=http',
'--certificatesresolvers.letsencrypt.acme.storage=/traefik/acme.json',
],
'labels' => $labels,
],
],
];
if (isDev()) {
$config['services']['traefik']['command'][] = '--api.insecure=true';
$config['services']['traefik']['command'][] = '--log.level=debug';
$config['services']['traefik']['command'][] = '--accesslog.filepath=/traefik/access.log';
$config['services']['traefik']['command'][] = '--accesslog.bufferingsize=100';
$config['services']['traefik']['volumes'][] = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/proxy/:/traefik';
} else {
$config['services']['traefik']['command'][] = '--api.insecure=false';
$config['services']['traefik']['volumes'][] = "{$proxy_path}:/traefik";
}
if ($server->isSwarm()) {
data_forget($config, 'services.traefik.container_name');
data_forget($config, 'services.traefik.restart');
data_forget($config, 'services.traefik.labels');
$config['services']['traefik']['command'][] = '--providers.swarm.endpoint=unix:///var/run/docker.sock';
$config['services']['traefik']['command'][] = '--providers.swarm.exposedbydefault=false';
$config['services']['traefik']['deploy'] = [
'labels' => $labels,
'placement' => [
'constraints' => [
'node.role==manager',
],
],
];
} else {
$config['services']['traefik']['command'][] = '--providers.docker=true';
$config['services']['traefik']['command'][] = '--providers.docker.exposedbydefault=false';
}
// Append custom commands (e.g., trustedIPs for Cloudflare)
if (! empty($custom_commands)) {
foreach ($custom_commands as $custom_command) {
$config['services']['traefik']['command'][] = $custom_command;
}
}
} elseif ($proxy_type === 'CADDY') {
$config = [
'networks' => $array_of_networks->toArray(),
'services' => [
'caddy' => [
'container_name' => 'coolify-proxy',
'image' => 'lucaslorentz/caddy-docker-proxy:2.8-alpine',
'restart' => RESTART_MODE,
'extra_hosts' => [
'host.docker.internal:host-gateway',
],
'environment' => [
'CADDY_DOCKER_POLLING_INTERVAL=5s',
'CADDY_DOCKER_CADDYFILE_PATH=/dynamic/Caddyfile',
],
'networks' => $filtered_networks->toArray(),
'ports' => [
'80:80',
'443:443',
'443:443/udp',
],
'labels' => [
'coolify.managed=true',
'coolify.proxy=true',
],
'volumes' => [
'/var/run/docker.sock:/var/run/docker.sock:ro',
"{$proxy_path}/dynamic:/dynamic",
"{$proxy_path}/config:/config",
"{$proxy_path}/data:/data",
],
],
],
];
} else {
return null;
}
$config = Yaml::dump($config, 12, 2);
SaveProxyConfiguration::run($server, $config);
return $config;
}
function getExactTraefikVersionFromContainer(Server $server): ?string
{
try {
Log::debug("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Checking for exact version");
// Method A: Execute traefik version command (most reliable)
$versionCommand = "docker exec coolify-proxy traefik version 2>/dev/null | grep -oP 'Version:\s+\K\d+\.\d+\.\d+'";
Log::debug("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Running: {$versionCommand}");
$output = instant_remote_process([$versionCommand], $server, false);
if (! empty(trim($output))) {
$version = trim($output);
Log::debug("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Detected exact version from command: {$version}");
return $version;
}
// Method B: Try OCI label as fallback
$labelCommand = "docker inspect coolify-proxy --format '{{index .Config.Labels \"org.opencontainers.image.version\"}}' 2>/dev/null";
Log::debug("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Trying OCI label");
$label = instant_remote_process([$labelCommand], $server, false);
if (! empty(trim($label))) {
// Extract version number from label (might have 'v' prefix)
if (preg_match('/(\d+\.\d+\.\d+)/', trim($label), $matches)) {
Log::debug("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Detected from OCI label: {$matches[1]}");
return $matches[1];
}
}
Log::debug("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Could not detect exact version");
return null;
} catch (\Exception $e) {
Log::error("getExactTraefikVersionFromContainer: Server '{$server->name}' (ID: {$server->id}) - Error: ".$e->getMessage());
return null;
}
}
function getTraefikVersionFromDockerCompose(Server $server): ?string
{
try {
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Starting version detection");
// Try to get exact version from running container (e.g., "3.6.0")
$exactVersion = getExactTraefikVersionFromContainer($server);
if ($exactVersion) {
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Using exact version: {$exactVersion}");
return $exactVersion;
}
// Fallback: Check image tag (current method)
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Falling back to image tag detection");
$containerName = 'coolify-proxy';
$inspectCommand = "docker inspect {$containerName} --format '{{.Config.Image}}' 2>/dev/null";
$image = instant_remote_process([$inspectCommand], $server, false);
if (empty(trim($image))) {
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Container '{$containerName}' not found or not running");
return null;
}
$image = trim($image);
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Running container image: {$image}");
// Extract version from image string (e.g., "traefik:v3.6" or "traefik:3.6.0" or "traefik:latest")
if (preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches)) {
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Extracted version from image tag: {$matches[1]}");
return $matches[1];
}
Log::debug("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Image format doesn't match expected pattern: {$image}");
return null;
} catch (\Exception $e) {
Log::error("getTraefikVersionFromDockerCompose: Server '{$server->name}' (ID: {$server->id}) - Error: ".$e->getMessage());
return null;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/services.php | bootstrap/helpers/services.php | <?php
use App\Models\Application;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Stringable;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
function replaceRegex(?string $name = null)
{
return "/\\\${?{$name}[^}]*}?|\\\${$name}\w+/";
}
function collectRegex(string $name)
{
return "/{$name}\w+/";
}
function replaceVariables(string $variable): Stringable
{
return str($variable)->before('}')->replaceFirst('$', '')->replaceFirst('{', '');
}
function getFilesystemVolumesFromServer(ServiceApplication|ServiceDatabase|Application $oneService, bool $isInit = false)
{
try {
if ($oneService->getMorphClass() === \App\Models\Application::class) {
$workdir = $oneService->workdir();
$server = $oneService->destination->server;
} else {
$workdir = $oneService->service->workdir();
$server = $oneService->service->server;
}
$fileVolumes = $oneService->fileStorages()->get();
$commands = collect([
"mkdir -p $workdir > /dev/null 2>&1 || true",
"cd $workdir",
]);
instant_remote_process($commands, $server);
foreach ($fileVolumes as $fileVolume) {
$path = str(data_get($fileVolume, 'fs_path'));
$content = data_get($fileVolume, 'content');
if ($path->startsWith('.')) {
$path = $path->after('.');
$fileLocation = $workdir.$path;
} else {
$fileLocation = $path;
}
// Exists and is a file
$isFile = instant_remote_process(["test -f $fileLocation && echo OK || echo NOK"], $server);
// Exists and is a directory
$isDir = instant_remote_process(["test -d $fileLocation && echo OK || echo NOK"], $server);
if ($isFile === 'OK') {
// If its a file & exists
$filesystemContent = instant_remote_process(["cat $fileLocation"], $server);
if ($fileVolume->is_based_on_git) {
$fileVolume->content = $filesystemContent;
}
$fileVolume->is_directory = false;
$fileVolume->save();
} elseif ($isDir === 'OK') {
// If its a directory & exists
$fileVolume->content = null;
$fileVolume->is_directory = true;
$fileVolume->save();
} elseif ($isFile === 'NOK' && $isDir === 'NOK' && ! $fileVolume->is_directory && $isInit && $content) {
// Does not exists (no dir or file), not flagged as directory, is init, has content
$fileVolume->content = $content;
$fileVolume->is_directory = false;
$fileVolume->save();
$content = base64_encode($content);
$dir = str($fileLocation)->dirname();
instant_remote_process([
"mkdir -p $dir",
"echo '$content' | base64 -d | tee $fileLocation",
], $server);
} elseif ($isFile === 'NOK' && $isDir === 'NOK' && $fileVolume->is_directory && $isInit) {
// Does not exists (no dir or file), flagged as directory, is init
$fileVolume->content = null;
$fileVolume->is_directory = true;
$fileVolume->save();
instant_remote_process(["mkdir -p $fileLocation"], $server);
} elseif ($isFile === 'NOK' && $isDir === 'NOK' && ! $fileVolume->is_directory && $isInit && is_null($content)) {
// Does not exists (no dir or file), not flagged as directory, is init, has no content => create directory
$fileVolume->content = null;
$fileVolume->is_directory = true;
$fileVolume->save();
instant_remote_process(["mkdir -p $fileLocation"], $server);
}
}
} catch (\Throwable $e) {
return handleError($e);
}
}
function updateCompose(ServiceApplication|ServiceDatabase $resource)
{
try {
$name = data_get($resource, 'name');
$dockerComposeRaw = data_get($resource, 'service.docker_compose_raw');
if (! $dockerComposeRaw) {
throw new \Exception('No compose file found or not a valid YAML file.');
}
$dockerCompose = Yaml::parse($dockerComposeRaw);
// Switch Image
$updatedImage = data_get_str($resource, 'image');
$currentImage = data_get_str($dockerCompose, "services.{$name}.image");
if ($currentImage !== $updatedImage) {
data_set($dockerCompose, "services.{$name}.image", $updatedImage->value());
$dockerComposeRaw = Yaml::dump($dockerCompose, 10, 2);
$resource->service->docker_compose_raw = $dockerComposeRaw;
$resource->service->save();
$resource->image = $updatedImage;
$resource->save();
}
// Extract SERVICE_URL and SERVICE_FQDN variable names from the compose template
// to ensure we use the exact names defined in the template (which may be abbreviated)
// IMPORTANT: Only extract variables that are DIRECTLY DECLARED for this service,
// not variables that are merely referenced from other services
$serviceConfig = data_get($dockerCompose, "services.{$name}");
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style: "- SERVICE_URL_APP_3000" or "- SERVICE_URL_APP_3000=value"
// Extract variable name (before '=' if present)
$envVarName = str($value)->before('=')->trim();
// Only include if it's a direct declaration (not a reference like ${VAR})
// Direct declarations look like: SERVICE_URL_APP or SERVICE_URL_APP_3000
// References look like: NEXT_PUBLIC_URL=${SERVICE_URL_APP}
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
} elseif (is_string($key)) {
// Map-style: "SERVICE_URL_APP_3000: value" or "SERVICE_FQDN_DB: localhost"
$envVarName = str($key);
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
// DO NOT extract variables that are only referenced with ${VAR_NAME} syntax
// Those belong to other services and will be updated when THOSE services are updated
}
// Remove duplicates
$templateVariableNames = array_unique($templateVariableNames);
// Extract unique service names to process (preserving the original case from template)
// This allows us to create both URL and FQDN pairs regardless of which one is in the template
$serviceNamesToProcess = [];
foreach ($templateVariableNames as $templateVarName) {
$parsed = parseServiceEnvironmentVariable($templateVarName);
// Extract the original service name with case preserved from the template
$strKey = str($templateVarName);
if ($parsed['has_port']) {
// For port-specific variables, get the name between SERVICE_URL_/SERVICE_FQDN_ and the last underscore
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->beforeLast('_')->value();
} else {
continue;
}
} else {
// For base variables, get everything after SERVICE_URL_/SERVICE_FQDN_
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->value();
} else {
continue;
}
}
// Use lowercase key for array indexing (to group case variations together)
$serviceKey = str($serviceName)->lower()->value();
// Track both base service name and port-specific variant
if (! isset($serviceNamesToProcess[$serviceKey])) {
$serviceNamesToProcess[$serviceKey] = [
'base' => $serviceName, // Preserve original case
'ports' => [],
];
}
// If this variable has a port, track it
if ($parsed['has_port'] && $parsed['port']) {
$serviceNamesToProcess[$serviceKey]['ports'][] = $parsed['port'];
}
}
// Delete all existing SERVICE_URL and SERVICE_FQDN variables for these service names
// We need to delete both URL and FQDN variants, with and without ports
foreach ($serviceNamesToProcess as $serviceInfo) {
$serviceName = $serviceInfo['base'];
// Delete base variables
$resource->service->environment_variables()->where('key', "SERVICE_URL_{$serviceName}")->delete();
$resource->service->environment_variables()->where('key', "SERVICE_FQDN_{$serviceName}")->delete();
// Delete port-specific variables
foreach ($serviceInfo['ports'] as $port) {
$resource->service->environment_variables()->where('key', "SERVICE_URL_{$serviceName}_{$port}")->delete();
$resource->service->environment_variables()->where('key', "SERVICE_FQDN_{$serviceName}_{$port}")->delete();
}
}
if ($resource->fqdn) {
$resourceFqdns = str($resource->fqdn)->explode(',');
$resourceFqdns = $resourceFqdns->first();
$url = Url::fromString($resourceFqdns);
$port = $url->getPort();
$path = $url->getPath();
// Prepare URL value (with scheme and host)
$urlValue = $url->getScheme().'://'.$url->getHost();
$urlValue = ($path === '/') ? $urlValue : $urlValue.$path;
// Prepare FQDN value (host only, no scheme)
$fqdnHost = $url->getHost();
$fqdnValue = str($fqdnHost)->after('://');
if ($path !== '/') {
$fqdnValue = $fqdnValue.$path;
}
// For each service name found in template, create BOTH SERVICE_URL and SERVICE_FQDN pairs
foreach ($serviceNamesToProcess as $serviceInfo) {
$serviceName = $serviceInfo['base'];
$ports = array_unique($serviceInfo['ports']);
// ALWAYS create base pair (without port)
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_URL_{$serviceName}",
], [
'value' => $urlValue,
'is_preview' => false,
]);
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_FQDN_{$serviceName}",
], [
'value' => $fqdnValue,
'is_preview' => false,
]);
// Create port-specific pairs for each port found in template or FQDN
$allPorts = $ports;
if ($port && ! in_array($port, $allPorts)) {
$allPorts[] = $port;
}
foreach ($allPorts as $portNum) {
$urlWithPort = $urlValue.':'.$portNum;
$fqdnWithPort = $fqdnValue.':'.$portNum;
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_URL_{$serviceName}_{$portNum}",
], [
'value' => $urlWithPort,
'is_preview' => false,
]);
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_FQDN_{$serviceName}_{$portNum}",
], [
'value' => $fqdnWithPort,
'is_preview' => false,
]);
}
}
}
} catch (\Throwable $e) {
return handleError($e);
}
}
function serviceKeys()
{
return get_service_templates()->keys();
}
/**
* Parse a SERVICE_URL_* or SERVICE_FQDN_* variable to extract the service name and port.
*
* This function detects if a service environment variable has a port suffix by checking
* if the last segment after the underscore is numeric.
*
* Examples:
* - SERVICE_URL_APP_3000 → ['service_name' => 'app', 'port' => '3000', 'has_port' => true]
* - SERVICE_URL_MY_API_8080 → ['service_name' => 'my_api', 'port' => '8080', 'has_port' => true]
* - SERVICE_URL_MY_APP → ['service_name' => 'my_app', 'port' => null, 'has_port' => false]
* - SERVICE_FQDN_REDIS_CACHE_6379 → ['service_name' => 'redis_cache', 'port' => '6379', 'has_port' => true]
*
* @param string $key The environment variable key (e.g., SERVICE_URL_APP_3000)
* @return array{service_name: string, port: string|null, has_port: bool} Parsed service information
*/
function parseServiceEnvironmentVariable(string $key): array
{
$strKey = str($key);
$lastSegment = $strKey->afterLast('_')->value();
$hasPort = is_numeric($lastSegment) && ctype_digit($lastSegment);
if ($hasPort) {
// Port-specific variable (e.g., SERVICE_URL_APP_3000)
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->lower()->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->beforeLast('_')->lower()->value();
} else {
$serviceName = '';
}
$port = $lastSegment;
} else {
// Base variable without port (e.g., SERVICE_URL_APP)
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->lower()->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->lower()->value();
} else {
$serviceName = '';
}
$port = null;
}
return [
'service_name' => $serviceName,
'port' => $port,
'has_port' => $hasPort,
];
}
/**
* Apply service-specific application prerequisites after service parse.
*
* This function configures application-level settings that are required for
* specific one-click services to work correctly (e.g., disabling gzip for Beszel,
* disabling strip prefix for Appwrite services).
*
* Must be called AFTER $service->parse() since it requires applications to exist.
*
* @param Service $service The service to apply prerequisites to
*/
function applyServiceApplicationPrerequisites(Service $service): void
{
try {
// Extract service name from service name (format: "servicename-uuid")
$serviceName = str($service->name)->beforeLast('-')->value();
// Apply gzip disabling if needed
if (array_key_exists($serviceName, NEEDS_TO_DISABLE_GZIP)) {
$applicationNames = NEEDS_TO_DISABLE_GZIP[$serviceName];
foreach ($applicationNames as $applicationName) {
$application = $service->applications()->whereName($applicationName)->first();
if ($application) {
$application->is_gzip_enabled = false;
$application->save();
}
}
}
// Apply stripprefix disabling if needed
if (array_key_exists($serviceName, NEEDS_TO_DISABLE_STRIPPREFIX)) {
$applicationNames = NEEDS_TO_DISABLE_STRIPPREFIX[$serviceName];
foreach ($applicationNames as $applicationName) {
$application = $service->applications()->whereName($applicationName)->first();
if ($application) {
$application->is_stripprefix_enabled = false;
$application->save();
}
}
}
} catch (\Throwable $e) {
// Log error but don't throw - prerequisites are nice-to-have, not critical
Log::error('Failed to apply service application prerequisites', [
'service_id' => $service->id,
'service_name' => $service->name,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/databases.php | bootstrap/helpers/databases.php | <?php
use App\Models\EnvironmentVariable;
use App\Models\S3Storage;
use App\Models\Server;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDocker;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Visus\Cuid2\Cuid2;
function create_standalone_postgresql($environmentId, $destinationUuid, ?array $otherData = null, string $databaseImage = 'postgres:16-alpine'): StandalonePostgresql
{
$destination = StandaloneDocker::where('uuid', $destinationUuid)->firstOrFail();
$database = new StandalonePostgresql;
$database->uuid = (new Cuid2);
$database->name = 'postgresql-database-'.$database->uuid;
$database->image = $databaseImage;
$database->postgres_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environmentId;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function create_standalone_redis($environment_id, $destination_uuid, ?array $otherData = null): StandaloneRedis
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneRedis;
$database->uuid = (new Cuid2);
$database->name = 'redis-database-'.$database->uuid;
$redis_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
if ($otherData && isset($otherData['redis_password'])) {
$redis_password = $otherData['redis_password'];
unset($otherData['redis_password']);
}
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
EnvironmentVariable::create([
'key' => 'REDIS_PASSWORD',
'value' => $redis_password,
'resourceable_type' => StandaloneRedis::class,
'resourceable_id' => $database->id,
'is_shared' => false,
]);
EnvironmentVariable::create([
'key' => 'REDIS_USERNAME',
'value' => 'default',
'resourceable_type' => StandaloneRedis::class,
'resourceable_id' => $database->id,
'is_shared' => false,
]);
return $database;
}
function create_standalone_mongodb($environment_id, $destination_uuid, ?array $otherData = null): StandaloneMongodb
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneMongodb;
$database->uuid = (new Cuid2);
$database->name = 'mongodb-database-'.$database->uuid;
$database->mongo_initdb_root_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function create_standalone_mysql($environment_id, $destination_uuid, ?array $otherData = null): StandaloneMysql
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneMysql;
$database->uuid = (new Cuid2);
$database->name = 'mysql-database-'.$database->uuid;
$database->mysql_root_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->mysql_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function create_standalone_mariadb($environment_id, $destination_uuid, ?array $otherData = null): StandaloneMariadb
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneMariadb;
$database->uuid = (new Cuid2);
$database->name = 'mariadb-database-'.$database->uuid;
$database->mariadb_root_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->mariadb_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function create_standalone_keydb($environment_id, $destination_uuid, ?array $otherData = null): StandaloneKeydb
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneKeydb;
$database->uuid = (new Cuid2);
$database->name = 'keydb-database-'.$database->uuid;
$database->keydb_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function create_standalone_dragonfly($environment_id, $destination_uuid, ?array $otherData = null): StandaloneDragonfly
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneDragonfly;
$database->uuid = (new Cuid2);
$database->name = 'dragonfly-database-'.$database->uuid;
$database->dragonfly_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function create_standalone_clickhouse($environment_id, $destination_uuid, ?array $otherData = null): StandaloneClickhouse
{
$destination = StandaloneDocker::where('uuid', $destination_uuid)->firstOrFail();
$database = new StandaloneClickhouse;
$database->uuid = (new Cuid2);
$database->name = 'clickhouse-database-'.$database->uuid;
$database->clickhouse_admin_password = \Illuminate\Support\Str::password(length: 64, symbols: false);
$database->environment_id = $environment_id;
$database->destination_id = $destination->id;
$database->destination_type = $destination->getMorphClass();
if ($otherData) {
$database->fill($otherData);
}
$database->save();
return $database;
}
function deleteBackupsLocally(string|array|null $filenames, Server $server): void
{
if (empty($filenames)) {
return;
}
if (is_string($filenames)) {
$filenames = [$filenames];
}
$quotedFiles = array_map(fn ($file) => "\"$file\"", $filenames);
instant_remote_process(['rm -f '.implode(' ', $quotedFiles)], $server, throwError: false);
$foldersToCheck = collect($filenames)->map(fn ($file) => dirname($file))->unique();
$foldersToCheck->each(fn ($folder) => deleteEmptyBackupFolder($folder, $server));
}
function deleteBackupsS3(string|array|null $filenames, S3Storage $s3): void
{
if (empty($filenames) || ! $s3) {
return;
}
if (is_string($filenames)) {
$filenames = [$filenames];
}
$disk = Storage::build([
'driver' => 's3',
'key' => $s3->key,
'secret' => $s3->secret,
'region' => $s3->region,
'bucket' => $s3->bucket,
'endpoint' => $s3->endpoint,
'use_path_style_endpoint' => true,
'aws_url' => $s3->awsUrl(),
]);
$disk->delete($filenames);
}
function deleteEmptyBackupFolder($folderPath, Server $server): void
{
$escapedPath = escapeshellarg($folderPath);
$escapedParentPath = escapeshellarg(dirname($folderPath));
$checkEmpty = instant_remote_process(["[ -d $escapedPath ] && [ -z \"$(ls -A $escapedPath)\" ] && echo 'empty' || echo 'not empty'"], $server, throwError: false);
if (trim($checkEmpty) === 'empty') {
instant_remote_process(["rmdir $escapedPath"], $server, throwError: false);
$checkParentEmpty = instant_remote_process(["[ -d $escapedParentPath ] && [ -z \"$(ls -A $escapedParentPath)\" ] && echo 'empty' || echo 'not empty'"], $server, throwError: false);
if (trim($checkParentEmpty) === 'empty') {
instant_remote_process(["rmdir $escapedParentPath"], $server, throwError: false);
}
}
}
function removeOldBackups($backup): void
{
try {
if ($backup->executions) {
// Delete old local backups (only if local backup is NOT disabled)
// Note: When disable_local_backup is enabled, each execution already marks its own
// local_storage_deleted status at the time of backup, so we don't need to retroactively
// update old executions
if (! $backup->disable_local_backup) {
$localBackupsToDelete = deleteOldBackupsLocally($backup);
if ($localBackupsToDelete->isNotEmpty()) {
$backup->executions()
->whereIn('id', $localBackupsToDelete->pluck('id'))
->update(['local_storage_deleted' => true]);
}
}
}
if ($backup->save_s3 && $backup->executions) {
$s3BackupsToDelete = deleteOldBackupsFromS3($backup);
if ($s3BackupsToDelete->isNotEmpty()) {
$backup->executions()
->whereIn('id', $s3BackupsToDelete->pluck('id'))
->update(['s3_storage_deleted' => true]);
}
}
// Delete execution records where all backup copies are gone
// Case 1: Both local and S3 backups are deleted
$backup->executions()
->where('local_storage_deleted', true)
->where('s3_storage_deleted', true)
->delete();
// Case 2: Local backup is deleted and S3 was never used (s3_uploaded is null)
$backup->executions()
->where('local_storage_deleted', true)
->whereNull('s3_uploaded')
->delete();
} catch (\Exception $e) {
throw $e;
}
}
function deleteOldBackupsLocally($backup): Collection
{
if (! $backup || ! $backup->executions) {
return collect();
}
$successfulBackups = $backup->executions()
->where('status', 'success')
->where('local_storage_deleted', false)
->orderBy('created_at', 'desc')
->get();
if ($successfulBackups->isEmpty()) {
return collect();
}
$retentionAmount = $backup->database_backup_retention_amount_locally;
$retentionDays = $backup->database_backup_retention_days_locally;
$maxStorageGB = $backup->database_backup_retention_max_storage_locally;
if ($retentionAmount === 0 && $retentionDays === 0 && $maxStorageGB === 0) {
return collect();
}
$backupsToDelete = collect();
if ($retentionAmount > 0) {
$byAmount = $successfulBackups->skip($retentionAmount);
$backupsToDelete = $backupsToDelete->merge($byAmount);
}
if ($retentionDays > 0) {
$oldestAllowedDate = $successfulBackups->first()->created_at->clone()->utc()->subDays($retentionDays);
$oldBackups = $successfulBackups->filter(fn ($execution) => $execution->created_at->utc() < $oldestAllowedDate);
$backupsToDelete = $backupsToDelete->merge($oldBackups);
}
if ($maxStorageGB > 0) {
$maxStorageBytes = $maxStorageGB * pow(1024, 3);
$totalSize = 0;
$backupsOverLimit = collect();
$backupsToCheck = $successfulBackups->skip(1);
foreach ($backupsToCheck as $backupExecution) {
$totalSize += (int) $backupExecution->size;
if ($totalSize > $maxStorageBytes) {
$backupsOverLimit = $successfulBackups->filter(
fn ($b) => $b->created_at->utc() <= $backupExecution->created_at->utc()
)->skip(1);
break;
}
}
$backupsToDelete = $backupsToDelete->merge($backupsOverLimit);
}
$backupsToDelete = $backupsToDelete->unique('id');
$processedBackups = collect();
$server = null;
if ($backup->database_type === \App\Models\ServiceDatabase::class) {
$server = $backup->database->service->server;
} else {
$server = $backup->database->destination->server;
}
if (! $server) {
return collect();
}
$filesToDelete = $backupsToDelete
->filter(fn ($execution) => ! empty($execution->filename))
->pluck('filename')
->all();
if (! empty($filesToDelete)) {
deleteBackupsLocally($filesToDelete, $server);
$processedBackups = $backupsToDelete;
}
return $processedBackups;
}
function deleteOldBackupsFromS3($backup): Collection
{
if (! $backup || ! $backup->executions || ! $backup->s3) {
return collect();
}
$successfulBackups = $backup->executions()
->where('status', 'success')
->where('s3_storage_deleted', false)
->orderBy('created_at', 'desc')
->get();
if ($successfulBackups->isEmpty()) {
return collect();
}
$retentionAmount = $backup->database_backup_retention_amount_s3;
$retentionDays = $backup->database_backup_retention_days_s3;
$maxStorageGB = $backup->database_backup_retention_max_storage_s3;
if ($retentionAmount === 0 && $retentionDays === 0 && $maxStorageGB === 0) {
return collect();
}
$backupsToDelete = collect();
if ($retentionAmount > 0) {
$byAmount = $successfulBackups->skip($retentionAmount);
$backupsToDelete = $backupsToDelete->merge($byAmount);
}
if ($retentionDays > 0) {
$oldestAllowedDate = $successfulBackups->first()->created_at->clone()->utc()->subDays($retentionDays);
$oldBackups = $successfulBackups->filter(fn ($execution) => $execution->created_at->utc() < $oldestAllowedDate);
$backupsToDelete = $backupsToDelete->merge($oldBackups);
}
if ($maxStorageGB > 0) {
$maxStorageBytes = $maxStorageGB * pow(1024, 3);
$totalSize = 0;
$backupsOverLimit = collect();
$backupsToCheck = $successfulBackups->skip(1);
foreach ($backupsToCheck as $backupExecution) {
$totalSize += (int) $backupExecution->size;
if ($totalSize > $maxStorageBytes) {
$backupsOverLimit = $successfulBackups->filter(
fn ($b) => $b->created_at->utc() <= $backupExecution->created_at->utc()
)->skip(1);
break;
}
}
$backupsToDelete = $backupsToDelete->merge($backupsOverLimit);
}
$backupsToDelete = $backupsToDelete->unique('id');
$processedBackups = collect();
$filesToDelete = $backupsToDelete
->filter(fn ($execution) => ! empty($execution->filename))
->pluck('filename')
->all();
if (! empty($filesToDelete)) {
deleteBackupsS3($filesToDelete, $backup->s3);
$processedBackups = $backupsToDelete;
}
return $processedBackups;
}
function isPublicPortAlreadyUsed(Server $server, int $port, ?string $id = null): bool
{
if ($id) {
$foundDatabase = $server->databases()->where('public_port', $port)->where('is_public', true)->where('id', '!=', $id)->first();
} else {
$foundDatabase = $server->databases()->where('public_port', $port)->where('is_public', true)->first();
}
if ($foundDatabase) {
return true;
}
return false;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/constants.php | bootstrap/helpers/constants.php | <?php
const REDACTED = '<REDACTED>';
const DATABASE_TYPES = ['postgresql', 'redis', 'mongodb', 'mysql', 'mariadb', 'keydb', 'dragonfly', 'clickhouse'];
const VALID_CRON_STRINGS = [
'every_minute' => '* * * * *',
'hourly' => '0 * * * *',
'daily' => '0 0 * * *',
'weekly' => '0 0 * * 0',
'monthly' => '0 0 1 * *',
'yearly' => '0 0 1 1 *',
'@hourly' => '0 * * * *',
'@daily' => '0 0 * * *',
'@weekly' => '0 0 * * 0',
'@monthly' => '0 0 1 * *',
'@yearly' => '0 0 1 1 *',
];
const RESTART_MODE = 'unless-stopped';
const DATABASE_DOCKER_IMAGES = [
'bitnami/mariadb',
'bitnami/mongodb',
'bitnami/redis',
'bitnamilegacy/mariadb',
'bitnamilegacy/mongodb',
'bitnamilegacy/redis',
'bitnamisecure/mariadb',
'bitnamisecure/mongodb',
'bitnamisecure/redis',
'mysql',
'bitnami/mysql',
'bitnamilegacy/mysql',
'bitnamisecure/mysql',
'mysql/mysql-server',
'mariadb',
'postgis/postgis',
'postgres',
'bitnami/postgresql',
'bitnamilegacy/postgresql',
'bitnamisecure/postgresql',
'supabase/postgres',
'elestio/postgres',
'mongo',
'redis',
'memcached',
'couchdb',
'neo4j',
'influxdb',
'clickhouse/clickhouse-server',
'timescaledb/timescaledb',
'timescaledb', // Matches timescale/timescaledb
'timescaledb-ha', // Matches timescale/timescaledb-ha
'pgvector/pgvector',
];
const SPECIFIC_SERVICES = [
'quay.io/minio/minio',
'minio/minio',
'ghcr.io/coollabsio/minio',
'coollabsio/minio',
'svhd/logto',
'dxflrs/garage',
];
// Based on /etc/os-release
const SUPPORTED_OS = [
'ubuntu debian raspbian pop',
'centos fedora rhel ol rocky amzn almalinux',
'sles opensuse-leap opensuse-tumbleweed',
'arch',
'alpine',
];
const NEEDS_TO_CONNECT_TO_PREDEFINED_NETWORK = [
'pgadmin',
'postgresus',
'redis-insight',
];
const NEEDS_TO_DISABLE_GZIP = [
'beszel' => ['beszel'],
];
const NEEDS_TO_DISABLE_STRIPPREFIX = [
'appwrite' => ['appwrite', 'appwrite-console', 'appwrite-realtime'],
];
const SHARED_VARIABLE_TYPES = ['team', 'project', 'environment'];
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/timezone.php | bootstrap/helpers/timezone.php | <?php
function getServerTimezone($server = null)
{
if (! $server) {
return 'UTC';
}
return data_get($server, 'settings.server_timezone', 'UTC');
}
function formatDateInServerTimezone($date, $server = null)
{
$serverTimezone = getServerTimezone($server);
$dateObj = new \DateTime($date);
try {
$dateObj->setTimezone(new \DateTimeZone($serverTimezone));
} catch (\Exception) {
$dateObj->setTimezone(new \DateTimeZone('UTC'));
}
return $dateObj->format('Y-m-d H:i:s T');
}
function calculateDuration($startDate, $endDate = null)
{
if (! $endDate) {
return null;
}
$start = new \DateTime($startDate);
$end = new \DateTime($endDate);
$interval = $start->diff($end);
if ($interval->days > 0) {
return $interval->format('%dd %Hh %Im %Ss');
} elseif ($interval->h > 0) {
return $interval->format('%Hh %Im %Ss');
} else {
return $interval->format('%Im %Ss');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/applications.php | bootstrap/helpers/applications.php | <?php
use App\Actions\Application\StopApplication;
use App\Enums\ApplicationDeploymentStatus;
use App\Jobs\ApplicationDeploymentJob;
use App\Jobs\VolumeCloneJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Server;
use App\Models\StandaloneDocker;
use Spatie\Url\Url;
use Visus\Cuid2\Cuid2;
function queue_application_deployment(Application $application, string $deployment_uuid, ?int $pull_request_id = 0, string $commit = 'HEAD', bool $force_rebuild = false, bool $is_webhook = false, bool $is_api = false, bool $restart_only = false, ?string $git_type = null, bool $no_questions_asked = false, ?Server $server = null, ?StandaloneDocker $destination = null, bool $only_this_server = false, bool $rollback = false)
{
$application_id = $application->id;
$deployment_link = Url::fromString($application->link()."/deployment/{$deployment_uuid}");
$deployment_url = $deployment_link->getPath();
$server_id = $application->destination->server->id;
$server_name = $application->destination->server->name;
$destination_id = $application->destination->id;
if ($server) {
$server_id = $server->id;
$server_name = $server->name;
}
if ($destination) {
$destination_id = $destination->id;
}
// Check if the deployment queue is full for this server
$serverForQueueCheck = $server ?? Server::find($server_id);
$queue_limit = $serverForQueueCheck->settings->deployment_queue_limit ?? 25;
$queued_count = ApplicationDeploymentQueue::where('server_id', $server_id)
->where('status', ApplicationDeploymentStatus::QUEUED->value)
->count();
if ($queued_count >= $queue_limit) {
return [
'status' => 'queue_full',
'message' => 'Deployment queue is full. Please wait for existing deployments to complete.',
];
}
// Check if there's already a deployment in progress or queued for this application and commit
$existing_deployment = ApplicationDeploymentQueue::where('application_id', $application_id)
->where('commit', $commit)
->where('pull_request_id', $pull_request_id)
->whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS->value, ApplicationDeploymentStatus::QUEUED->value])
->first();
if ($existing_deployment) {
// If force_rebuild is true or rollback is true or no_questions_asked is true, we'll still create a new deployment
if (! $force_rebuild && ! $rollback && ! $no_questions_asked) {
// Return the existing deployment's details
return [
'status' => 'skipped',
'message' => 'Deployment already queued for this commit.',
'deployment_uuid' => $existing_deployment->deployment_uuid,
'existing_deployment' => $existing_deployment,
];
}
}
$deployment = ApplicationDeploymentQueue::create([
'application_id' => $application_id,
'application_name' => $application->name,
'server_id' => $server_id,
'server_name' => $server_name,
'destination_id' => $destination_id,
'deployment_uuid' => $deployment_uuid,
'deployment_url' => $deployment_url,
'pull_request_id' => $pull_request_id,
'force_rebuild' => $force_rebuild,
'is_webhook' => $is_webhook,
'is_api' => $is_api,
'restart_only' => $restart_only,
'commit' => $commit,
'rollback' => $rollback,
'git_type' => $git_type,
'only_this_server' => $only_this_server,
]);
if ($no_questions_asked) {
$deployment->update([
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
ApplicationDeploymentJob::dispatch(
application_deployment_queue_id: $deployment->id,
);
} elseif (next_queuable($server_id, $application_id, $commit, $pull_request_id)) {
$deployment->update([
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
ApplicationDeploymentJob::dispatch(
application_deployment_queue_id: $deployment->id,
);
}
return [
'status' => 'queued',
'message' => 'Deployment queued.',
'deployment_uuid' => $deployment_uuid,
];
}
function force_start_deployment(ApplicationDeploymentQueue $deployment)
{
$deployment->update([
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
ApplicationDeploymentJob::dispatch(
application_deployment_queue_id: $deployment->id,
);
}
function queue_next_deployment(Application $application)
{
$server_id = $application->destination->server_id;
$queued_deployments = ApplicationDeploymentQueue::where('server_id', $server_id)
->where('status', ApplicationDeploymentStatus::QUEUED)
->get()
->sortBy('created_at');
foreach ($queued_deployments as $next_deployment) {
// Check if this queued deployment can actually run
if (next_queuable($next_deployment->server_id, $next_deployment->application_id, $next_deployment->commit, $next_deployment->pull_request_id)) {
$next_deployment->update([
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
ApplicationDeploymentJob::dispatch(
application_deployment_queue_id: $next_deployment->id,
);
}
}
}
function next_queuable(string $server_id, string $application_id, string $commit = 'HEAD', int $pull_request_id = 0): bool
{
// Check if there's already a deployment in progress for this application with the same pull_request_id
// This allows normal deployments and PR deployments to run concurrently
$in_progress = ApplicationDeploymentQueue::where('application_id', $application_id)
->where('pull_request_id', $pull_request_id)
->where('status', ApplicationDeploymentStatus::IN_PROGRESS->value)
->exists();
if ($in_progress) {
return false;
}
// Check server's concurrent build limit
$server = Server::find($server_id);
$concurrent_builds = $server->settings->concurrent_builds;
$active_deployments = ApplicationDeploymentQueue::where('server_id', $server_id)
->where('status', ApplicationDeploymentStatus::IN_PROGRESS->value)
->count();
if ($active_deployments >= $concurrent_builds) {
return false;
}
return true;
}
function next_after_cancel(?Server $server = null)
{
if ($server) {
$next_found = ApplicationDeploymentQueue::where('server_id', data_get($server, 'id'))
->where('status', ApplicationDeploymentStatus::QUEUED)
->get()
->sortBy('created_at');
if ($next_found->count() > 0) {
foreach ($next_found as $next) {
// Use next_queuable to properly check if this deployment can run
if (next_queuable($next->server_id, $next->application_id, $next->commit, $next->pull_request_id)) {
$next->update([
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
ApplicationDeploymentJob::dispatch(
application_deployment_queue_id: $next->id,
);
}
}
}
}
}
function clone_application(Application $source, $destination, array $overrides = [], bool $cloneVolumeData = false): Application
{
$uuid = $overrides['uuid'] ?? (string) new Cuid2;
$server = $destination->server;
// Prepare name and URL
$name = $overrides['name'] ?? 'clone-of-'.str($source->name)->limit(20).'-'.$uuid;
$applicationSettings = $source->settings;
$url = $overrides['fqdn'] ?? $source->fqdn;
if ($server->proxyType() !== 'NONE' && $applicationSettings->is_container_label_readonly_enabled === true) {
$url = generateUrl(server: $server, random: $uuid);
}
// Clone the application
$newApplication = $source->replicate([
'id',
'created_at',
'updated_at',
'additional_servers_count',
'additional_networks_count',
])->fill(array_merge([
'uuid' => $uuid,
'name' => $name,
'fqdn' => $url,
'status' => 'exited',
'destination_id' => $destination->id,
], $overrides));
$newApplication->save();
// Update custom labels if needed
if ($newApplication->destination->server->proxyType() !== 'NONE' && $applicationSettings->is_container_label_readonly_enabled === true) {
$customLabels = str(implode('|coolify|', generateLabelsApplication($newApplication)))->replace('|coolify|', "\n");
$newApplication->custom_labels = base64_encode($customLabels);
$newApplication->save();
}
// Clone settings
$newApplication->settings()->delete();
if ($applicationSettings) {
$newApplicationSettings = $applicationSettings->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'application_id' => $newApplication->id,
]);
$newApplicationSettings->save();
}
// Clone tags
$tags = $source->tags;
foreach ($tags as $tag) {
$newApplication->tags()->attach($tag->id);
}
// Clone scheduled tasks
$scheduledTasks = $source->scheduled_tasks()->get();
foreach ($scheduledTasks as $task) {
$newTask = $task->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => (string) new Cuid2,
'application_id' => $newApplication->id,
'team_id' => currentTeam()->id,
]);
$newTask->save();
}
// Clone previews with FQDN regeneration
$applicationPreviews = $source->previews()->get();
foreach ($applicationPreviews as $preview) {
$newPreview = $preview->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => (string) new Cuid2,
'application_id' => $newApplication->id,
'status' => 'exited',
'fqdn' => null,
'docker_compose_domains' => null,
]);
$newPreview->save();
// Regenerate FQDN for the cloned preview
if ($newApplication->build_pack === 'dockercompose') {
$newPreview->generate_preview_fqdn_compose();
} else {
$newPreview->generate_preview_fqdn();
}
}
// Clone persistent volumes
$persistentVolumes = $source->persistentStorages()->get();
foreach ($persistentVolumes as $volume) {
$newName = '';
if (str_starts_with($volume->name, $source->uuid)) {
$newName = str($volume->name)->replace($source->uuid, $newApplication->uuid);
} else {
$newName = $newApplication->uuid.'-'.str($volume->name)->afterLast('-');
}
$newPersistentVolume = $volume->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'name' => $newName,
'resource_id' => $newApplication->id,
]);
$newPersistentVolume->save();
if ($cloneVolumeData) {
try {
StopApplication::dispatch($source, false, false);
$sourceVolume = $volume->name;
$targetVolume = $newPersistentVolume->name;
$sourceServer = $source->destination->server;
$targetServer = $newApplication->destination->server;
VolumeCloneJob::dispatch($sourceVolume, $targetVolume, $sourceServer, $targetServer, $newPersistentVolume);
queue_application_deployment(
deployment_uuid: (string) new Cuid2,
application: $source,
server: $sourceServer,
destination: $source->destination,
no_questions_asked: true
);
} catch (\Exception $e) {
\Log::error('Failed to copy volume data for '.$volume->name.': '.$e->getMessage());
}
}
}
// Clone file storages
$fileStorages = $source->fileStorages()->get();
foreach ($fileStorages as $storage) {
$newStorage = $storage->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'resource_id' => $newApplication->id,
]);
$newStorage->save();
}
// Clone production environment variables without triggering the created hook
$environmentVariables = $source->environment_variables()->get();
foreach ($environmentVariables as $environmentVariable) {
\App\Models\EnvironmentVariable::withoutEvents(function () use ($environmentVariable, $newApplication) {
$newEnvironmentVariable = $environmentVariable->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'resourceable_id' => $newApplication->id,
'resourceable_type' => $newApplication->getMorphClass(),
'is_preview' => false,
]);
$newEnvironmentVariable->save();
});
}
// Clone preview environment variables
$previewEnvironmentVariables = $source->environment_variables_preview()->get();
foreach ($previewEnvironmentVariables as $previewEnvironmentVariable) {
\App\Models\EnvironmentVariable::withoutEvents(function () use ($previewEnvironmentVariable, $newApplication) {
$newPreviewEnvironmentVariable = $previewEnvironmentVariable->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'resourceable_id' => $newApplication->id,
'resourceable_type' => $newApplication->getMorphClass(),
'is_preview' => true,
]);
$newPreviewEnvironmentVariable->save();
});
}
return $newApplication;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/api.php | bootstrap/helpers/api.php | <?php
use App\Enums\BuildPackTypes;
use App\Enums\RedirectTypes;
use App\Enums\StaticImageTypes;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
function getTeamIdFromToken()
{
$token = auth()->user()->currentAccessToken();
return data_get($token, 'team_id');
}
function invalidTokenResponse()
{
return response()->json(['message' => 'Invalid token.', 'docs' => 'https://coolify.io/docs/api-reference/authorization'], 400);
}
function serializeApiResponse($data)
{
if ($data instanceof Collection) {
return $data->map(function ($d) {
$d = collect($d)->sortKeys();
$created_at = data_get($d, 'created_at');
$updated_at = data_get($d, 'updated_at');
if ($created_at) {
unset($d['created_at']);
$d['created_at'] = $created_at;
}
if ($updated_at) {
unset($d['updated_at']);
$d['updated_at'] = $updated_at;
}
if (data_get($d, 'name')) {
$d = $d->prepend($d['name'], 'name');
}
if (data_get($d, 'description')) {
$d = $d->prepend($d['description'], 'description');
}
if (data_get($d, 'uuid')) {
$d = $d->prepend($d['uuid'], 'uuid');
}
if (! is_null(data_get($d, 'id'))) {
$d = $d->prepend($d['id'], 'id');
}
return $d;
});
} else {
$d = collect($data)->sortKeys();
$created_at = data_get($d, 'created_at');
$updated_at = data_get($d, 'updated_at');
if ($created_at) {
unset($d['created_at']);
$d['created_at'] = $created_at;
}
if ($updated_at) {
unset($d['updated_at']);
$d['updated_at'] = $updated_at;
}
if (data_get($d, 'name')) {
$d = $d->prepend($d['name'], 'name');
}
if (data_get($d, 'description')) {
$d = $d->prepend($d['description'], 'description');
}
if (data_get($d, 'uuid')) {
$d = $d->prepend($d['uuid'], 'uuid');
}
if (! is_null(data_get($d, 'id'))) {
$d = $d->prepend($d['id'], 'id');
}
return $d;
}
}
function sharedDataApplications()
{
return [
'git_repository' => 'string',
'git_branch' => 'string',
'build_pack' => Rule::enum(BuildPackTypes::class),
'is_static' => 'boolean',
'static_image' => Rule::enum(StaticImageTypes::class),
'domains' => 'string',
'redirect' => Rule::enum(RedirectTypes::class),
'git_commit_sha' => 'string',
'docker_registry_image_name' => 'string|nullable',
'docker_registry_image_tag' => 'string|nullable',
'install_command' => 'string|nullable',
'build_command' => 'string|nullable',
'start_command' => 'string|nullable',
'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/',
'ports_mappings' => 'string|regex:/^(\d+:\d+)(,\d+:\d+)*$/|nullable',
'custom_network_aliases' => 'string|nullable',
'base_directory' => 'string|nullable',
'publish_directory' => 'string|nullable',
'health_check_enabled' => 'boolean',
'health_check_path' => 'string',
'health_check_port' => 'string|nullable',
'health_check_host' => 'string',
'health_check_method' => 'string',
'health_check_return_code' => 'numeric',
'health_check_scheme' => 'string',
'health_check_response_text' => 'string|nullable',
'health_check_interval' => 'numeric',
'health_check_timeout' => 'numeric',
'health_check_retries' => 'numeric',
'health_check_start_period' => 'numeric',
'limits_memory' => 'string',
'limits_memory_swap' => 'string',
'limits_memory_swappiness' => 'numeric',
'limits_memory_reservation' => 'string',
'limits_cpus' => 'string',
'limits_cpuset' => 'string|nullable',
'limits_cpu_shares' => 'numeric',
'custom_labels' => 'string|nullable',
'custom_docker_run_options' => 'string|nullable',
'post_deployment_command' => 'string|nullable',
'post_deployment_command_container' => 'string',
'pre_deployment_command' => 'string|nullable',
'pre_deployment_command_container' => 'string',
'manual_webhook_secret_github' => 'string|nullable',
'manual_webhook_secret_gitlab' => 'string|nullable',
'manual_webhook_secret_bitbucket' => 'string|nullable',
'manual_webhook_secret_gitea' => 'string|nullable',
'docker_compose_location' => 'string',
'docker_compose' => 'string|nullable',
'docker_compose_raw' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_custom_start_command' => 'string|nullable',
'docker_compose_custom_build_command' => 'string|nullable',
];
}
function validateIncomingRequest(Request $request)
{
// check if request is json
if (! $request->isJson()) {
return response()->json([
'message' => 'Invalid request.',
'error' => 'Content-Type must be application/json.',
], 400);
}
// check if request is valid json
if (! json_decode($request->getContent())) {
return response()->json([
'message' => 'Invalid request.',
'error' => 'Invalid JSON.',
], 400);
}
// check if valid json is empty
if (empty($request->json()->all())) {
return response()->json([
'message' => 'Invalid request.',
'error' => 'Empty JSON.',
], 400);
}
}
function removeUnnecessaryFieldsFromRequest(Request $request)
{
$request->offsetUnset('project_uuid');
$request->offsetUnset('environment_name');
$request->offsetUnset('environment_uuid');
$request->offsetUnset('destination_uuid');
$request->offsetUnset('server_uuid');
$request->offsetUnset('type');
$request->offsetUnset('domains');
$request->offsetUnset('instant_deploy');
$request->offsetUnset('github_app_uuid');
$request->offsetUnset('private_key_uuid');
$request->offsetUnset('use_build_server');
$request->offsetUnset('is_static');
$request->offsetUnset('force_domain_override');
$request->offsetUnset('autogenerate_domain');
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/subscriptions.php | bootstrap/helpers/subscriptions.php | <?php
use App\Models\Team;
use Stripe\Stripe;
function isSubscriptionActive()
{
return once(function () {
if (! isCloud()) {
return false;
}
$team = currentTeam();
if (! $team) {
return false;
}
$subscription = $team?->subscription;
if (is_null($subscription)) {
return false;
}
if (isStripe()) {
return $subscription->stripe_invoice_paid === true;
}
return false;
});
}
function isSubscriptionOnGracePeriod()
{
return once(function () {
$team = currentTeam();
if (! $team) {
return false;
}
$subscription = $team?->subscription;
if (! $subscription) {
return false;
}
if (isStripe()) {
return $subscription->stripe_cancel_at_period_end;
}
return false;
});
}
function subscriptionProvider()
{
return config('subscription.provider');
}
function isStripe()
{
return config('subscription.provider') === 'stripe';
}
function getStripeCustomerPortalSession(Team $team)
{
Stripe::setApiKey(config('subscription.stripe_api_key'));
$return_url = route('subscription.show');
$stripe_customer_id = data_get($team, 'subscription.stripe_customer_id');
if (! $stripe_customer_id) {
return null;
}
return \Stripe\BillingPortal\Session::create([
'customer' => $stripe_customer_id,
'return_url' => $return_url,
]);
}
function allowedPathsForUnsubscribedAccounts()
{
return [
'subscription/new',
'login',
'logout',
'force-password-reset',
'livewire/update',
'admin',
];
}
function allowedPathsForBoardingAccounts()
{
return [
...allowedPathsForUnsubscribedAccounts(),
'onboarding',
'livewire/update',
];
}
function allowedPathsForInvalidAccounts()
{
return [
'logout',
'verify',
'force-password-reset',
'livewire/update',
];
}
function updateStripeCustomerEmail(Team $team, string $newEmail): void
{
if (! isStripe()) {
return;
}
$stripe_customer_id = data_get($team, 'subscription.stripe_customer_id');
if (! $stripe_customer_id) {
return;
}
Stripe::setApiKey(config('subscription.stripe_api_key'));
\Stripe\Customer::update(
$stripe_customer_id,
['email' => $newEmail]
);
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/bootstrap/helpers/sudo.php | bootstrap/helpers/sudo.php | <?php
use App\Models\Server;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
function shouldChangeOwnership(string $path): bool
{
$path = trim($path);
$systemPaths = ['/var', '/etc', '/usr', '/opt', '/sys', '/proc', '/dev', '/bin', '/sbin', '/lib', '/lib64', '/boot', '/root', '/home', '/media', '/mnt', '/srv', '/run'];
foreach ($systemPaths as $systemPath) {
if ($path === $systemPath || Str::startsWith($path, $systemPath.'/')) {
return false;
}
}
$isCoolifyPath = Str::startsWith($path, '/data/coolify') || Str::startsWith($path, '/tmp/coolify');
return $isCoolifyPath;
}
function parseCommandsByLineForSudo(Collection $commands, Server $server): array
{
$commands = $commands->map(function ($line) {
$trimmedLine = trim($line);
// All bash keywords that should not receive sudo prefix
// Using word boundary matching to avoid prefix collisions (e.g., 'do' vs 'docker', 'if' vs 'ifconfig', 'fi' vs 'find')
$bashKeywords = [
'cd',
'command',
'declare',
'echo',
'export',
'local',
'readonly',
'return',
'true',
'if',
'fi',
'for',
'done',
'while',
'until',
'case',
'esac',
'select',
'then',
'else',
'elif',
'break',
'continue',
'do',
];
// Special case: comments (no collision risk with '#')
if (str_starts_with($trimmedLine, '#')) {
return $line;
}
// Check all keywords with word boundary matching
// Match keyword followed by space, semicolon, or end of line
foreach ($bashKeywords as $keyword) {
if (preg_match('/^'.preg_quote($keyword, '/').'(\s|;|$)/', $trimmedLine)) {
// Special handling for 'if' - insert sudo after 'if '
if ($keyword === 'if') {
return preg_replace('/^(\s*)if\s+/', '$1if sudo ', $line);
}
return $line;
}
}
return "sudo $line";
});
$commands = $commands->map(function ($line) use ($server) {
if (Str::startsWith($line, 'sudo mkdir -p')) {
$path = trim(Str::after($line, 'sudo mkdir -p'));
if (shouldChangeOwnership($path)) {
return "$line && sudo chown -R $server->user:$server->user $path && sudo chmod -R o-rwx $path";
}
return $line;
}
return $line;
});
$commands = $commands->map(function ($line) {
$line = str($line);
// Detect complex piped commands that should be wrapped in bash -c
$isComplexPipeCommand = (
$line->contains(' | sh') ||
$line->contains(' | bash') ||
($line->contains(' | ') && ($line->contains('||') || $line->contains('&&')))
);
// If it's a complex pipe command and starts with sudo, wrap it in bash -c
if ($isComplexPipeCommand && $line->startsWith('sudo ')) {
$commandWithoutSudo = $line->after('sudo ')->value();
// Escape single quotes for bash -c by replacing ' with '\''
$escapedCommand = str_replace("'", "'\\''", $commandWithoutSudo);
return "sudo bash -c '$escapedCommand'";
}
// For non-complex commands, apply the original logic
if (str($line)->contains('$(')) {
$line = $line->replace('$(', '$(sudo ');
}
if (! $isComplexPipeCommand && str($line)->contains('||')) {
$line = $line->replace('||', '|| sudo');
}
if (! $isComplexPipeCommand && str($line)->contains('&&')) {
$line = $line->replace('&&', '&& sudo');
}
// Don't insert sudo into pipes for complex commands
if (! $isComplexPipeCommand && str($line)->contains(' | ')) {
$line = $line->replace(' | ', ' | sudo ');
}
return $line->value();
});
return $commands->toArray();
}
function parseLineForSudo(string $command, Server $server): string
{
if (! str($command)->startSwith('cd') && ! str($command)->startSwith('command')) {
$command = "sudo $command";
}
if (Str::startsWith($command, 'sudo mkdir -p')) {
$path = trim(Str::after($command, 'sudo mkdir -p'));
if (shouldChangeOwnership($path)) {
$command = "$command && sudo chown -R $server->user:$server->user $path && sudo chmod -R o-rwx $path";
}
}
if (str($command)->contains('$(') || str($command)->contains('`')) {
$command = str($command)->replace('$(', '$(sudo ')->replace('`', '`sudo ')->value();
}
if (str($command)->contains('||')) {
$command = str($command)->replace('||', '|| sudo ')->value();
}
if (str($command)->contains('&&')) {
$command = str($command)->replace('&&', '&& sudo ')->value();
}
return $command;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Pest.php | tests/Pest.php | <?php
/*
|--------------------------------------------------------------------------
| Test Case
|--------------------------------------------------------------------------
|
| The closure you provide to your test functions is always bound to a specific PHPUnit test
| case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may
| need to change it using the "uses()" function to bind a different classes or traits.
|
*/
uses(Tests\TestCase::class)->in('Feature');
/*
|--------------------------------------------------------------------------
| Expectations
|--------------------------------------------------------------------------
|
| When you're writing tests, you often need to check that values meet certain conditions. The
| "expect()" function gives you access to a set of "expectations" methods that you can use
| to assert different things. Of course, you may extend the Expectation API at any time.
|
*/
// expect()->extend('toBeOne', function () {
// return $this->toBe(1);
// });
/*
|--------------------------------------------------------------------------
| Functions
|--------------------------------------------------------------------------
|
| While Pest is very powerful out-of-the-box, you may have some testing code specific to your
| project that you don't want to repeat in every file. Here you can also expose helpers as
| global functions to help you to reduce the number of lines of code in your test files.
|
*/
// function something()
// {
// // ..
// }
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/TestCase.php | tests/TestCase.php | <?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/CreatesApplication.php | tests/CreatesApplication.php | <?php
namespace Tests;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Application;
trait CreatesApplication
{
/**
* Creates the application.
*/
public function createApplication(): Application
{
$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/DuskTestCase.php | tests/DuskTestCase.php | <?php
namespace Tests;
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Illuminate\Support\Collection;
use Laravel\Dusk\TestCase as BaseTestCase;
abstract class DuskTestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Prepare for Dusk test execution.
*
* @beforeClass
*/
public static function prepare(): void
{
if (! static::runningInSail()) {
static::startChromeDriver();
}
}
/**
* Create the RemoteWebDriver instance.
*/
protected function driver(): RemoteWebDriver
{
$options = (new ChromeOptions)->addArguments(collect([
$this->shouldStartMaximized() ? '--start-maximized' : '--window-size=1920,1080',
])->unless($this->hasHeadlessDisabled(), function (Collection $items) {
return $items->merge([
'--disable-gpu',
'--headless=new',
]);
})->all());
return RemoteWebDriver::create(
'http://localhost:4444',
DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY,
$options
)
);
}
/**
* Determine if the browser window should start maximized.
*/
protected function baseUrl()
{
return 'http://localhost:8000';
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Traits/HandlesTestDatabase.php | tests/Traits/HandlesTestDatabase.php | <?php
namespace Tests\Traits;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
trait HandlesTestDatabase
{
protected function setUpTestDatabase(): void
{
try {
// Create test database if it doesn't exist
$database = config('database.connections.testing.database');
$this->createTestDatabase($database);
// Run migrations
Artisan::call('migrate:fresh', [
'--database' => 'testing',
'--seed' => false,
]);
} catch (\Exception $e) {
$this->tearDownTestDatabase();
throw $e;
}
}
protected function tearDownTestDatabase(): void
{
try {
// Drop test database
$database = config('database.connections.testing.database');
$this->dropTestDatabase($database);
} catch (\Exception $e) {
// Log error but don't throw
error_log('Failed to tear down test database: '.$e->getMessage());
}
}
protected function createTestDatabase($database)
{
try {
// Connect to postgres database to create/drop test database
config(['database.connections.pgsql.database' => 'postgres']);
DB::purge('pgsql');
DB::reconnect('pgsql');
// Drop if exists and create new database
DB::connection('pgsql')->statement("DROP DATABASE IF EXISTS $database WITH (FORCE);");
DB::connection('pgsql')->statement("CREATE DATABASE $database;");
// Switch back to testing connection
DB::disconnect('pgsql');
DB::reconnect('testing');
} catch (\Exception $e) {
$this->tearDownTestDatabase();
throw new \Exception('Could not create test database: '.$e->getMessage());
}
}
protected function dropTestDatabase($database)
{
try {
// Connect to postgres database to drop test database
config(['database.connections.pgsql.database' => 'postgres']);
DB::purge('pgsql');
DB::reconnect('pgsql');
// Drop the test database
DB::connection('pgsql')->statement("DROP DATABASE IF EXISTS $database WITH (FORCE);");
DB::disconnect('pgsql');
} catch (\Exception $e) {
// Log error but don't throw
error_log('Failed to drop test database: '.$e->getMessage());
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Browser/LoginTest.php | tests/Browser/LoginTest.php | <?php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Throwable;
class LoginTest extends DuskTestCase
{
/**
* A basic test for the login page.
* Login with the test user and assert that the user is redirected to the dashboard.
*
* @return void
*
* @throws Throwable
*/
public function test_login()
{
$this->browse(callback: function (Browser $browser) {
$browser->loginWithRootUser()
->assertPathIs('/')
->assertSee('Dashboard');
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Browser/Project/ProjectTest.php | tests/Browser/Project/ProjectTest.php | <?php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Throwable;
class ProjectTest extends DuskTestCase
{
/**
* A basic test for the projects page.
* Login with the test user and assert that the user is redirected to the projects page.
*
* @return void
*
* @throws Throwable
*/
public function test_login()
{
$this->browse(function (Browser $browser) {
$browser->loginWithRootUser()
->visit('/projects')
->assertSee('Projects');
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Browser/Project/ProjectAddNewTest.php | tests/Browser/Project/ProjectAddNewTest.php | <?php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Throwable;
class ProjectAddNewTest extends DuskTestCase
{
/**
* A basic test for the projects page.
* Login with the test user and assert that the user is redirected to the projects page.
*
* @return void
*
* @throws Throwable
*/
public function test_login()
{
$this->browse(function (Browser $browser) {
$browser->loginWithRootUser()
->visit('/projects')
->pressAndWaitFor('+ Add', 1)
->assertSee('New Project')
->screenshot('project-add-new-1')
->type('name', 'Test Project')
->screenshot('project-add-new-2')
->press('Continue')
->assertSee('Test Project.')
->screenshot('project-add-new-3');
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Browser/Project/ProjectSearchTest.php | tests/Browser/Project/ProjectSearchTest.php | <?php
namespace Tests\Browser;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use Throwable;
class ProjectSearchTest extends DuskTestCase
{
/**
* A basic test for the projects page.
* Login with the test user and assert that the user is redirected to the projects page.
*
* @return void
*
* @throws Throwable
*/
public function test_login()
{
$this->browse(function (Browser $browser) {
$browser->loginWithRootUser()
->visit('/projects')
->type('[x-model="search"]', 'joi43j4oi32j4o2')
->assertSee('No project found with the search term "joi43j4oi32j4o2".')
->screenshot('project-search-not-found');
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ConvertingGitUrlsTest.php | tests/Feature/ConvertingGitUrlsTest.php | <?php
use App\Models\GithubApp;
test('convertGitUrlsForDeployKeyAndGithubAppAndHttpUrl', function () {
$githubApp = GithubApp::find(0);
$result = convertGitUrl('andrasbacsai/coolify-examples.git', 'deploy_key', $githubApp);
expect($result)->toBe([
'repository' => 'git@github.com:andrasbacsai/coolify-examples.git',
'port' => 22,
]);
});
test('convertGitUrlsForDeployKeyAndGithubAppAndSshUrl', function () {
$githubApp = GithubApp::find(0);
$result = convertGitUrl('git@github.com:andrasbacsai/coolify-examples.git', 'deploy_key', $githubApp);
expect($result)->toBe([
'repository' => 'git@github.com:andrasbacsai/coolify-examples.git',
'port' => 22,
]);
});
test('convertGitUrlsForDeployKeyAndHttpUrl', function () {
$result = convertGitUrl('andrasbacsai/coolify-examples.git', 'deploy_key', null);
expect($result)->toBe([
'repository' => 'andrasbacsai/coolify-examples.git',
'port' => 22,
]);
});
test('convertGitUrlsForDeployKeyAndSshUrl', function () {
$result = convertGitUrl('git@github.com:andrasbacsai/coolify-examples.git', 'deploy_key', null);
expect($result)->toBe([
'repository' => 'git@github.com:andrasbacsai/coolify-examples.git',
'port' => 22,
]);
});
test('convertGitUrlsForSourceAndSshUrl', function () {
$result = convertGitUrl('git@github.com:andrasbacsai/coolify-examples.git', 'source', null);
expect($result)->toBe([
'repository' => 'git@github.com:andrasbacsai/coolify-examples.git',
'port' => 22,
]);
});
test('convertGitUrlsForSourceAndHttpUrl', function () {
$result = convertGitUrl('andrasbacsai/coolify-examples.git', 'source', null);
expect($result)->toBe([
'repository' => 'andrasbacsai/coolify-examples.git',
'port' => 22,
]);
});
test('convertGitUrlsForSourceAndSshUrlWithCustomPort', function () {
$result = convertGitUrl('git@git.domain.com:766/group/project.git', 'source', null);
expect($result)->toBe([
'repository' => 'git@git.domain.com:group/project.git',
'port' => '766',
]);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/MultilineEnvironmentVariableTest.php | tests/Feature/MultilineEnvironmentVariableTest.php | <?php
test('multiline environment variables are properly escaped for docker build args', function () {
$sshKey = '-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
-----END OPENSSH PRIVATE KEY-----';
$variables = [
['key' => 'SSH_PRIVATE_KEY', 'value' => "'{$sshKey}'", 'is_multiline' => true],
['key' => 'REGULAR_VAR', 'value' => 'simple value', 'is_multiline' => false],
];
$buildArgs = generateDockerBuildArgs($variables);
// SSH key should use double quotes and have proper escaping
$sshArg = $buildArgs->first();
expect($sshArg)->toStartWith('--build-arg SSH_PRIVATE_KEY="');
expect($sshArg)->toEndWith('"');
expect($sshArg)->toContain('BEGIN OPENSSH PRIVATE KEY');
expect($sshArg)->not->toContain("'BEGIN"); // Should not have the wrapper single quotes
// Regular var should use escapeshellarg (single quotes)
$regularArg = $buildArgs->last();
expect($regularArg)->toBe("--build-arg REGULAR_VAR='simple value'");
});
test('multiline variables with special bash characters are escaped correctly', function () {
$valueWithSpecialChars = "line1\nline2 with \"quotes\"\nline3 with \$variables\nline4 with `backticks`";
$variables = [
['key' => 'SPECIAL_VALUE', 'value' => "'{$valueWithSpecialChars}'", 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// Verify double quotes are escaped
expect($arg)->toContain('\\"quotes\\"');
// Verify dollar signs are escaped
expect($arg)->toContain('\\$variables');
// Verify backticks are escaped
expect($arg)->toContain('\\`backticks\\`');
});
test('single-line environment variables use escapeshellarg', function () {
$variables = [
['key' => 'SIMPLE_VAR', 'value' => 'simple value with spaces', 'is_multiline' => false],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// Should use single quotes from escapeshellarg
expect($arg)->toBe("--build-arg SIMPLE_VAR='simple value with spaces'");
});
test('multiline certificate with newlines is preserved', function () {
$certificate = '-----BEGIN CERTIFICATE-----
MIIDXTCCAkWgAwIBAgIJAKL0UG+mRkSvMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV
BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
aWRnaXRzIFB0eSBMdGQwHhcNMTkwOTE3MDUzMzI5WhcNMjkwOTE0MDUzMzI5WjBF
-----END CERTIFICATE-----';
$variables = [
['key' => 'TLS_CERT', 'value' => "'{$certificate}'", 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// Newlines should be preserved in the output
expect($arg)->toContain("\n");
expect($arg)->toContain('BEGIN CERTIFICATE');
expect($arg)->toContain('END CERTIFICATE');
expect(substr_count($arg, "\n"))->toBeGreaterThan(0);
});
test('multiline JSON configuration is properly escaped', function () {
$jsonConfig = '{
"key": "value",
"nested": {
"array": [1, 2, 3]
}
}';
$variables = [
['key' => 'JSON_CONFIG', 'value' => "'{$jsonConfig}'", 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// All double quotes in JSON should be escaped
expect($arg)->toContain('\\"key\\"');
expect($arg)->toContain('\\"value\\"');
expect($arg)->toContain('\\"nested\\"');
});
test('empty multiline variable is handled correctly', function () {
$variables = [
['key' => 'EMPTY_VAR', 'value' => "''", 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
expect($arg)->toBe('--build-arg EMPTY_VAR=""');
});
test('multiline variable with only newlines', function () {
$onlyNewlines = "\n\n\n";
$variables = [
['key' => 'NEWLINES_ONLY', 'value' => "'{$onlyNewlines}'", 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
expect($arg)->toContain("\n");
// Should have 3 newlines preserved
expect(substr_count($arg, "\n"))->toBe(3);
});
test('multiline variable with backslashes is escaped correctly', function () {
$valueWithBackslashes = "path\\to\\file\nC:\\Windows\\System32";
$variables = [
['key' => 'PATH_VAR', 'value' => "'{$valueWithBackslashes}'", 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// Backslashes should be doubled
expect($arg)->toContain('path\\\\to\\\\file');
expect($arg)->toContain('C:\\\\Windows\\\\System32');
});
test('generateDockerEnvFlags produces correct format', function () {
$variables = [
['key' => 'NORMAL_VAR', 'value' => 'value', 'is_multiline' => false],
['key' => 'MULTILINE_VAR', 'value' => "'line1\nline2'", 'is_multiline' => true],
];
$envFlags = generateDockerEnvFlags($variables);
expect($envFlags)->toContain('-e NORMAL_VAR=');
expect($envFlags)->toContain('-e MULTILINE_VAR="');
expect($envFlags)->toContain('line1');
expect($envFlags)->toContain('line2');
});
test('helper functions work with collection input', function () {
$variables = collect([
(object) ['key' => 'VAR1', 'value' => 'value1', 'is_multiline' => false],
(object) ['key' => 'VAR2', 'value' => "'multiline\nvalue'", 'is_multiline' => true],
]);
$buildArgs = generateDockerBuildArgs($variables);
expect($buildArgs)->toHaveCount(2);
$envFlags = generateDockerEnvFlags($variables);
expect($envFlags)->toBeString();
expect($envFlags)->toContain('-e VAR1=');
expect($envFlags)->toContain('-e VAR2="');
});
test('variables without is_multiline default to false', function () {
$variables = [
['key' => 'NO_FLAG_VAR', 'value' => 'some value'],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// Should use escapeshellarg (single quotes) since is_multiline defaults to false
expect($arg)->toBe("--build-arg NO_FLAG_VAR='some value'");
});
test('real world SSH key example', function () {
// Simulate what real_value returns (wrapped in single quotes)
$sshKey = "'-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
-----END OPENSSH PRIVATE KEY-----'";
$variables = [
['key' => 'KEY', 'value' => $sshKey, 'is_multiline' => true],
];
$buildArgs = generateDockerBuildArgs($variables);
$arg = $buildArgs->first();
// Should produce clean output without wrapper quotes
expect($arg)->toStartWith('--build-arg KEY="-----BEGIN OPENSSH PRIVATE KEY-----');
expect($arg)->toEndWith('-----END OPENSSH PRIVATE KEY-----"');
// Should NOT have the escaped quote sequence that was in the bug
expect($arg)->not->toContain("''");
expect($arg)->not->toContain("'\\''");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ConvertArraysTest.php | tests/Feature/ConvertArraysTest.php | <?php
test('isAssociativeArray', function () {
expect(isAssociativeArray([1, 2, 3]))->toBeFalse();
expect(isAssociativeArray(collect([1, 2, 3])))->toBeFalse();
expect(isAssociativeArray(collect(['a' => 1, 'b' => 2, 'c' => 3])))->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/DeploymentCancellationApiTest.php | tests/Feature/DeploymentCancellationApiTest.php | <?php
use App\Enums\ApplicationDeploymentStatus;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Create an API token for the user
$this->token = $this->user->createToken('test-token', ['*'], $this->team->id);
$this->bearerToken = $this->token->plainTextToken;
// Create a server for the team
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
});
describe('POST /api/v1/deployments/{uuid}/cancel', function () {
test('returns 401 when not authenticated', function () {
$response = $this->postJson('/api/v1/deployments/fake-uuid/cancel');
$response->assertStatus(401);
});
test('returns 404 when deployment not found', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/deployments/non-existent-uuid/cancel');
$response->assertStatus(404);
$response->assertJson(['message' => 'Deployment not found.']);
});
test('returns 403 when user does not own the deployment', function () {
// Create another team and server
$otherTeam = Team::factory()->create();
$otherServer = Server::factory()->create(['team_id' => $otherTeam->id]);
// Create a deployment on the other team's server
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'test-deployment-uuid',
'application_id' => 1,
'server_id' => $otherServer->id,
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
$response->assertStatus(403);
$response->assertJson(['message' => 'You do not have permission to cancel this deployment.']);
});
test('returns 400 when deployment is already finished', function () {
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'finished-deployment-uuid',
'application_id' => 1,
'server_id' => $this->server->id,
'status' => ApplicationDeploymentStatus::FINISHED->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
$response->assertStatus(400);
$response->assertJsonFragment(['Deployment cannot be cancelled']);
});
test('returns 400 when deployment is already failed', function () {
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'failed-deployment-uuid',
'application_id' => 1,
'server_id' => $this->server->id,
'status' => ApplicationDeploymentStatus::FAILED->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
$response->assertStatus(400);
$response->assertJsonFragment(['Deployment cannot be cancelled']);
});
test('returns 400 when deployment is already cancelled', function () {
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'cancelled-deployment-uuid',
'application_id' => 1,
'server_id' => $this->server->id,
'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
$response->assertStatus(400);
$response->assertJsonFragment(['Deployment cannot be cancelled']);
});
test('successfully cancels queued deployment', function () {
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'queued-deployment-uuid',
'application_id' => 1,
'server_id' => $this->server->id,
'status' => ApplicationDeploymentStatus::QUEUED->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
// Expect success (200) or 500 if server connection fails (which is expected in test environment)
expect($response->status())->toBeIn([200, 500]);
// Verify deployment status was updated to cancelled
$deployment->refresh();
expect($deployment->status)->toBe(ApplicationDeploymentStatus::CANCELLED_BY_USER->value);
});
test('successfully cancels in-progress deployment', function () {
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'in-progress-deployment-uuid',
'application_id' => 1,
'server_id' => $this->server->id,
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
// Expect success (200) or 500 if server connection fails (which is expected in test environment)
expect($response->status())->toBeIn([200, 500]);
// Verify deployment status was updated to cancelled
$deployment->refresh();
expect($deployment->status)->toBe(ApplicationDeploymentStatus::CANCELLED_BY_USER->value);
});
test('returns correct response structure on success', function () {
$deployment = ApplicationDeploymentQueue::create([
'deployment_uuid' => 'success-deployment-uuid',
'application_id' => 1,
'server_id' => $this->server->id,
'status' => ApplicationDeploymentStatus::IN_PROGRESS->value,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/deployments/{$deployment->deployment_uuid}/cancel");
if ($response->status() === 200) {
$response->assertJsonStructure([
'message',
'deployment_uuid',
'status',
]);
$response->assertJson([
'deployment_uuid' => $deployment->deployment_uuid,
'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
]);
}
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/TeamPolicyTest.php | tests/Feature/TeamPolicyTest.php | <?php
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner, admin, and member
$this->team = Team::factory()->create();
$this->owner = User::factory()->create();
$this->admin = User::factory()->create();
$this->member = User::factory()->create();
$this->team->members()->attach($this->owner->id, ['role' => 'owner']);
$this->team->members()->attach($this->admin->id, ['role' => 'admin']);
$this->team->members()->attach($this->member->id, ['role' => 'member']);
});
describe('update permission', function () {
test('owner can update team', function () {
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
expect($this->owner->can('update', $this->team))->toBeTrue();
});
test('admin can update team', function () {
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
expect($this->admin->can('update', $this->team))->toBeTrue();
});
test('member cannot update team', function () {
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
expect($this->member->can('update', $this->team))->toBeFalse();
});
test('non-team member cannot update team', function () {
$outsider = User::factory()->create();
$this->actingAs($outsider);
session(['currentTeam' => $this->team]);
expect($outsider->can('update', $this->team))->toBeFalse();
});
});
describe('delete permission', function () {
test('owner can delete team', function () {
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
expect($this->owner->can('delete', $this->team))->toBeTrue();
});
test('admin can delete team', function () {
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
expect($this->admin->can('delete', $this->team))->toBeTrue();
});
test('member cannot delete team', function () {
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
expect($this->member->can('delete', $this->team))->toBeFalse();
});
test('non-team member cannot delete team', function () {
$outsider = User::factory()->create();
$this->actingAs($outsider);
session(['currentTeam' => $this->team]);
expect($outsider->can('delete', $this->team))->toBeFalse();
});
});
describe('manageMembers permission', function () {
test('owner can manage members', function () {
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
expect($this->owner->can('manageMembers', $this->team))->toBeTrue();
});
test('admin can manage members', function () {
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
expect($this->admin->can('manageMembers', $this->team))->toBeTrue();
});
test('member cannot manage members', function () {
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
expect($this->member->can('manageMembers', $this->team))->toBeFalse();
});
test('non-team member cannot manage members', function () {
$outsider = User::factory()->create();
$this->actingAs($outsider);
session(['currentTeam' => $this->team]);
expect($outsider->can('manageMembers', $this->team))->toBeFalse();
});
});
describe('viewAdmin permission', function () {
test('owner can view admin panel', function () {
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
expect($this->owner->can('viewAdmin', $this->team))->toBeTrue();
});
test('admin can view admin panel', function () {
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
expect($this->admin->can('viewAdmin', $this->team))->toBeTrue();
});
test('member cannot view admin panel', function () {
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
expect($this->member->can('viewAdmin', $this->team))->toBeFalse();
});
test('non-team member cannot view admin panel', function () {
$outsider = User::factory()->create();
$this->actingAs($outsider);
session(['currentTeam' => $this->team]);
expect($outsider->can('viewAdmin', $this->team))->toBeFalse();
});
});
describe('manageInvitations permission (privilege escalation fix)', function () {
test('owner can manage invitations', function () {
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
expect($this->owner->can('manageInvitations', $this->team))->toBeTrue();
});
test('admin can manage invitations', function () {
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
expect($this->admin->can('manageInvitations', $this->team))->toBeTrue();
});
test('member cannot manage invitations (SECURITY FIX)', function () {
// This test verifies the privilege escalation vulnerability is fixed
// Previously, members could see and manage admin invitations
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
expect($this->member->can('manageInvitations', $this->team))->toBeFalse();
});
test('non-team member cannot manage invitations', function () {
$outsider = User::factory()->create();
$this->actingAs($outsider);
session(['currentTeam' => $this->team]);
expect($outsider->can('manageInvitations', $this->team))->toBeFalse();
});
});
describe('view permission', function () {
test('owner can view team', function () {
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
expect($this->owner->can('view', $this->team))->toBeTrue();
});
test('admin can view team', function () {
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
expect($this->admin->can('view', $this->team))->toBeTrue();
});
test('member can view team', function () {
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
expect($this->member->can('view', $this->team))->toBeTrue();
});
test('non-team member cannot view team', function () {
$outsider = User::factory()->create();
$this->actingAs($outsider);
session(['currentTeam' => $this->team]);
expect($outsider->can('view', $this->team))->toBeFalse();
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ApplicationBuildpackCleanupTest.php | tests/Feature/ApplicationBuildpackCleanupTest.php | <?php
use App\Models\Application;
use App\Models\Environment;
use App\Models\EnvironmentVariable;
use App\Models\Project;
use App\Models\Team;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
describe('Application Model Buildpack Cleanup', function () {
test('model clears dockerfile fields when build_pack changes from dockerfile to nixpacks', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM node:18\nHEALTHCHECK CMD curl -f http://localhost/ || exit 1',
'dockerfile_location' => '/Dockerfile',
'dockerfile_target_build' => 'production',
'custom_healthcheck_found' => true,
]);
// Change buildpack to nixpacks
$application->build_pack = 'nixpacks';
$application->save();
// Reload from database
$application->refresh();
// Verify dockerfile fields were cleared
expect($application->build_pack)->toBe('nixpacks');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->dockerfile_target_build)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
test('model clears dockerfile fields when build_pack changes from dockerfile to static', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM nginx:alpine',
'dockerfile_location' => '/custom.Dockerfile',
'dockerfile_target_build' => 'prod',
'custom_healthcheck_found' => true,
]);
$application->build_pack = 'static';
$application->save();
$application->refresh();
expect($application->build_pack)->toBe('static');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->dockerfile_target_build)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
test('model clears dockercompose fields when build_pack changes from dockercompose to nixpacks', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockercompose',
'docker_compose_domains' => '{"app": "example.com"}',
'docker_compose_raw' => 'version: "3.8"\nservices:\n app:\n image: nginx',
]);
// Add environment variables that should be deleted
EnvironmentVariable::create([
'application_id' => $application->id,
'key' => 'SERVICE_FQDN_APP',
'value' => 'app.example.com',
'is_build_time' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'application_id' => $application->id,
'key' => 'SERVICE_URL_APP',
'value' => 'http://app.example.com',
'is_build_time' => false,
'is_preview' => false,
]);
EnvironmentVariable::create([
'application_id' => $application->id,
'key' => 'REGULAR_VAR',
'value' => 'should_remain',
'is_build_time' => false,
'is_preview' => false,
]);
$application->build_pack = 'nixpacks';
$application->save();
$application->refresh();
expect($application->build_pack)->toBe('nixpacks');
expect($application->docker_compose_domains)->toBeNull();
expect($application->docker_compose_raw)->toBeNull();
// Verify SERVICE_FQDN_* and SERVICE_URL_* were deleted
expect($application->environment_variables()->where('key', 'SERVICE_FQDN_APP')->count())->toBe(0);
expect($application->environment_variables()->where('key', 'SERVICE_URL_APP')->count())->toBe(0);
// Verify regular variables remain
expect($application->environment_variables()->where('key', 'REGULAR_VAR')->count())->toBe(1);
});
test('model does not clear dockerfile fields when switching to dockerfile', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'nixpacks',
'dockerfile' => null,
]);
$application->build_pack = 'dockerfile';
$application->save();
$application->refresh();
// When switching TO dockerfile, no cleanup should happen
expect($application->build_pack)->toBe('dockerfile');
});
test('model does not clear fields when switching between non-dockerfile buildpacks', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'nixpacks',
'dockerfile' => null,
'dockerfile_location' => null,
]);
$application->build_pack = 'static';
$application->save();
$application->refresh();
expect($application->build_pack)->toBe('static');
expect($application->dockerfile)->toBeNull();
});
test('model does not trigger cleanup when build_pack is not changed', function () {
$team = Team::factory()->create();
$project = Project::factory()->create(['team_id' => $team->id]);
$environment = Environment::factory()->create(['project_id' => $project->id]);
$application = Application::factory()->create([
'environment_id' => $environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM alpine:latest',
'dockerfile_location' => '/Dockerfile',
'custom_healthcheck_found' => true,
]);
// Update another field without changing build_pack
$application->name = 'Updated Name';
$application->save();
$application->refresh();
// Dockerfile fields should remain unchanged
expect($application->build_pack)->toBe('dockerfile');
expect($application->dockerfile)->toBe('FROM alpine:latest');
expect($application->dockerfile_location)->toBe('/Dockerfile');
expect($application->custom_healthcheck_found)->toBeTrue();
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/DatabaseBackupCreationApiTest.php | tests/Feature/DatabaseBackupCreationApiTest.php | <?php
use App\Models\StandalonePostgresql;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Create an API token for the user
$this->token = $this->user->createToken('test-token', ['*'], $this->team->id);
$this->bearerToken = $this->token->plainTextToken;
// Mock a database - we'll use Mockery to avoid needing actual database setup
$this->database = \Mockery::mock(StandalonePostgresql::class);
$this->database->shouldReceive('getAttribute')->with('id')->andReturn(1);
$this->database->shouldReceive('getAttribute')->with('uuid')->andReturn('test-db-uuid');
$this->database->shouldReceive('getAttribute')->with('postgres_db')->andReturn('testdb');
$this->database->shouldReceive('type')->andReturn('standalone-postgresql');
$this->database->shouldReceive('getMorphClass')->andReturn('App\Models\StandalonePostgresql');
});
afterEach(function () {
\Mockery::close();
});
describe('POST /api/v1/databases/{uuid}/backups', function () {
test('creates backup configuration with minimal required fields', function () {
// This is a unit-style test using mocks to avoid database dependency
// For full integration testing, this should be run inside Docker
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => 'daily',
]);
// Since we're mocking, this test verifies the endpoint exists and basic validation
// Full integration tests should be run in Docker environment
expect($response->status())->toBeIn([201, 404, 422]);
});
test('validates frequency is required', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'enabled' => true,
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors(['frequency']);
});
test('validates s3_storage_uuid required when save_s3 is true', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => 'daily',
'save_s3' => true,
]);
// Should fail validation because s3_storage_uuid is missing
expect($response->status())->toBeIn([404, 422]);
});
test('rejects invalid frequency format', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => 'invalid-frequency',
]);
expect($response->status())->toBeIn([404, 422]);
});
test('rejects request without authentication', function () {
$response = $this->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => 'daily',
]);
$response->assertStatus(401);
});
test('validates retention fields are integers with minimum 0', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => 'daily',
'database_backup_retention_amount_locally' => -1,
]);
expect($response->status())->toBeIn([404, 422]);
});
test('accepts valid cron expressions', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => '0 2 * * *', // Daily at 2 AM
]);
// Will fail with 404 because database doesn't exist, but validates the request format
expect($response->status())->toBeIn([201, 404, 422]);
});
test('accepts predefined frequency values', function () {
$frequencies = ['every_minute', 'hourly', 'daily', 'weekly', 'monthly', 'yearly'];
foreach ($frequencies as $frequency) {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => $frequency,
]);
// Will fail with 404 because database doesn't exist, but validates the request format
expect($response->status())->toBeIn([201, 404, 422]);
}
});
test('rejects extra fields not in allowed list', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/databases/test-db-uuid/backups', [
'frequency' => 'daily',
'invalid_field' => 'invalid_value',
]);
expect($response->status())->toBeIn([404, 422]);
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/BuildpackSwitchCleanupTest.php | tests/Feature/BuildpackSwitchCleanupTest.php | <?php
use App\Livewire\Project\Application\General;
use App\Models\Application;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Set current team
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
// Create project and environment
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create(['project_id' => $this->project->id]);
});
describe('Buildpack Switching Cleanup', function () {
test('clears dockerfile fields when switching from dockerfile to nixpacks', function () {
// Create an application with dockerfile buildpack and dockerfile content
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM node:18\nHEALTHCHECK CMD curl -f http://localhost/ || exit 1',
'dockerfile_location' => '/Dockerfile',
'dockerfile_target_build' => 'production',
'custom_healthcheck_found' => true,
]);
// Switch to nixpacks buildpack
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->set('buildPack', 'nixpacks')
->call('updatedBuildPack');
// Verify dockerfile fields were cleared
$application->refresh();
expect($application->build_pack)->toBe('nixpacks');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->dockerfile_target_build)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
test('clears dockerfile fields when switching from dockerfile to static', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM nginx:alpine',
'dockerfile_location' => '/custom.Dockerfile',
'dockerfile_target_build' => 'prod',
'custom_healthcheck_found' => true,
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->set('buildPack', 'static')
->call('updatedBuildPack');
$application->refresh();
expect($application->build_pack)->toBe('static');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->dockerfile_target_build)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
test('does not clear dockerfile fields when switching to dockerfile', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'nixpacks',
'dockerfile' => null,
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->set('buildPack', 'dockerfile')
->call('updatedBuildPack');
// When switching TO dockerfile, fields remain as they were
$application->refresh();
expect($application->build_pack)->toBe('dockerfile');
});
test('does not affect fields when switching between non-dockerfile buildpacks', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'nixpacks',
'dockerfile' => null,
'dockerfile_location' => null,
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->set('buildPack', 'static')
->call('updatedBuildPack');
$application->refresh();
expect($application->build_pack)->toBe('static');
expect($application->dockerfile)->toBeNull();
});
test('clears dockerfile fields when switching from dockerfile to dockercompose', function () {
$application = Application::factory()->create([
'environment_id' => $this->environment->id,
'build_pack' => 'dockerfile',
'dockerfile' => 'FROM alpine:latest',
'dockerfile_location' => '/docker/Dockerfile',
'custom_healthcheck_found' => true,
]);
Livewire::test(General::class, ['application' => $application])
->assertSuccessful()
->set('buildPack', 'dockercompose')
->call('updatedBuildPack');
$application->refresh();
expect($application->build_pack)->toBe('dockercompose');
expect($application->dockerfile)->toBeNull();
expect($application->dockerfile_location)->toBeNull();
expect($application->custom_healthcheck_found)->toBeFalse();
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ConvertContainerEnvsToArray.php | tests/Feature/ConvertContainerEnvsToArray.php | <?php
test('convertContainerEnvsToArray', function () {
$data = '[
{
"Id": "c9248632fb1f1ba4b0d885f78ebadf6af6233799a645d2f5c749088dbf55d79f",
"Created": "2025-05-21T11:58:44.902108064Z",
"Path": "docker-entrypoint.sh",
"Args": [
"postgres"
],
"State": {
"Status": "running",
"Running": true,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 1114005,
"ExitCode": 0,
"Error": "",
"StartedAt": "2025-05-22T08:47:41.404232362Z",
"FinishedAt": "2025-05-22T08:47:36.222181133Z"
},
"Image": "sha256:4100a24644378a24cdbe3def6fc2346999c53d87b12180c221ebb17f05259948",
"ResolvConfPath": "/var/lib/docker/containers/c9248632fb1f1ba4b0d885f78ebadf6af6233799a645d2f5c749088dbf55d79f/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/c9248632fb1f1ba4b0d885f78ebadf6af6233799a645d2f5c749088dbf55d79f/hostname",
"HostsPath": "/var/lib/docker/containers/c9248632fb1f1ba4b0d885f78ebadf6af6233799a645d2f5c749088dbf55d79f/hosts",
"LogPath": "/var/lib/docker/containers/c9248632fb1f1ba4b0d885f78ebadf6af6233799a645d2f5c749088dbf55d79f/c9248632fb1f1ba4b0d885f78ebadf6af6233799a645d2f5c749088dbf55d79f-json.log",
"Name": "/coolify-db",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {
"max-file": "5",
"max-size": "20m"
}
},
"NetworkMode": "coolify",
"PortBindings": {
"5432/tcp": [
{
"HostIp": "",
"HostPort": "5432"
}
]
},
"RestartPolicy": {
"Name": "always",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"ConsoleSize": [
0,
0
],
"CapAdd": null,
"CapDrop": null,
"CgroupnsMode": "private",
"Dns": null,
"DnsOptions": null,
"DnsSearch": null,
"ExtraHosts": [],
"GroupAdd": null,
"IpcMode": "private",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 8405385216,
"Runtime": "runc",
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null,
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": null,
"DeviceCgroupRules": null,
"DeviceRequests": null,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": null,
"PidsLimit": null,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"Mounts": [
{
"Type": "volume",
"Source": "coolify_dev_postgres_data",
"Target": "/var/lib/postgresql/data",
"VolumeOptions": {}
}
],
"MaskedPaths": [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware",
"/sys/devices/virtual/powercap"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/4a03d9a49852aeb72cd14417b5122d5b45bb1f8f51c2644568dca8ad3c263a92-init/diff:/var/lib/docker/overlay2/eea7d1cf26dc92bf884306de3cc589cfdfe0eedb8429030c89cdeb2e8b2c27dd/diff:/var/lib/docker/overlay2/d15ed074d3ab9b42ca38bf18310826afd6155263bc5e897b9182790538b17a54/diff:/var/lib/docker/overlay2/f0ef521fb8a7b9a62d9975bf5b8329895d4aa8d0b10591ad99b5f4d4898b85fe/diff:/var/lib/docker/overlay2/11e83afbece0e9b0e14040f1488f8261e2829cda6b9ebbe3acf042e73b89170b/diff:/var/lib/docker/overlay2/e098a4be50ff4cac048956f4da13b1cdd2a5a768589b5d0d159ab6dcd751919b/diff:/var/lib/docker/overlay2/c9693cd93928bcc8b3f22d90c59f46560fa14a66ad023e4b52e3ae80fa2cd852/diff:/var/lib/docker/overlay2/0d1e07c496139e1ce46ed1137f2d8ae555f02c00e7093ea6026721d8c349c7bd/diff:/var/lib/docker/overlay2/a75a4a3040d8aaa1996cec1c6c0137699f5c2d3deeefa0db684fe0e1d0d78173/diff:/var/lib/docker/overlay2/9709d71704fb9654bb8a2665f989e3559702e58150f27d3768edd994c53fb079/diff:/var/lib/docker/overlay2/75b02083af6cbeb1d90a53d9ad1fffa04671a8ef9068a11e84f1ec1ec102bfad/diff:/var/lib/docker/overlay2/2b13fe91ba5fbbbd5c7077a0f908d863d0c55f42e060be5cca5f51e24e395a29/diff",
"MergedDir": "/var/lib/docker/overlay2/4a03d9a49852aeb72cd14417b5122d5b45bb1f8f51c2644568dca8ad3c263a92/merged",
"UpperDir": "/var/lib/docker/overlay2/4a03d9a49852aeb72cd14417b5122d5b45bb1f8f51c2644568dca8ad3c263a92/diff",
"WorkDir": "/var/lib/docker/overlay2/4a03d9a49852aeb72cd14417b5122d5b45bb1f8f51c2644568dca8ad3c263a92/work"
},
"Name": "overlay2"
},
"Mounts": [
{
"Type": "volume",
"Name": "coolify_dev_postgres_data",
"Source": "/var/lib/docker/volumes/coolify_dev_postgres_data/_data",
"Destination": "/var/lib/postgresql/data",
"Driver": "local",
"Mode": "z",
"RW": true,
"Propagation": ""
}
],
"Config": {
"Hostname": "c9248632fb1f",
"Domainname": "",
"User": "",
"AttachStdin": false,
"AttachStdout": true,
"AttachStderr": true,
"ExposedPorts": {
"5432/tcp": {}
},
"Tty": false,
"OpenStdin": false,
"StdinOnce": false,
"Env": [
"RAY_ENABLED=true=123",
"REGISTRY_URL=docker.io",
"SUBSCRIPTION_PROVIDER=stripe",
"TELESCOPE_ENABLED=false",
"POSTGRES_HOST_AUTH_METHOD=trust",
"DB_PASSWORD=password",
"SSH_MUX_ENABLED=true",
"SELF_HOSTED=false",
"APP_DEBUG=true",
"DB_HOST=host.docker.internal",
"POSTGRES_DB=coolify",
"APP_KEY=base64:8VEfVNVkXQ9mH2L33WBWNMF4eQ0BWD5CTzB9mIxcl+k=",
"DEBUGBAR_ENABLED=false",
"APP_ID=development",
"DB_DATABASE=coolify",
"DUSK_DRIVER_URL=http://selenium:4444",
"DB_USERNAME=coolify",
"APP_NAME=Coolify Development",
"APP_PORT=8000",
"DB_PORT=5432",
"APP_URL=http://localhost",
"APP_ENV=local",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"GOSU_VERSION=1.17",
"LANG=en_US.utf8",
"PG_MAJOR=15",
"PG_VERSION=15.13",
"PG_SHA256=4f62e133d22ea08a0401b0840920e26698644d01a80c34341fb732dd0a90ca5d",
"DOCKER_PG_LLVM_DEPS=llvm19-dev \t\tclang19",
"PGDATA=/var/lib/postgresql/data"
],
"Cmd": [
"postgres"
],
"Image": "postgres:15-alpine",
"Volumes": {
"/var/lib/postgresql/data": {}
},
"WorkingDir": "/",
"Entrypoint": [
"docker-entrypoint.sh"
],
"OnBuild": null,
"Labels": {
"com.docker.compose.config-hash": "56325981c5d891690fff628668ace4c434c4e457c91d85a0994f35a2409efd05",
"com.docker.compose.container-number": "1",
"com.docker.compose.depends_on": "",
"com.docker.compose.image": "sha256:4100a24644378a24cdbe3def6fc2346999c53d87b12180c221ebb17f05259948",
"com.docker.compose.oneoff": "False",
"com.docker.compose.project": "coolify",
"com.docker.compose.project.config_files": "/Users/heyandras/devel/coolify/docker-compose.yml,/Users/heyandras/devel/coolify/docker-compose.dev.yml",
"com.docker.compose.project.working_dir": "/Users/heyandras/devel/coolify",
"com.docker.compose.service": "postgres",
"com.docker.compose.version": "2.32.4"
},
"StopSignal": "SIGINT"
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "8e341f80f5ea70fc7ab183d7cb1f7fe1032b9d98214b0d51665259cc7ebff355",
"SandboxKey": "/var/run/docker/netns/8e341f80f5ea",
"Ports": {
"5432/tcp": [
{
"HostIp": "0.0.0.0",
"HostPort": "5432"
},
{
"HostIp": "::",
"HostPort": "5432"
}
]
},
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"coolify": {
"IPAMConfig": null,
"Links": null,
"Aliases": [
"coolify-db",
"postgres"
],
"MacAddress": "02:42:c0:a8:61:02",
"DriverOpts": null,
"NetworkID": "be1908fb78d9ae5f82d294f8943e0dc597135abbe335a5286e434f4989fd0b3f",
"EndpointID": "40440f9c3f3018bb88af01bd198c3640f7ae3f296010dbe645b3725855aef72f",
"Gateway": "192.168.97.1",
"IPAddress": "192.168.97.2",
"IPPrefixLen": 24,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"DNSNames": [
"coolify-db",
"postgres",
"c9248632fb1f"
]
}
}
}
}
]';
$envs = format_docker_envs_to_json($data);
$this->assertEquals('true=123', $envs->get('RAY_ENABLED'));
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/DatabaseBackupJobTest.php | tests/Feature/DatabaseBackupJobTest.php | <?php
use App\Models\ScheduledDatabaseBackupExecution;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
uses(RefreshDatabase::class);
test('scheduled_database_backup_executions table has s3_uploaded column', function () {
expect(Schema::hasColumn('scheduled_database_backup_executions', 's3_uploaded'))->toBeTrue();
});
test('s3_uploaded column is nullable', function () {
$columns = Schema::getColumns('scheduled_database_backup_executions');
$s3UploadedColumn = collect($columns)->firstWhere('name', 's3_uploaded');
expect($s3UploadedColumn)->not->toBeNull();
expect($s3UploadedColumn['nullable'])->toBeTrue();
});
test('scheduled database backup execution model casts s3_uploaded correctly', function () {
$model = new ScheduledDatabaseBackupExecution;
$casts = $model->getCasts();
expect($casts)->toHaveKey('s3_uploaded');
expect($casts['s3_uploaded'])->toBe('boolean');
});
test('scheduled database backup execution model casts storage deletion fields correctly', function () {
$model = new ScheduledDatabaseBackupExecution;
$casts = $model->getCasts();
expect($casts)->toHaveKey('local_storage_deleted');
expect($casts['local_storage_deleted'])->toBe('boolean');
expect($casts)->toHaveKey('s3_storage_deleted');
expect($casts['s3_storage_deleted'])->toBe('boolean');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/CloudProviderTokenApiTest.php | tests/Feature/CloudProviderTokenApiTest.php | <?php
use App\Models\CloudProviderToken;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Set the current team session before creating the token
session(['currentTeam' => $this->team]);
// Create an API token for the user
$this->token = $this->user->createToken('test-token', ['*']);
$this->bearerToken = $this->token->plainTextToken;
});
describe('GET /api/v1/cloud-tokens', function () {
test('lists all cloud provider tokens for the team', function () {
// Create some tokens
CloudProviderToken::factory()->count(3)->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/cloud-tokens');
$response->assertStatus(200);
$response->assertJsonCount(3);
$response->assertJsonStructure([
'*' => ['uuid', 'name', 'provider', 'team_id', 'servers_count', 'created_at', 'updated_at'],
]);
});
test('does not include tokens from other teams', function () {
// Create tokens for this team
CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
]);
// Create tokens for another team
$otherTeam = Team::factory()->create();
CloudProviderToken::factory()->count(2)->create([
'team_id' => $otherTeam->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/cloud-tokens');
$response->assertStatus(200);
$response->assertJsonCount(1);
});
test('rejects request without authentication', function () {
$response = $this->getJson('/api/v1/cloud-tokens');
$response->assertStatus(401);
});
});
describe('GET /api/v1/cloud-tokens/{uuid}', function () {
test('gets cloud provider token by UUID', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
'name' => 'My Hetzner Token',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson("/api/v1/cloud-tokens/{$token->uuid}");
$response->assertStatus(200);
$response->assertJsonFragment(['name' => 'My Hetzner Token', 'provider' => 'hetzner']);
});
test('returns 404 for non-existent token', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/cloud-tokens/non-existent-uuid');
$response->assertStatus(404);
});
test('cannot access token from another team', function () {
$otherTeam = Team::factory()->create();
$token = CloudProviderToken::factory()->create([
'team_id' => $otherTeam->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson("/api/v1/cloud-tokens/{$token->uuid}");
$response->assertStatus(404);
});
});
describe('POST /api/v1/cloud-tokens', function () {
test('creates a Hetzner cloud provider token', function () {
// Mock Hetzner API validation
Http::fake([
'https://api.hetzner.cloud/v1/servers' => Http::response([], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'hetzner',
'token' => 'test-hetzner-token',
'name' => 'My Hetzner Token',
]);
$response->assertStatus(201);
$response->assertJsonStructure(['uuid']);
// Verify token was created
$this->assertDatabaseHas('cloud_provider_tokens', [
'team_id' => $this->team->id,
'provider' => 'hetzner',
'name' => 'My Hetzner Token',
]);
});
test('creates a DigitalOcean cloud provider token', function () {
// Mock DigitalOcean API validation
Http::fake([
'https://api.digitalocean.com/v2/account' => Http::response([], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'digitalocean',
'token' => 'test-do-token',
'name' => 'My DO Token',
]);
$response->assertStatus(201);
$response->assertJsonStructure(['uuid']);
});
test('validates provider is required', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'token' => 'test-token',
'name' => 'My Token',
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors(['provider']);
});
test('validates token is required', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'hetzner',
'name' => 'My Token',
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors(['token']);
});
test('validates name is required', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'hetzner',
'token' => 'test-token',
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors(['name']);
});
test('validates provider must be hetzner or digitalocean', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'invalid-provider',
'token' => 'test-token',
'name' => 'My Token',
]);
$response->assertStatus(422);
$response->assertJsonValidationErrors(['provider']);
});
test('rejects invalid Hetzner token', function () {
// Mock failed Hetzner API validation
Http::fake([
'https://api.hetzner.cloud/v1/servers' => Http::response([], 401),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'hetzner',
'token' => 'invalid-token',
'name' => 'My Token',
]);
$response->assertStatus(400);
$response->assertJson(['message' => 'Invalid hetzner token. Please check your API token.']);
});
test('rejects extra fields not in allowed list', function () {
Http::fake([
'https://api.hetzner.cloud/v1/servers' => Http::response([], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/cloud-tokens', [
'provider' => 'hetzner',
'token' => 'test-token',
'name' => 'My Token',
'invalid_field' => 'invalid_value',
]);
$response->assertStatus(422);
});
});
describe('PATCH /api/v1/cloud-tokens/{uuid}', function () {
test('updates cloud provider token name', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
'name' => 'Old Name',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->patchJson("/api/v1/cloud-tokens/{$token->uuid}", [
'name' => 'New Name',
]);
$response->assertStatus(200);
// Verify token name was updated
$this->assertDatabaseHas('cloud_provider_tokens', [
'uuid' => $token->uuid,
'name' => 'New Name',
]);
});
test('validates name is required', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->patchJson("/api/v1/cloud-tokens/{$token->uuid}", []);
$response->assertStatus(422);
$response->assertJsonValidationErrors(['name']);
});
test('cannot update token from another team', function () {
$otherTeam = Team::factory()->create();
$token = CloudProviderToken::factory()->create([
'team_id' => $otherTeam->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->patchJson("/api/v1/cloud-tokens/{$token->uuid}", [
'name' => 'New Name',
]);
$response->assertStatus(404);
});
});
describe('DELETE /api/v1/cloud-tokens/{uuid}', function () {
test('deletes cloud provider token', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->deleteJson("/api/v1/cloud-tokens/{$token->uuid}");
$response->assertStatus(200);
$response->assertJson(['message' => 'Cloud provider token deleted.']);
// Verify token was deleted
$this->assertDatabaseMissing('cloud_provider_tokens', [
'uuid' => $token->uuid,
]);
});
test('cannot delete token from another team', function () {
$otherTeam = Team::factory()->create();
$token = CloudProviderToken::factory()->create([
'team_id' => $otherTeam->id,
'provider' => 'hetzner',
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->deleteJson("/api/v1/cloud-tokens/{$token->uuid}");
$response->assertStatus(404);
});
test('returns 404 for non-existent token', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->deleteJson('/api/v1/cloud-tokens/non-existent-uuid');
$response->assertStatus(404);
});
});
describe('POST /api/v1/cloud-tokens/{uuid}/validate', function () {
test('validates a valid Hetzner token', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
]);
Http::fake([
'https://api.hetzner.cloud/v1/servers' => Http::response([], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/cloud-tokens/{$token->uuid}/validate");
$response->assertStatus(200);
$response->assertJson(['valid' => true, 'message' => 'Token is valid.']);
});
test('detects invalid Hetzner token', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
]);
Http::fake([
'https://api.hetzner.cloud/v1/servers' => Http::response([], 401),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/cloud-tokens/{$token->uuid}/validate");
$response->assertStatus(200);
$response->assertJson(['valid' => false, 'message' => 'Invalid hetzner token. Please check your API token.']);
});
test('validates a valid DigitalOcean token', function () {
$token = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'digitalocean',
]);
Http::fake([
'https://api.digitalocean.com/v2/account' => Http::response([], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson("/api/v1/cloud-tokens/{$token->uuid}/validate");
$response->assertStatus(200);
$response->assertJson(['valid' => true, 'message' => 'Token is valid.']);
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/CleanupRedisTest.php | tests/Feature/CleanupRedisTest.php | <?php
use App\Console\Commands\CleanupRedis;
use Illuminate\Support\Facades\Redis;
beforeEach(function () {
config(['horizon.prefix' => 'horizon:']);
});
it('handles Redis scan returning false gracefully', function () {
// Mock Redis connection
$redisMock = Mockery::mock();
// Mock scan() returning false (error case)
$redisMock->shouldReceive('scan')
->once()
->with(0, ['match' => '*', 'count' => 100])
->andReturn(false);
// Mock keys() for initial scan and overlapping queues cleanup
$redisMock->shouldReceive('keys')
->with('*')
->andReturn([]);
Redis::shouldReceive('connection')
->with('horizon')
->andReturn($redisMock);
// Run the command in dry-run mode with restart flag to trigger cleanupStuckJobs
// Use skip-overlapping to avoid additional keys() calls
$this->artisan(CleanupRedis::class, ['--dry-run' => true, '--restart' => true, '--skip-overlapping' => true])
->expectsOutput('DRY RUN MODE - No data will be deleted')
->expectsOutputToContain('Redis scan failed, stopping key retrieval')
->assertSuccessful();
});
it('successfully scans Redis keys when scan returns valid results', function () {
// Mock Redis connection
$redisMock = Mockery::mock();
// Mock successful scan() that returns keys
// First iteration returns cursor 1 and some keys
$redisMock->shouldReceive('scan')
->once()
->with(0, ['match' => '*', 'count' => 100])
->andReturn([1, ['horizon:job:1', 'horizon:job:2']]);
// Second iteration returns cursor 0 (end of scan) and more keys
$redisMock->shouldReceive('scan')
->once()
->with(1, ['match' => '*', 'count' => 100])
->andReturn([0, ['horizon:job:3']]);
// Mock keys() for initial scan
$redisMock->shouldReceive('keys')
->with('*')
->andReturn([]);
// Mock command() for type checking on each key
$redisMock->shouldReceive('command')
->with('type', Mockery::any())
->andReturn(5); // Hash type
// Mock command() for hgetall to get job data
$redisMock->shouldReceive('command')
->with('hgetall', Mockery::any())
->andReturn([
'status' => 'processing',
'reserved_at' => time() - 60, // Started 1 minute ago
'payload' => json_encode(['displayName' => 'TestJob']),
]);
Redis::shouldReceive('connection')
->with('horizon')
->andReturn($redisMock);
// Run the command with restart flag to trigger cleanupStuckJobs
$this->artisan(CleanupRedis::class, ['--dry-run' => true, '--restart' => true, '--skip-overlapping' => true])
->expectsOutput('DRY RUN MODE - No data will be deleted')
->assertSuccessful();
});
it('handles empty scan results gracefully', function () {
// Mock Redis connection
$redisMock = Mockery::mock();
// Mock scan() returning empty results
$redisMock->shouldReceive('scan')
->once()
->with(0, ['match' => '*', 'count' => 100])
->andReturn([0, []]); // Cursor 0 and no keys
// Mock keys() for initial scan
$redisMock->shouldReceive('keys')
->with('*')
->andReturn([]);
Redis::shouldReceive('connection')
->with('horizon')
->andReturn($redisMock);
// Run the command with restart flag
$this->artisan(CleanupRedis::class, ['--dry-run' => true, '--restart' => true, '--skip-overlapping' => true])
->expectsOutput('DRY RUN MODE - No data will be deleted')
->assertSuccessful();
});
it('uses lowercase option keys for scan', function () {
// Mock Redis connection
$redisMock = Mockery::mock();
// Verify that scan is called with lowercase keys: 'match' and 'count'
$redisMock->shouldReceive('scan')
->once()
->with(0, ['match' => '*', 'count' => 100])
->andReturn([0, []]);
// Mock keys() for initial scan
$redisMock->shouldReceive('keys')
->with('*')
->andReturn([]);
Redis::shouldReceive('connection')
->with('horizon')
->andReturn($redisMock);
// Run the command with restart flag
$this->artisan(CleanupRedis::class, ['--dry-run' => true, '--restart' => true, '--skip-overlapping' => true])
->assertSuccessful();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/CheckTraefikVersionJobTest.php | tests/Feature/CheckTraefikVersionJobTest.php | <?php
use App\Models\Server;
use App\Models\Team;
use App\Notifications\Server\TraefikVersionOutdated;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Notification;
uses(RefreshDatabase::class);
beforeEach(function () {
Notification::fake();
});
it('detects servers table has detected_traefik_version column', function () {
expect(\Illuminate\Support\Facades\Schema::hasColumn('servers', 'detected_traefik_version'))->toBeTrue();
});
it('server model casts detected_traefik_version as string', function () {
$server = Server::factory()->make();
expect($server->getFillable())->toContain('detected_traefik_version');
});
it('notification settings have traefik_outdated fields', function () {
$team = Team::factory()->create();
// Check Email notification settings
expect($team->emailNotificationSettings)->toHaveKey('traefik_outdated_email_notifications');
// Check Discord notification settings
expect($team->discordNotificationSettings)->toHaveKey('traefik_outdated_discord_notifications');
// Check Telegram notification settings
expect($team->telegramNotificationSettings)->toHaveKey('traefik_outdated_telegram_notifications');
expect($team->telegramNotificationSettings)->toHaveKey('telegram_notifications_traefik_outdated_thread_id');
// Check Slack notification settings
expect($team->slackNotificationSettings)->toHaveKey('traefik_outdated_slack_notifications');
// Check Pushover notification settings
expect($team->pushoverNotificationSettings)->toHaveKey('traefik_outdated_pushover_notifications');
// Check Webhook notification settings
expect($team->webhookNotificationSettings)->toHaveKey('traefik_outdated_webhook_notifications');
});
it('versions.json contains traefik branches with patch versions', function () {
$versionsPath = base_path('versions.json');
expect(File::exists($versionsPath))->toBeTrue();
$versions = json_decode(File::get($versionsPath), true);
expect($versions)->toHaveKey('traefik');
$traefikVersions = $versions['traefik'];
expect($traefikVersions)->toBeArray();
// Each branch should have format like "v3.6" => "3.6.0"
foreach ($traefikVersions as $branch => $version) {
expect($branch)->toMatch('/^v\d+\.\d+$/'); // e.g., "v3.6"
expect($version)->toMatch('/^\d+\.\d+\.\d+$/'); // e.g., "3.6.0"
}
});
it('formats version with v prefix for display', function () {
// Test the formatVersion logic from notification class
$version = '3.6';
$formatted = str_starts_with($version, 'v') ? $version : "v{$version}";
expect($formatted)->toBe('v3.6');
$versionWithPrefix = 'v3.6';
$formatted2 = str_starts_with($versionWithPrefix, 'v') ? $versionWithPrefix : "v{$versionWithPrefix}";
expect($formatted2)->toBe('v3.6');
});
it('compares semantic versions correctly', function () {
// Test version comparison logic used in job
$currentVersion = 'v3.5';
$latestVersion = 'v3.6';
$isOutdated = version_compare(ltrim($currentVersion, 'v'), ltrim($latestVersion, 'v'), '<');
expect($isOutdated)->toBeTrue();
// Test equal versions
$sameVersion = version_compare(ltrim('3.6', 'v'), ltrim('3.6', 'v'), '=');
expect($sameVersion)->toBeTrue();
// Test newer version
$newerVersion = version_compare(ltrim('3.7', 'v'), ltrim('3.6', 'v'), '>');
expect($newerVersion)->toBeTrue();
});
it('notification class accepts servers collection with outdated info', function () {
$team = Team::factory()->create();
$server1 = Server::factory()->make([
'name' => 'Server 1',
'team_id' => $team->id,
'detected_traefik_version' => 'v3.5.0',
]);
$server1->outdatedInfo = [
'current' => '3.5.0',
'latest' => '3.5.6',
'type' => 'patch_update',
];
$server2 = Server::factory()->make([
'name' => 'Server 2',
'team_id' => $team->id,
'detected_traefik_version' => 'v3.4.0',
]);
$server2->outdatedInfo = [
'current' => '3.4.0',
'latest' => '3.6.0',
'type' => 'minor_upgrade',
];
$servers = collect([$server1, $server2]);
$notification = new TraefikVersionOutdated($servers);
expect($notification->servers)->toHaveCount(2);
expect($notification->servers->first()->outdatedInfo['type'])->toBe('patch_update');
expect($notification->servers->last()->outdatedInfo['type'])->toBe('minor_upgrade');
});
it('notification channels can be retrieved', function () {
$team = Team::factory()->create();
$notification = new TraefikVersionOutdated(collect());
$channels = $notification->via($team);
expect($channels)->toBeArray();
});
it('traefik version check command exists', function () {
$commands = \Illuminate\Support\Facades\Artisan::all();
expect($commands)->toHaveKey('traefik:check-version');
});
it('job handles servers with no proxy type', function () {
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
]);
// Server without proxy configuration returns null for proxyType()
expect($server->proxyType())->toBeNull();
});
it('handles latest tag correctly', function () {
// Test that 'latest' tag is not considered for outdated comparison
$currentVersion = 'latest';
$latestVersion = '3.6';
// Job skips notification for 'latest' tag
$shouldNotify = $currentVersion !== 'latest';
expect($shouldNotify)->toBeFalse();
});
it('groups servers by team correctly', function () {
$team1 = Team::factory()->create(['name' => 'Team 1']);
$team2 = Team::factory()->create(['name' => 'Team 2']);
$servers = collect([
(object) ['team_id' => $team1->id, 'name' => 'Server 1'],
(object) ['team_id' => $team1->id, 'name' => 'Server 2'],
(object) ['team_id' => $team2->id, 'name' => 'Server 3'],
]);
$grouped = $servers->groupBy('team_id');
expect($grouped)->toHaveCount(2);
expect($grouped[$team1->id])->toHaveCount(2);
expect($grouped[$team2->id])->toHaveCount(1);
});
it('server check job exists and has correct structure', function () {
expect(class_exists(\App\Jobs\CheckTraefikVersionForServerJob::class))->toBeTrue();
// Verify CheckTraefikVersionForServerJob has required properties
$reflection = new \ReflectionClass(\App\Jobs\CheckTraefikVersionForServerJob::class);
expect($reflection->hasProperty('tries'))->toBeTrue();
expect($reflection->hasProperty('timeout'))->toBeTrue();
// Verify it implements ShouldQueue
$interfaces = class_implements(\App\Jobs\CheckTraefikVersionForServerJob::class);
expect($interfaces)->toContain(\Illuminate\Contracts\Queue\ShouldQueue::class);
});
it('sends immediate notifications when outdated traefik is detected', function () {
// Notifications are now sent immediately from CheckTraefikVersionForServerJob
// when outdated Traefik is detected, rather than being aggregated and delayed
$team = Team::factory()->create();
$server = Server::factory()->make([
'name' => 'Server 1',
'team_id' => $team->id,
]);
$server->outdatedInfo = [
'current' => '3.5.0',
'latest' => '3.5.6',
'type' => 'patch_update',
];
// Each server triggers its own notification immediately
$notification = new TraefikVersionOutdated(collect([$server]));
expect($notification->servers)->toHaveCount(1);
expect($notification->servers->first()->outdatedInfo['type'])->toBe('patch_update');
});
it('notification generates correct server proxy URLs', function () {
$team = Team::factory()->create();
$server = Server::factory()->create([
'name' => 'Test Server',
'team_id' => $team->id,
'uuid' => 'test-uuid-123',
]);
$server->outdatedInfo = [
'current' => '3.5.0',
'latest' => '3.5.6',
'type' => 'patch_update',
];
$notification = new TraefikVersionOutdated(collect([$server]));
$mail = $notification->toMail($team);
// Verify the mail has the transformed servers with URLs
expect($mail->viewData['servers'])->toHaveCount(1);
expect($mail->viewData['servers'][0]['name'])->toBe('Test Server');
expect($mail->viewData['servers'][0]['uuid'])->toBe('test-uuid-123');
expect($mail->viewData['servers'][0]['url'])->toBe(base_url().'/server/test-uuid-123/proxy');
expect($mail->viewData['servers'][0]['outdatedInfo'])->toBeArray();
});
it('notification transforms multiple servers with URLs correctly', function () {
$team = Team::factory()->create();
$server1 = Server::factory()->create([
'name' => 'Server 1',
'team_id' => $team->id,
'uuid' => 'uuid-1',
]);
$server1->outdatedInfo = [
'current' => '3.5.0',
'latest' => '3.5.6',
'type' => 'patch_update',
];
$server2 = Server::factory()->create([
'name' => 'Server 2',
'team_id' => $team->id,
'uuid' => 'uuid-2',
]);
$server2->outdatedInfo = [
'current' => '3.4.0',
'latest' => '3.6.0',
'type' => 'minor_upgrade',
'upgrade_target' => 'v3.6',
];
$servers = collect([$server1, $server2]);
$notification = new TraefikVersionOutdated($servers);
$mail = $notification->toMail($team);
// Verify both servers have URLs
expect($mail->viewData['servers'])->toHaveCount(2);
expect($mail->viewData['servers'][0]['name'])->toBe('Server 1');
expect($mail->viewData['servers'][0]['url'])->toBe(base_url().'/server/uuid-1/proxy');
expect($mail->viewData['servers'][1]['name'])->toBe('Server 2');
expect($mail->viewData['servers'][1]['url'])->toBe(base_url().'/server/uuid-2/proxy');
});
it('notification uses base_url helper not config app.url', function () {
$team = Team::factory()->create();
$server = Server::factory()->create([
'name' => 'Test Server',
'team_id' => $team->id,
'uuid' => 'test-uuid',
]);
$server->outdatedInfo = [
'current' => '3.5.0',
'latest' => '3.5.6',
'type' => 'patch_update',
];
$notification = new TraefikVersionOutdated(collect([$server]));
$mail = $notification->toMail($team);
// Verify URL starts with base_url() not config('app.url')
$generatedUrl = $mail->viewData['servers'][0]['url'];
expect($generatedUrl)->toStartWith(base_url());
expect($generatedUrl)->not->toContain('localhost');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ServerSettingSentinelRestartTest.php | tests/Feature/ServerSettingSentinelRestartTest.php | <?php
use App\Models\Server;
use App\Models\ServerSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create user (which automatically creates a team)
$user = User::factory()->create();
$this->team = $user->teams()->first();
// Create server with the team
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
]);
});
it('detects sentinel_token changes with wasChanged', function () {
$changeDetected = false;
// Register a test listener that will be called after the model's booted listeners
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if ($settings->wasChanged('sentinel_token')) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$settings->sentinel_token = 'new-token-value';
$settings->save();
expect($changeDetected)->toBeTrue();
});
it('detects sentinel_custom_url changes with wasChanged', function () {
$changeDetected = false;
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if ($settings->wasChanged('sentinel_custom_url')) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$settings->sentinel_custom_url = 'https://new-url.com';
$settings->save();
expect($changeDetected)->toBeTrue();
});
it('detects sentinel_metrics_refresh_rate_seconds changes with wasChanged', function () {
$changeDetected = false;
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if ($settings->wasChanged('sentinel_metrics_refresh_rate_seconds')) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$settings->sentinel_metrics_refresh_rate_seconds = 60;
$settings->save();
expect($changeDetected)->toBeTrue();
});
it('detects sentinel_metrics_history_days changes with wasChanged', function () {
$changeDetected = false;
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if ($settings->wasChanged('sentinel_metrics_history_days')) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$settings->sentinel_metrics_history_days = 14;
$settings->save();
expect($changeDetected)->toBeTrue();
});
it('detects sentinel_push_interval_seconds changes with wasChanged', function () {
$changeDetected = false;
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if ($settings->wasChanged('sentinel_push_interval_seconds')) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$settings->sentinel_push_interval_seconds = 30;
$settings->save();
expect($changeDetected)->toBeTrue();
});
it('does not detect changes when unrelated field is changed', function () {
$changeDetected = false;
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if (
$settings->wasChanged('sentinel_token') ||
$settings->wasChanged('sentinel_custom_url') ||
$settings->wasChanged('sentinel_metrics_refresh_rate_seconds') ||
$settings->wasChanged('sentinel_metrics_history_days') ||
$settings->wasChanged('sentinel_push_interval_seconds')
) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$settings->is_reachable = ! $settings->is_reachable;
$settings->save();
expect($changeDetected)->toBeFalse();
});
it('does not detect changes when sentinel field is set to same value', function () {
$changeDetected = false;
ServerSetting::updated(function ($settings) use (&$changeDetected) {
if ($settings->wasChanged('sentinel_token')) {
$changeDetected = true;
}
});
$settings = $this->server->settings;
$currentToken = $settings->sentinel_token;
$settings->sentinel_token = $currentToken;
$settings->save();
expect($changeDetected)->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ServerStorageCheckIndependenceTest.php | tests/Feature/ServerStorageCheckIndependenceTest.php | <?php
use App\Jobs\ServerCheckJob;
use App\Jobs\ServerManagerJob;
use App\Jobs\ServerStorageCheckJob;
use App\Models\Server;
use App\Models\Team;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
uses(RefreshDatabase::class);
beforeEach(function () {
Queue::fake();
});
afterEach(function () {
Carbon::setTestNow();
});
it('does not dispatch storage check when sentinel is in sync', function () {
// When: ServerManagerJob runs at 11 PM
Carbon::setTestNow(Carbon::parse('2025-01-15 23:00:00', 'UTC'));
// Given: A server with Sentinel recently updated (in sync)
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now(),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => '0 23 * * *',
'server_timezone' => 'UTC',
]);
$job = new ServerManagerJob;
$job->handle();
// Then: ServerStorageCheckJob should NOT be dispatched (Sentinel handles it via PushServerUpdateJob)
Queue::assertNotPushed(ServerStorageCheckJob::class);
});
it('dispatches storage check when sentinel is out of sync', function () {
// When: ServerManagerJob runs at 11 PM
Carbon::setTestNow(Carbon::parse('2025-01-15 23:00:00', 'UTC'));
// Given: A server with Sentinel out of sync (last update 10 minutes ago)
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now()->subMinutes(10),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => '0 23 * * *',
'server_timezone' => 'UTC',
]);
$job = new ServerManagerJob;
$job->handle();
// Then: Both ServerCheckJob and ServerStorageCheckJob should be dispatched
Queue::assertPushed(ServerCheckJob::class);
Queue::assertPushed(ServerStorageCheckJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('dispatches storage check when sentinel is disabled', function () {
// When: ServerManagerJob runs at 11 PM
Carbon::setTestNow(Carbon::parse('2025-01-15 23:00:00', 'UTC'));
// Given: A server with Sentinel disabled
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now()->subHours(24),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => '0 23 * * *',
'server_timezone' => 'UTC',
'is_metrics_enabled' => false,
]);
$job = new ServerManagerJob;
$job->handle();
// Then: ServerStorageCheckJob should be dispatched
Queue::assertPushed(ServerStorageCheckJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('respects custom hourly storage check frequency when sentinel is out of sync', function () {
// When: ServerManagerJob runs at the top of the hour (23:00)
Carbon::setTestNow(Carbon::parse('2025-01-15 23:00:00', 'UTC'));
// Given: A server with hourly storage check frequency and Sentinel out of sync
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now()->subMinutes(10),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => '0 * * * *',
'server_timezone' => 'UTC',
]);
$job = new ServerManagerJob;
$job->handle();
// Then: ServerStorageCheckJob should be dispatched
Queue::assertPushed(ServerStorageCheckJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('handles VALID_CRON_STRINGS mapping correctly when sentinel is out of sync', function () {
// When: ServerManagerJob runs at the top of the hour
Carbon::setTestNow(Carbon::parse('2025-01-15 23:00:00', 'UTC'));
// Given: A server with 'hourly' string (should be converted to '0 * * * *') and Sentinel out of sync
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now()->subMinutes(10),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => 'hourly',
'server_timezone' => 'UTC',
]);
$job = new ServerManagerJob;
$job->handle();
// Then: ServerStorageCheckJob should be dispatched (hourly was converted to cron)
Queue::assertPushed(ServerStorageCheckJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('respects server timezone for storage checks when sentinel is out of sync', function () {
// When: ServerManagerJob runs at 11 PM New York time (4 AM UTC next day)
Carbon::setTestNow(Carbon::parse('2025-01-16 04:00:00', 'UTC'));
// Given: A server in America/New_York timezone (UTC-5) configured for 11 PM local time and Sentinel out of sync
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now()->subMinutes(10),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => '0 23 * * *',
'server_timezone' => 'America/New_York',
]);
$job = new ServerManagerJob;
$job->handle();
// Then: ServerStorageCheckJob should be dispatched
Queue::assertPushed(ServerStorageCheckJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('does not dispatch storage check outside schedule', function () {
// When: ServerManagerJob runs at 10 PM (not 11 PM)
Carbon::setTestNow(Carbon::parse('2025-01-15 22:00:00', 'UTC'));
// Given: A server with daily storage check at 11 PM
$team = Team::factory()->create();
$server = Server::factory()->create([
'team_id' => $team->id,
'sentinel_updated_at' => now(),
]);
$server->settings->update([
'server_disk_usage_check_frequency' => '0 23 * * *',
'server_timezone' => 'UTC',
]);
$job = new ServerManagerJob;
$job->handle();
// Then: ServerStorageCheckJob should NOT be dispatched
Queue::assertNotPushed(ServerStorageCheckJob::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/HetznerServerCreationTest.php | tests/Feature/HetznerServerCreationTest.php | <?php
use App\Livewire\Server\New\ByHetzner;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
// Note: Full Livewire integration tests require database setup
// These tests verify the SSH key merging logic and public_net configuration
it('validates public_net configuration with IPv4 and IPv6 enabled', function () {
$enableIpv4 = true;
$enableIpv6 = true;
$publicNet = [
'enable_ipv4' => $enableIpv4,
'enable_ipv6' => $enableIpv6,
];
expect($publicNet)->toBe([
'enable_ipv4' => true,
'enable_ipv6' => true,
]);
});
it('validates public_net configuration with IPv4 only', function () {
$enableIpv4 = true;
$enableIpv6 = false;
$publicNet = [
'enable_ipv4' => $enableIpv4,
'enable_ipv6' => $enableIpv6,
];
expect($publicNet)->toBe([
'enable_ipv4' => true,
'enable_ipv6' => false,
]);
});
it('validates public_net configuration with IPv6 only', function () {
$enableIpv4 = false;
$enableIpv6 = true;
$publicNet = [
'enable_ipv4' => $enableIpv4,
'enable_ipv6' => $enableIpv6,
];
expect($publicNet)->toBe([
'enable_ipv4' => false,
'enable_ipv6' => true,
]);
});
it('validates IP address selection prefers IPv4 when both are enabled', function () {
$enableIpv4 = true;
$enableIpv6 = true;
$hetznerServer = [
'public_net' => [
'ipv4' => ['ip' => '1.2.3.4'],
'ipv6' => ['ip' => '2001:db8::1'],
],
];
$ipAddress = null;
if ($enableIpv4 && isset($hetznerServer['public_net']['ipv4']['ip'])) {
$ipAddress = $hetznerServer['public_net']['ipv4']['ip'];
} elseif ($enableIpv6 && isset($hetznerServer['public_net']['ipv6']['ip'])) {
$ipAddress = $hetznerServer['public_net']['ipv6']['ip'];
}
expect($ipAddress)->toBe('1.2.3.4');
});
it('validates IP address selection uses IPv6 when only IPv6 is enabled', function () {
$enableIpv4 = false;
$enableIpv6 = true;
$hetznerServer = [
'public_net' => [
'ipv4' => ['ip' => '1.2.3.4'],
'ipv6' => ['ip' => '2001:db8::1'],
],
];
$ipAddress = null;
if ($enableIpv4 && isset($hetznerServer['public_net']['ipv4']['ip'])) {
$ipAddress = $hetznerServer['public_net']['ipv4']['ip'];
} elseif ($enableIpv6 && isset($hetznerServer['public_net']['ipv6']['ip'])) {
$ipAddress = $hetznerServer['public_net']['ipv6']['ip'];
}
expect($ipAddress)->toBe('2001:db8::1');
});
it('validates SSH key array merging logic with Coolify key', function () {
$coolifyKeyId = 123;
$selectedHetznerKeys = [];
$sshKeys = array_merge(
[$coolifyKeyId],
$selectedHetznerKeys
);
$sshKeys = array_unique($sshKeys);
$sshKeys = array_values($sshKeys);
expect($sshKeys)->toBe([123])
->and(count($sshKeys))->toBe(1);
});
it('validates SSH key array merging with additional Hetzner keys', function () {
$coolifyKeyId = 123;
$selectedHetznerKeys = [456, 789];
$sshKeys = array_merge(
[$coolifyKeyId],
$selectedHetznerKeys
);
$sshKeys = array_unique($sshKeys);
$sshKeys = array_values($sshKeys);
expect($sshKeys)->toBe([123, 456, 789])
->and(count($sshKeys))->toBe(3);
});
it('validates deduplication when Coolify key is also in selected keys', function () {
$coolifyKeyId = 123;
$selectedHetznerKeys = [123, 456, 789];
$sshKeys = array_merge(
[$coolifyKeyId],
$selectedHetznerKeys
);
$sshKeys = array_unique($sshKeys);
$sshKeys = array_values($sshKeys);
expect($sshKeys)->toBe([123, 456, 789])
->and(count($sshKeys))->toBe(3);
});
describe('Boarding Flow Integration', function () {
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner that has boarding enabled
$this->team = Team::factory()->create([
'show_boarding' => true,
]);
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Set current team and act as user
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
});
test('completes boarding when server is created from onboarding', function () {
// Verify boarding is initially enabled
expect($this->team->fresh()->show_boarding)->toBeTrue();
// Mount the component with from_onboarding flag
$component = Livewire::test(ByHetzner::class)
->set('from_onboarding', true);
// Verify the from_onboarding property is set
expect($component->get('from_onboarding'))->toBeTrue();
// After successful server creation in the actual component,
// the boarding should be marked as complete
// Note: We can't fully test the createServer method without mocking Hetzner API
// but we can verify the boarding completion logic is in place
});
test('boarding flag remains unchanged when not from onboarding', function () {
// Verify boarding is initially enabled
expect($this->team->fresh()->show_boarding)->toBeTrue();
// Mount the component without from_onboarding flag (default false)
Livewire::test(ByHetzner::class)
->set('from_onboarding', false);
// Boarding should still be enabled since it wasn't created from onboarding
expect($this->team->fresh()->show_boarding)->toBeTrue();
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/HetznerApiTest.php | tests/Feature/HetznerApiTest.php | <?php
use App\Models\CloudProviderToken;
use App\Models\PrivateKey;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Create an API token for the user
session(['currentTeam' => $this->team]);
$this->token = $this->user->createToken('test-token', ['*']);
$this->bearerToken = $this->token->plainTextToken;
// Create a Hetzner cloud provider token
$this->hetznerToken = CloudProviderToken::factory()->create([
'team_id' => $this->team->id,
'provider' => 'hetzner',
'token' => 'test-hetzner-api-token',
]);
// Create a private key
$this->privateKey = PrivateKey::factory()->create([
'team_id' => $this->team->id,
]);
});
describe('GET /api/v1/hetzner/locations', function () {
test('gets Hetzner locations', function () {
Http::fake([
'https://api.hetzner.cloud/v1/locations*' => Http::response([
'locations' => [
['id' => 1, 'name' => 'nbg1', 'description' => 'Nuremberg 1 DC Park 1', 'country' => 'DE', 'city' => 'Nuremberg'],
['id' => 2, 'name' => 'hel1', 'description' => 'Helsinki 1 DC Park 8', 'country' => 'FI', 'city' => 'Helsinki'],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/locations?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(2);
$response->assertJsonFragment(['name' => 'nbg1']);
});
test('requires cloud_provider_token_id parameter', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/locations');
$response->assertStatus(422);
$response->assertJsonValidationErrors(['cloud_provider_token_id']);
});
test('returns 404 for non-existent token', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/locations?cloud_provider_token_id=non-existent-uuid');
$response->assertStatus(404);
});
});
describe('GET /api/v1/hetzner/server-types', function () {
test('gets Hetzner server types', function () {
Http::fake([
'https://api.hetzner.cloud/v1/server_types*' => Http::response([
'server_types' => [
['id' => 1, 'name' => 'cx11', 'description' => 'CX11', 'cores' => 1, 'memory' => 2.0, 'disk' => 20],
['id' => 2, 'name' => 'cx21', 'description' => 'CX21', 'cores' => 2, 'memory' => 4.0, 'disk' => 40],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/server-types?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(2);
$response->assertJsonFragment(['name' => 'cx11']);
});
test('filters out deprecated server types', function () {
Http::fake([
'https://api.hetzner.cloud/v1/server_types*' => Http::response([
'server_types' => [
['id' => 1, 'name' => 'cx11', 'deprecated' => false],
['id' => 2, 'name' => 'cx21', 'deprecated' => true],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/server-types?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(1);
$response->assertJsonFragment(['name' => 'cx11']);
$response->assertJsonMissing(['name' => 'cx21']);
});
});
describe('GET /api/v1/hetzner/images', function () {
test('gets Hetzner images', function () {
Http::fake([
'https://api.hetzner.cloud/v1/images*' => Http::response([
'images' => [
['id' => 1, 'name' => 'ubuntu-20.04', 'type' => 'system', 'deprecated' => false],
['id' => 2, 'name' => 'ubuntu-22.04', 'type' => 'system', 'deprecated' => false],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/images?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(2);
$response->assertJsonFragment(['name' => 'ubuntu-20.04']);
});
test('filters out deprecated images', function () {
Http::fake([
'https://api.hetzner.cloud/v1/images*' => Http::response([
'images' => [
['id' => 1, 'name' => 'ubuntu-20.04', 'type' => 'system', 'deprecated' => false],
['id' => 2, 'name' => 'ubuntu-16.04', 'type' => 'system', 'deprecated' => true],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/images?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(1);
$response->assertJsonFragment(['name' => 'ubuntu-20.04']);
$response->assertJsonMissing(['name' => 'ubuntu-16.04']);
});
test('filters out non-system images', function () {
Http::fake([
'https://api.hetzner.cloud/v1/images*' => Http::response([
'images' => [
['id' => 1, 'name' => 'ubuntu-20.04', 'type' => 'system', 'deprecated' => false],
['id' => 2, 'name' => 'my-snapshot', 'type' => 'snapshot', 'deprecated' => false],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/images?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(1);
$response->assertJsonFragment(['name' => 'ubuntu-20.04']);
$response->assertJsonMissing(['name' => 'my-snapshot']);
});
});
describe('GET /api/v1/hetzner/ssh-keys', function () {
test('gets Hetzner SSH keys', function () {
Http::fake([
'https://api.hetzner.cloud/v1/ssh_keys*' => Http::response([
'ssh_keys' => [
['id' => 1, 'name' => 'my-key', 'fingerprint' => 'aa:bb:cc:dd'],
['id' => 2, 'name' => 'another-key', 'fingerprint' => 'ee:ff:11:22'],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->getJson('/api/v1/hetzner/ssh-keys?cloud_provider_token_id='.$this->hetznerToken->uuid);
$response->assertStatus(200);
$response->assertJsonCount(2);
$response->assertJsonFragment(['name' => 'my-key']);
});
});
describe('POST /api/v1/servers/hetzner', function () {
test('creates a Hetzner server', function () {
// Mock Hetzner API calls
Http::fake([
'https://api.hetzner.cloud/v1/ssh_keys*' => Http::response([
'ssh_keys' => [],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
'https://api.hetzner.cloud/v1/ssh_keys' => Http::response([
'ssh_key' => ['id' => 123, 'fingerprint' => 'aa:bb:cc:dd'],
], 201),
'https://api.hetzner.cloud/v1/servers' => Http::response([
'server' => [
'id' => 456,
'name' => 'test-server',
'public_net' => [
'ipv4' => ['ip' => '1.2.3.4'],
'ipv6' => ['ip' => '2001:db8::1'],
],
],
], 201),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'name' => 'test-server',
'private_key_uuid' => $this->privateKey->uuid,
'enable_ipv4' => true,
'enable_ipv6' => true,
]);
$response->assertStatus(201);
$response->assertJsonStructure(['uuid', 'hetzner_server_id', 'ip']);
$response->assertJsonFragment(['hetzner_server_id' => 456, 'ip' => '1.2.3.4']);
// Verify server was created in database
$this->assertDatabaseHas('servers', [
'name' => 'test-server',
'ip' => '1.2.3.4',
'team_id' => $this->team->id,
'hetzner_server_id' => 456,
]);
});
test('generates server name if not provided', function () {
Http::fake([
'https://api.hetzner.cloud/v1/ssh_keys*' => Http::response([
'ssh_keys' => [],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
'https://api.hetzner.cloud/v1/ssh_keys' => Http::response([
'ssh_key' => ['id' => 123, 'fingerprint' => 'aa:bb:cc:dd'],
], 201),
'https://api.hetzner.cloud/v1/servers' => Http::response([
'server' => [
'id' => 456,
'public_net' => [
'ipv4' => ['ip' => '1.2.3.4'],
],
],
], 201),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => $this->privateKey->uuid,
]);
$response->assertStatus(201);
// Verify a server was created with a generated name
$this->assertDatabaseCount('servers', 1);
});
test('validates required fields', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', []);
$response->assertStatus(422);
$response->assertJsonValidationErrors([
'cloud_provider_token_id',
'location',
'server_type',
'image',
'private_key_uuid',
]);
});
test('validates cloud_provider_token_id exists', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => 'non-existent-uuid',
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => $this->privateKey->uuid,
]);
$response->assertStatus(404);
$response->assertJson(['message' => 'Hetzner cloud provider token not found.']);
});
test('validates private_key_uuid exists', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => 'non-existent-uuid',
]);
$response->assertStatus(404);
$response->assertJson(['message' => 'Private key not found.']);
});
test('prefers IPv4 when both IPv4 and IPv6 are enabled', function () {
Http::fake([
'https://api.hetzner.cloud/v1/ssh_keys*' => Http::response([
'ssh_keys' => [],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
'https://api.hetzner.cloud/v1/ssh_keys' => Http::response([
'ssh_key' => ['id' => 123],
], 201),
'https://api.hetzner.cloud/v1/servers' => Http::response([
'server' => [
'id' => 456,
'public_net' => [
'ipv4' => ['ip' => '1.2.3.4'],
'ipv6' => ['ip' => '2001:db8::1'],
],
],
], 201),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => $this->privateKey->uuid,
'enable_ipv4' => true,
'enable_ipv6' => true,
]);
$response->assertStatus(201);
$response->assertJsonFragment(['ip' => '1.2.3.4']);
});
test('uses IPv6 when only IPv6 is enabled', function () {
Http::fake([
'https://api.hetzner.cloud/v1/ssh_keys*' => Http::response([
'ssh_keys' => [],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
'https://api.hetzner.cloud/v1/ssh_keys' => Http::response([
'ssh_key' => ['id' => 123],
], 201),
'https://api.hetzner.cloud/v1/servers' => Http::response([
'server' => [
'id' => 456,
'public_net' => [
'ipv4' => ['ip' => null],
'ipv6' => ['ip' => '2001:db8::1'],
],
],
], 201),
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => $this->privateKey->uuid,
'enable_ipv4' => false,
'enable_ipv6' => true,
]);
$response->assertStatus(201);
$response->assertJsonFragment(['ip' => '2001:db8::1']);
});
test('rejects extra fields not in allowed list', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
'Content-Type' => 'application/json',
])->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => $this->privateKey->uuid,
'invalid_field' => 'invalid_value',
]);
$response->assertStatus(422);
});
test('rejects request without authentication', function () {
$response = $this->postJson('/api/v1/servers/hetzner', [
'cloud_provider_token_id' => $this->hetznerToken->uuid,
'location' => 'nbg1',
'server_type' => 'cx11',
'image' => 15512617,
'private_key_uuid' => $this->privateKey->uuid,
]);
$response->assertStatus(401);
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/CoolifyTaskRetryTest.php | tests/Feature/CoolifyTaskRetryTest.php | <?php
use App\Jobs\CoolifyTask;
use App\Models\Server;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
uses(RefreshDatabase::class);
it('can dispatch CoolifyTask successfully', function () {
// Skip if no servers available
$server = Server::where('ip', '!=', '1.2.3.4')->first();
if (! $server) {
$this->markTestSkipped('No servers available for testing');
}
Queue::fake();
// Create an activity for the task
$activity = activity()
->withProperties([
'server_uuid' => $server->uuid,
'command' => 'echo "test"',
'type' => 'inline',
])
->event('inline')
->log('[]');
// Dispatch the job
CoolifyTask::dispatch(
activity: $activity,
ignore_errors: false,
call_event_on_finish: null,
call_event_data: null
);
// Assert job was dispatched
Queue::assertPushed(CoolifyTask::class);
});
it('has correct retry configuration on CoolifyTask', function () {
$server = Server::where('ip', '!=', '1.2.3.4')->first();
if (! $server) {
$this->markTestSkipped('No servers available for testing');
}
$activity = activity()
->withProperties([
'server_uuid' => $server->uuid,
'command' => 'echo "test"',
'type' => 'inline',
])
->event('inline')
->log('[]');
$job = new CoolifyTask(
activity: $activity,
ignore_errors: false,
call_event_on_finish: null,
call_event_data: null
);
// Assert retry configuration
expect($job->tries)->toBe(3);
expect($job->maxExceptions)->toBe(1);
expect($job->timeout)->toBe(600);
expect($job->backoff())->toBe([30, 90, 180]);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/TeamInvitationEmailNormalizationTest.php | tests/Feature/TeamInvitationEmailNormalizationTest.php | <?php
use App\Models\Team;
use App\Models\TeamInvitation;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
test('team invitation normalizes email to lowercase', function () {
// Create a team
$team = Team::factory()->create();
// Create invitation with mixed case email
$invitation = TeamInvitation::create([
'team_id' => $team->id,
'uuid' => 'test-uuid-123',
'email' => 'Test@Example.com', // Mixed case
'role' => 'member',
'link' => 'https://example.com/invite/test-uuid-123',
'via' => 'link',
]);
// Verify email was normalized to lowercase
expect($invitation->email)->toBe('test@example.com');
});
test('team invitation works with existing user email', function () {
// Create a team
$team = Team::factory()->create();
// Create a user with lowercase email
$user = User::factory()->create([
'email' => 'test@example.com',
'name' => 'Test User',
]);
// Create invitation with mixed case email
$invitation = TeamInvitation::create([
'team_id' => $team->id,
'uuid' => 'test-uuid-123',
'email' => 'Test@Example.com', // Mixed case
'role' => 'member',
'link' => 'https://example.com/invite/test-uuid-123',
'via' => 'link',
]);
// Verify the invitation email matches the user email (both normalized)
expect($invitation->email)->toBe($user->email);
// Verify user lookup works
$foundUser = User::whereEmail($invitation->email)->first();
expect($foundUser)->not->toBeNull();
expect($foundUser->id)->toBe($user->id);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ServiceFqdnUpdatePathTest.php | tests/Feature/ServiceFqdnUpdatePathTest.php | <?php
/**
* Feature tests to verify that FQDN updates don't cause path duplication
* for services with path-based SERVICE_URL/SERVICE_FQDN template variables.
*
* This tests the fix for GitHub issue #7363 where Appwrite and MindsDB services
* had their paths duplicated (e.g., /v1/realtime/v1/realtime) after FQDN updates.
*
* IMPORTANT: These tests require database access and must be run inside Docker:
* docker exec coolify php artisan test --filter ServiceFqdnUpdatePathTest
*/
use App\Models\Server;
use App\Models\Service;
use App\Models\ServiceApplication;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
test('Appwrite realtime service does not duplicate path on FQDN update', function () {
// Create a server
$server = Server::factory()->create([
'name' => 'test-server',
'ip' => '127.0.0.1',
]);
// Load Appwrite template
$appwriteTemplate = file_get_contents(base_path('templates/compose/appwrite.yaml'));
// Create Appwrite service
$service = Service::factory()->create([
'server_id' => $server->id,
'name' => 'appwrite-test',
'docker_compose_raw' => $appwriteTemplate,
]);
// Create the appwrite-realtime service application
$serviceApp = ServiceApplication::factory()->create([
'service_id' => $service->id,
'name' => 'appwrite-realtime',
'fqdn' => 'https://test.abc/v1/realtime',
]);
// Parse the service (simulates initial setup)
$service->parse();
// Get environment variable
$urlVar = $service->environment_variables()
->where('key', 'SERVICE_URL_APPWRITE')
->first();
// Initial setup should have path once
expect($urlVar)->not->toBeNull()
->and($urlVar->value)->not->toContain('/v1/realtime/v1/realtime')
->and($urlVar->value)->toContain('/v1/realtime');
// Simulate user updating FQDN
$serviceApp->fqdn = 'https://newdomain.com/v1/realtime';
$serviceApp->save();
// Call parse again (this is where the bug occurred)
$service->parse();
// Check that path is not duplicated
$urlVar = $service->environment_variables()
->where('key', 'SERVICE_URL_APPWRITE')
->first();
expect($urlVar)->not->toBeNull()
->and($urlVar->value)->not->toContain('/v1/realtime/v1/realtime')
->and($urlVar->value)->toContain('/v1/realtime');
})->skip('Requires database and Appwrite template - run in Docker');
test('Appwrite console service does not duplicate /console path', function () {
$server = Server::factory()->create();
$appwriteTemplate = file_get_contents(base_path('templates/compose/appwrite.yaml'));
$service = Service::factory()->create([
'server_id' => $server->id,
'docker_compose_raw' => $appwriteTemplate,
]);
$serviceApp = ServiceApplication::factory()->create([
'service_id' => $service->id,
'name' => 'appwrite-console',
'fqdn' => 'https://test.abc/console',
]);
// Parse service
$service->parse();
// Update FQDN
$serviceApp->fqdn = 'https://newdomain.com/console';
$serviceApp->save();
// Parse again
$service->parse();
// Verify no duplication
$urlVar = $service->environment_variables()
->where('key', 'SERVICE_URL_APPWRITE')
->first();
expect($urlVar)->not->toBeNull()
->and($urlVar->value)->not->toContain('/console/console')
->and($urlVar->value)->toContain('/console');
})->skip('Requires database and Appwrite template - run in Docker');
test('MindsDB service does not duplicate /api path', function () {
$server = Server::factory()->create();
$mindsdbTemplate = file_get_contents(base_path('templates/compose/mindsdb.yaml'));
$service = Service::factory()->create([
'server_id' => $server->id,
'docker_compose_raw' => $mindsdbTemplate,
]);
$serviceApp = ServiceApplication::factory()->create([
'service_id' => $service->id,
'name' => 'mindsdb',
'fqdn' => 'https://test.abc/api',
]);
// Parse service
$service->parse();
// Update FQDN multiple times
$serviceApp->fqdn = 'https://domain1.com/api';
$serviceApp->save();
$service->parse();
$serviceApp->fqdn = 'https://domain2.com/api';
$serviceApp->save();
$service->parse();
// Verify no duplication after multiple updates
$urlVar = $service->environment_variables()
->where('key', 'SERVICE_URL_API')
->orWhere('key', 'LIKE', 'SERVICE_URL_%')
->first();
expect($urlVar)->not->toBeNull()
->and($urlVar->value)->not->toContain('/api/api');
})->skip('Requires database and MindsDB template - run in Docker');
test('service without path declaration is not affected', function () {
$server = Server::factory()->create();
// Create a simple service without path in template
$simpleTemplate = <<<'YAML'
services:
redis:
image: redis:7
environment:
- SERVICE_FQDN_REDIS
YAML;
$service = Service::factory()->create([
'server_id' => $server->id,
'docker_compose_raw' => $simpleTemplate,
]);
$serviceApp = ServiceApplication::factory()->create([
'service_id' => $service->id,
'name' => 'redis',
'fqdn' => 'https://redis.test.abc',
]);
// Parse service
$service->parse();
$fqdnBefore = $service->environment_variables()
->where('key', 'SERVICE_FQDN_REDIS')
->first()?->value;
// Update FQDN
$serviceApp->fqdn = 'https://redis.newdomain.com';
$serviceApp->save();
// Parse again
$service->parse();
$fqdnAfter = $service->environment_variables()
->where('key', 'SERVICE_FQDN_REDIS')
->first()?->value;
// Should work normally without issues
expect($fqdnAfter)->toBe('redis.newdomain.com')
->and($fqdnAfter)->not->toContain('//');
})->skip('Requires database - run in Docker');
test('multiple FQDN updates never cause path duplication', function () {
$server = Server::factory()->create();
$appwriteTemplate = file_get_contents(base_path('templates/compose/appwrite.yaml'));
$service = Service::factory()->create([
'server_id' => $server->id,
'docker_compose_raw' => $appwriteTemplate,
]);
$serviceApp = ServiceApplication::factory()->create([
'service_id' => $service->id,
'name' => 'appwrite-realtime',
'fqdn' => 'https://test.abc/v1/realtime',
]);
// Update FQDN 10 times and parse each time
for ($i = 1; $i <= 10; $i++) {
$serviceApp->fqdn = "https://domain{$i}.com/v1/realtime";
$serviceApp->save();
$service->parse();
// Check path is never duplicated
$urlVar = $service->environment_variables()
->where('key', 'SERVICE_URL_APPWRITE')
->first();
expect($urlVar)->not->toBeNull()
->and($urlVar->value)->not->toContain('/v1/realtime/v1/realtime')
->and($urlVar->value)->toContain('/v1/realtime');
}
})->skip('Requires database and Appwrite template - run in Docker');
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/GithubSourceChangeTest.php | tests/Feature/GithubSourceChangeTest.php | <?php
use App\Livewire\Source\Github\Change;
use App\Models\GithubApp;
use App\Models\PrivateKey;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Set current team
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
});
describe('GitHub Source Change Component', function () {
test('can mount with newly created github app with null app_id', function () {
// Create a GitHub app without app_id (simulating a newly created source)
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'team_id' => $this->team->id,
'is_system_wide' => false,
// app_id is intentionally not set (null in database)
]);
// Test that the component can mount without errors
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->assertSet('appId', null)
->assertSet('installationId', null)
->assertSet('clientId', null)
->assertSet('clientSecret', null)
->assertSet('webhookSecret', null)
->assertSet('privateKeyId', null);
});
test('can mount with fully configured github app', function () {
$privateKey = PrivateKey::create([
'name' => 'Test Key',
'private_key' => 'test-private-key-content',
'team_id' => $this->team->id,
]);
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'app_id' => 12345,
'installation_id' => 67890,
'client_id' => 'test-client-id',
'client_secret' => 'test-client-secret',
'webhook_secret' => 'test-webhook-secret',
'private_key_id' => $privateKey->id,
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->assertSet('appId', 12345)
->assertSet('installationId', 67890)
->assertSet('clientId', 'test-client-id')
->assertSet('clientSecret', 'test-client-secret')
->assertSet('webhookSecret', 'test-webhook-secret')
->assertSet('privateKeyId', $privateKey->id);
});
test('can update github app from null to valid values', function () {
$privateKey = PrivateKey::create([
'name' => 'Test Key',
'private_key' => 'test-private-key-content',
'team_id' => $this->team->id,
]);
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->set('appId', 12345)
->set('installationId', 67890)
->set('clientId', 'new-client-id')
->set('clientSecret', 'new-client-secret')
->set('webhookSecret', 'new-webhook-secret')
->set('privateKeyId', $privateKey->id)
->call('submit')
->assertDispatched('success');
// Verify the database was updated
$githubApp->refresh();
expect($githubApp->app_id)->toBe(12345);
expect($githubApp->installation_id)->toBe(67890);
expect($githubApp->client_id)->toBe('new-client-id');
expect($githubApp->private_key_id)->toBe($privateKey->id);
});
test('validation allows nullable values for app configuration', function () {
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
// Test that validation passes with null values
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->call('submit')
->assertHasNoErrors();
});
test('createGithubAppManually redirects to avoid morphing issues', function () {
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
// Test that createGithubAppManually redirects instead of updating in place
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->call('createGithubAppManually')
->assertRedirect(route('source.github.show', ['github_app_uuid' => $githubApp->uuid]));
// Verify the database was updated
$githubApp->refresh();
expect($githubApp->app_id)->toBe('1234567890');
expect($githubApp->installation_id)->toBe('1234567890');
});
test('checkPermissions validates required fields', function () {
// Create a GitHub app without app_id and private_key_id
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
// Test that checkPermissions fails with appropriate error
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->call('checkPermissions')
->assertDispatched('error', function ($event, $message) {
return str_contains($message, 'App ID') && str_contains($message, 'Private Key');
});
});
test('checkPermissions validates private key exists', function () {
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'app_id' => 12345,
'private_key_id' => 99999, // Non-existent private key ID
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
// Test that checkPermissions fails when private key doesn't exist
Livewire::withQueryParams(['github_app_uuid' => $githubApp->uuid])
->test(Change::class)
->assertSuccessful()
->call('checkPermissions')
->assertDispatched('error', function ($event, $message) {
return str_contains($message, 'Private Key not found');
});
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/TeamInvitationPrivilegeEscalationTest.php | tests/Feature/TeamInvitationPrivilegeEscalationTest.php | <?php
use App\Livewire\Team\InviteLink;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner, admin, and member
$this->team = Team::factory()->create();
$this->owner = User::factory()->create();
$this->admin = User::factory()->create();
$this->member = User::factory()->create();
$this->team->members()->attach($this->owner->id, ['role' => 'owner']);
$this->team->members()->attach($this->admin->id, ['role' => 'admin']);
$this->team->members()->attach($this->member->id, ['role' => 'member']);
});
describe('privilege escalation prevention', function () {
test('member cannot invite admin (SECURITY FIX)', function () {
// Login as member
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
// Attempt to invite someone as admin
Livewire::test(InviteLink::class)
->set('email', 'newadmin@example.com')
->set('role', 'admin')
->call('viaLink')
->assertDispatched('error');
});
test('member cannot invite owner (SECURITY FIX)', function () {
// Login as member
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
// Attempt to invite someone as owner
Livewire::test(InviteLink::class)
->set('email', 'newowner@example.com')
->set('role', 'owner')
->call('viaLink')
->assertDispatched('error');
});
test('admin cannot invite owner', function () {
// Login as admin
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
// Attempt to invite someone as owner
Livewire::test(InviteLink::class)
->set('email', 'newowner@example.com')
->set('role', 'owner')
->call('viaLink')
->assertDispatched('error');
});
test('admin can invite member', function () {
// Login as admin
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
// Invite someone as member
Livewire::test(InviteLink::class)
->set('email', 'newmember@example.com')
->set('role', 'member')
->call('viaLink')
->assertDispatched('success');
// Verify invitation was created
$this->assertDatabaseHas('team_invitations', [
'email' => 'newmember@example.com',
'role' => 'member',
'team_id' => $this->team->id,
]);
});
test('admin can invite admin', function () {
// Login as admin
$this->actingAs($this->admin);
session(['currentTeam' => $this->team]);
// Invite someone as admin
Livewire::test(InviteLink::class)
->set('email', 'newadmin@example.com')
->set('role', 'admin')
->call('viaLink')
->assertDispatched('success');
// Verify invitation was created
$this->assertDatabaseHas('team_invitations', [
'email' => 'newadmin@example.com',
'role' => 'admin',
'team_id' => $this->team->id,
]);
});
test('owner can invite member', function () {
// Login as owner
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
// Invite someone as member
Livewire::test(InviteLink::class)
->set('email', 'newmember@example.com')
->set('role', 'member')
->call('viaLink')
->assertDispatched('success');
// Verify invitation was created
$this->assertDatabaseHas('team_invitations', [
'email' => 'newmember@example.com',
'role' => 'member',
'team_id' => $this->team->id,
]);
});
test('owner can invite admin', function () {
// Login as owner
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
// Invite someone as admin
Livewire::test(InviteLink::class)
->set('email', 'newadmin@example.com')
->set('role', 'admin')
->call('viaLink')
->assertDispatched('success');
// Verify invitation was created
$this->assertDatabaseHas('team_invitations', [
'email' => 'newadmin@example.com',
'role' => 'admin',
'team_id' => $this->team->id,
]);
});
test('owner can invite owner', function () {
// Login as owner
$this->actingAs($this->owner);
session(['currentTeam' => $this->team]);
// Invite someone as owner
Livewire::test(InviteLink::class)
->set('email', 'newowner@example.com')
->set('role', 'owner')
->call('viaLink')
->assertDispatched('success');
// Verify invitation was created
$this->assertDatabaseHas('team_invitations', [
'email' => 'newowner@example.com',
'role' => 'owner',
'team_id' => $this->team->id,
]);
});
test('member cannot bypass policy by calling viaEmail', function () {
// Login as member
$this->actingAs($this->member);
session(['currentTeam' => $this->team]);
// Attempt to invite someone as admin via email
Livewire::test(InviteLink::class)
->set('email', 'newadmin@example.com')
->set('role', 'admin')
->call('viaEmail')
->assertDispatched('error');
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/StartupExecutionCleanupTest.php | tests/Feature/StartupExecutionCleanupTest.php | <?php
use App\Models\ScheduledDatabaseBackup;
use App\Models\ScheduledDatabaseBackupExecution;
use App\Models\ScheduledTask;
use App\Models\ScheduledTaskExecution;
use App\Models\StandalonePostgresql;
use App\Models\Team;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Notification;
uses(RefreshDatabase::class);
beforeEach(function () {
// Freeze time for consistent testing
Carbon::setTestNow('2025-01-15 12:00:00');
// Fake notifications to ensure none are sent
Notification::fake();
});
afterEach(function () {
Carbon::setTestNow();
});
test('app:init marks stuck scheduled task executions as failed', function () {
// Create a team for the scheduled task
$team = Team::factory()->create();
// Create a scheduled task
$scheduledTask = ScheduledTask::factory()->create([
'team_id' => $team->id,
]);
// Create multiple task executions with 'running' status
$runningExecution1 = ScheduledTaskExecution::create([
'scheduled_task_id' => $scheduledTask->id,
'status' => 'running',
'started_at' => Carbon::now()->subMinutes(10),
]);
$runningExecution2 = ScheduledTaskExecution::create([
'scheduled_task_id' => $scheduledTask->id,
'status' => 'running',
'started_at' => Carbon::now()->subMinutes(5),
]);
// Create a completed execution (should not be affected)
$completedExecution = ScheduledTaskExecution::create([
'scheduled_task_id' => $scheduledTask->id,
'status' => 'success',
'started_at' => Carbon::now()->subMinutes(15),
'finished_at' => Carbon::now()->subMinutes(14),
]);
// Run the app:init command
Artisan::call('app:init');
// Refresh models from database
$runningExecution1->refresh();
$runningExecution2->refresh();
$completedExecution->refresh();
// Assert running executions are now failed
expect($runningExecution1->status)->toBe('failed')
->and($runningExecution1->message)->toBe('Marked as failed during Coolify startup - job was interrupted')
->and($runningExecution1->finished_at)->not->toBeNull()
->and($runningExecution1->finished_at->toDateTimeString())->toBe('2025-01-15 12:00:00');
expect($runningExecution2->status)->toBe('failed')
->and($runningExecution2->message)->toBe('Marked as failed during Coolify startup - job was interrupted')
->and($runningExecution2->finished_at)->not->toBeNull();
// Assert completed execution is unchanged
expect($completedExecution->status)->toBe('success')
->and($completedExecution->message)->toBeNull();
// Assert NO notifications were sent
Notification::assertNothingSent();
});
test('app:init marks stuck database backup executions as failed', function () {
// Create a team for the scheduled backup
$team = Team::factory()->create();
// Create a database
$database = StandalonePostgresql::factory()->create([
'team_id' => $team->id,
]);
// Create a scheduled backup
$scheduledBackup = ScheduledDatabaseBackup::factory()->create([
'team_id' => $team->id,
'database_id' => $database->id,
'database_type' => StandalonePostgresql::class,
]);
// Create multiple backup executions with 'running' status
$runningBackup1 = ScheduledDatabaseBackupExecution::create([
'scheduled_database_backup_id' => $scheduledBackup->id,
'status' => 'running',
'database_name' => 'test_db',
]);
$runningBackup2 = ScheduledDatabaseBackupExecution::create([
'scheduled_database_backup_id' => $scheduledBackup->id,
'status' => 'running',
'database_name' => 'test_db_2',
]);
// Create a successful backup (should not be affected)
$successfulBackup = ScheduledDatabaseBackupExecution::create([
'scheduled_database_backup_id' => $scheduledBackup->id,
'status' => 'success',
'database_name' => 'test_db_3',
'finished_at' => Carbon::now()->subMinutes(20),
]);
// Run the app:init command
Artisan::call('app:init');
// Refresh models from database
$runningBackup1->refresh();
$runningBackup2->refresh();
$successfulBackup->refresh();
// Assert running backups are now failed
expect($runningBackup1->status)->toBe('failed')
->and($runningBackup1->message)->toBe('Marked as failed during Coolify startup - job was interrupted')
->and($runningBackup1->finished_at)->not->toBeNull()
->and($runningBackup1->finished_at->toDateTimeString())->toBe('2025-01-15 12:00:00');
expect($runningBackup2->status)->toBe('failed')
->and($runningBackup2->message)->toBe('Marked as failed during Coolify startup - job was interrupted')
->and($runningBackup2->finished_at)->not->toBeNull();
// Assert successful backup is unchanged
expect($successfulBackup->status)->toBe('success')
->and($successfulBackup->message)->toBeNull();
// Assert NO notifications were sent
Notification::assertNothingSent();
});
test('app:init handles cleanup when no stuck executions exist', function () {
// Create a team
$team = Team::factory()->create();
// Create a scheduled task
$scheduledTask = ScheduledTask::factory()->create([
'team_id' => $team->id,
]);
// Create only completed executions
ScheduledTaskExecution::create([
'scheduled_task_id' => $scheduledTask->id,
'status' => 'success',
'started_at' => Carbon::now()->subMinutes(10),
'finished_at' => Carbon::now()->subMinutes(9),
]);
ScheduledTaskExecution::create([
'scheduled_task_id' => $scheduledTask->id,
'status' => 'failed',
'started_at' => Carbon::now()->subMinutes(20),
'finished_at' => Carbon::now()->subMinutes(19),
]);
// Run the app:init command (should not fail)
$exitCode = Artisan::call('app:init');
// Assert command succeeded
expect($exitCode)->toBe(0);
// Assert all executions remain unchanged
expect(ScheduledTaskExecution::where('status', 'running')->count())->toBe(0)
->and(ScheduledTaskExecution::where('status', 'success')->count())->toBe(1)
->and(ScheduledTaskExecution::where('status', 'failed')->count())->toBe(1);
// Assert NO notifications were sent
Notification::assertNothingSent();
});
test('cleanup does not send notifications even when team has notification settings', function () {
// Create a team with notification settings enabled
$team = Team::factory()->create([
'smtp_enabled' => true,
'smtp_from_address' => 'test@example.com',
]);
// Create a scheduled task
$scheduledTask = ScheduledTask::factory()->create([
'team_id' => $team->id,
]);
// Create a running execution
$runningExecution = ScheduledTaskExecution::create([
'scheduled_task_id' => $scheduledTask->id,
'status' => 'running',
'started_at' => Carbon::now()->subMinutes(5),
]);
// Run the app:init command
Artisan::call('app:init');
// Refresh model
$runningExecution->refresh();
// Assert execution is failed
expect($runningExecution->status)->toBe('failed');
// Assert NO notifications were sent despite team having notification settings
Notification::assertNothingSent();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/CloudInitScriptTest.php | tests/Feature/CloudInitScriptTest.php | <?php
// Note: These tests verify cloud-init script logic without database setup
it('validates cloud-init script is included in server params when provided', function () {
$cloudInitScript = "#!/bin/bash\necho 'Hello World'";
$params = [
'name' => 'test-server',
'server_type' => 'cx11',
'image' => 1,
'location' => 'nbg1',
'start_after_create' => true,
'ssh_keys' => [123],
'public_net' => [
'enable_ipv4' => true,
'enable_ipv6' => true,
],
];
// Add cloud-init script if provided
if (! empty($cloudInitScript)) {
$params['user_data'] = $cloudInitScript;
}
expect($params)
->toHaveKey('user_data')
->and($params['user_data'])->toBe("#!/bin/bash\necho 'Hello World'");
});
it('validates cloud-init script is not included when empty', function () {
$cloudInitScript = null;
$params = [
'name' => 'test-server',
'server_type' => 'cx11',
'image' => 1,
'location' => 'nbg1',
'start_after_create' => true,
'ssh_keys' => [123],
'public_net' => [
'enable_ipv4' => true,
'enable_ipv6' => true,
],
];
// Add cloud-init script if provided
if (! empty($cloudInitScript)) {
$params['user_data'] = $cloudInitScript;
}
expect($params)->not->toHaveKey('user_data');
});
it('validates cloud-init script is not included when empty string', function () {
$cloudInitScript = '';
$params = [
'name' => 'test-server',
'server_type' => 'cx11',
'image' => 1,
'location' => 'nbg1',
'start_after_create' => true,
'ssh_keys' => [123],
'public_net' => [
'enable_ipv4' => true,
'enable_ipv6' => true,
],
];
// Add cloud-init script if provided
if (! empty($cloudInitScript)) {
$params['user_data'] = $cloudInitScript;
}
expect($params)->not->toHaveKey('user_data');
});
it('validates cloud-init script with multiline content', function () {
$cloudInitScript = "#cloud-config\n\npackages:\n - nginx\n - git\n\nruncmd:\n - systemctl start nginx";
$params = [
'name' => 'test-server',
'server_type' => 'cx11',
'image' => 1,
'location' => 'nbg1',
'start_after_create' => true,
'ssh_keys' => [123],
'public_net' => [
'enable_ipv4' => true,
'enable_ipv6' => true,
],
];
// Add cloud-init script if provided
if (! empty($cloudInitScript)) {
$params['user_data'] = $cloudInitScript;
}
expect($params)
->toHaveKey('user_data')
->and($params['user_data'])->toContain('#cloud-config')
->and($params['user_data'])->toContain('packages:')
->and($params['user_data'])->toContain('runcmd:');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/GithubAppsListApiTest.php | tests/Feature/GithubAppsListApiTest.php | <?php
use App\Models\GithubApp;
use App\Models\PrivateKey;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Create an API token for the user
$this->token = $this->user->createToken('test-token', ['*'], $this->team->id);
$this->bearerToken = $this->token->plainTextToken;
// Create a private key for the team
$this->privateKey = PrivateKey::create([
'name' => 'Test Key',
'private_key' => 'test-private-key-content',
'team_id' => $this->team->id,
]);
});
describe('GET /api/v1/github-apps', function () {
test('returns 401 when not authenticated', function () {
$response = $this->getJson('/api/v1/github-apps');
$response->assertStatus(401);
});
test('returns empty array when no github apps exist', function () {
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
])->getJson('/api/v1/github-apps');
$response->assertStatus(200);
$response->assertJson([]);
});
test('returns team github apps', function () {
// Create a GitHub app for the team
$githubApp = GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'app_id' => 12345,
'installation_id' => 67890,
'client_id' => 'test-client-id',
'client_secret' => 'test-client-secret',
'webhook_secret' => 'test-webhook-secret',
'private_key_id' => $this->privateKey->id,
'team_id' => $this->team->id,
'is_system_wide' => false,
'is_public' => false,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
])->getJson('/api/v1/github-apps');
$response->assertStatus(200);
$response->assertJsonCount(1);
$response->assertJsonFragment([
'name' => 'Test GitHub App',
'app_id' => 12345,
]);
});
test('does not return sensitive data', function () {
// Create a GitHub app
GithubApp::create([
'name' => 'Test GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'app_id' => 12345,
'installation_id' => 67890,
'client_id' => 'test-client-id',
'client_secret' => 'secret-should-be-hidden',
'webhook_secret' => 'webhook-secret-should-be-hidden',
'private_key_id' => $this->privateKey->id,
'team_id' => $this->team->id,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
])->getJson('/api/v1/github-apps');
$response->assertStatus(200);
$json = $response->json();
// Ensure sensitive data is not present
expect($json[0])->not->toHaveKey('client_secret');
expect($json[0])->not->toHaveKey('webhook_secret');
});
test('returns system-wide github apps', function () {
// Create a system-wide GitHub app
$systemApp = GithubApp::create([
'name' => 'System GitHub App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'app_id' => 11111,
'installation_id' => 22222,
'client_id' => 'system-client-id',
'client_secret' => 'system-secret',
'webhook_secret' => 'system-webhook',
'private_key_id' => $this->privateKey->id,
'team_id' => $this->team->id,
'is_system_wide' => true,
]);
// Create another team and user
$otherTeam = Team::factory()->create();
$otherUser = User::factory()->create();
$otherTeam->members()->attach($otherUser->id, ['role' => 'owner']);
$otherToken = $otherUser->createToken('other-token', ['*'], $otherTeam->id);
// System-wide apps should be visible to other teams
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$otherToken->plainTextToken,
])->getJson('/api/v1/github-apps');
$response->assertStatus(200);
$response->assertJsonFragment([
'name' => 'System GitHub App',
'is_system_wide' => true,
]);
});
test('does not return other teams github apps', function () {
// Create a GitHub app for this team
GithubApp::create([
'name' => 'Team 1 App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'app_id' => 11111,
'installation_id' => 22222,
'client_id' => 'team1-client-id',
'client_secret' => 'team1-secret',
'webhook_secret' => 'team1-webhook',
'private_key_id' => $this->privateKey->id,
'team_id' => $this->team->id,
'is_system_wide' => false,
]);
// Create another team with a GitHub app
$otherTeam = Team::factory()->create();
$otherPrivateKey = PrivateKey::create([
'name' => 'Other Key',
'private_key' => 'other-key',
'team_id' => $otherTeam->id,
]);
GithubApp::create([
'name' => 'Team 2 App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'app_id' => 33333,
'installation_id' => 44444,
'client_id' => 'team2-client-id',
'client_secret' => 'team2-secret',
'webhook_secret' => 'team2-webhook',
'private_key_id' => $otherPrivateKey->id,
'team_id' => $otherTeam->id,
'is_system_wide' => false,
]);
// Request from first team should only see their app
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
])->getJson('/api/v1/github-apps');
$response->assertStatus(200);
$response->assertJsonCount(1);
$response->assertJsonFragment(['name' => 'Team 1 App']);
$response->assertJsonMissing(['name' => 'Team 2 App']);
});
test('returns correct response structure', function () {
GithubApp::create([
'name' => 'Test App',
'api_url' => 'https://api.github.com',
'html_url' => 'https://github.com',
'custom_user' => 'git',
'custom_port' => 22,
'app_id' => 12345,
'installation_id' => 67890,
'client_id' => 'client-id',
'client_secret' => 'secret',
'webhook_secret' => 'webhook',
'private_key_id' => $this->privateKey->id,
'team_id' => $this->team->id,
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '.$this->bearerToken,
])->getJson('/api/v1/github-apps');
$response->assertStatus(200);
$response->assertJsonStructure([
[
'id',
'uuid',
'name',
'api_url',
'html_url',
'custom_user',
'custom_port',
'app_id',
'installation_id',
'client_id',
'private_key_id',
'team_id',
'type',
],
]);
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/DockerCustomCommandsTest.php | tests/Feature/DockerCustomCommandsTest.php | <?php
test('Hostname', function () {
$input = '--hostname=test';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'hostname' => 'test',
]);
});
test('HostnameWithoutEqualSign', function () {
$input = '--hostname test';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'hostname' => 'test',
]);
});
test('HostnameWithoutEqualSignAndHyphens', function () {
$input = '--hostname my-super-host';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'hostname' => 'my-super-host',
]);
});
test('HostnameWithHyphens', function () {
$input = '--hostname=my-super-host';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'hostname' => 'my-super-host',
]);
});
test('ConvertCapAdd', function () {
$input = '--cap-add=NET_ADMIN --cap-add=NET_RAW --cap-add SYS_ADMIN';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'cap_add' => ['NET_ADMIN', 'NET_RAW', 'SYS_ADMIN'],
]);
});
test('ConvertIp', function () {
$input = '--cap-add=NET_ADMIN --cap-add=NET_RAW --cap-add SYS_ADMIN --ip 127.0.0.1 --ip 127.0.0.2';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'cap_add' => ['NET_ADMIN', 'NET_RAW', 'SYS_ADMIN'],
'ip' => ['127.0.0.1', '127.0.0.2'],
]);
});
test('ConvertPrivilegedAndInit', function () {
$input = '---privileged --init';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'privileged' => true,
'init' => true,
]);
});
test('ConvertUlimit', function () {
$input = '--ulimit nofile=262144:262144';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'ulimits' => [
'nofile' => [
'soft' => '262144',
'hard' => '262144',
],
],
]);
});
test('ConvertGpusWithGpuId', function () {
$input = '--gpus "device=GPU-0000000000000000"';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'deploy' => [
'resources' => [
'reservations' => [
'devices' => [
[
'driver' => 'nvidia',
'capabilities' => ['gpu'],
'device_ids' => ['GPU-0000000000000000'],
],
],
],
],
],
]);
});
test('ConvertGpus', function () {
$input = '--gpus all';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'deploy' => [
'resources' => [
'reservations' => [
'devices' => [
[
'driver' => 'nvidia',
'capabilities' => ['gpu'],
],
],
],
],
],
]);
});
test('ConvertGpusWithQuotes', function () {
$input = '--gpus "device=0,1"';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'deploy' => [
'resources' => [
'reservations' => [
'devices' => [
[
'driver' => 'nvidia',
'capabilities' => ['gpu'],
'device_ids' => ['0', '1'],
],
],
],
],
],
]);
});
test('ConvertEntrypointSimple', function () {
$input = '--entrypoint /bin/sh';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => '/bin/sh',
]);
});
test('ConvertEntrypointWithEquals', function () {
$input = '--entrypoint=/bin/bash';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => '/bin/bash',
]);
});
test('ConvertEntrypointWithArguments', function () {
$input = '--entrypoint "sh -c npm install"';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => 'sh -c npm install',
]);
});
test('ConvertEntrypointWithSingleQuotes', function () {
$input = "--entrypoint 'memcached -m 256'";
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => 'memcached -m 256',
]);
});
test('ConvertEntrypointWithOtherOptions', function () {
$input = '--entrypoint /bin/bash --cap-add SYS_ADMIN --privileged';
$output = convertDockerRunToCompose($input);
expect($output)->toHaveKeys(['entrypoint', 'cap_add', 'privileged'])
->and($output['entrypoint'])->toBe('/bin/bash')
->and($output['cap_add'])->toBe(['SYS_ADMIN'])
->and($output['privileged'])->toBe(true);
});
test('ConvertEntrypointComplex', function () {
$input = '--entrypoint "sh -c \'npm install && npm start\'"';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => "sh -c 'npm install && npm start'",
]);
});
test('ConvertEntrypointWithEscapedDoubleQuotes', function () {
$input = '--entrypoint "python -c \"print(\'hi\')\""';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => "python -c \"print('hi')\"",
]);
});
test('ConvertEntrypointWithEscapedSingleQuotesInDoubleQuotes', function () {
$input = '--entrypoint "sh -c \"echo \'hello\'\""';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => "sh -c \"echo 'hello'\"",
]);
});
test('ConvertEntrypointSingleQuotedWithDoubleQuotesInside', function () {
$input = '--entrypoint \'python -c "print(\"hi\")"\'';
$output = convertDockerRunToCompose($input);
expect($output)->toBe([
'entrypoint' => 'python -c "print(\"hi\")"',
]);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/DeletesUserSessionsTest.php | tests/Feature/DeletesUserSessionsTest.php | <?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
uses(RefreshDatabase::class);
it('invalidates sessions when password changes', function () {
// Create a user
$user = User::factory()->create([
'password' => Hash::make('old-password'),
]);
// Create fake session records for the user
DB::table('sessions')->insert([
[
'id' => 'session-1',
'user_id' => $user->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'Test Browser',
'payload' => base64_encode('test-payload-1'),
'last_activity' => now()->timestamp,
],
[
'id' => 'session-2',
'user_id' => $user->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'Test Browser',
'payload' => base64_encode('test-payload-2'),
'last_activity' => now()->timestamp,
],
]);
// Verify sessions exist
expect(DB::table('sessions')->where('user_id', $user->id)->count())->toBe(2);
// Change password
$user->password = Hash::make('new-password');
$user->save();
// Verify all sessions for this user were deleted
expect(DB::table('sessions')->where('user_id', $user->id)->count())->toBe(0);
});
it('does not invalidate sessions when password is unchanged', function () {
// Create a user
$user = User::factory()->create([
'password' => Hash::make('password'),
]);
// Create fake session records for the user
DB::table('sessions')->insert([
[
'id' => 'session-1',
'user_id' => $user->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'Test Browser',
'payload' => base64_encode('test-payload'),
'last_activity' => now()->timestamp,
],
]);
// Update other user fields (not password)
$user->name = 'New Name';
$user->save();
// Verify session still exists
expect(DB::table('sessions')->where('user_id', $user->id)->count())->toBe(1);
});
it('does not invalidate sessions when password is set to same value', function () {
// Create a user with a specific password
$hashedPassword = Hash::make('password');
$user = User::factory()->create([
'password' => $hashedPassword,
]);
// Create fake session records for the user
DB::table('sessions')->insert([
[
'id' => 'session-1',
'user_id' => $user->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'Test Browser',
'payload' => base64_encode('test-payload'),
'last_activity' => now()->timestamp,
],
]);
// Set password to the same value
$user->password = $hashedPassword;
$user->save();
// Verify session still exists (password didn't actually change)
expect(DB::table('sessions')->where('user_id', $user->id)->count())->toBe(1);
});
it('invalidates sessions only for the user whose password changed', function () {
// Create two users
$user1 = User::factory()->create([
'password' => Hash::make('password1'),
]);
$user2 = User::factory()->create([
'password' => Hash::make('password2'),
]);
// Create sessions for both users
DB::table('sessions')->insert([
[
'id' => 'session-user1',
'user_id' => $user1->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'Test Browser',
'payload' => base64_encode('test-payload-1'),
'last_activity' => now()->timestamp,
],
[
'id' => 'session-user2',
'user_id' => $user2->id,
'ip_address' => '127.0.0.1',
'user_agent' => 'Test Browser',
'payload' => base64_encode('test-payload-2'),
'last_activity' => now()->timestamp,
],
]);
// Change password for user1 only
$user1->password = Hash::make('new-password1');
$user1->save();
// Verify user1's sessions were deleted but user2's remain
expect(DB::table('sessions')->where('user_id', $user1->id)->count())->toBe(0);
expect(DB::table('sessions')->where('user_id', $user2->id)->count())->toBe(1);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ServerSettingWasChangedTest.php | tests/Feature/ServerSettingWasChangedTest.php | <?php
use App\Models\Server;
use App\Models\ServerSetting;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
it('wasChanged returns true after saving a changed field', function () {
// Create user and server
$user = User::factory()->create();
$team = $user->teams()->first();
$server = Server::factory()->create(['team_id' => $team->id]);
$settings = $server->settings;
// Change a field
$settings->is_reachable = ! $settings->is_reachable;
$settings->save();
// In the updated hook, wasChanged should return true
expect($settings->wasChanged('is_reachable'))->toBeTrue();
});
it('isDirty returns false after saving', function () {
// Create user and server
$user = User::factory()->create();
$team = $user->teams()->first();
$server = Server::factory()->create(['team_id' => $team->id]);
$settings = $server->settings;
// Change a field
$settings->is_reachable = ! $settings->is_reachable;
$settings->save();
// After save, isDirty returns false (this is the bug)
expect($settings->isDirty('is_reachable'))->toBeFalse();
});
it('can detect sentinel_token changes with wasChanged', function () {
// Create user and server
$user = User::factory()->create();
$team = $user->teams()->first();
$server = Server::factory()->create(['team_id' => $team->id]);
$settings = $server->settings;
$originalToken = $settings->sentinel_token;
// Create a tracking variable using model events
$tokenWasChanged = false;
ServerSetting::updated(function ($model) use (&$tokenWasChanged) {
if ($model->wasChanged('sentinel_token')) {
$tokenWasChanged = true;
}
});
// Change the token
$settings->sentinel_token = 'new-token-value-for-testing';
$settings->save();
expect($tokenWasChanged)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/LoginRateLimitIPTest.php | tests/Feature/LoginRateLimitIPTest.php | <?php
it('tests login rate limiting with different IPs like the Python script', function () {
// Create a test route that mimics login behavior
// We'll directly test the rate limiter behavior
$baseUrl = '/login';
$email = 'grumpinout+admin@wearehackerone.com';
// First, get a CSRF token by visiting the login page
$loginPageResponse = $this->get($baseUrl);
$loginPageResponse->assertSuccessful();
// Extract CSRF token using regex similar to Python script
preg_match('/name="_token"\s+value="([^"]+)"/', $loginPageResponse->getContent(), $matches);
$token = $matches[1] ?? null;
expect($token)->not->toBeNull('CSRF token should be found');
// Test 14 login attempts with different IPs (like the Python script does 1-14)
$results = [];
for ($i = 1; $i <= 14; $i++) {
$spoofedIp = "198.51.100.{$i}";
$response = $this->withHeader('X-Forwarded-For', $spoofedIp)
->post($baseUrl, [
'_token' => $token,
'email' => $email,
'password' => "WrongPass{$i}!",
]);
$statusCode = $response->getStatusCode();
$rateLimitLimit = $response->headers->get('X-RateLimit-Limit');
$rateLimitRemaining = $response->headers->get('X-RateLimit-Remaining');
$results[$i] = [
'ip' => $spoofedIp,
'status' => $statusCode,
'rate_limit' => $rateLimitLimit,
'rate_limit_remaining' => $rateLimitRemaining,
];
// Print output similar to Python script
echo 'Attempt '.str_pad($i, 2, '0', STR_PAD_LEFT).": status=$statusCode, RL=$rateLimitLimit/$rateLimitRemaining\n";
// Add a small delay like the Python script (0.2 seconds)
usleep(200000);
}
// Verify results
expect($results)->toHaveCount(14);
// Check that we got responses for all attempts
foreach ($results as $i => $result) {
expect($result['status'])->toBeGreaterThanOrEqual(200);
expect($result['ip'])->toBe("198.51.100.{$i}");
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/GithubSourceCreateTest.php | tests/Feature/GithubSourceCreateTest.php | <?php
use App\Livewire\Source\Github\Create;
use App\Models\GithubApp;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a team with owner
$this->team = Team::factory()->create();
$this->user = User::factory()->create();
$this->team->members()->attach($this->user->id, ['role' => 'owner']);
// Set current team
$this->actingAs($this->user);
session(['currentTeam' => $this->team]);
});
describe('GitHub Source Create Component', function () {
test('creates github app with default values', function () {
Livewire::test(Create::class)
->assertSuccessful()
->set('name', 'my-test-app')
->call('createGitHubApp')
->assertRedirect();
$githubApp = GithubApp::where('name', 'my-test-app')->first();
expect($githubApp)->not->toBeNull();
expect($githubApp->name)->toBe('my-test-app');
expect($githubApp->api_url)->toBe('https://api.github.com');
expect($githubApp->html_url)->toBe('https://github.com');
expect($githubApp->custom_user)->toBe('git');
expect($githubApp->custom_port)->toBe(22);
expect($githubApp->is_system_wide)->toBeFalse();
expect($githubApp->team_id)->toBe($this->team->id);
});
test('creates github app with system wide enabled', function () {
Livewire::test(Create::class)
->assertSuccessful()
->set('name', 'system-wide-app')
->set('is_system_wide', true)
->call('createGitHubApp')
->assertRedirect();
$githubApp = GithubApp::where('name', 'system-wide-app')->first();
expect($githubApp)->not->toBeNull();
expect($githubApp->is_system_wide)->toBeTrue();
});
test('creates github app with custom organization', function () {
Livewire::test(Create::class)
->assertSuccessful()
->set('name', 'org-app')
->set('organization', 'my-org')
->call('createGitHubApp')
->assertRedirect();
$githubApp = GithubApp::where('name', 'org-app')->first();
expect($githubApp)->not->toBeNull();
expect($githubApp->organization)->toBe('my-org');
});
test('creates github app with custom git settings', function () {
Livewire::test(Create::class)
->assertSuccessful()
->set('name', 'enterprise-app')
->set('api_url', 'https://github.enterprise.com/api/v3')
->set('html_url', 'https://github.enterprise.com')
->set('custom_user', 'git-custom')
->set('custom_port', 2222)
->call('createGitHubApp')
->assertRedirect();
$githubApp = GithubApp::where('name', 'enterprise-app')->first();
expect($githubApp)->not->toBeNull();
expect($githubApp->api_url)->toBe('https://github.enterprise.com/api/v3');
expect($githubApp->html_url)->toBe('https://github.enterprise.com');
expect($githubApp->custom_user)->toBe('git-custom');
expect($githubApp->custom_port)->toBe(2222);
});
test('validates required fields', function () {
Livewire::test(Create::class)
->assertSuccessful()
->set('name', '')
->call('createGitHubApp')
->assertHasErrors(['name']);
});
test('redirects to github app show page after creation', function () {
$component = Livewire::test(Create::class)
->set('name', 'redirect-test')
->call('createGitHubApp');
$githubApp = GithubApp::where('name', 'redirect-test')->first();
$component->assertRedirect(route('source.github.show', ['github_app_uuid' => $githubApp->uuid]));
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/Utf8HandlingTest.php | tests/Feature/Utf8HandlingTest.php | <?php
namespace Tests\Feature;
use Tests\TestCase;
class Utf8HandlingTest extends TestCase
{
public function test_sanitize_utf8_text_handles_malformed_utf8()
{
// Test with valid UTF-8
$validUtf8 = 'Hello World! 🚀';
$this->assertEquals($validUtf8, sanitize_utf8_text($validUtf8));
// Test with empty string
$this->assertEquals('', sanitize_utf8_text(''));
// Test with malformed UTF-8 (binary data)
$malformedUtf8 = "Hello\x80\x81\x82World";
$sanitized = sanitize_utf8_text($malformedUtf8);
$this->assertTrue(mb_check_encoding($sanitized, 'UTF-8'));
// Test that JSON encoding works after sanitization
$testArray = ['output' => $sanitized];
$this->assertIsString(json_encode($testArray, JSON_THROW_ON_ERROR));
}
public function test_remove_iip_handles_malformed_utf8()
{
// Test with malformed UTF-8 in command output
$malformedOutput = "Processing image\x80\x81file.webp";
$cleaned = remove_iip($malformedOutput);
$this->assertTrue(mb_check_encoding($cleaned, 'UTF-8'));
// Test that JSON encoding works after cleaning
$this->assertIsString(json_encode(['output' => $cleaned], JSON_THROW_ON_ERROR));
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/SentinelUpdateCheckIndependenceTest.php | tests/Feature/SentinelUpdateCheckIndependenceTest.php | <?php
use App\Jobs\CheckAndStartSentinelJob;
use App\Jobs\ServerManagerJob;
use App\Models\InstanceSettings;
use App\Models\Server;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Queue;
uses(RefreshDatabase::class);
beforeEach(function () {
Queue::fake();
// Create user (which automatically creates a team)
$user = User::factory()->create();
$this->team = $user->teams()->first();
// Create server with sentinel enabled
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
]);
// Enable sentinel on the server
$this->server->settings->update([
'is_sentinel_enabled' => true,
'server_timezone' => 'UTC',
]);
$this->server->refresh();
});
afterEach(function () {
Carbon::setTestNow(); // Reset frozen time
});
it('dispatches sentinel check hourly regardless of instance update_check_frequency setting', function () {
// Set instance update_check_frequency to yearly (most infrequent option)
$instanceSettings = InstanceSettings::first();
$instanceSettings->update([
'update_check_frequency' => '0 0 1 1 *', // Yearly - January 1st at midnight
'instance_timezone' => 'UTC',
]);
// Set time to top of any hour (sentinel should check every hour)
Carbon::setTestNow('2025-06-15 14:00:00'); // Random hour, not January 1st
// Run ServerManagerJob
$job = new ServerManagerJob;
$job->handle();
// Assert that CheckAndStartSentinelJob was dispatched despite yearly update check frequency
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) {
return $job->server->id === $this->server->id;
});
});
it('does not dispatch sentinel check when not at top of hour', function () {
// Set instance update_check_frequency to hourly (most frequent)
$instanceSettings = InstanceSettings::first();
$instanceSettings->update([
'update_check_frequency' => '0 * * * *', // Hourly
'instance_timezone' => 'UTC',
]);
// Set time to middle of the hour (sentinel check cron won't match)
Carbon::setTestNow('2025-06-15 14:30:00'); // 30 minutes past the hour
// Run ServerManagerJob
$job = new ServerManagerJob;
$job->handle();
// Assert that CheckAndStartSentinelJob was NOT dispatched (not top of hour)
Queue::assertNotPushed(CheckAndStartSentinelJob::class);
});
it('dispatches sentinel check at every hour mark throughout the day', function () {
$instanceSettings = InstanceSettings::first();
$instanceSettings->update([
'update_check_frequency' => '0 0 1 1 *', // Yearly
'instance_timezone' => 'UTC',
]);
// Test multiple hours throughout a day
$hoursToTest = [0, 6, 12, 18, 23]; // Various hours of the day
foreach ($hoursToTest as $hour) {
Queue::fake(); // Reset queue for each test
Carbon::setTestNow("2025-06-15 {$hour}:00:00");
$job = new ServerManagerJob;
$job->handle();
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) {
return $job->server->id === $this->server->id;
}, "Failed to dispatch sentinel check at hour {$hour}");
}
});
it('respects server timezone when checking sentinel updates', function () {
// Update server timezone to America/New_York
$this->server->settings->update([
'server_timezone' => 'America/New_York',
]);
$instanceSettings = InstanceSettings::first();
$instanceSettings->update([
'instance_timezone' => 'UTC',
]);
// Set time to 17:00 UTC which is 12:00 PM EST (top of hour in server's timezone)
Carbon::setTestNow('2025-01-15 17:00:00');
$job = new ServerManagerJob;
$job->handle();
// Should dispatch because it's top of hour in server's timezone (America/New_York)
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) {
return $job->server->id === $this->server->id;
});
});
it('does not dispatch sentinel check for servers without sentinel enabled', function () {
// Disable sentinel
$this->server->settings->update([
'is_sentinel_enabled' => false,
]);
$instanceSettings = InstanceSettings::first();
$instanceSettings->update([
'update_check_frequency' => '0 * * * *',
'instance_timezone' => 'UTC',
]);
Carbon::setTestNow('2025-06-15 14:00:00');
$job = new ServerManagerJob;
$job->handle();
// Should NOT dispatch because sentinel is disabled
Queue::assertNotPushed(CheckAndStartSentinelJob::class);
});
it('handles multiple servers with different sentinel configurations', function () {
// Create a second server with sentinel disabled
$server2 = Server::factory()->create([
'team_id' => $this->team->id,
]);
$server2->settings->update([
'is_sentinel_enabled' => false,
'server_timezone' => 'UTC',
]);
// Create a third server with sentinel enabled
$server3 = Server::factory()->create([
'team_id' => $this->team->id,
]);
$server3->settings->update([
'is_sentinel_enabled' => true,
'server_timezone' => 'UTC',
]);
$instanceSettings = InstanceSettings::first();
$instanceSettings->update([
'instance_timezone' => 'UTC',
]);
Carbon::setTestNow('2025-06-15 14:00:00');
$job = new ServerManagerJob;
$job->handle();
// Should dispatch for server1 (sentinel enabled) and server3 (sentinel enabled)
Queue::assertPushed(CheckAndStartSentinelJob::class, 2);
// Verify it was dispatched for the correct servers
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) {
return $job->server->id === $this->server->id;
});
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) use ($server3) {
return $job->server->id === $server3->id;
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ServerPatchCheckNotificationTest.php | tests/Feature/ServerPatchCheckNotificationTest.php | <?php
use App\Models\InstanceSettings;
use App\Models\Server;
use App\Notifications\Server\ServerPatchCheck;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create a real InstanceSettings record in the test database
// This avoids Mockery alias/overload issues that pollute global state
$this->setInstanceSettings = function ($fqdn = null, $publicIpv4 = null, $publicIpv6 = null) {
InstanceSettings::query()->delete();
InstanceSettings::create([
'id' => 0,
'fqdn' => $fqdn,
'public_ipv4' => $publicIpv4,
'public_ipv6' => $publicIpv6,
]);
};
$this->createMockServer = function ($uuid, $name = 'Test Server') {
$mockServer = Mockery::mock(Server::class);
$mockServer->shouldReceive('getAttribute')
->with('uuid')
->andReturn($uuid);
$mockServer->shouldReceive('getAttribute')
->with('name')
->andReturn($name);
$mockServer->shouldReceive('setAttribute')->andReturnSelf();
$mockServer->shouldReceive('getSchemalessAttributes')->andReturn([]);
$mockServer->uuid = $uuid;
$mockServer->name = $name;
return $mockServer;
};
});
afterEach(function () {
Mockery::close();
});
it('generates url using base_url instead of APP_URL', function () {
// Set InstanceSettings to return a specific FQDN
($this->setInstanceSettings)('https://coolify.example.com');
$mockServer = ($this->createMockServer)('test-server-uuid');
$patchData = [
'total_updates' => 5,
'updates' => [],
'osId' => 'ubuntu',
'package_manager' => 'apt',
];
$notification = new ServerPatchCheck($mockServer, $patchData);
// The URL should use the FQDN from InstanceSettings, not APP_URL
expect($notification->serverUrl)->toBe('https://coolify.example.com/server/test-server-uuid/security/patches');
});
it('falls back to public_ipv4 with port when fqdn is not set', function () {
// Set InstanceSettings to return public IPv4
($this->setInstanceSettings)(null, '192.168.1.100');
$mockServer = ($this->createMockServer)('test-server-uuid');
$patchData = [
'total_updates' => 3,
'updates' => [],
'osId' => 'debian',
'package_manager' => 'apt',
];
$notification = new ServerPatchCheck($mockServer, $patchData);
// The URL should use public IPv4 with default port 8000
expect($notification->serverUrl)->toBe('http://192.168.1.100:8000/server/test-server-uuid/security/patches');
});
it('includes server url in all notification channels', function () {
($this->setInstanceSettings)('https://coolify.test');
$mockServer = ($this->createMockServer)('abc-123', 'Test Server');
$patchData = [
'total_updates' => 10,
'updates' => [
[
'package' => 'nginx',
'current_version' => '1.18',
'new_version' => '1.20',
'architecture' => 'amd64',
'repository' => 'main',
],
],
'osId' => 'ubuntu',
'package_manager' => 'apt',
];
$notification = new ServerPatchCheck($mockServer, $patchData);
// Check Discord
$discord = $notification->toDiscord();
expect($discord->description)->toContain('https://coolify.test/server/abc-123/security/patches');
// Check Telegram
$telegram = $notification->toTelegram();
expect($telegram['buttons'][0]['url'])->toBe('https://coolify.test/server/abc-123/security/patches');
// Check Pushover
$pushover = $notification->toPushover();
expect($pushover->buttons[0]['url'])->toBe('https://coolify.test/server/abc-123/security/patches');
// Check Slack
$slack = $notification->toSlack();
expect($slack->description)->toContain('https://coolify.test/server/abc-123/security/patches');
// Check Webhook
$webhook = $notification->toWebhook();
expect($webhook['url'])->toBe('https://coolify.test/server/abc-123/security/patches');
});
it('uses correct url in error notifications', function () {
($this->setInstanceSettings)('https://coolify.production.com');
$mockServer = ($this->createMockServer)('error-server-uuid', 'Error Server');
$patchData = [
'error' => 'Failed to connect to package manager',
'osId' => 'ubuntu',
'package_manager' => 'apt',
];
$notification = new ServerPatchCheck($mockServer, $patchData);
// Check error Discord notification
$discord = $notification->toDiscord();
expect($discord->description)->toContain('https://coolify.production.com/server/error-server-uuid/security/patches');
// Check error webhook
$webhook = $notification->toWebhook();
expect($webhook['url'])->toBe('https://coolify.production.com/server/error-server-uuid/security/patches')
->and($webhook['event'])->toBe('server_patch_check_error');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/EnvironmentVariableSharedSpacingTest.php | tests/Feature/EnvironmentVariableSharedSpacingTest.php | <?php
use App\Models\Application;
use App\Models\Environment;
use App\Models\EnvironmentVariable;
use App\Models\Project;
use App\Models\SharedEnvironmentVariable;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
// Create test user and team
$this->user = User::factory()->create();
$this->team = Team::factory()->create();
$this->user->teams()->attach($this->team);
// Create project and environment
$this->project = Project::factory()->create(['team_id' => $this->team->id]);
$this->environment = Environment::factory()->create([
'project_id' => $this->project->id,
]);
// Create application for testing
$this->application = Application::factory()->create([
'environment_id' => $this->environment->id,
]);
});
test('shared variable preserves spacing in reference', function () {
$env = EnvironmentVariable::create([
'key' => 'TEST_VAR',
'value' => '{{ project.aaa }}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
$env->refresh();
expect($env->value)->toBe('{{ project.aaa }}');
});
test('shared variable preserves no-space format', function () {
$env = EnvironmentVariable::create([
'key' => 'TEST_VAR',
'value' => '{{project.aaa}}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
$env->refresh();
expect($env->value)->toBe('{{project.aaa}}');
});
test('shared variable with spaces resolves correctly', function () {
// Create shared variable
$shared = SharedEnvironmentVariable::create([
'key' => 'TEST_KEY',
'value' => 'test-value-123',
'type' => 'project',
'project_id' => $this->project->id,
'team_id' => $this->team->id,
]);
// Create env var with spaces
$env = EnvironmentVariable::create([
'key' => 'MY_VAR',
'value' => '{{ project.TEST_KEY }}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
// Verify it resolves correctly
$realValue = $env->real_value;
expect($realValue)->toBe('test-value-123');
});
test('shared variable without spaces resolves correctly', function () {
// Create shared variable
$shared = SharedEnvironmentVariable::create([
'key' => 'TEST_KEY',
'value' => 'test-value-456',
'type' => 'project',
'project_id' => $this->project->id,
'team_id' => $this->team->id,
]);
// Create env var without spaces
$env = EnvironmentVariable::create([
'key' => 'MY_VAR',
'value' => '{{project.TEST_KEY}}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
// Verify it resolves correctly
$realValue = $env->real_value;
expect($realValue)->toBe('test-value-456');
});
test('shared variable with extra internal spaces resolves correctly', function () {
// Create shared variable
$shared = SharedEnvironmentVariable::create([
'key' => 'TEST_KEY',
'value' => 'test-value-789',
'type' => 'project',
'project_id' => $this->project->id,
'team_id' => $this->team->id,
]);
// Create env var with multiple spaces
$env = EnvironmentVariable::create([
'key' => 'MY_VAR',
'value' => '{{ project.TEST_KEY }}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
// Verify it resolves correctly (parser trims when extracting)
$realValue = $env->real_value;
expect($realValue)->toBe('test-value-789');
});
test('is_shared attribute detects variable with spaces', function () {
$env = EnvironmentVariable::create([
'key' => 'TEST',
'value' => '{{ project.aaa }}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
expect($env->is_shared)->toBeTrue();
});
test('is_shared attribute detects variable without spaces', function () {
$env = EnvironmentVariable::create([
'key' => 'TEST',
'value' => '{{project.aaa}}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
expect($env->is_shared)->toBeTrue();
});
test('non-shared variable preserves spaces', function () {
$env = EnvironmentVariable::create([
'key' => 'REGULAR',
'value' => 'regular value with spaces',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
$env->refresh();
expect($env->value)->toBe('regular value with spaces');
});
test('mixed content with shared variable preserves all spacing', function () {
$env = EnvironmentVariable::create([
'key' => 'MIXED',
'value' => 'prefix {{ project.aaa }} suffix',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
$env->refresh();
expect($env->value)->toBe('prefix {{ project.aaa }} suffix');
});
test('multiple shared variables preserve individual spacing', function () {
$env = EnvironmentVariable::create([
'key' => 'MULTI',
'value' => '{{ project.a }} and {{team.b}}',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
$env->refresh();
expect($env->value)->toBe('{{ project.a }} and {{team.b}}');
});
test('leading and trailing spaces are trimmed', function () {
$env = EnvironmentVariable::create([
'key' => 'TRIMMED',
'value' => ' {{ project.aaa }} ',
'resource_id' => $this->application->id,
'resource_type' => $this->application->getMorphClass(),
]);
$env->refresh();
// External spaces trimmed, internal preserved
expect($env->value)->toBe('{{ project.aaa }}');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/IpAllowlistTest.php | tests/Feature/IpAllowlistTest.php | <?php
test('IP allowlist with single IPs', function () {
$testCases = [
['ip' => '192.168.1.100', 'allowlist' => ['192.168.1.100'], 'expected' => true],
['ip' => '192.168.1.101', 'allowlist' => ['192.168.1.100'], 'expected' => false],
['ip' => '10.0.0.1', 'allowlist' => ['10.0.0.1', '192.168.1.100'], 'expected' => true],
];
foreach ($testCases as $case) {
$result = checkIPAgainstAllowlist($case['ip'], $case['allowlist']);
expect($result)->toBe($case['expected']);
}
});
test('IP allowlist with CIDR notation', function () {
$testCases = [
['ip' => '192.168.1.50', 'allowlist' => ['192.168.1.0/24'], 'expected' => true],
['ip' => '192.168.2.50', 'allowlist' => ['192.168.1.0/24'], 'expected' => false],
['ip' => '10.0.0.5', 'allowlist' => ['10.0.0.0/8'], 'expected' => true],
['ip' => '11.0.0.5', 'allowlist' => ['10.0.0.0/8'], 'expected' => false],
['ip' => '172.16.5.10', 'allowlist' => ['172.16.0.0/12'], 'expected' => true],
['ip' => '172.32.0.1', 'allowlist' => ['172.16.0.0/12'], 'expected' => false],
];
foreach ($testCases as $case) {
$result = checkIPAgainstAllowlist($case['ip'], $case['allowlist']);
expect($result)->toBe($case['expected']);
}
});
test('IP allowlist with 0.0.0.0 allows all', function () {
$testIps = [
'1.2.3.4',
'192.168.1.1',
'10.0.0.1',
'255.255.255.255',
'127.0.0.1',
];
// Test 0.0.0.0 without subnet
foreach ($testIps as $ip) {
$result = checkIPAgainstAllowlist($ip, ['0.0.0.0']);
expect($result)->toBeTrue();
}
// Test 0.0.0.0 with any subnet notation - should still allow all
foreach ($testIps as $ip) {
expect(checkIPAgainstAllowlist($ip, ['0.0.0.0/0']))->toBeTrue();
expect(checkIPAgainstAllowlist($ip, ['0.0.0.0/8']))->toBeTrue();
expect(checkIPAgainstAllowlist($ip, ['0.0.0.0/24']))->toBeTrue();
expect(checkIPAgainstAllowlist($ip, ['0.0.0.0/32']))->toBeTrue();
}
});
test('IP allowlist with mixed entries', function () {
$allowlist = ['192.168.1.100', '10.0.0.0/8', '172.16.0.0/16'];
$testCases = [
['ip' => '192.168.1.100', 'expected' => true], // Exact match
['ip' => '192.168.1.101', 'expected' => false], // No match
['ip' => '10.5.5.5', 'expected' => true], // Matches 10.0.0.0/8
['ip' => '172.16.255.255', 'expected' => true], // Matches 172.16.0.0/16
['ip' => '172.17.0.1', 'expected' => false], // Outside 172.16.0.0/16
['ip' => '8.8.8.8', 'expected' => false], // No match
];
foreach ($testCases as $case) {
$result = checkIPAgainstAllowlist($case['ip'], $allowlist);
expect($result)->toBe($case['expected']);
}
});
test('IP allowlist handles empty and invalid entries', function () {
// Empty allowlist blocks all
expect(checkIPAgainstAllowlist('192.168.1.1', []))->toBeFalse();
expect(checkIPAgainstAllowlist('192.168.1.1', ['']))->toBeFalse();
// Handles spaces
expect(checkIPAgainstAllowlist('192.168.1.100', [' 192.168.1.100 ']))->toBeTrue();
expect(checkIPAgainstAllowlist('10.0.0.5', [' 10.0.0.0/8 ']))->toBeTrue();
// Invalid entries are skipped
expect(checkIPAgainstAllowlist('192.168.1.1', ['invalid.ip']))->toBeFalse();
expect(checkIPAgainstAllowlist('192.168.1.1', ['192.168.1.0/33']))->toBeFalse(); // Invalid mask
expect(checkIPAgainstAllowlist('192.168.1.1', ['192.168.1.0/-1']))->toBeFalse(); // Invalid mask
});
test('IP allowlist with various subnet sizes', function () {
// /32 - single host
expect(checkIPAgainstAllowlist('192.168.1.1', ['192.168.1.1/32']))->toBeTrue();
expect(checkIPAgainstAllowlist('192.168.1.2', ['192.168.1.1/32']))->toBeFalse();
// /31 - point-to-point link
expect(checkIPAgainstAllowlist('192.168.1.0', ['192.168.1.0/31']))->toBeTrue();
expect(checkIPAgainstAllowlist('192.168.1.1', ['192.168.1.0/31']))->toBeTrue();
expect(checkIPAgainstAllowlist('192.168.1.2', ['192.168.1.0/31']))->toBeFalse();
// /16 - class B
expect(checkIPAgainstAllowlist('172.16.0.1', ['172.16.0.0/16']))->toBeTrue();
expect(checkIPAgainstAllowlist('172.16.255.255', ['172.16.0.0/16']))->toBeTrue();
expect(checkIPAgainstAllowlist('172.17.0.1', ['172.16.0.0/16']))->toBeFalse();
// /0 - all addresses
expect(checkIPAgainstAllowlist('1.1.1.1', ['0.0.0.0/0']))->toBeTrue();
expect(checkIPAgainstAllowlist('255.255.255.255', ['0.0.0.0/0']))->toBeTrue();
});
test('IP allowlist comma-separated string input', function () {
// Test with comma-separated string (as it would come from the settings)
$allowlistString = '192.168.1.100,10.0.0.0/8,172.16.0.0/16';
$allowlist = explode(',', $allowlistString);
expect(checkIPAgainstAllowlist('192.168.1.100', $allowlist))->toBeTrue();
expect(checkIPAgainstAllowlist('10.5.5.5', $allowlist))->toBeTrue();
expect(checkIPAgainstAllowlist('172.16.10.10', $allowlist))->toBeTrue();
expect(checkIPAgainstAllowlist('8.8.8.8', $allowlist))->toBeFalse();
});
test('ValidIpOrCidr validation rule', function () {
$rule = new \App\Rules\ValidIpOrCidr;
// Helper function to test validation
$validate = function ($value) use ($rule) {
$errors = [];
$fail = function ($message) use (&$errors) {
$errors[] = $message;
};
$rule->validate('allowed_ips', $value, $fail);
return empty($errors);
};
// Valid cases - should pass
expect($validate(''))->toBeTrue(); // Empty is allowed
expect($validate('0.0.0.0'))->toBeTrue(); // 0.0.0.0 is allowed
expect($validate('192.168.1.1'))->toBeTrue(); // Valid IP
expect($validate('192.168.1.0/24'))->toBeTrue(); // Valid CIDR
expect($validate('10.0.0.0/8'))->toBeTrue(); // Valid CIDR
expect($validate('192.168.1.1,10.0.0.1'))->toBeTrue(); // Multiple valid IPs
expect($validate('192.168.1.0/24,10.0.0.0/8'))->toBeTrue(); // Multiple CIDRs
expect($validate('0.0.0.0/0'))->toBeTrue(); // 0.0.0.0 with subnet
expect($validate('0.0.0.0/24'))->toBeTrue(); // 0.0.0.0 with any subnet
expect($validate(' 192.168.1.1 '))->toBeTrue(); // With spaces
// Invalid cases - should fail
expect($validate('1'))->toBeFalse(); // Single digit
expect($validate('abc'))->toBeFalse(); // Invalid text
expect($validate('192.168.1.256'))->toBeFalse(); // Invalid IP (256)
expect($validate('192.168.1.0/33'))->toBeFalse(); // Invalid CIDR mask (>32)
expect($validate('192.168.1.0/-1'))->toBeFalse(); // Invalid CIDR mask (<0)
expect($validate('192.168.1.1,abc'))->toBeFalse(); // Mix of valid and invalid
expect($validate('192.168.1.1,192.168.1.256'))->toBeFalse(); // Mix with invalid IP
expect($validate('192.168.1.0/24/32'))->toBeFalse(); // Invalid CIDR format
expect($validate('not.an.ip.address'))->toBeFalse(); // Invalid format
expect($validate('192.168'))->toBeFalse(); // Incomplete IP
expect($validate('192.168.1.1.1'))->toBeFalse(); // Too many octets
});
test('ValidIpOrCidr validation rule error messages', function () {
$rule = new \App\Rules\ValidIpOrCidr;
// Helper function to get error message
$getError = function ($value) use ($rule) {
$errors = [];
$fail = function ($message) use (&$errors) {
$errors[] = $message;
};
$rule->validate('allowed_ips', $value, $fail);
return $errors[0] ?? null;
};
// Test error messages
$error = $getError('1');
expect($error)->toContain('not valid IP addresses or CIDR notations');
expect($error)->toContain('1');
$error = $getError('192.168.1.1,abc,10.0.0.256');
expect($error)->toContain('abc');
expect($error)->toContain('10.0.0.256');
expect($error)->not->toContain('192.168.1.1'); // Valid IP should not be in error
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/TrustHostsMiddlewareTest.php | tests/Feature/TrustHostsMiddlewareTest.php | <?php
use App\Http\Middleware\TrustHosts;
use App\Models\InstanceSettings;
use Illuminate\Support\Facades\Cache;
uses(\Illuminate\Foundation\Testing\RefreshDatabase::class);
beforeEach(function () {
// Clear cache before each test to ensure isolation
Cache::forget('instance_settings_fqdn_host');
});
it('trusts the configured FQDN from InstanceSettings', function () {
// Create instance settings with FQDN
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'https://coolify.example.com']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
expect($hosts)->toContain('coolify.example.com');
});
it('rejects password reset request with malicious host header', function () {
// Set up instance settings with legitimate FQDN
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'https://coolify.example.com']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
// The malicious host should NOT be in the trusted hosts
expect($hosts)->not->toContain('coolify.example.com.evil.com');
expect($hosts)->toContain('coolify.example.com');
});
it('handles missing FQDN gracefully', function () {
// Create instance settings without FQDN
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => null]
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
// Should still return APP_URL pattern without throwing
expect($hosts)->not->toBeEmpty();
});
it('filters out null and empty values from trusted hosts', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => '']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
// Should not contain empty strings or null
foreach ($hosts as $host) {
if ($host !== null) {
expect($host)->not->toBeEmpty();
}
}
});
it('extracts host from FQDN with protocol and port', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'https://coolify.example.com:8443']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
expect($hosts)->toContain('coolify.example.com');
});
it('handles exception during InstanceSettings fetch', function () {
// Drop the instance_settings table to simulate installation
\Schema::dropIfExists('instance_settings');
$middleware = new TrustHosts($this->app);
// Should not throw an exception
$hosts = $middleware->hosts();
expect($hosts)->not->toBeEmpty();
});
it('trusts IP addresses with port', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'http://65.21.3.91:8000']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
expect($hosts)->toContain('65.21.3.91');
});
it('trusts IP addresses without port', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'http://192.168.1.100']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
expect($hosts)->toContain('192.168.1.100');
});
it('rejects malicious host when using IP address', function () {
// Simulate an instance using IP address
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'http://65.21.3.91:8000']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
// The malicious host attempting to mimic the IP should NOT be trusted
expect($hosts)->not->toContain('65.21.3.91.evil.com');
expect($hosts)->not->toContain('evil.com');
expect($hosts)->toContain('65.21.3.91');
});
it('trusts IPv6 addresses', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'http://[2001:db8::1]:8000']
);
$middleware = new TrustHosts($this->app);
$hosts = $middleware->hosts();
// IPv6 addresses are enclosed in brackets, getHost() should handle this
expect($hosts)->toContain('[2001:db8::1]');
});
it('invalidates cache when FQDN is updated', function () {
// Set initial FQDN
$settings = InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'https://old-domain.com']
);
// First call should cache it
$middleware = new TrustHosts($this->app);
$hosts1 = $middleware->hosts();
expect($hosts1)->toContain('old-domain.com');
// Verify cache exists
expect(Cache::has('instance_settings_fqdn_host'))->toBeTrue();
// Update FQDN - should trigger cache invalidation
$settings->fqdn = 'https://new-domain.com';
$settings->save();
// Cache should be cleared
expect(Cache::has('instance_settings_fqdn_host'))->toBeFalse();
// New call should return updated host
$middleware2 = new TrustHosts($this->app);
$hosts2 = $middleware2->hosts();
expect($hosts2)->toContain('new-domain.com');
expect($hosts2)->not->toContain('old-domain.com');
});
it('caches trusted hosts to avoid database queries on every request', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'https://coolify.example.com']
);
// Clear cache first
Cache::forget('instance_settings_fqdn_host');
// First call - should query database and cache result
$middleware1 = new TrustHosts($this->app);
$hosts1 = $middleware1->hosts();
// Verify result is cached
expect(Cache::has('instance_settings_fqdn_host'))->toBeTrue();
expect(Cache::get('instance_settings_fqdn_host'))->toBe('coolify.example.com');
// Subsequent calls should use cache (no DB query)
$middleware2 = new TrustHosts($this->app);
$hosts2 = $middleware2->hosts();
expect($hosts1)->toBe($hosts2);
expect($hosts2)->toContain('coolify.example.com');
});
it('caches negative results when no FQDN is configured', function () {
// Create instance settings without FQDN
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => null]
);
// Clear cache first
Cache::forget('instance_settings_fqdn_host');
// First call - should query database and cache empty string sentinel
$middleware1 = new TrustHosts($this->app);
$hosts1 = $middleware1->hosts();
// Verify empty string sentinel is cached (not null, which wouldn't be cached)
expect(Cache::has('instance_settings_fqdn_host'))->toBeTrue();
expect(Cache::get('instance_settings_fqdn_host'))->toBe('');
// Subsequent calls should use cached sentinel value
$middleware2 = new TrustHosts($this->app);
$hosts2 = $middleware2->hosts();
expect($hosts1)->toBe($hosts2);
// Should only contain APP_URL pattern, not any FQDN
expect($hosts2)->not->toBeEmpty();
});
it('skips host validation for terminal auth routes', function () {
// These routes should be accessible with any Host header (for internal container communication)
$response = $this->postJson('/terminal/auth', [], [
'Host' => 'coolify:8080', // Internal Docker host
]);
// Should not get 400 Bad Host (might get 401 Unauthorized instead)
expect($response->status())->not->toBe(400);
});
it('skips host validation for terminal auth ips route', function () {
// These routes should be accessible with any Host header (for internal container communication)
$response = $this->postJson('/terminal/auth/ips', [], [
'Host' => 'soketi:6002', // Another internal Docker host
]);
// Should not get 400 Bad Host (might get 401 Unauthorized instead)
expect($response->status())->not->toBe(400);
});
it('still enforces host validation for non-terminal routes', function () {
InstanceSettings::updateOrCreate(
['id' => 0],
['fqdn' => 'https://coolify.example.com']
);
// Regular routes should still validate Host header
$response = $this->get('/', [
'Host' => 'evil.com',
]);
// Should get 400 Bad Host for untrusted host
expect($response->status())->toBe(400);
});
it('skips host validation for API routes', function () {
// All API routes use token-based auth (Sanctum), not host validation
// They should be accessible from any host (mobile apps, CLI tools, scripts)
// Test health check endpoint
$response = $this->get('/api/health', [
'Host' => 'internal-lb.local',
]);
expect($response->status())->not->toBe(400);
// Test v1 health check
$response = $this->get('/api/v1/health', [
'Host' => '10.0.0.5',
]);
expect($response->status())->not->toBe(400);
// Test feedback endpoint
$response = $this->post('/api/feedback', [], [
'Host' => 'mobile-app.local',
]);
expect($response->status())->not->toBe(400);
});
it('skips host validation for webhook endpoints', function () {
// All webhook routes are under /webhooks/* prefix (see RouteServiceProvider)
// and use cryptographic signature validation instead of host validation
// Test GitHub webhook
$response = $this->post('/webhooks/source/github/events', [], [
'Host' => 'github-webhook-proxy.local',
]);
expect($response->status())->not->toBe(400);
// Test GitLab webhook
$response = $this->post('/webhooks/source/gitlab/events/manual', [], [
'Host' => 'gitlab.example.com',
]);
expect($response->status())->not->toBe(400);
// Test Stripe webhook
$response = $this->post('/webhooks/payments/stripe/events', [], [
'Host' => 'stripe-webhook-forwarder.local',
]);
expect($response->status())->not->toBe(400);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/ExecuteContainerCommandTest.php | tests/Feature/ExecuteContainerCommandTest.php | <?php
namespace Tests\Feature;
use App\Models\Application;
use App\Models\Server;
use App\Models\User;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;
use Tests\Traits\HandlesTestDatabase;
class ExecuteContainerCommandTest extends TestCase
{
use HandlesTestDatabase;
private $user;
private $team;
private $server;
private $application;
protected function setUp(): void
{
parent::setUp();
// Only set up database for tests that need it
if ($this->shouldSetUpDatabase()) {
$this->setUpTestDatabase();
}
// Create test data
$this->user = User::factory()->create();
$this->team = $this->user->teams()->first();
$this->server = Server::factory()->create(['team_id' => $this->team->id]);
$this->application = Application::factory()->create();
// Login the user
$this->actingAs($this->user);
}
protected function tearDown(): void
{
if ($this->shouldSetUpDatabase()) {
$this->tearDownTestDatabase();
}
parent::tearDown();
}
private function shouldSetUpDatabase(): bool
{
return in_array($this->name(), [
'it_allows_valid_container_access',
'it_prevents_cross_server_container_access',
]);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/Service/EditDomainPortValidationTest.php | tests/Feature/Service/EditDomainPortValidationTest.php | <?php
use App\Livewire\Project\Service\EditDomain;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\StandaloneDocker;
use App\Models\Team;
use App\Models\User;
use Livewire\Livewire;
beforeEach(function () {
// Create user and team
$this->user = User::factory()->create();
$this->team = Team::factory()->create();
$this->user->teams()->attach($this->team, ['role' => 'owner']);
$this->actingAs($this->user);
// Create server
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
]);
// Create standalone docker destination
$this->destination = StandaloneDocker::factory()->create([
'server_id' => $this->server->id,
]);
// Create project and environment
$this->project = Project::factory()->create([
'team_id' => $this->team->id,
]);
$this->environment = Environment::factory()->create([
'project_id' => $this->project->id,
]);
// Create service with a name that maps to a template with required port
$this->service = Service::factory()->create([
'name' => 'supabase-test123',
'server_id' => $this->server->id,
'destination_id' => $this->destination->id,
'destination_type' => $this->destination->getMorphClass(),
'environment_id' => $this->environment->id,
]);
// Create service application
$this->serviceApplication = ServiceApplication::factory()->create([
'service_id' => $this->service->id,
'fqdn' => 'http://example.com:8000',
]);
// Mock get_service_templates to return a service with required port
if (! function_exists('get_service_templates_mock')) {
function get_service_templates_mock()
{
return collect([
'supabase' => [
'name' => 'Supabase',
'port' => '8000',
'documentation' => 'https://supabase.com',
],
]);
}
}
});
it('loads the EditDomain component with required port', function () {
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->assertSet('requiredPort', 8000)
->assertSet('fqdn', 'http://example.com:8000')
->assertOk();
});
it('shows warning modal when trying to remove required port', function () {
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->set('fqdn', 'http://example.com') // Remove port
->call('submit')
->assertSet('showPortWarningModal', true)
->assertSet('requiredPort', 8000);
});
it('allows port removal when user confirms', function () {
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->set('fqdn', 'http://example.com') // Remove port
->call('submit')
->assertSet('showPortWarningModal', true)
->call('confirmRemovePort')
->assertSet('showPortWarningModal', false);
// Verify the FQDN was updated in database
$this->serviceApplication->refresh();
expect($this->serviceApplication->fqdn)->toBe('http://example.com');
});
it('cancels port removal when user cancels', function () {
$originalFqdn = $this->serviceApplication->fqdn;
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->set('fqdn', 'http://example.com') // Remove port
->call('submit')
->assertSet('showPortWarningModal', true)
->call('cancelRemovePort')
->assertSet('showPortWarningModal', false)
->assertSet('fqdn', $originalFqdn); // Should revert to original
});
it('allows saving when port is changed to different port', function () {
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->set('fqdn', 'http://example.com:3000') // Change to different port
->call('submit')
->assertSet('showPortWarningModal', false); // Should not show warning
// Verify the FQDN was updated
$this->serviceApplication->refresh();
expect($this->serviceApplication->fqdn)->toBe('http://example.com:3000');
});
it('allows saving when all domains have ports (multiple domains)', function () {
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->set('fqdn', 'http://example.com:8000,https://app.example.com:8080')
->call('submit')
->assertSet('showPortWarningModal', false); // Should not show warning
});
it('shows warning when at least one domain is missing port (multiple domains)', function () {
Livewire::test(EditDomain::class, ['applicationId' => $this->serviceApplication->id])
->set('fqdn', 'http://example.com:8000,https://app.example.com') // Second domain missing port
->call('submit')
->assertSet('showPortWarningModal', true);
});
it('does not show warning for services without required port', function () {
// Create a service without required port (e.g., cloudflared)
$serviceWithoutPort = Service::factory()->create([
'name' => 'cloudflared-test456',
'server_id' => $this->server->id,
'destination_id' => $this->destination->id,
'destination_type' => $this->destination->getMorphClass(),
'environment_id' => $this->environment->id,
]);
$appWithoutPort = ServiceApplication::factory()->create([
'service_id' => $serviceWithoutPort->id,
'fqdn' => 'http://example.com',
]);
Livewire::test(EditDomain::class, ['applicationId' => $appWithoutPort->id])
->set('fqdn', 'http://example.com') // No port
->call('submit')
->assertSet('showPortWarningModal', false); // Should not show warning
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Feature/Proxy/RestartProxyTest.php | tests/Feature/Proxy/RestartProxyTest.php | <?php
namespace Tests\Feature\Proxy;
use App\Jobs\RestartProxyJob;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;
use Tests\TestCase;
class RestartProxyTest extends TestCase
{
use RefreshDatabase;
protected User $user;
protected Team $team;
protected Server $server;
protected function setUp(): void
{
parent::setUp();
// Create test user and team
$this->user = User::factory()->create();
$this->team = Team::factory()->create(['name' => 'Test Team']);
$this->user->teams()->attach($this->team);
// Create test server
$this->server = Server::factory()->create([
'team_id' => $this->team->id,
'name' => 'Test Server',
'ip' => '192.168.1.100',
]);
// Authenticate user
$this->actingAs($this->user);
}
public function test_restart_dispatches_job_for_all_servers()
{
Queue::fake();
Livewire::test('server.navbar', ['server' => $this->server])
->call('restart');
// Assert job was dispatched
Queue::assertPushed(RestartProxyJob::class, function ($job) {
return $job->server->id === $this->server->id;
});
}
public function test_restart_dispatches_job_for_localhost_server()
{
Queue::fake();
// Create localhost server (id = 0)
$localhostServer = Server::factory()->create([
'id' => 0,
'team_id' => $this->team->id,
'name' => 'Localhost',
'ip' => 'host.docker.internal',
]);
Livewire::test('server.navbar', ['server' => $localhostServer])
->call('restart');
// Assert job was dispatched
Queue::assertPushed(RestartProxyJob::class, function ($job) use ($localhostServer) {
return $job->server->id === $localhostServer->id;
});
}
public function test_restart_shows_info_message()
{
Queue::fake();
Livewire::test('server.navbar', ['server' => $this->server])
->call('restart')
->assertDispatched('info', 'Proxy restart initiated. Monitor progress in activity logs.');
}
public function test_unauthorized_user_cannot_restart_proxy()
{
Queue::fake();
// Create another user without access
$unauthorizedUser = User::factory()->create();
$this->actingAs($unauthorizedUser);
Livewire::test('server.navbar', ['server' => $this->server])
->call('restart')
->assertForbidden();
// Assert job was NOT dispatched
Queue::assertNotPushed(RestartProxyJob::class);
}
public function test_restart_prevents_concurrent_jobs_via_without_overlapping()
{
Queue::fake();
// Dispatch job twice
Livewire::test('server.navbar', ['server' => $this->server])
->call('restart');
Livewire::test('server.navbar', ['server' => $this->server])
->call('restart');
// Assert job was pushed twice (WithoutOverlapping middleware will handle deduplication)
Queue::assertPushed(RestartProxyJob::class, 2);
// Get the jobs
$jobs = Queue::pushed(RestartProxyJob::class);
// Verify both jobs have WithoutOverlapping middleware
foreach ($jobs as $job) {
$middleware = $job['job']->middleware();
$this->assertCount(1, $middleware);
$this->assertInstanceOf(\Illuminate\Queue\Middleware\WithoutOverlapping::class, $middleware[0]);
}
}
public function test_restart_uses_server_team_id()
{
Queue::fake();
Livewire::test('server.navbar', ['server' => $this->server])
->call('restart');
Queue::assertPushed(RestartProxyJob::class, function ($job) {
return $job->server->team_id === $this->team->id;
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ScheduledJobManagerLockTest.php | tests/Unit/ScheduledJobManagerLockTest.php | <?php
use App\Jobs\ScheduledJobManager;
use Illuminate\Queue\Middleware\WithoutOverlapping;
it('uses WithoutOverlapping middleware with expireAfter to prevent stale locks', function () {
$job = new ScheduledJobManager;
$middleware = $job->middleware();
// Assert middleware exists
expect($middleware)->toBeArray()
->and($middleware)->toHaveCount(1);
$overlappingMiddleware = $middleware[0];
// Assert it's a WithoutOverlapping instance
expect($overlappingMiddleware)->toBeInstanceOf(WithoutOverlapping::class);
// Use reflection to check private properties
$reflection = new ReflectionClass($overlappingMiddleware);
// Check expireAfter is set (should be 60 seconds - matches job frequency)
$expiresAfterProperty = $reflection->getProperty('expiresAfter');
$expiresAfterProperty->setAccessible(true);
$expiresAfter = $expiresAfterProperty->getValue($overlappingMiddleware);
expect($expiresAfter)->toBe(60)
->and($expiresAfter)->toBeGreaterThan(0, 'expireAfter must be set to prevent stale locks');
// Check releaseAfter is NOT set (we use dontRelease)
$releaseAfterProperty = $reflection->getProperty('releaseAfter');
$releaseAfterProperty->setAccessible(true);
$releaseAfter = $releaseAfterProperty->getValue($overlappingMiddleware);
expect($releaseAfter)->toBeNull('releaseAfter should be null when using dontRelease()');
// Check the lock key
$keyProperty = $reflection->getProperty('key');
$keyProperty->setAccessible(true);
$key = $keyProperty->getValue($overlappingMiddleware);
expect($key)->toBe('scheduled-job-manager');
});
it('prevents stale locks by ensuring expireAfter is always set', function () {
$job = new ScheduledJobManager;
$middleware = $job->middleware();
$overlappingMiddleware = $middleware[0];
$reflection = new ReflectionClass($overlappingMiddleware);
$expiresAfterProperty = $reflection->getProperty('expiresAfter');
$expiresAfterProperty->setAccessible(true);
$expiresAfter = $expiresAfterProperty->getValue($overlappingMiddleware);
// Critical check: expireAfter MUST be set to prevent GitHub issue #4539
expect($expiresAfter)->not->toBeNull(
'expireAfter() is required to prevent stale locks (see GitHub #4539)'
);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/S3RestoreTest.php | tests/Unit/S3RestoreTest.php | <?php
test('S3 path is cleaned correctly', function () {
// Test that leading slashes are removed
$path = '/backups/database.gz';
$cleanPath = ltrim($path, '/');
expect($cleanPath)->toBe('backups/database.gz');
// Test path without leading slash remains unchanged
$path2 = 'backups/database.gz';
$cleanPath2 = ltrim($path2, '/');
expect($cleanPath2)->toBe('backups/database.gz');
});
test('S3 container name is generated correctly', function () {
$resourceUuid = 'test-database-uuid';
$containerName = "s3-restore-{$resourceUuid}";
expect($containerName)->toBe('s3-restore-test-database-uuid');
expect($containerName)->toStartWith('s3-restore-');
});
test('S3 download directory is created correctly', function () {
$resourceUuid = 'test-database-uuid';
$downloadDir = "/tmp/s3-restore-{$resourceUuid}";
expect($downloadDir)->toBe('/tmp/s3-restore-test-database-uuid');
expect($downloadDir)->toStartWith('/tmp/s3-restore-');
});
test('cancelS3Download cleans up correctly', function () {
// Test that cleanup directory path is correct
$resourceUuid = 'test-database-uuid';
$downloadDir = "/tmp/s3-restore-{$resourceUuid}";
$containerName = "s3-restore-{$resourceUuid}";
expect($downloadDir)->toContain($resourceUuid);
expect($containerName)->toContain($resourceUuid);
});
test('S3 file path formats are handled correctly', function () {
$paths = [
'/backups/db.gz',
'backups/db.gz',
'/nested/path/to/backup.sql.gz',
'backup-2025-01-15.gz',
];
foreach ($paths as $path) {
$cleanPath = ltrim($path, '/');
expect($cleanPath)->not->toStartWith('/');
}
});
test('formatBytes helper formats file sizes correctly', function () {
// Test various file sizes
expect(formatBytes(0))->toBe('0 B');
expect(formatBytes(null))->toBe('0 B');
expect(formatBytes(1024))->toBe('1 KB');
expect(formatBytes(1048576))->toBe('1 MB');
expect(formatBytes(1073741824))->toBe('1 GB');
expect(formatBytes(1099511627776))->toBe('1 TB');
// Test with different sizes
expect(formatBytes(512))->toBe('512 B');
expect(formatBytes(2048))->toBe('2 KB');
expect(formatBytes(5242880))->toBe('5 MB');
expect(formatBytes(10737418240))->toBe('10 GB');
// Test precision
expect(formatBytes(1536, 2))->toBe('1.5 KB');
expect(formatBytes(1572864, 1))->toBe('1.5 MB');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ScheduledTaskJobTimeoutTest.php | tests/Unit/ScheduledTaskJobTimeoutTest.php | <?php
use App\Jobs\ScheduledTaskJob;
use Illuminate\Support\Facades\Log;
beforeEach(function () {
// Mock Log facade to prevent actual logging during tests
Log::spy();
});
it('has executionId property for timeout handling', function () {
$reflection = new ReflectionClass(ScheduledTaskJob::class);
// Verify executionId property exists
expect($reflection->hasProperty('executionId'))->toBeTrue();
// Verify it's protected (will be serialized with the job)
$property = $reflection->getProperty('executionId');
expect($property->isProtected())->toBeTrue();
});
it('has failed method that handles job failures', function () {
$reflection = new ReflectionClass(ScheduledTaskJob::class);
// Verify failed() method exists
expect($reflection->hasMethod('failed'))->toBeTrue();
// Verify it accepts a Throwable parameter
$method = $reflection->getMethod('failed');
$parameters = $method->getParameters();
expect($parameters)->toHaveCount(1);
expect($parameters[0]->getName())->toBe('exception');
expect($parameters[0]->allowsNull())->toBeTrue();
});
it('failed method implementation reloads execution from database', function () {
// Read the failed() method source code to verify it reloads from database
$reflection = new ReflectionClass(ScheduledTaskJob::class);
$method = $reflection->getMethod('failed');
// Get the file and method source
$filename = $reflection->getFileName();
$startLine = $method->getStartLine();
$endLine = $method->getEndLine();
$source = file($filename);
$methodSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify the implementation includes reloading from database
expect($methodSource)
->toContain('$this->executionId')
->toContain('ScheduledTaskExecution::find')
->toContain('ScheduledTaskExecution::query')
->toContain('scheduled_task_id')
->toContain('orderBy')
->toContain('status')
->toContain('failed')
->toContain('notify');
});
it('failed method updates execution with error_details field', function () {
// Read the failed() method source code to verify error_details is populated
$reflection = new ReflectionClass(ScheduledTaskJob::class);
$method = $reflection->getMethod('failed');
// Get the file and method source
$filename = $reflection->getFileName();
$startLine = $method->getStartLine();
$endLine = $method->getEndLine();
$source = file($filename);
$methodSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify the implementation populates error_details field
expect($methodSource)->toContain('error_details');
});
it('failed method logs when execution cannot be found', function () {
// Read the failed() method source code to verify defensive logging
$reflection = new ReflectionClass(ScheduledTaskJob::class);
$method = $reflection->getMethod('failed');
// Get the file and method source
$filename = $reflection->getFileName();
$startLine = $method->getStartLine();
$endLine = $method->getEndLine();
$source = file($filename);
$methodSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify the implementation logs a warning if execution is not found
expect($methodSource)
->toContain('Could not find execution log')
->toContain('warning');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/RestoreJobFinishedSecurityTest.php | tests/Unit/RestoreJobFinishedSecurityTest.php | <?php
/**
* Security tests for RestoreJobFinished event to ensure it uses secure path validation.
*/
describe('RestoreJobFinished event security', function () {
it('validates that safe paths pass validation', function () {
$validPaths = [
'/tmp/restore-backup.sql',
'/tmp/restore-script.sh',
'/tmp/database-dump-'.uniqid().'.sql',
];
foreach ($validPaths as $path) {
expect(isSafeTmpPath($path))->toBeTrue();
}
});
it('validates that malicious paths fail validation', function () {
$maliciousPaths = [
'/tmp/../etc/passwd',
'/tmp/foo/../../etc/shadow',
'/etc/sensitive-file',
'/var/www/config.php',
'/tmp/../../../root/.ssh/id_rsa',
];
foreach ($maliciousPaths as $path) {
expect(isSafeTmpPath($path))->toBeFalse();
}
});
it('rejects URL-encoded path traversal attempts', function () {
$encodedTraversalPaths = [
'/tmp/%2e%2e/etc/passwd',
'/tmp/foo%2f%2e%2e%2f%2e%2e/etc/shadow',
urlencode('/tmp/../etc/passwd'),
];
foreach ($encodedTraversalPaths as $path) {
expect(isSafeTmpPath($path))->toBeFalse();
}
});
it('handles edge cases correctly', function () {
// Too short
expect(isSafeTmpPath('/tmp'))->toBeFalse();
expect(isSafeTmpPath('/tmp/'))->toBeFalse();
// Null/empty
expect(isSafeTmpPath(null))->toBeFalse();
expect(isSafeTmpPath(''))->toBeFalse();
// Null byte injection
expect(isSafeTmpPath("/tmp/file.sql\0../../etc/passwd"))->toBeFalse();
// Valid edge cases
expect(isSafeTmpPath('/tmp/x'))->toBeTrue();
expect(isSafeTmpPath('/tmp/very/deeply/nested/path/to/file.sql'))->toBeTrue();
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServerQueryScopeTest.php | tests/Unit/ServerQueryScopeTest.php | <?php
use App\Enums\ProxyTypes;
use App\Models\Server;
use Illuminate\Database\Eloquent\Builder;
use Mockery;
it('filters servers by proxy type using whereProxyType scope', function () {
// Mock the Builder
$mockBuilder = Mockery::mock(Builder::class);
// Expect the where method to be called with the correct parameters
$mockBuilder->shouldReceive('where')
->once()
->with('proxy->type', ProxyTypes::TRAEFIK->value)
->andReturnSelf();
// Create a server instance and call the scope
$server = new Server;
$result = $server->scopeWhereProxyType($mockBuilder, ProxyTypes::TRAEFIK->value);
// Assert the builder is returned
expect($result)->toBe($mockBuilder);
});
it('can chain whereProxyType scope with other query methods', function () {
// Mock the Builder
$mockBuilder = Mockery::mock(Builder::class);
// Expect multiple chained calls
$mockBuilder->shouldReceive('where')
->once()
->with('proxy->type', ProxyTypes::CADDY->value)
->andReturnSelf();
// Create a server instance and call the scope
$server = new Server;
$result = $server->scopeWhereProxyType($mockBuilder, ProxyTypes::CADDY->value);
// Assert the builder is returned for chaining
expect($result)->toBe($mockBuilder);
});
it('accepts any proxy type string value', function () {
// Mock the Builder
$mockBuilder = Mockery::mock(Builder::class);
// Test with a custom proxy type
$customProxyType = 'custom-proxy';
$mockBuilder->shouldReceive('where')
->once()
->with('proxy->type', $customProxyType)
->andReturnSelf();
// Create a server instance and call the scope
$server = new Server;
$result = $server->scopeWhereProxyType($mockBuilder, $customProxyType);
// Assert the builder is returned
expect($result)->toBe($mockBuilder);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationConfigurationChangeTest.php | tests/Unit/ApplicationConfigurationChangeTest.php | <?php
/**
* Unit test to verify that custom_network_aliases is included in configuration change detection.
* Tests the behavior of the isConfigurationChanged method by verifying that different
* custom_network_aliases values produce different configuration hashes.
*/
it('different custom_network_aliases values produce different hashes', function () {
// Test that the hash calculation includes custom_network_aliases by computing hashes with different values
$hash1 = md5(base64_encode('test'.'api.internal,api.local'));
$hash2 = md5(base64_encode('test'.'api.internal,api.local,api.staging'));
$hash3 = md5(base64_encode('test'.null));
expect($hash1)->not->toBe($hash2)
->and($hash1)->not->toBe($hash3)
->and($hash2)->not->toBe($hash3);
});
/**
* Unit test to verify that inject_build_args_to_dockerfile is included in configuration change detection.
* Tests the behavior of the isConfigurationChanged method by verifying that different
* inject_build_args_to_dockerfile values produce different configuration hashes.
*/
it('different inject_build_args_to_dockerfile values produce different hashes', function () {
// Test that the hash calculation includes inject_build_args_to_dockerfile by computing hashes with different values
// true becomes '1', false becomes '', so they produce different hashes
$hash1 = md5(base64_encode('test'.true)); // 'test1'
$hash2 = md5(base64_encode('test'.false)); // 'test'
$hash3 = md5(base64_encode('test')); // 'test'
expect($hash1)->not->toBe($hash2)
->and($hash2)->toBe($hash3); // false and empty string produce the same result
});
/**
* Unit test to verify that include_source_commit_in_build is included in configuration change detection.
* Tests the behavior of the isConfigurationChanged method by verifying that different
* include_source_commit_in_build values produce different configuration hashes.
*/
it('different include_source_commit_in_build values produce different hashes', function () {
// Test that the hash calculation includes include_source_commit_in_build by computing hashes with different values
// true becomes '1', false becomes '', so they produce different hashes
$hash1 = md5(base64_encode('test'.true)); // 'test1'
$hash2 = md5(base64_encode('test'.false)); // 'test'
$hash3 = md5(base64_encode('test')); // 'test'
expect($hash1)->not->toBe($hash2)
->and($hash2)->toBe($hash3); // false and empty string produce the same result
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/PathTraversalSecurityTest.php | tests/Unit/PathTraversalSecurityTest.php | <?php
/**
* Security tests for isSafeTmpPath() function to prevent path traversal attacks.
*/
describe('isSafeTmpPath() security validation', function () {
it('rejects null and empty paths', function () {
expect(isSafeTmpPath(null))->toBeFalse();
expect(isSafeTmpPath(''))->toBeFalse();
expect(isSafeTmpPath(' '))->toBeFalse();
});
it('rejects paths shorter than minimum length', function () {
expect(isSafeTmpPath('/tmp'))->toBeFalse();
expect(isSafeTmpPath('/tmp/'))->toBeFalse();
expect(isSafeTmpPath('/tmp/a'))->toBeTrue(); // 6 chars exactly, should pass
});
it('accepts valid /tmp/ paths', function () {
expect(isSafeTmpPath('/tmp/file.txt'))->toBeTrue();
expect(isSafeTmpPath('/tmp/backup.sql'))->toBeTrue();
expect(isSafeTmpPath('/tmp/subdir/file.txt'))->toBeTrue();
expect(isSafeTmpPath('/tmp/very/deep/nested/path/file.sql'))->toBeTrue();
});
it('rejects obvious path traversal attempts with ..', function () {
expect(isSafeTmpPath('/tmp/../etc/passwd'))->toBeFalse();
expect(isSafeTmpPath('/tmp/foo/../etc/passwd'))->toBeFalse();
expect(isSafeTmpPath('/tmp/foo/bar/../../etc/passwd'))->toBeFalse();
expect(isSafeTmpPath('/tmp/foo/../../../etc/passwd'))->toBeFalse();
});
it('rejects paths that do not start with /tmp/', function () {
expect(isSafeTmpPath('/etc/passwd'))->toBeFalse();
expect(isSafeTmpPath('/home/user/file.txt'))->toBeFalse();
expect(isSafeTmpPath('/var/log/app.log'))->toBeFalse();
expect(isSafeTmpPath('tmp/file.txt'))->toBeFalse(); // Missing leading /
expect(isSafeTmpPath('./tmp/file.txt'))->toBeFalse();
});
it('handles double slashes by normalizing them', function () {
// Double slashes are normalized out, so these should pass
expect(isSafeTmpPath('/tmp//file.txt'))->toBeTrue();
expect(isSafeTmpPath('/tmp/foo//bar.txt'))->toBeTrue();
});
it('handles relative directory references by normalizing them', function () {
// ./ references are normalized out, so these should pass
expect(isSafeTmpPath('/tmp/./file.txt'))->toBeTrue();
expect(isSafeTmpPath('/tmp/foo/./bar.txt'))->toBeTrue();
});
it('handles trailing slashes correctly', function () {
expect(isSafeTmpPath('/tmp/file.txt/'))->toBeTrue();
expect(isSafeTmpPath('/tmp/subdir/'))->toBeTrue();
});
it('rejects sophisticated path traversal attempts', function () {
// URL encoded .. will be decoded and then rejected
expect(isSafeTmpPath('/tmp/%2e%2e/etc/passwd'))->toBeFalse();
// Mixed case /TMP doesn't start with /tmp/
expect(isSafeTmpPath('/TMP/file.txt'))->toBeFalse();
expect(isSafeTmpPath('/TMP/../etc/passwd'))->toBeFalse();
// URL encoded slashes with .. (should decode to /tmp/../../etc/passwd)
expect(isSafeTmpPath('/tmp/..%2f..%2fetc/passwd'))->toBeFalse();
// Null byte injection attempt (if string contains it)
expect(isSafeTmpPath("/tmp/file.txt\0../../etc/passwd"))->toBeFalse();
});
it('validates paths even when directories do not exist', function () {
// These paths don't exist but should be validated structurally
expect(isSafeTmpPath('/tmp/nonexistent/file.txt'))->toBeTrue();
expect(isSafeTmpPath('/tmp/totally/fake/deeply/nested/path.sql'))->toBeTrue();
// But traversal should still be blocked even if dir doesn't exist
expect(isSafeTmpPath('/tmp/nonexistent/../etc/passwd'))->toBeFalse();
});
it('handles real path resolution when directory exists', function () {
// Create a real temp directory to test realpath() logic
$testDir = '/tmp/phpunit-test-'.uniqid();
mkdir($testDir, 0755, true);
try {
expect(isSafeTmpPath($testDir.'/file.txt'))->toBeTrue();
expect(isSafeTmpPath($testDir.'/subdir/file.txt'))->toBeTrue();
} finally {
rmdir($testDir);
}
});
it('prevents symlink-based traversal attacks', function () {
// Create a temp directory and symlink
$testDir = '/tmp/phpunit-symlink-test-'.uniqid();
mkdir($testDir, 0755, true);
// Try to create a symlink to /etc (may not work in all environments)
$symlinkPath = $testDir.'/evil-link';
try {
// Attempt to create symlink (skip test if not possible)
if (@symlink('/etc', $symlinkPath)) {
// If we successfully created a symlink to /etc,
// isSafeTmpPath should resolve it and reject paths through it
$testPath = $symlinkPath.'/passwd';
// The resolved path would be /etc/passwd, not /tmp/...
// So it should be rejected
$result = isSafeTmpPath($testPath);
// Clean up before assertion
unlink($symlinkPath);
rmdir($testDir);
expect($result)->toBeFalse();
} else {
// Can't create symlink, skip this specific test
$this->markTestSkipped('Cannot create symlinks in this environment');
}
} catch (Exception $e) {
// Clean up on any error
if (file_exists($symlinkPath)) {
unlink($symlinkPath);
}
if (file_exists($testDir)) {
rmdir($testDir);
}
throw $e;
}
});
it('has consistent behavior with or without trailing slash', function () {
expect(isSafeTmpPath('/tmp/file.txt'))->toBe(isSafeTmpPath('/tmp/file.txt/'));
expect(isSafeTmpPath('/tmp/subdir/file.sql'))->toBe(isSafeTmpPath('/tmp/subdir/file.sql/'));
});
});
/**
* Integration test for S3RestoreJobFinished event using the secure path validation.
*/
describe('S3RestoreJobFinished path validation', function () {
it('validates that safe paths pass validation', function () {
// Test with valid paths - should pass validation
$validData = [
'serverTmpPath' => '/tmp/valid-backup.sql',
'scriptPath' => '/tmp/valid-script.sh',
'containerTmpPath' => '/tmp/container-file.sql',
];
expect(isSafeTmpPath($validData['serverTmpPath']))->toBeTrue();
expect(isSafeTmpPath($validData['scriptPath']))->toBeTrue();
expect(isSafeTmpPath($validData['containerTmpPath']))->toBeTrue();
});
it('validates that malicious paths fail validation', function () {
// Test with malicious paths - should fail validation
$maliciousData = [
'serverTmpPath' => '/tmp/../etc/passwd',
'scriptPath' => '/tmp/../../etc/shadow',
'containerTmpPath' => '/etc/important-config',
];
// Verify that our helper would reject these paths
expect(isSafeTmpPath($maliciousData['serverTmpPath']))->toBeFalse();
expect(isSafeTmpPath($maliciousData['scriptPath']))->toBeFalse();
expect(isSafeTmpPath($maliciousData['containerTmpPath']))->toBeFalse();
});
it('validates realistic S3 restore paths', function () {
// These are the kinds of paths that would actually be used
$realisticPaths = [
'/tmp/coolify-s3-restore-'.uniqid().'.sql',
'/tmp/db-backup-'.date('Y-m-d').'.dump',
'/tmp/restore-script-'.uniqid().'.sh',
];
foreach ($realisticPaths as $path) {
expect(isSafeTmpPath($path))->toBeTrue();
}
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationDeploymentNixpacksNullEnvTest.php | tests/Unit/ApplicationDeploymentNixpacksNullEnvTest.php | <?php
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\EnvironmentVariable;
/**
* Test to verify that null and empty environment variables are filtered out
* when generating Nixpacks configuration.
*
* This test verifies the fix for the issue where null or empty environment variable
* values would be passed to Nixpacks as `--env KEY=` (with no value), causing
* JSON parsing errors: "invalid type: null, expected a string at line 12 column 27"
*
* The fix ensures that:
* 1. User-defined environment variables with null or empty values are filtered out
* 2. COOLIFY_* environment variables with null or empty values are filtered out
* 3. Only environment variables with valid non-empty values are passed to Nixpacks
*/
it('filters out null environment variables from nixpacks build command', function () {
// Mock application with nixpacks build pack
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('nixpacks');
$mockApplication->build_pack = 'nixpacks';
// Mock environment variables - some with null/empty values
$envVar1 = Mockery::mock(EnvironmentVariable::class);
$envVar1->key = 'VALID_VAR';
$envVar1->real_value = 'valid_value';
$envVar2 = Mockery::mock(EnvironmentVariable::class);
$envVar2->key = 'NULL_VAR';
$envVar2->real_value = null;
$envVar3 = Mockery::mock(EnvironmentVariable::class);
$envVar3->key = 'EMPTY_VAR';
$envVar3->real_value = '';
$envVar4 = Mockery::mock(EnvironmentVariable::class);
$envVar4->key = 'ANOTHER_VALID_VAR';
$envVar4->real_value = 'another_value';
$nixpacksEnvVars = collect([$envVar1, $envVar2, $envVar3, $envVar4]);
$mockApplication->shouldReceive('getAttribute')
->with('nixpacks_environment_variables')
->andReturn($nixpacksEnvVars);
// Mock application deployment queue
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$mockQueue->shouldReceive('getAttribute')->with('application_id')->andReturn(1);
$mockQueue->application_id = 1;
// Mock the job
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
// Set private properties
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
// Mock generate_coolify_env_variables to return some values including null
$job->shouldReceive('generate_coolify_env_variables')
->andReturn(collect([
'COOLIFY_FQDN' => 'example.com',
'COOLIFY_URL' => null, // null value that should be filtered
'COOLIFY_BRANCH' => '', // empty value that should be filtered
'SOURCE_COMMIT' => 'abc123',
]));
// Call the private method
$method = $reflection->getMethod('generate_nixpacks_env_variables');
$method->setAccessible(true);
$method->invoke($job);
// Get the generated env_nixpacks_args
$envArgsProperty = $reflection->getProperty('env_nixpacks_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
// Verify that only valid environment variables are included
expect($envArgs)->toContain('--env VALID_VAR=valid_value');
expect($envArgs)->toContain('--env ANOTHER_VALID_VAR=another_value');
expect($envArgs)->toContain('--env COOLIFY_FQDN=example.com');
expect($envArgs)->toContain('--env SOURCE_COMMIT=abc123');
// Verify that null and empty environment variables are filtered out
expect($envArgs)->not->toContain('NULL_VAR');
expect($envArgs)->not->toContain('EMPTY_VAR');
expect($envArgs)->not->toContain('COOLIFY_URL');
expect($envArgs)->not->toContain('COOLIFY_BRANCH');
// Verify no environment variables end with just '=' (which indicates null/empty value)
expect($envArgs)->not->toMatch('/--env [A-Z_]+=$/');
expect($envArgs)->not->toMatch('/--env [A-Z_]+= /');
});
it('filters out null environment variables from nixpacks preview deployments', function () {
// Mock application with nixpacks build pack
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('nixpacks');
$mockApplication->build_pack = 'nixpacks';
// Mock preview environment variables - some with null/empty values
$envVar1 = Mockery::mock(EnvironmentVariable::class);
$envVar1->key = 'PREVIEW_VAR';
$envVar1->real_value = 'preview_value';
$envVar2 = Mockery::mock(EnvironmentVariable::class);
$envVar2->key = 'NULL_PREVIEW_VAR';
$envVar2->real_value = null;
$previewEnvVars = collect([$envVar1, $envVar2]);
$mockApplication->shouldReceive('getAttribute')
->with('nixpacks_environment_variables_preview')
->andReturn($previewEnvVars);
// Mock application deployment queue
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$mockQueue->shouldReceive('getAttribute')->with('application_id')->andReturn(1);
$mockQueue->application_id = 1;
// Mock the job
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
// Set private properties
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 123); // Non-zero for preview deployment
// Mock generate_coolify_env_variables
$job->shouldReceive('generate_coolify_env_variables')
->andReturn(collect([
'COOLIFY_FQDN' => 'preview.example.com',
]));
// Call the private method
$method = $reflection->getMethod('generate_nixpacks_env_variables');
$method->setAccessible(true);
$method->invoke($job);
// Get the generated env_nixpacks_args
$envArgsProperty = $reflection->getProperty('env_nixpacks_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
// Verify that only valid environment variables are included
expect($envArgs)->toContain('--env PREVIEW_VAR=preview_value');
expect($envArgs)->toContain('--env COOLIFY_FQDN=preview.example.com');
// Verify that null environment variables are filtered out
expect($envArgs)->not->toContain('NULL_PREVIEW_VAR');
});
it('handles all environment variables being null or empty', function () {
// Mock application with nixpacks build pack
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('nixpacks');
$mockApplication->build_pack = 'nixpacks';
// Mock environment variables - all null or empty
$envVar1 = Mockery::mock(EnvironmentVariable::class);
$envVar1->key = 'NULL_VAR';
$envVar1->real_value = null;
$envVar2 = Mockery::mock(EnvironmentVariable::class);
$envVar2->key = 'EMPTY_VAR';
$envVar2->real_value = '';
$nixpacksEnvVars = collect([$envVar1, $envVar2]);
$mockApplication->shouldReceive('getAttribute')
->with('nixpacks_environment_variables')
->andReturn($nixpacksEnvVars);
// Mock application deployment queue
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$mockQueue->shouldReceive('getAttribute')->with('application_id')->andReturn(1);
$mockQueue->application_id = 1;
// Mock the job
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
// Set private properties
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
// Mock generate_coolify_env_variables to return all null/empty values
$job->shouldReceive('generate_coolify_env_variables')
->andReturn(collect([
'COOLIFY_URL' => null,
'COOLIFY_BRANCH' => '',
]));
// Call the private method
$method = $reflection->getMethod('generate_nixpacks_env_variables');
$method->setAccessible(true);
$method->invoke($job);
// Get the generated env_nixpacks_args
$envArgsProperty = $reflection->getProperty('env_nixpacks_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
// Verify that the result is empty or contains no environment variables
expect($envArgs)->toBe('');
});
it('preserves environment variables with zero values', function () {
// Mock application with nixpacks build pack
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('nixpacks');
$mockApplication->build_pack = 'nixpacks';
// Mock environment variables with zero values (which should NOT be filtered)
$envVar1 = Mockery::mock(EnvironmentVariable::class);
$envVar1->key = 'ZERO_VALUE';
$envVar1->real_value = '0';
$envVar2 = Mockery::mock(EnvironmentVariable::class);
$envVar2->key = 'FALSE_VALUE';
$envVar2->real_value = 'false';
$nixpacksEnvVars = collect([$envVar1, $envVar2]);
$mockApplication->shouldReceive('getAttribute')
->with('nixpacks_environment_variables')
->andReturn($nixpacksEnvVars);
// Mock application deployment queue
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$mockQueue->shouldReceive('getAttribute')->with('application_id')->andReturn(1);
$mockQueue->application_id = 1;
// Mock the job
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
// Set private properties
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
// Mock generate_coolify_env_variables
$job->shouldReceive('generate_coolify_env_variables')
->andReturn(collect([]));
// Call the private method
$method = $reflection->getMethod('generate_nixpacks_env_variables');
$method->setAccessible(true);
$method->invoke($job);
// Get the generated env_nixpacks_args
$envArgsProperty = $reflection->getProperty('env_nixpacks_args');
$envArgsProperty->setAccessible(true);
$envArgs = $envArgsProperty->getValue($job);
// Verify that zero and false string values are preserved
expect($envArgs)->toContain('--env ZERO_VALUE=0');
expect($envArgs)->toContain('--env FALSE_VALUE=false');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ClickhouseOfficialImageMigrationTest.php | tests/Unit/ClickhouseOfficialImageMigrationTest.php | <?php
use App\Models\StandaloneClickhouse;
test('clickhouse uses clickhouse_db field in internal connection string', function () {
$clickhouse = new StandaloneClickhouse();
$clickhouse->clickhouse_admin_user = 'testuser';
$clickhouse->clickhouse_admin_password = 'testpass';
$clickhouse->clickhouse_db = 'mydb';
$clickhouse->uuid = 'test-uuid';
$internalUrl = $clickhouse->internal_db_url;
expect($internalUrl)
->toContain('mydb')
->toContain('testuser')
->toContain('test-uuid');
});
test('clickhouse defaults to default database when clickhouse_db is null', function () {
$clickhouse = new StandaloneClickhouse();
$clickhouse->clickhouse_admin_user = 'testuser';
$clickhouse->clickhouse_admin_password = 'testpass';
$clickhouse->clickhouse_db = null;
$clickhouse->uuid = 'test-uuid';
$internalUrl = $clickhouse->internal_db_url;
expect($internalUrl)->toContain('/default');
});
test('clickhouse external url uses correct database', function () {
$clickhouse = new StandaloneClickhouse();
$clickhouse->clickhouse_admin_user = 'admin';
$clickhouse->clickhouse_admin_password = 'secret';
$clickhouse->clickhouse_db = 'production';
$clickhouse->uuid = 'prod-uuid';
$clickhouse->is_public = true;
$clickhouse->public_port = 8123;
$clickhouse->destination = new class {
public $server;
public function __construct() {
$this->server = new class {
public function __get($name) {
if ($name === 'getIp') return '1.2.3.4';
}
};
}
};
$externalUrl = $clickhouse->external_db_url;
expect($externalUrl)->toContain('production');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationWatchPathsTest.php | tests/Unit/ApplicationWatchPathsTest.php | <?php
use App\Models\Application;
/**
* This matches the CURRENT (broken) behavior without negation support
* which is what the old Application.php had
*/
function matchWatchPathsCurrentBehavior(array $changed_files, ?array $watch_paths): array
{
if (is_null($watch_paths) || empty($watch_paths)) {
return [];
}
$matches = [];
foreach ($changed_files as $file) {
foreach ($watch_paths as $pattern) {
$pattern = trim($pattern);
if (empty($pattern)) {
continue;
}
// Old implementation just uses fnmatch directly
// This means !patterns are treated as literal strings
if (fnmatch($pattern, $file)) {
$matches[] = $file;
break;
}
}
}
return $matches;
}
/**
* Use the shared implementation from Application model
*/
function matchWatchPaths(array $changed_files, ?array $watch_paths): array
{
$modifiedFiles = collect($changed_files);
$watchPaths = is_null($watch_paths) ? null : collect($watch_paths);
$result = Application::matchPaths($modifiedFiles, $watchPaths);
return $result->toArray();
}
it('returns false when watch paths is null', function () {
$changed_files = ['docker-compose.yml', 'README.md'];
$watch_paths = null;
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->toBeEmpty();
});
it('triggers with exact match', function () {
$watch_paths = ['docker-compose.yml', 'Dockerfile'];
// Exact match should return matches
$matches = matchWatchPaths(['docker-compose.yml'], $watch_paths);
expect($matches)->toHaveCount(1);
expect($matches)->toEqual(['docker-compose.yml']);
$matches = matchWatchPaths(['Dockerfile'], $watch_paths);
expect($matches)->toHaveCount(1);
expect($matches)->toEqual(['Dockerfile']);
// Non-matching file should return empty
$matches = matchWatchPaths(['README.md'], $watch_paths);
expect($matches)->toBeEmpty();
});
it('triggers with wildcard patterns', function () {
$watch_paths = ['*.yml', 'src/**/*.php', 'config/*'];
// Wildcard matches
expect(matchWatchPaths(['docker-compose.yml'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['production.yml'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['src/Controllers/UserController.php'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['src/Models/User.php'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['config/app.php'], $watch_paths))->not->toBeEmpty();
// Non-matching files
expect(matchWatchPaths(['README.md'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['src/index.js'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['configurations/deep/file.php'], $watch_paths))->toBeEmpty();
});
it('triggers with multiple files', function () {
$watch_paths = ['docker-compose.yml', '*.env'];
// At least one file matches
$changed_files = ['README.md', 'docker-compose.yml', 'package.json'];
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->not->toBeEmpty();
expect($matches)->toContain('docker-compose.yml');
// No files match
$changed_files = ['README.md', 'package.json', 'src/index.js'];
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->toBeEmpty();
});
it('handles leading slash include and negation', function () {
// Include with leading slash - leading slash patterns may not match as expected with fnmatch
// The current implementation doesn't handle leading slashes specially
expect(matchWatchPaths(['docs/index.md'], ['/docs/**']))->toEqual([]);
// With only negation patterns, files that DON'T match the exclusion are included
// docs/index.md DOES match docs/**, so it should be excluded
expect(matchWatchPaths(['docs/index.md'], ['!/docs/**']))->toEqual(['docs/index.md']);
// src/app.ts does NOT match docs/**, so it should be included
expect(matchWatchPaths(['src/app.ts'], ['!/docs/**']))->toEqual(['src/app.ts']);
});
it('triggers with complex patterns', function () {
// fnmatch doesn't support {a,b} syntax, so we need to use separate patterns
$watch_paths = ['**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx'];
// JavaScript/TypeScript files should match
expect(matchWatchPaths(['src/index.js'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['components/Button.jsx'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['types/user.ts'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['pages/Home.tsx'], $watch_paths))->not->toBeEmpty();
// Deeply nested files should match
expect(matchWatchPaths(['src/components/ui/Button.tsx'], $watch_paths))->not->toBeEmpty();
// Non-matching files
expect(matchWatchPaths(['README.md'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['package.json'], $watch_paths))->toBeEmpty();
});
it('triggers with question mark pattern', function () {
$watch_paths = ['test?.txt', 'file-?.yml'];
// Single character wildcard matches
expect(matchWatchPaths(['test1.txt'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['testA.txt'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['file-1.yml'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['file-B.yml'], $watch_paths))->not->toBeEmpty();
// Non-matching files
expect(matchWatchPaths(['test.txt'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['test12.txt'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['file.yml'], $watch_paths))->toBeEmpty();
});
it('triggers with character set pattern', function () {
$watch_paths = ['[abc]test.txt', 'file[0-9].yml'];
// Character set matches
expect(matchWatchPaths(['atest.txt'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['btest.txt'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['ctest.txt'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['file1.yml'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['file9.yml'], $watch_paths))->not->toBeEmpty();
// Non-matching files
expect(matchWatchPaths(['dtest.txt'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['test.txt'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['fileA.yml'], $watch_paths))->toBeEmpty();
});
it('triggers with empty watch paths', function () {
$watch_paths = [];
$matches = matchWatchPaths(['any-file.txt'], $watch_paths);
expect($matches)->toBeEmpty();
});
it('triggers with whitespace only patterns', function () {
$watch_paths = ['', ' ', ' '];
$matches = matchWatchPaths(['any-file.txt'], $watch_paths);
expect($matches)->toBeEmpty();
});
it('triggers for docker compose typical patterns', function () {
$watch_paths = ['docker-compose*.yml', '.env*', 'Dockerfile*', 'services/**'];
// Docker Compose related files
expect(matchWatchPaths(['docker-compose.yml'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['docker-compose.prod.yml'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['docker-compose-dev.yml'], $watch_paths))->not->toBeEmpty();
// Environment files
expect(matchWatchPaths(['.env'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['.env.local'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['.env.production'], $watch_paths))->not->toBeEmpty();
// Dockerfile variations
expect(matchWatchPaths(['Dockerfile'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['Dockerfile.prod'], $watch_paths))->not->toBeEmpty();
// Service files
expect(matchWatchPaths(['services/api/app.js'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['services/web/index.html'], $watch_paths))->not->toBeEmpty();
// Non-matching files (e.g., documentation, configs outside services)
expect(matchWatchPaths(['README.md'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['package.json'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['config/nginx.conf'], $watch_paths))->toBeEmpty();
});
it('handles negation pattern with non matching file', function () {
// Test case: file that does NOT match the exclusion pattern should trigger
$changed_files = ['docker-compose/index.ts'];
$watch_paths = ['!docker-compose-test/**'];
// Since the file docker-compose/index.ts does NOT match the exclusion pattern docker-compose-test/**
// it should trigger the deployment (file is included by default when only exclusion patterns exist)
// This means: "deploy everything EXCEPT files in docker-compose-test/**"
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->not->toBeEmpty();
expect($matches)->toEqual(['docker-compose/index.ts']);
// Test the opposite: file that DOES match the exclusion pattern should NOT trigger
$changed_files = ['docker-compose-test/index.ts'];
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->toBeEmpty();
// Test with deeper path
$changed_files = ['docker-compose-test/sub/dir/file.ts'];
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->toBeEmpty();
});
it('handles mixed inclusion and exclusion patterns', function () {
// Include all JS files but exclude test directories
$watch_paths = ['**/*.js', '!**/*test*/**'];
// Should match: JS files not in test directories
expect(matchWatchPaths(['src/index.js'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['components/Button.js'], $watch_paths))->not->toBeEmpty();
// Should NOT match: JS files in test directories
expect(matchWatchPaths(['test/unit/app.js'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['src/test-utils/helper.js'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['docker-compose-test/index.js'], $watch_paths))->toBeEmpty();
// Should NOT match: non-JS files
expect(matchWatchPaths(['README.md'], $watch_paths))->toBeEmpty();
});
it('handles multiple negation patterns', function () {
// Exclude multiple directories
$watch_paths = ['!tests/**', '!docs/**', '!*.md'];
// Should match: files not in excluded patterns
expect(matchWatchPaths(['src/index.js'], $watch_paths))->not->toBeEmpty();
expect(matchWatchPaths(['docker-compose.yml'], $watch_paths))->not->toBeEmpty();
// Should NOT match: files in excluded patterns
expect(matchWatchPaths(['tests/unit/test.js'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['docs/api.html'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['README.md'], $watch_paths))->toBeEmpty();
expect(matchWatchPaths(['CHANGELOG.md'], $watch_paths))->toBeEmpty();
});
it('demonstrates current broken behavior with negation patterns', function () {
// This test demonstrates the CURRENT broken behavior
// where negation patterns are treated as literal strings
$changed_files = ['docker-compose/index.ts'];
$watch_paths = ['!docker-compose-test/**'];
// With the current broken implementation, this returns empty
// because it tries to match files starting with literal "!"
$matches = matchWatchPathsCurrentBehavior($changed_files, $watch_paths);
expect($matches)->toBeEmpty(); // This is why your webhook doesn't trigger!
// Even if the file had ! in the path, fnmatch would treat ! as a literal character
// not as a negation operator, so it still wouldn't match the pattern correctly
$changed_files = ['test/file.ts'];
$matches = matchWatchPathsCurrentBehavior($changed_files, $watch_paths);
expect($matches)->toBeEmpty();
});
it('handles order based matching with conflicting patterns', function () {
// Test case 1: Exclude then include - last pattern (include) should win
$changed_files = ['docker-compose/index.ts'];
$watch_paths = ['!docker-compose/**', 'docker-compose/**'];
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->not->toBeEmpty();
expect($matches)->toEqual(['docker-compose/index.ts']);
// Test case 2: Include then exclude - last pattern (exclude) should win
$watch_paths = ['docker-compose/**', '!docker-compose/**'];
$matches = matchWatchPaths($changed_files, $watch_paths);
expect($matches)->toBeEmpty();
});
it('handles order based matching with multiple overlapping patterns', function () {
$changed_files = ['src/test/unit.js', 'src/components/Button.js', 'test/integration.js'];
// Include all JS, then exclude test dirs, then re-include specific test file
$watch_paths = [
'**/*.js', // Include all JS files
'!**/test/**', // Exclude all test directories
'src/test/unit.js', // Re-include this specific test file
];
$matches = matchWatchPaths($changed_files, $watch_paths);
// src/test/unit.js should be included (last specific pattern wins)
// src/components/Button.js should be included (only matches first pattern)
// test/integration.js should be excluded (matches exclude pattern, no override)
expect($matches)->toHaveCount(2);
expect($matches)->toContain('src/test/unit.js');
expect($matches)->toContain('src/components/Button.js');
expect($matches)->not->toContain('test/integration.js');
});
it('handles order based matching with specific overrides', function () {
$changed_files = [
'docs/api.md',
'docs/guide.md',
'docs/internal/secret.md',
'src/index.js',
];
// Exclude all docs, then include specific docs subdirectory
$watch_paths = [
'!docs/**', // Exclude all docs
'docs/internal/**', // But include internal docs
'src/**', // Include src files
];
$matches = matchWatchPaths($changed_files, $watch_paths);
// Only docs/internal/secret.md and src/index.js should be included
expect($matches)->toHaveCount(2);
expect($matches)->toContain('docs/internal/secret.md');
expect($matches)->toContain('src/index.js');
expect($matches)->not->toContain('docs/api.md');
expect($matches)->not->toContain('docs/guide.md');
});
it('preserves order precedence in pattern matching', function () {
$changed_files = ['app/config.json'];
// Multiple conflicting patterns - last match should win
$watch_paths = [
'**/*.json', // Include (matches)
'!app/**', // Exclude (matches)
'app/*.json', // Include (matches) - THIS SHOULD WIN
];
$matches = matchWatchPaths($changed_files, $watch_paths);
// File should be included because last matching pattern is inclusive
expect($matches)->not->toBeEmpty();
expect($matches)->toEqual(['app/config.json']);
// Now reverse the last two patterns
$watch_paths = [
'**/*.json', // Include (matches)
'app/*.json', // Include (matches)
'!app/**', // Exclude (matches) - THIS SHOULD WIN
];
$matches = matchWatchPaths($changed_files, $watch_paths);
// File should be excluded because last matching pattern is exclusive
expect($matches)->toBeEmpty();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/PreviewDeploymentPortTest.php | tests/Unit/PreviewDeploymentPortTest.php | <?php
/**
* Unit tests for preview deployment port handling.
*
* Tests verify that preview FQDNs correctly preserve the port from the original
* domain URL, which is required for Caddy proxy labels to work correctly.
*
* @see https://github.com/coollabsio/coolify/issues/2184
*/
use Spatie\Url\Url;
it('extracts port from domain URL with custom port', function () {
$domain = 'https://example.com:3000';
$url = Url::fromString($domain);
$port = $url->getPort();
expect($port)->toBe(3000);
});
it('returns null port for domain URL without port', function () {
$domain = 'https://example.com';
$url = Url::fromString($domain);
$port = $url->getPort();
expect($port)->toBeNull();
});
it('extracts port from HTTP URL with custom port', function () {
$domain = 'http://example.com:8080';
$url = Url::fromString($domain);
$port = $url->getPort();
expect($port)->toBe(8080);
});
it('generates preview FQDN with port preserved', function () {
$domain = 'https://example.com:3000';
$url = Url::fromString($domain);
$template = '{{pr_id}}.{{domain}}';
$pullRequestId = 42;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$preview_fqdn = str_replace('{{random}}', 'abc123', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}";
expect($preview_fqdn)->toBe('https://42.example.com:3000');
});
it('generates preview FQDN without port when original has no port', function () {
$domain = 'https://example.com';
$url = Url::fromString($domain);
$template = '{{pr_id}}.{{domain}}';
$pullRequestId = 42;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$preview_fqdn = str_replace('{{random}}', 'abc123', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}";
expect($preview_fqdn)->toBe('https://42.example.com');
});
it('handles multiple domains with different ports', function () {
$domains = [
'https://app.example.com:3000',
'https://api.example.com:8080',
'https://web.example.com',
];
$preview_fqdns = [];
$template = 'pr-{{pr_id}}.{{domain}}';
$pullRequestId = 123;
foreach ($domains as $domain) {
$url = Url::fromString($domain);
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$preview_fqdn = str_replace('{{random}}', 'xyz', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}";
$preview_fqdns[] = $preview_fqdn;
}
expect($preview_fqdns[0])->toBe('https://pr-123.app.example.com:3000');
expect($preview_fqdns[1])->toBe('https://pr-123.api.example.com:8080');
expect($preview_fqdns[2])->toBe('https://pr-123.web.example.com');
});
it('extracts all URL components correctly', function () {
$domain = 'https://app.example.com:3000/api/v1';
$url = Url::fromString($domain);
expect($url->getScheme())->toBe('https');
expect($url->getHost())->toBe('app.example.com');
expect($url->getPort())->toBe(3000);
expect($url->getPath())->toBe('/api/v1');
});
it('formats port string correctly for URL construction', function () {
// Test port formatting logic
$testCases = [
['port' => 3000, 'expected' => ':3000'],
['port' => 8080, 'expected' => ':8080'],
['port' => 80, 'expected' => ':80'],
['port' => 443, 'expected' => ':443'],
['port' => null, 'expected' => ''],
];
foreach ($testCases as $case) {
$portInt = $case['port'];
$port = $portInt !== null ? ':'.$portInt : '';
expect($port)->toBe($case['expected']);
}
});
// Tests for path preservation in preview URLs
// @see https://github.com/coollabsio/coolify/issues/2184#issuecomment-3638971221
it('generates preview FQDN with port and path preserved', function () {
$domain = 'https://api.example.com:3000/api/v1';
$url = Url::fromString($domain);
$template = '{{pr_id}}.{{domain}}';
$pullRequestId = 42;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$preview_fqdn = str_replace('{{random}}', 'abc123', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
expect($preview_fqdn)->toBe('https://42.api.example.com:3000/api/v1');
});
it('generates preview FQDN with path only (no port)', function () {
$domain = 'https://api.example.com/api';
$url = Url::fromString($domain);
$template = '{{pr_id}}.{{domain}}';
$pullRequestId = 99;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$preview_fqdn = str_replace('{{random}}', 'abc123', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
expect($preview_fqdn)->toBe('https://99.api.example.com/api');
});
it('handles multiple domains with different ports and paths', function () {
$domains = [
'https://app.example.com:3000/dashboard',
'https://api.example.com:8080/api/v1',
'https://web.example.com/admin',
'https://static.example.com',
];
$preview_fqdns = [];
$template = 'pr-{{pr_id}}.{{domain}}';
$pullRequestId = 123;
foreach ($domains as $domain) {
$url = Url::fromString($domain);
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$preview_fqdn = str_replace('{{random}}', 'xyz', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
$preview_fqdns[] = $preview_fqdn;
}
expect($preview_fqdns[0])->toBe('https://pr-123.app.example.com:3000/dashboard');
expect($preview_fqdns[1])->toBe('https://pr-123.api.example.com:8080/api/v1');
expect($preview_fqdns[2])->toBe('https://pr-123.web.example.com/admin');
expect($preview_fqdns[3])->toBe('https://pr-123.static.example.com');
});
it('preserves trailing slash in URL path', function () {
$domain = 'https://api.example.com/api/';
$url = Url::fromString($domain);
$template = '{{pr_id}}.{{domain}}';
$pullRequestId = 55;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$preview_fqdn = str_replace('{{random}}', 'abc123', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
// Trailing slash is preserved: /api/ stays as /api/
expect($preview_fqdn)->toBe('https://55.api.example.com/api/');
});
it('excludes root path from preview FQDN', function () {
// Edge case: URL with explicit root path "/" should NOT append the slash
$domain = 'https://example.com/';
$url = Url::fromString($domain);
$template = '{{pr_id}}.{{domain}}';
$pullRequestId = 42;
$host = $url->getHost();
$schema = $url->getScheme();
$portInt = $url->getPort();
$port = $portInt !== null ? ':'.$portInt : '';
$urlPath = $url->getPath();
$path = ($urlPath !== '' && $urlPath !== '/') ? $urlPath : '';
$preview_fqdn = str_replace('{{random}}', 'abc123', $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $pullRequestId, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn{$port}{$path}";
// Root path "/" should be excluded, resulting in no trailing slash
expect($urlPath)->toBe('/');
expect($path)->toBe('');
expect($preview_fqdn)->toBe('https://42.example.com');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ValidGitRepositoryUrlTest.php | tests/Unit/ValidGitRepositoryUrlTest.php | <?php
use App\Rules\ValidGitRepositoryUrl;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
uses(TestCase::class);
it('validates standard GitHub URLs', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://github.com/user/repo',
'https://github.com/user/repo.git',
'https://github.com/user/repo-with-dashes',
'https://github.com/user/repo_with_underscores',
'https://github.com/user/repo.with.dots',
'https://github.com/organization/repository',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for URL: {$url}");
}
});
it('validates GitLab URLs', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://gitlab.com/user/repo',
'https://gitlab.com/user/repo.git',
'https://gitlab.com/organization/repository',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for URL: {$url}");
}
});
it('validates Bitbucket URLs', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://bitbucket.org/user/repo',
'https://bitbucket.org/user/repo.git',
'https://bitbucket.org/organization/repository',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for URL: {$url}");
}
});
it('validates tangled.sh URLs with @ symbol', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://tangled.org/@tangled.org/site',
'https://tangled.org/@user/repo',
'https://tangled.org/@organization/project',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for URL: {$url}");
}
});
it('validates SourceHut URLs with ~ symbol', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://git.sr.ht/~user/repo',
'https://git.sr.ht/~user/project',
'https://git.sr.ht/~organization/repository',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for URL: {$url}");
}
});
it('validates other Git hosting services', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://codeberg.org/user/repo',
'https://codeberg.org/user/repo.git',
'https://gitea.com/user/repo',
'https://gitea.com/user/repo.git',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for URL: {$url}");
}
});
it('validates SSH URLs when allowed', function () {
$rule = new ValidGitRepositoryUrl(allowSSH: true);
$validUrls = [
'git@github.com:user/repo.git',
'git@gitlab.com:user/repo.git',
'git@bitbucket.org:user/repo.git',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for SSH URL: {$url}");
}
});
it('rejects SSH URLs when not allowed', function () {
$rule = new ValidGitRepositoryUrl(allowSSH: false);
$invalidUrls = [
'git@github.com:user/repo.git',
'git@gitlab.com:user/repo.git',
];
foreach ($invalidUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("SSH URL should be rejected: {$url}");
expect($validator->errors()->first('url'))->toContain('SSH URLs are not allowed');
}
});
it('validates git:// protocol URLs', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'git://github.com/user/repo.git',
'git://gitlab.com/user/repo.git',
'git://git.sr.ht:~user/repo.git',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Failed for git:// URL: {$url}");
}
});
it('rejects URLs with query parameters', function () {
$rule = new ValidGitRepositoryUrl;
$invalidUrls = [
'https://github.com/user/repo?ref=main',
'https://github.com/user/repo?token=abc123',
'https://github.com/user/repo?utm_source=test',
];
foreach ($invalidUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("URL with query parameters should be rejected: {$url}");
expect($validator->errors()->first('url'))->toContain('invalid characters');
}
});
it('rejects URLs with fragments', function () {
$rule = new ValidGitRepositoryUrl;
$invalidUrls = [
'https://github.com/user/repo#main',
'https://github.com/user/repo#readme',
];
foreach ($invalidUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("URL with fragments should be rejected: {$url}");
expect($validator->errors()->first('url'))->toContain('invalid characters');
}
});
it('rejects internal/localhost URLs', function () {
$rule = new ValidGitRepositoryUrl;
$invalidUrls = [
'https://localhost/user/repo',
'https://127.0.0.1/user/repo',
'https://0.0.0.0/user/repo',
'https://::1/user/repo',
'https://example.local/user/repo',
];
foreach ($invalidUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Internal URL should be rejected: {$url}");
$errorMessage = $validator->errors()->first('url');
expect(in_array($errorMessage, [
'The url cannot point to internal hosts.',
'The url cannot use IP addresses.',
'The url is not a valid URL.',
]))->toBeTrue("Unexpected error message: {$errorMessage}");
}
});
it('rejects IP addresses when not allowed', function () {
$rule = new ValidGitRepositoryUrl(allowIP: false);
$invalidUrls = [
'https://192.168.1.1/user/repo',
'https://10.0.0.1/user/repo',
'https://172.16.0.1/user/repo',
];
foreach ($invalidUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("IP address URL should be rejected: {$url}");
expect($validator->errors()->first('url'))->toContain('IP addresses');
}
});
it('allows IP addresses when explicitly allowed', function () {
$rule = new ValidGitRepositoryUrl(allowIP: true);
$validUrls = [
'https://192.168.1.1/user/repo',
'https://10.0.0.1/user/repo',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("IP address URL should be allowed: {$url}");
}
});
it('rejects dangerous shell metacharacters', function () {
$rule = new ValidGitRepositoryUrl;
$dangerousChars = [';', '|', '&', '$', '`', '(', ')', '{', '}', '[', ']', '<', '>', '\n', '\r', '\0', '"', "'", '\\', '!', '?', '*', '^', '%', '=', '+', '#'];
foreach ($dangerousChars as $char) {
$url = "https://github.com/user/repo{$char}";
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("URL with dangerous character '{$char}' should be rejected");
expect($validator->errors()->first('url'))->toContain('invalid characters');
}
});
it('rejects command substitution patterns', function () {
$rule = new ValidGitRepositoryUrl;
$dangerousPatterns = [
'https://github.com/user/$(whoami)',
'https://github.com/user/${USER}',
'https://github.com/user;;',
'https://github.com/user&&',
'https://github.com/user||',
'https://github.com/user>>',
'https://github.com/user<<',
'https://github.com/user\\n',
'https://github.com/user../',
];
foreach ($dangerousPatterns as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("URL with dangerous pattern should be rejected: {$url}");
$errorMessage = $validator->errors()->first('url');
expect(in_array($errorMessage, [
'The url contains invalid characters.',
'The url contains invalid patterns.',
]))->toBeTrue("Unexpected error message: {$errorMessage}");
}
});
it('rejects invalid URL formats', function () {
$rule = new ValidGitRepositoryUrl;
$invalidUrls = [
'not-a-url',
'ftp://github.com/user/repo',
'file:///path/to/repo',
'ssh://github.com/user/repo',
'https://',
'http://',
'git@',
];
foreach ($invalidUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Invalid URL format should be rejected: {$url}");
}
});
it('accepts empty values', function () {
$rule = new ValidGitRepositoryUrl;
$validator = Validator::make(['url' => ''], ['url' => $rule]);
expect($validator->passes())->toBeTrue('Empty URL should be accepted');
$validator = Validator::make(['url' => null], ['url' => $rule]);
expect($validator->passes())->toBeTrue('Null URL should be accepted');
});
it('validates complex repository paths', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://github.com/user/repo-with-many-dashes',
'https://github.com/user/repo_with_many_underscores',
'https://github.com/user/repo.with.many.dots',
'https://github.com/user/repo@version',
'https://github.com/user/repo~backup',
'https://github.com/user/repo@version~backup',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Complex path should be valid: {$url}");
}
});
it('validates nested repository paths', function () {
$rule = new ValidGitRepositoryUrl;
$validUrls = [
'https://github.com/org/suborg/repo',
'https://gitlab.com/group/subgroup/project',
'https://tangled.org/@org/suborg/project',
'https://git.sr.ht/~user/project/subproject',
];
foreach ($validUrls as $url) {
$validator = Validator::make(['url' => $url], ['url' => $rule]);
expect($validator->passes())->toBeTrue("Nested path should be valid: {$url}");
}
});
it('provides meaningful error messages', function () {
$rule = new ValidGitRepositoryUrl;
$testCases = [
[
'url' => 'https://github.com/user; rm -rf /',
'expectedError' => 'invalid characters',
],
[
'url' => 'https://github.com/user/repo?token=secret',
'expectedError' => 'invalid characters',
],
[
'url' => 'https://localhost/user/repo',
'expectedError' => 'internal hosts',
],
];
foreach ($testCases as $testCase) {
$validator = Validator::make(['url' => $testCase['url']], ['url' => $rule]);
expect($validator->fails())->toBeTrue("Should fail for: {$testCase['url']}");
expect($validator->errors()->first('url'))->toContain($testCase['expectedError']);
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerfileArgInsertionTest.php | tests/Unit/DockerfileArgInsertionTest.php | <?php
use App\Jobs\ApplicationDeploymentJob;
/**
* Test the Dockerfile ARG insertion logic
* This tests the fix for GitHub issue #7118
*/
it('finds FROM instructions in simple dockerfile', function () {
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$dockerfile = collect([
'FROM node:16',
'WORKDIR /app',
'COPY . .',
]);
$result = $job->findFromInstructionLines($dockerfile);
expect($result)->toBe([0]);
});
it('finds FROM instructions with comments before', function () {
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$dockerfile = collect([
'# Build stage',
'# Another comment',
'FROM node:16',
'WORKDIR /app',
]);
$result = $job->findFromInstructionLines($dockerfile);
expect($result)->toBe([2]);
});
it('finds multiple FROM instructions in multi-stage dockerfile', function () {
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$dockerfile = collect([
'FROM node:16 AS builder',
'WORKDIR /app',
'RUN npm install',
'',
'FROM nginx:alpine',
'COPY --from=builder /app/dist /usr/share/nginx/html',
]);
$result = $job->findFromInstructionLines($dockerfile);
expect($result)->toBe([0, 4]);
});
it('handles FROM with different cases', function () {
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$dockerfile = collect([
'from node:16',
'From nginx:alpine',
'FROM alpine:latest',
]);
$result = $job->findFromInstructionLines($dockerfile);
expect($result)->toBe([0, 1, 2]);
});
it('returns empty array when no FROM instructions found', function () {
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$dockerfile = collect([
'# Just comments',
'WORKDIR /app',
'RUN npm install',
]);
$result = $job->findFromInstructionLines($dockerfile);
expect($result)->toBe([]);
});
it('inserts ARGs after FROM in simple dockerfile', function () {
$dockerfile = collect([
'FROM node:16',
'WORKDIR /app',
'COPY . .',
]);
$fromLines = [0];
$argsToInsert = collect(['ARG MY_VAR=value', 'ARG ANOTHER_VAR']);
foreach (array_reverse($fromLines) as $fromLineIndex) {
foreach ($argsToInsert->reverse() as $arg) {
$dockerfile->splice($fromLineIndex + 1, 0, [$arg]);
}
}
expect($dockerfile[0])->toBe('FROM node:16');
expect($dockerfile[1])->toBe('ARG MY_VAR=value');
expect($dockerfile[2])->toBe('ARG ANOTHER_VAR');
expect($dockerfile[3])->toBe('WORKDIR /app');
});
it('inserts ARGs after each FROM in multi-stage dockerfile', function () {
$dockerfile = collect([
'FROM node:16 AS builder',
'WORKDIR /app',
'',
'FROM nginx:alpine',
'COPY --from=builder /app/dist /usr/share/nginx/html',
]);
$fromLines = [0, 3];
$argsToInsert = collect(['ARG MY_VAR=value']);
foreach (array_reverse($fromLines) as $fromLineIndex) {
foreach ($argsToInsert->reverse() as $arg) {
$dockerfile->splice($fromLineIndex + 1, 0, [$arg]);
}
}
// First stage
expect($dockerfile[0])->toBe('FROM node:16 AS builder');
expect($dockerfile[1])->toBe('ARG MY_VAR=value');
expect($dockerfile[2])->toBe('WORKDIR /app');
// Second stage (index shifted by +1 due to inserted ARG)
expect($dockerfile[4])->toBe('FROM nginx:alpine');
expect($dockerfile[5])->toBe('ARG MY_VAR=value');
});
it('inserts ARGs after FROM when comments precede FROM', function () {
$dockerfile = collect([
'# Build stage comment',
'FROM node:16',
'WORKDIR /app',
]);
$fromLines = [1];
$argsToInsert = collect(['ARG MY_VAR=value']);
foreach (array_reverse($fromLines) as $fromLineIndex) {
foreach ($argsToInsert->reverse() as $arg) {
$dockerfile->splice($fromLineIndex + 1, 0, [$arg]);
}
}
expect($dockerfile[0])->toBe('# Build stage comment');
expect($dockerfile[1])->toBe('FROM node:16');
expect($dockerfile[2])->toBe('ARG MY_VAR=value');
expect($dockerfile[3])->toBe('WORKDIR /app');
});
it('handles real-world nuxt multi-stage dockerfile with comments', function () {
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$dockerfile = collect([
'# Build Stage 1',
'',
'FROM node:22-alpine AS build',
'WORKDIR /app',
'',
'RUN corepack enable',
'',
'# Copy package.json and your lockfile, here we add pnpm-lock.yaml for illustration',
'COPY package.json pnpm-lock.yaml .npmrc ./',
'',
'# Install dependencies',
'RUN pnpm i',
'',
'# Copy the entire project',
'COPY . ./',
'',
'# Build the project',
'RUN pnpm run build',
'',
'# Build Stage 2',
'',
'FROM node:22-alpine',
'WORKDIR /app',
'',
'# Only `.output` folder is needed from the build stage',
'COPY --from=build /app/.output/ ./',
'',
'# Change the port and host',
'ENV PORT=80',
'ENV HOST=0.0.0.0',
'',
'EXPOSE 80',
'',
'CMD ["node", "/app/server/index.mjs"]',
]);
// Find FROM instructions
$fromLines = $job->findFromInstructionLines($dockerfile);
expect($fromLines)->toBe([2, 21]);
// Simulate ARG insertion
$argsToInsert = collect(['ARG BUILD_VAR=production']);
foreach (array_reverse($fromLines) as $fromLineIndex) {
foreach ($argsToInsert->reverse() as $arg) {
$dockerfile->splice($fromLineIndex + 1, 0, [$arg]);
}
}
// Verify first stage
expect($dockerfile[2])->toBe('FROM node:22-alpine AS build');
expect($dockerfile[3])->toBe('ARG BUILD_VAR=production');
expect($dockerfile[4])->toBe('WORKDIR /app');
// Verify second stage (index shifted by +1 due to first ARG insertion)
expect($dockerfile[22])->toBe('FROM node:22-alpine');
expect($dockerfile[23])->toBe('ARG BUILD_VAR=production');
expect($dockerfile[24])->toBe('WORKDIR /app');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceParserImageUpdateTest.php | tests/Unit/ServiceParserImageUpdateTest.php | <?php
/**
* Unit tests to verify that service parser correctly handles image updates
* without creating duplicate ServiceApplication or ServiceDatabase records.
*
* These tests verify the fix for the issue where changing an image in a
* docker-compose file would create a new service instead of updating the existing one.
*/
it('ensures service parser does not include image in firstOrCreate query', function () {
// Read the serviceParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that firstOrCreate is called with only name and service_id
// and NOT with image parameter in the ServiceApplication presave loop
expect($parsersFile)
->toContain("firstOrCreate([\n 'name' => \$serviceName,\n 'service_id' => \$resource->id,\n ]);")
->not->toContain("firstOrCreate([\n 'name' => \$serviceName,\n 'image' => \$image,\n 'service_id' => \$resource->id,\n ]);");
});
it('ensures service parser updates image after finding or creating service', function () {
// Read the serviceParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that image update logic exists after firstOrCreate
expect($parsersFile)
->toContain('// Update image if it changed')
->toContain('if ($savedService->image !== $image) {')
->toContain('$savedService->image = $image;')
->toContain('$savedService->save();');
});
it('ensures parseDockerComposeFile does not create duplicates on null savedService', function () {
// Read the parseDockerComposeFile function from shared.php
$sharedFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/shared.php');
// Check that the duplicate creation logic after is_null check has been fixed
// The old code would create a duplicate if savedService was null
// The new code checks for null within the else block and creates only if needed
expect($sharedFile)
->toContain('if (is_null($savedService)) {')
->toContain('$savedService = ServiceDatabase::create([');
});
it('verifies image update logic is present in parseDockerComposeFile', function () {
// Read the parseDockerComposeFile function from shared.php
$sharedFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/shared.php');
// Verify the image update logic exists
expect($sharedFile)
->toContain('// Check if image changed')
->toContain('if ($savedService->image !== $image) {')
->toContain('$savedService->image = $image;')
->toContain('$savedService->save();');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServicePortSpecificVariablesTest.php | tests/Unit/ServicePortSpecificVariablesTest.php | <?php
/**
* Unit tests to verify that SERVICE_URL_* and SERVICE_FQDN_* variables
* with port suffixes are properly handled and populated.
*
* These variables should include the port number in both the key name and the URL value.
* Example: SERVICE_URL_UMAMI_3000 should be populated with http://domain.com:3000
*/
it('ensures parsers.php populates port-specific SERVICE variables', function () {
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that the fix is in place
$hasPortSpecificComment = str_contains($parsersFile, 'For port-specific variables');
$usesFqdnWithPort = str_contains($parsersFile, '$fqdnWithPort');
$usesUrlWithPort = str_contains($parsersFile, '$urlWithPort');
expect($hasPortSpecificComment)->toBeTrue('Should have comment about port-specific variables');
expect($usesFqdnWithPort)->toBeTrue('Should use $fqdnWithPort for port variables');
expect($usesUrlWithPort)->toBeTrue('Should use $urlWithPort for port variables');
});
it('verifies SERVICE_URL variable naming convention', function () {
// Test the naming convention for port-specific variables
// Base variable (no port): SERVICE_URL_UMAMI
$baseKey = 'SERVICE_URL_UMAMI';
expect(substr_count($baseKey, '_'))->toBe(2);
// Port-specific variable: SERVICE_URL_UMAMI_3000
$portKey = 'SERVICE_URL_UMAMI_3000';
expect(substr_count($portKey, '_'))->toBe(3);
// Extract service name
$serviceName = str($portKey)->after('SERVICE_URL_')->beforeLast('_')->lower()->value();
expect($serviceName)->toBe('umami');
// Extract port
$port = str($portKey)->afterLast('_')->value();
expect($port)->toBe('3000');
});
it('verifies SERVICE_FQDN variable naming convention', function () {
// Test the naming convention for port-specific FQDN variables
// Base variable (no port): SERVICE_FQDN_POSTGRES
$baseKey = 'SERVICE_FQDN_POSTGRES';
expect(substr_count($baseKey, '_'))->toBe(2);
// Port-specific variable: SERVICE_FQDN_POSTGRES_5432
$portKey = 'SERVICE_FQDN_POSTGRES_5432';
expect(substr_count($portKey, '_'))->toBe(3);
// Extract service name
$serviceName = str($portKey)->after('SERVICE_FQDN_')->beforeLast('_')->lower()->value();
expect($serviceName)->toBe('postgres');
// Extract port
$port = str($portKey)->afterLast('_')->value();
expect($port)->toBe('5432');
});
it('verifies URL with port format', function () {
// Test that URLs with ports are formatted correctly
$baseUrl = 'http://umami-abc123.domain.com';
$port = '3000';
$urlWithPort = "$baseUrl:$port";
expect($urlWithPort)->toBe('http://umami-abc123.domain.com:3000');
expect($urlWithPort)->toContain(':3000');
});
it('verifies FQDN with port format', function () {
// Test that FQDNs with ports are formatted correctly
$baseFqdn = 'postgres-xyz789.domain.com';
$port = '5432';
$fqdnWithPort = "$baseFqdn:$port";
expect($fqdnWithPort)->toBe('postgres-xyz789.domain.com:5432');
expect($fqdnWithPort)->toContain(':5432');
});
it('verifies port extraction from variable name', function () {
// Test extracting port from various variable names
$tests = [
'SERVICE_URL_APP_3000' => '3000',
'SERVICE_URL_API_8080' => '8080',
'SERVICE_FQDN_DB_5432' => '5432',
'SERVICE_FQDN_REDIS_6379' => '6379',
];
foreach ($tests as $varName => $expectedPort) {
$port = str($varName)->afterLast('_')->value();
expect($port)->toBe($expectedPort, "Port extraction failed for $varName");
}
});
it('verifies service name extraction with port suffix', function () {
// Test extracting service name when port is present
$tests = [
'SERVICE_URL_APP_3000' => 'app',
'SERVICE_URL_MY_API_8080' => 'my_api',
'SERVICE_FQDN_DB_5432' => 'db',
'SERVICE_FQDN_REDIS_CACHE_6379' => 'redis_cache',
];
foreach ($tests as $varName => $expectedService) {
if (str($varName)->startsWith('SERVICE_URL_')) {
$serviceName = str($varName)->after('SERVICE_URL_')->beforeLast('_')->lower()->value();
} else {
$serviceName = str($varName)->after('SERVICE_FQDN_')->beforeLast('_')->lower()->value();
}
expect($serviceName)->toBe($expectedService, "Service name extraction failed for $varName");
}
});
it('verifies distinction between base and port-specific variables', function () {
// Test that base and port-specific variables are different
$baseUrl = 'SERVICE_URL_UMAMI';
$portUrl = 'SERVICE_URL_UMAMI_3000';
expect($baseUrl)->not->toBe($portUrl);
expect(substr_count($baseUrl, '_'))->toBe(2);
expect(substr_count($portUrl, '_'))->toBe(3);
// Port-specific should contain port number
expect(str($portUrl)->contains('_3000'))->toBeTrue();
expect(str($baseUrl)->contains('_3000'))->toBeFalse();
});
it('verifies multiple port variables for same service', function () {
// Test that a service can have multiple port-specific variables
$service = 'api';
$ports = ['3000', '8080', '9090'];
foreach ($ports as $port) {
$varName = "SERVICE_URL_API_$port";
// Should have 3 underscores
expect(substr_count($varName, '_'))->toBe(3);
// Should extract correct service name
$serviceName = str($varName)->after('SERVICE_URL_')->beforeLast('_')->lower()->value();
expect($serviceName)->toBe('api');
// Should extract correct port
$extractedPort = str($varName)->afterLast('_')->value();
expect($extractedPort)->toBe($port);
}
});
it('verifies common port numbers are handled correctly', function () {
// Test common port numbers used in applications
$commonPorts = [
'80' => 'HTTP',
'443' => 'HTTPS',
'3000' => 'Node.js/React',
'5432' => 'PostgreSQL',
'6379' => 'Redis',
'8080' => 'Alternative HTTP',
'9000' => 'PHP-FPM',
];
foreach ($commonPorts as $port => $description) {
$varName = "SERVICE_URL_APP_$port";
expect(substr_count($varName, '_'))->toBe(3, "Failed for $description port $port");
$extractedPort = str($varName)->afterLast('_')->value();
expect($extractedPort)->toBe((string) $port, "Port extraction failed for $description");
}
});
it('detects port-specific variables with numeric suffix', function () {
// Test that variables ending with a numeric port are detected correctly
// This tests the logic: if last segment after _ is numeric, it's a port
$tests = [
// 2-underscore pattern: single-word service name + port
'SERVICE_URL_MYAPP_3000' => ['service' => 'myapp', 'port' => '3000', 'hasPort' => true],
'SERVICE_URL_REDIS_6379' => ['service' => 'redis', 'port' => '6379', 'hasPort' => true],
'SERVICE_FQDN_NGINX_80' => ['service' => 'nginx', 'port' => '80', 'hasPort' => true],
// 3-underscore pattern: two-word service name + port
'SERVICE_URL_MY_API_8080' => ['service' => 'my_api', 'port' => '8080', 'hasPort' => true],
'SERVICE_URL_WEB_APP_3000' => ['service' => 'web_app', 'port' => '3000', 'hasPort' => true],
'SERVICE_FQDN_DB_SERVER_5432' => ['service' => 'db_server', 'port' => '5432', 'hasPort' => true],
// 4-underscore pattern: three-word service name + port
'SERVICE_URL_REDIS_CACHE_SERVER_6379' => ['service' => 'redis_cache_server', 'port' => '6379', 'hasPort' => true],
'SERVICE_URL_MY_LONG_APP_8080' => ['service' => 'my_long_app', 'port' => '8080', 'hasPort' => true],
'SERVICE_FQDN_POSTGRES_PRIMARY_DB_5432' => ['service' => 'postgres_primary_db', 'port' => '5432', 'hasPort' => true],
// Non-numeric suffix: should NOT be treated as port-specific
'SERVICE_URL_MY_APP' => ['service' => 'my_app', 'port' => null, 'hasPort' => false],
'SERVICE_URL_REDIS_PRIMARY' => ['service' => 'redis_primary', 'port' => null, 'hasPort' => false],
'SERVICE_FQDN_WEB_SERVER' => ['service' => 'web_server', 'port' => null, 'hasPort' => false],
'SERVICE_URL_APP_CACHE_REDIS' => ['service' => 'app_cache_redis', 'port' => null, 'hasPort' => false],
// Edge numeric cases
'SERVICE_URL_APP_0' => ['service' => 'app', 'port' => '0', 'hasPort' => true], // Port 0
'SERVICE_URL_APP_99999' => ['service' => 'app', 'port' => '99999', 'hasPort' => true], // Port out of range
'SERVICE_URL_APP_3.14' => ['service' => 'app_3.14', 'port' => null, 'hasPort' => false], // Float (should not be port)
'SERVICE_URL_APP_1e5' => ['service' => 'app_1e5', 'port' => null, 'hasPort' => false], // Scientific notation
// Edge cases
'SERVICE_URL_APP' => ['service' => 'app', 'port' => null, 'hasPort' => false],
'SERVICE_FQDN_DB' => ['service' => 'db', 'port' => null, 'hasPort' => false],
];
foreach ($tests as $varName => $expected) {
// Use the actual helper function from bootstrap/helpers/services.php
$parsed = parseServiceEnvironmentVariable($varName);
expect($parsed['service_name'])->toBe($expected['service'], "Service name mismatch for $varName");
expect($parsed['port'])->toBe($expected['port'], "Port mismatch for $varName");
expect($parsed['has_port'])->toBe($expected['hasPort'], "Port detection mismatch for $varName");
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/PrivateKeyStorageTest.php | tests/Unit/PrivateKeyStorageTest.php | <?php
use App\Models\PrivateKey;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class PrivateKeyStorageTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
// Set up a test team for the tests
$this->actingAs(\App\Models\User::factory()->create());
}
protected function getValidPrivateKey(): string
{
return '-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
-----END OPENSSH PRIVATE KEY-----';
}
/** @test */
public function it_successfully_stores_private_key_in_filesystem()
{
Storage::fake('ssh-keys');
$privateKey = PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
$this->assertDatabaseHas('private_keys', [
'id' => $privateKey->id,
'name' => 'Test Key',
]);
$filename = "ssh_key@{$privateKey->uuid}";
Storage::disk('ssh-keys')->assertExists($filename);
$storedContent = Storage::disk('ssh-keys')->get($filename);
$this->assertEquals($privateKey->private_key, $storedContent);
}
/** @test */
public function it_throws_exception_when_storage_fails()
{
Storage::fake('ssh-keys');
// Mock Storage::put to return false (simulating storage failure)
Storage::shouldReceive('disk')
->with('ssh-keys')
->andReturn(
\Mockery::mock()
->shouldReceive('exists')
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::any(), 'test')
->andReturn(true)
->shouldReceive('delete')
->with(\Mockery::any())
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/ssh_key@/'), \Mockery::any())
->andReturn(false) // Simulate storage failure
->getMock()
);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('Failed to write SSH key to filesystem');
PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
// Assert that no database record was created due to transaction rollback
$this->assertDatabaseMissing('private_keys', [
'name' => 'Test Key',
]);
}
/** @test */
public function it_throws_exception_when_storage_directory_is_not_writable()
{
Storage::fake('ssh-keys');
// Mock Storage disk to simulate directory not writable
Storage::shouldReceive('disk')
->with('ssh-keys')
->andReturn(
\Mockery::mock()
->shouldReceive('exists')
->with('')
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/\.test_write_/'), 'test')
->andReturn(false) // Simulate directory not writable
->getMock()
);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('SSH keys storage directory is not writable');
PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
}
/** @test */
public function it_creates_storage_directory_if_not_exists()
{
Storage::fake('ssh-keys');
// Mock Storage disk to simulate directory not existing, then being created
Storage::shouldReceive('disk')
->with('ssh-keys')
->andReturn(
\Mockery::mock()
->shouldReceive('exists')
->with('')
->andReturn(false) // Directory doesn't exist
->shouldReceive('makeDirectory')
->with('')
->andReturn(true) // Successfully create directory
->shouldReceive('put')
->with(\Mockery::pattern('/\.test_write_/'), 'test')
->andReturn(true) // Directory is writable after creation
->shouldReceive('delete')
->with(\Mockery::pattern('/\.test_write_/'))
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/ssh_key@/'), \Mockery::any())
->andReturn(true)
->shouldReceive('exists')
->with(\Mockery::pattern('/ssh_key@/'))
->andReturn(true)
->shouldReceive('get')
->with(\Mockery::pattern('/ssh_key@/'))
->andReturn($this->getValidPrivateKey())
->getMock()
);
$privateKey = PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
$this->assertDatabaseHas('private_keys', [
'id' => $privateKey->id,
'name' => 'Test Key',
]);
}
/** @test */
public function it_throws_exception_when_file_content_verification_fails()
{
Storage::fake('ssh-keys');
// Mock Storage disk to simulate file being created but with wrong content
Storage::shouldReceive('disk')
->with('ssh-keys')
->andReturn(
\Mockery::mock()
->shouldReceive('exists')
->with('')
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/\.test_write_/'), 'test')
->andReturn(true)
->shouldReceive('delete')
->with(\Mockery::pattern('/\.test_write_/'))
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/ssh_key@/'), \Mockery::any())
->andReturn(true) // File created successfully
->shouldReceive('exists')
->with(\Mockery::pattern('/ssh_key@/'))
->andReturn(true) // File exists
->shouldReceive('get')
->with(\Mockery::pattern('/ssh_key@/'))
->andReturn('corrupted content') // But content is wrong
->shouldReceive('delete')
->with(\Mockery::pattern('/ssh_key@/'))
->andReturn(true) // Clean up bad file
->getMock()
);
$this->expectException(\Exception::class);
$this->expectExceptionMessage('SSH key file content verification failed');
PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
// Assert that no database record was created due to transaction rollback
$this->assertDatabaseMissing('private_keys', [
'name' => 'Test Key',
]);
}
/** @test */
public function it_successfully_deletes_private_key_from_filesystem()
{
Storage::fake('ssh-keys');
$privateKey = PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
$filename = "ssh_key@{$privateKey->uuid}";
Storage::disk('ssh-keys')->assertExists($filename);
$privateKey->delete();
Storage::disk('ssh-keys')->assertMissing($filename);
}
/** @test */
public function it_handles_database_transaction_rollback_on_storage_failure()
{
Storage::fake('ssh-keys');
// Count initial private keys
$initialCount = PrivateKey::count();
// Mock storage failure after database save
Storage::shouldReceive('disk')
->with('ssh-keys')
->andReturn(
\Mockery::mock()
->shouldReceive('exists')
->with('')
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/\.test_write_/'), 'test')
->andReturn(true)
->shouldReceive('delete')
->with(\Mockery::pattern('/\.test_write_/'))
->andReturn(true)
->shouldReceive('put')
->with(\Mockery::pattern('/ssh_key@/'), \Mockery::any())
->andReturn(false) // Storage fails
->getMock()
);
try {
PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
} catch (\Exception $e) {
// Expected exception
}
// Assert that database was rolled back
$this->assertEquals($initialCount, PrivateKey::count());
$this->assertDatabaseMissing('private_keys', [
'name' => 'Test Key',
]);
}
/** @test */
public function it_successfully_updates_private_key_with_transaction()
{
Storage::fake('ssh-keys');
$privateKey = PrivateKey::createAndStore([
'name' => 'Test Key',
'description' => 'Test Description',
'private_key' => $this->getValidPrivateKey(),
'team_id' => currentTeam()->id,
]);
$newPrivateKey = str_replace('Test', 'Updated', $this->getValidPrivateKey());
$privateKey->updatePrivateKey([
'name' => 'Updated Key',
'private_key' => $newPrivateKey,
]);
$this->assertDatabaseHas('private_keys', [
'id' => $privateKey->id,
'name' => 'Updated Key',
]);
$filename = "ssh_key@{$privateKey->uuid}";
$storedContent = Storage::disk('ssh-keys')->get($filename);
$this->assertEquals($newPrivateKey, $storedContent);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.