From 555b46a7d84d22a0f9ff0f30f22d3797ff8b3171 Mon Sep 17 00:00:00 2001 From: ShadowArcanist <162910371+ShadowArcanist@users.noreply.github.com> Date: Tue, 24 Feb 2026 00:45:33 +0530 Subject: [PATCH 01/30] chore(repo): improve contributor guidelines --- CONTRIBUTING.md | 463 +++++++++++++++++++++--------------------------- 1 file changed, 205 insertions(+), 258 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9aec08420..af8c7503c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,298 +1,245 @@ # Contributing to Coolify +We’re happy that you’re interested in contributing to Coolify! -> "First, thanks for considering contributing to my project. It really means a lot!" - [@andrasbacsai](https://github.com/andrasbacsai) +There are many ways to help: +- Answer questions in GitHub Discussions or Discord +- Report reproducible bugs +- Submit pull requests to fix issues +- Add new one-click services +- Improve documentation -You can ask for guidance anytime on our [Discord server](https://coollabs.io/discord) in the `#contribute` channel. +Coolify is a PaaS used by 400,000+ people worldwide and maintained by two active maintainers. Contributions are welcome — but **alignment matters more than quantity**. -To understand the tech stack, please refer to the [Tech Stack](TECH_STACK.md) document. - -## Table of Contents - -1. [Setup Development Environment](#1-setup-development-environment) -2. [Verify Installation](#2-verify-installation-optional) -3. [Fork and Setup Local Repository](#3-fork-and-setup-local-repository) -4. [Set up Environment Variables](#4-set-up-environment-variables) -5. [Start Coolify](#5-start-coolify) -6. [Start Development](#6-start-development) -7. [Create a Pull Request](#7-create-a-pull-request) -8. [Development Notes](#development-notes) -9. [Resetting Development Environment](#resetting-development-environment) -10. [Additional Contribution Guidelines](#additional-contribution-guidelines) - -## 1. Setup Development Environment - -Follow the steps below for your operating system: - -
-Windows - -1. Install `docker-ce`, Docker Desktop (or similar): - - Docker CE (recommended): - - Install Windows Subsystem for Linux v2 (WSL2) by following this guide: [Install WSL](https://learn.microsoft.com/en-us/windows/wsl/install?ref=coolify) - - After installing WSL2, install Docker CE for your Linux distribution by following this guide: [Install Docker Engine](https://docs.docker.com/engine/install/?ref=coolify) - - Make sure to choose the appropriate Linux distribution (e.g., Ubuntu) when following the Docker installation guide - - Install Docker Desktop (easier): - - Download and install [Docker Desktop for Windows](https://docs.docker.com/desktop/install/windows-install/?ref=coolify) - - Ensure WSL2 backend is enabled in Docker Desktop settings - -2. Install Spin: - - Follow the instructions to install Spin on Windows from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-windows#download-and-install-spin-into-wsl2?ref=coolify) - -
- -
-MacOS - -1. Install Orbstack, Docker Desktop (or similar): - - Orbstack (recommended, as it is a faster and lighter alternative to Docker Desktop): - - Download and install [Orbstack](https://docs.orbstack.dev/quick-start#installation?ref=coolify) - - Docker Desktop: - - Download and install [Docker Desktop for Mac](https://docs.docker.com/desktop/install/mac-install/?ref=coolify) - -2. Install Spin: - - Follow the instructions to install Spin on MacOS from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-macos/#download-and-install-spin?ref=coolify) - -
- -
-Linux - -1. Install Docker Engine, Docker Desktop (or similar): - - Docker Engine (recommended, as there is no VM overhead): - - Follow the official [Docker Engine installation guide](https://docs.docker.com/engine/install/?ref=coolify) for your Linux distribution - - Docker Desktop: - - If you want a GUI, you can use [Docker Desktop for Linux](https://docs.docker.com/desktop/install/linux-install/?ref=coolify) - -2. Install Spin: - - Follow the instructions to install Spin on Linux from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-linux#configure-docker-permissions?ref=coolify) - -
- -## 2. Verify Installation (Optional) - -After installing Docker (or Orbstack) and Spin, verify the installation: - -1. Open a terminal or command prompt -2. Run the following commands: - ```bash - docker --version - spin --version - ``` - You should see version information for both Docker and Spin. - -## 3. Fork and Setup Local Repository - -1. Fork the [Coolify](https://github.com/coollabsio/coolify) repository to your GitHub account. - -2. Install a code editor on your machine (choose one): - - | Editor | Platform | Download Link | - |--------|----------|---------------| - | Visual Studio Code (recommended free) | Windows/macOS/Linux | [Download](https://code.visualstudio.com/download?ref=coolify) | - | Cursor (recommended but paid) | Windows/macOS/Linux | [Download](https://www.cursor.com/?ref=coolify) | - | Zed (very fast) | macOS/Linux | [Download](https://zed.dev/download?ref=coolify) | - -3. Clone the Coolify Repository from your fork to your local machine - - Use `git clone` in the command line, or - - Use GitHub Desktop (recommended): - - Download and install from [https://desktop.github.com/](https://desktop.github.com/?ref=coolify) - - Open GitHub Desktop and login with your GitHub account - - Click on `File` -> `Clone Repository` select `github.com` as the repository location, then select your forked Coolify repository, choose the local path and then click `Clone` - -4. Open the cloned Coolify Repository in your chosen code editor. - -## 4. Set up Environment Variables - -1. In the Code Editor, locate the `.env.development.example` file in the root directory of your local Coolify repository. -2. Duplicate the `.env.development.example` file and rename the copy to `.env`. -3. Open the new `.env` file and review its contents. Adjust any environment variables as needed for your development setup. -4. If you encounter errors during database migrations, update the database connection settings in your `.env` file. Use the IP address or hostname of your PostgreSQL database container. You can find this information by running `docker ps` after executing `spin up`. -5. Save the changes to your `.env` file. - -## 5. Start Coolify - -1. Open a terminal in the local Coolify directory. -2. Run the following command in the terminal (leave that terminal open): - ```bash - spin up - ``` - -> [!NOTE] -> You may see some errors, but don't worry; this is expected. - -3. If you encounter permission errors, especially on macOS, use: - ```bash - sudo spin up - ``` - -> [!NOTE] -> If you change environment variables afterwards or anything seems broken, press Ctrl + C to stop the process and run `spin up` again. - -## 6. Start Development - -1. Access your Coolify instance: - - URL: `http://localhost:8000` - - Login: `test@example.com` - - Password: `password` - -2. Additional development tools: - - | Tool | URL | Note | - |------|-----|------| - | Laravel Horizon (scheduler) | `http://localhost:8000/horizon` | Only accessible when logged in as root user | - | Mailpit (email catcher) | `http://localhost:8025` | | - | Telescope (debugging tool) | `http://localhost:8000/telescope` | Disabled by default | - -> [!NOTE] -> To enable Telescope, add the following to your `.env` file: -> ```env -> TELESCOPE_ENABLED=true -> ``` - -## 7. Create a Pull Request +This guide explains **what kind of contributions are likely to be accepted** and how to submit them properly. Following it saves time for both you and the maintainers. > [!IMPORTANT] -> Please read the [Pull Request Guidelines](#pull-request-guidelines) carefully before creating your PR. +> These guidelines may feel stricter than in many open-source projects. That is intentional. +> Clear structure and boundaries prevent maintainer burnout and keep the project sustainable long-term. -1. After making changes or adding a new service: - - Commit your changes to your forked repository. - - Push the changes to your GitHub account. -2. Creating the Pull Request (PR): - - Navigate to the main Coolify repository on GitHub. - - Click the "Pull requests" tab. - - Click the green "New pull request" button. - - Choose your fork and `next` branch as the compare branch. - - Click "Create pull request". +## High-Level Expectations +- Coolify has a clear product direction. +- Ownership and decisions are centralized. +- Review capacity is limited. +- Not every contribution will be accepted — even if technically correct. -3. Filling out the PR details: - - Give your PR a descriptive title. - - Use the Pull Request Template provided and fill in the details. +This is normal for a two-maintainer project. -> [!IMPORTANT] -> Always set the base branch for your PR to the `next` branch of the Coolify repository, not the `v4.x` branch. -4. Submit your PR: - - Review your changes one last time. - - Click "Create pull request" to submit. +## State of the Project +Coolify is currently at v4 and is still in beta. While v4 is stable, it has some limitations, including: +- Limited scaling support +- A more complex user experience +- Other smaller issues that need refinement -> [!NOTE] -> Make sure your PR is out of draft mode as soon as it's ready for review. PRs that are in draft mode for a long time may be closed by maintainers. +These limitations will be addressed in Coolify v5, which is in the planning stage. However, the maintainers are focused on releasing a stable v4 version before dedicating time to v5 development. Because of this, major features, architectural changes, or significant UI changes will not be accepted for v4 at this stage. -After submission, maintainers will review your PR and may request changes or provide feedback. +We welcome contributions that help stabilize v4, but larger changes will be saved for v5 once we have a stable v4 release. -#### Pull Request Guidelines -To maintain high-quality contributions and efficient review process: -- **Target Branch**: Always target the `next` branch, never `v4.x` or any other branch. PRs targeting incorrect branches will be closed without review. -- **Descriptive Titles**: Use clear, concise PR titles that describe the change (e.g., "fix: one click postgresql database stuck in restart loop" instead of "Fix database"). -- **PR Descriptions**: Provide detailed, meaningful descriptions. Avoid generic or AI-generated fluff. Include: - - What the change does - - Why it's needed - - How to test it - - Any breaking changes - - Screenshot or video recording of your changes working without any issues - - Links to related issues -- **Link to Issues**: All PRs must link to an existing GitHub issue. If no issue exists, create one first. Unrelated PRs may be closed. -- **Single Responsibility**: Each PR should address one issue or feature. Do not bundle unrelated changes. -- **Draft Mode**: Use draft PRs for work-in-progress. Convert to ready-for-review only when complete and tested. -- **Review Readiness**: Ensure your PR is ready for review within a reasonable timeframe (max 7 days in draft). Stale drafts may be closed. -- **Current Focus**: We are currently prioritizing stability and bug fixes over new features. PRs adding new features may not be reviewed, or may be closed without review to maintain focus. -- **Language Translations**: Coolify currently supports only English. Pull requests for new language translations will not be accepted. Multi-language support may be considered in the next major version (v5). -- **AI Usage Policy**: We are not against AI tools—we use them ourselves. However, AI discourse is mandatory: You must fully understand the changes in your PR and be able to explain them clearly. Many PRs using AI lack this understanding, leading to untested or incorrect submissions. If you use AI, ensure you can articulate what the code does, why it was changed, and how it was tested. -#### Review Process -- **Response Time**: Maintainers will review PRs promptly, but complex changes may take time. Be patient and responsive to feedback. -- **Revisions**: Address all review comments. Unresolved feedback may lead to PR closure. -- **Merge Criteria**: PRs are merged only after: - - All tests pass (including CI) - - Code review approval -- **Closing PRs**: PRs may be closed for: - - Inactivity (>7 days without response) - - Failure to meet guidelines - - Duplicate or superseded work - - Security or quality concerns +## What Makes a Strong Contribution +The following types of contributions are most likely to be accepted: -#### Code Quality, Testing, and Bounty Submissions -All contributions must adhere to the highest standards of code quality and testing: +- **Bug fixes** (with clear reproduction steps) +- **Documentation improvements** (typos, clarifications, examples, guides) +- **Features discussed and aligned beforehand** +- **New service templates** requested by the community +- **Small, focused pull requests** -- **Testing Required**: Every PR must include steps to test your changes. Untested code will not be reviewed or merged. -- **Local Verification**: Ensure your changes work in the development environment. Test all affected features thoroughly. -- **Code Standards**: Follow the existing code style, conventions, and patterns in the codebase. -- **No AI-Generated Code**: Do not submit code generated by AI tools without fully understanding and verifying it. AI-generated submissions that are untested or incorrect will be rejected immediately. +If your change is small and obvious (typo fix, small bug, minor docs update), you may open a pull request directly. -**For PRs that claim bounties:** -- **Eligibility**: Bounty PRs must strictly follow all guidelines above. Untested, poorly described, or non-compliant PRs will not qualify for bounty rewards. -- **Original Work**: Bounties are for genuine contributions. Submitting AI-generated or copied code solely for bounty claims will result in disqualification and potential removal from contributing. -- **Quality Standards**: Bounty submissions are held to even higher standards. Ensure comprehensive testing, clear documentation, and alignment with project goals. When maintainers review the changes, they should work as expected (the things mentioned in the PR description plus what the bounty issuer needs). -- **Claim Process**: Only successfully merged PRs that pass all reviews (core maintainers + bounty issuer) and meet bounty criteria will be awarded. Follow the issue's bounty guidelines precisely. -- **Prioritization**: Contributor PRs are prioritized over first-time or new contributors. -- **Developer Experience**: We highly advise beginners to avoid participating in bug bounties for our codebase. Most of the time, they don't know what they are changing, how it affects other parts of the system, or if their changes are even correct. -- **Review Comments**: When maintainers ask questions, you should be able to respond properly without generic or AI-generated fluff. +## Keep Changes Focused +Only modify what is necessary to achieve your goal. -## Development Notes +If you are fixing a bug in `file.yaml`, do not: +- Reformat unrelated files +- Refactor unrelated code +- Fix style issues elsewhere +- Combine multiple unrelated changes -When working on Coolify, keep the following in mind: +Even “improvements” increase review complexity. -1. **Database Migrations**: After switching branches or making changes to the database structure, always run migrations: - ```bash - docker exec -it coolify php artisan migrate - ``` +**One pull request = one logical change.** -2. **Resetting Development Setup**: To reset your development setup to a clean database with default values: - ```bash - docker exec -it coolify php artisan migrate:fresh --seed - ``` +If you want to refactor or clean up code, discuss it first and submit it separately. -3. **Troubleshooting**: If you encounter unexpected behavior, ensure your database is up-to-date with the latest migrations and if possible reset the development setup to eliminate any environment-specific issues. -> [!IMPORTANT] -> Forgetting to migrate the database can cause problems, so make it a habit to run migrations after pulling changes or switching branches. +## Discussion Is Required for Larger Changes +For anything beyond a small fix, you must discuss it before opening a pull request. -## Resetting Development Environment +This includes: +- New features +- UI/UX changes +- Changes to default behavior +- Refactors or cleanup work +- Performance rewrites +- Architectural changes +- Changes touching many files -If you encounter issues or break your database or something else, follow these steps to start from a clean slate (works since `v4.0.0-beta.342`): +Discussion happens in GitHub Discussions: https://github.com/coollabsio/coolify/discussions/categories/general -1. Stop all running containers `ctrl + c`. +Pull requests introducing major changes without prior discussion will be closed without review. -2. Remove all Coolify containers: - ```bash - docker rm coolify coolify-db coolify-redis coolify-realtime coolify-testing-host coolify-minio coolify-vite-1 coolify-mail - ``` +This ensures alignment before significant work is done. -3. Remove Coolify volumes (it is possible that the volumes have no `coolify` prefix on your machine, in that case remove the prefix from the command): - ```bash - docker volume rm coolify_dev_backups_data coolify_dev_postgres_data coolify_dev_redis_data coolify_dev_coolify_data coolify_dev_minio_data - ``` -4. Remove unused images: - ```bash - docker image prune -a - ``` +## What This Project Is Not +To set clear expectations: +- Coolify is not optimized for first-time open-source contributors +- We do not provide beginner-focused mentorship issues +- Large unsolicited changes are unlikely to be accepted +- Broad refactors or style rewrites are not helpful +- Low-effort AI-generated pull requests will be closed -5. Start Coolify again: - ```bash - spin up - ``` +AI usage is allowed. However, contributors must fully understand what their changes do and why. -6. Run database migrations and seeders: - ```bash - docker exec -it coolify php artisan migrate:fresh --seed - ``` +Clear expectations help everyone use their time effectively. -After completing these steps, you'll have a fresh development setup. -> [!IMPORTANT] -> Always run database migrations and seeders after switching branches or pulling updates to ensure your local database structure matches the current codebase and includes necessary seed data. +# Ways to Contribute +## 1. Support Contributions +We use Discord for most support requests and GitHub Discussions for help. -## Additional Contribution Guidelines +### Requesting Support +If you need help: +- Provide complete and detailed information +- Include logs, screenshots, and steps to reproduce +- Be respectful — support is voluntary -### Contributing a New Service +Do not ping people for attention. They respond when available. -To add a new service to Coolify, please refer to our documentation: -[Adding a New Service](https://coolify.io/docs/get-started/contribute/service) +### Providing Support +If you help others: +- Verify your information before sharing +- Be patient and respectful +- Remember that not everyone has the same experience level -### Contributing to Documentation -To contribute to the Coolify documentation, please refer to this guide: -[Contributing to the Coolify Documentation](https://github.com/coollabsio/documentation-coolify/blob/main/readme.md) +## 2. Bug Report Contributions +Create a GitHub issue **only** if: +- The bug is reproducible +- You have confirmed no existing issue already covers it + +For questions or general help, use GitHub Discussions or the Discord support channel. + +Bug reports must include: +- Clear reproduction steps +- Expected result +- Actual result + +Incomplete reports may be closed. + + +## 3. Code Contributions +Maintainers may close pull requests at their discretion, without explanation. + +### Issue Requirement +Every pull request should reference and close an Issue or Discussion. + +If none exists, create one first. + +Pull requests without linked issue or discussions may not be reviewed and can be closed at any time. + + +## Commit Message Format +All commits must start with an action and category: +- `fix(ui):` — UI-related fixes +- `feat(api):` — API-related changes +- `feat(service):` — One-click service changes + +Examples: +- `fix(api): version endpoint returns wrong data` +- `feat(service): add supabase` + +Use the commit description only for concise context. + +Walls of text listing every change in description will be rejected. + + +## Pull Request Title Format +Pull request titles follow the same format: +- `fix(ui):` +- `feat(api):` +- `feat(service):` + +Examples: +- `fix(api): version endpoint returns wrong data` +- `feat(service): add supabase` + + +## AI Usage Disclosure +If AI tools were used at any stage, mention it in the pull request description. + +AI is allowed. + +However: +- You must understand every change +- You must verify correctness +- You must ensure it follows project patterns + +AI-generated pull requests without clear understanding will be closed. + + +## Test Before Submitting +Before submitting a pull request: +- Test your changes thoroughly +- Verify they work in a clean environment +- Provide detailed testing steps in the PR description + +If maintainers cannot reproduce working behavior, the PR will be closed without further review. + + +## Submitting a Pull Request +- GitHub will auto-populate the PR template +- The contributor agreement must remain intact +- Pull requests without the contributor agreement will be closed +- All pull requests must target the `next` branch +- PRs targeting other branches will be closed without review + + +## Bounty Issues +Community members may create bounty issues for features or improvements. + +Important: +- Only existing contributors are eligible +- First-time contributors targeting bounty issues will be automatically closed and maybe excluded from contributing. + +This policy exists to prevent spam. We close 30+ bounty-targeted spam PRs per week. + + +## FAQ +**Q: Should I ask before fixing a typo or a small bug?** +A: No, small, obvious fixes like typos or narrowly-scoped bug fixes can be submitted as a PR directly. + +**Q: I have an idea for a new feature.** +A: Awesome! Discuss it first in GitHub Discussions or Discord. **Do not** open a PR for new features without prior alignment. + +**Q: My PR was closed without detailed feedback.** +A: This usually means it didn’t align with the project’s direction, required more review bandwidth than available, or targeted major changes not allowed in v4. This is normal for a two-maintainer project. + +**Q: Can I work on an open issue?** +A: Comment on the issue first to confirm it’s still relevant and that no one else is actively working on it. For anything beyond a small fix, discuss your approach before implementing. + +**Q: I noticed code that could be cleaned up while working on my change.** +A: Focus only on your stated goal. Cleanups or refactors should be submitted as separate PRs after discussion. + +**Q: Can I use AI to help with my PR?** +A: Yes, AI-assisted contributions are allowed. But you must fully understand and verify the changes. PRs that appear to be generated by AI without context understanding will be closed. + +**Q: Can I work on a bounty issue as a first-time contributor?** +A: No, bounty issues are reserved for existing contributors. First-time contributors targeting bounty issues will have their PRs closed without review. This prevents spam and ensures bounties go to contributors familiar with the project. + +**Q: My PR was closed without review. Can I submit a new one?** +A: Yes, but keep in mind a PR closure is feedback, not a rejection of your effort. It usually means the PR didn’t match the project goals or guidelines. Address these issues first — repeating the same approach may hurt your standing with maintainers. + + +# Development Guides +## Local Development +To build and run Coolify locally, see: [Development](./DEVELOPMENT.md) + +## Adding a New Service +To add a new one-click service, follow: https://coolify.io/docs/get-started/contribute/service + +## Contributing to Documentation +To contribute to documentation, see: https://coolify.io/docs/get-started/contribute/documentation \ No newline at end of file From 4776a572317cc1afc362c40a09dcad41b7fecfd8 Mon Sep 17 00:00:00 2001 From: ShadowArcanist <162910371+ShadowArcanist@users.noreply.github.com> Date: Tue, 24 Feb 2026 00:46:28 +0530 Subject: [PATCH 02/30] chore(repo): improve development guide --- DEVELOPMENT.md | 212 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 DEVELOPMENT.md diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md new file mode 100644 index 000000000..69f2dc760 --- /dev/null +++ b/DEVELOPMENT.md @@ -0,0 +1,212 @@ +# Contributing to Coolify +> "First, thanks for considering contributing to my project. It really means a lot!" - [@andrasbacsai](https://github.com/andrasbacsai) + +You can ask for guidance anytime on our [Discord server](https://coollabs.io/discord) in the `#contribute` channel. + +To understand the tech stack, please refer to the [Tech Stack](TECH_STACK.md) document. + + +## Table of Contents +1. [Setup Development Environment](#1-setup-development-environment) +2. [Verify Installation](#2-verify-installation-optional) +3. [Fork and Setup Local Repository](#3-fork-and-setup-local-repository) +4. [Set up Environment Variables](#4-set-up-environment-variables) +5. [Start Coolify](#5-start-coolify) +6. [Start Development](#6-start-development) +7. [Create a Pull Request](#7-create-a-pull-request) +8. [Development Notes](#development-notes) +9. [Resetting Development Environment](#resetting-development-environment) +10. [Additional Contribution Guidelines](#additional-contribution-guidelines) + + +## 1. Setup Development Environment +Follow the steps below for your operating system: + +
+Windows + +1. Install `docker-ce`, Docker Desktop (or similar): + - Docker CE (recommended): + - Install Windows Subsystem for Linux v2 (WSL2) by following this guide: [Install WSL](https://learn.microsoft.com/en-us/windows/wsl/install?ref=coolify) + - After installing WSL2, install Docker CE for your Linux distribution by following this guide: [Install Docker Engine](https://docs.docker.com/engine/install/?ref=coolify) + - Make sure to choose the appropriate Linux distribution (e.g., Ubuntu) when following the Docker installation guide + - Install Docker Desktop (easier): + - Download and install [Docker Desktop for Windows](https://docs.docker.com/desktop/install/windows-install/?ref=coolify) + - Ensure WSL2 backend is enabled in Docker Desktop settings + +2. Install Spin: + - Follow the instructions to install Spin on Windows from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-windows#download-and-install-spin-into-wsl2?ref=coolify) + +
+ +
+MacOS + +1. Install Orbstack, Docker Desktop (or similar): + - Orbstack (recommended, as it is a faster and lighter alternative to Docker Desktop): + - Download and install [Orbstack](https://docs.orbstack.dev/quick-start#installation?ref=coolify) + - Docker Desktop: + - Download and install [Docker Desktop for Mac](https://docs.docker.com/desktop/install/mac-install/?ref=coolify) + +2. Install Spin: + - Follow the instructions to install Spin on MacOS from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-macos/#download-and-install-spin?ref=coolify) + +
+ +
+Linux + +1. Install Docker Engine, Docker Desktop (or similar): + - Docker Engine (recommended, as there is no VM overhead): + - Follow the official [Docker Engine installation guide](https://docs.docker.com/engine/install/?ref=coolify) for your Linux distribution + - Docker Desktop: + - If you want a GUI, you can use [Docker Desktop for Linux](https://docs.docker.com/desktop/install/linux-install/?ref=coolify) + +2. Install Spin: + - Follow the instructions to install Spin on Linux from the [Spin documentation](https://serversideup.net/open-source/spin/docs/installation/install-linux#configure-docker-permissions?ref=coolify) + +
+ + +## 2. Verify Installation (Optional) +After installing Docker (or Orbstack) and Spin, verify the installation: + +1. Open a terminal or command prompt +2. Run the following commands: + ```bash + docker --version + spin --version + ``` + You should see version information for both Docker and Spin. + + +## 3. Fork and Setup Local Repository +1. Fork the [Coolify](https://github.com/coollabsio/coolify) repository to your GitHub account. + +2. Install a code editor on your machine (choose one): + + | Editor | Platform | Download Link | + |--------|----------|---------------| + | Visual Studio Code (recommended free) | Windows/macOS/Linux | [Download](https://code.visualstudio.com/download?ref=coolify) | + | Cursor (recommended but paid) | Windows/macOS/Linux | [Download](https://www.cursor.com/?ref=coolify) | + | Zed (very fast) | Windows/macOS/Linux | [Download](https://zed.dev/download?ref=coolify) | + +3. Clone the Coolify Repository from your fork to your local machine + - Use `git clone` in the command line, or + - Use GitHub Desktop (recommended): + - Download and install from [https://desktop.github.com/](https://desktop.github.com/?ref=coolify) + - Open GitHub Desktop and login with your GitHub account + - Click on `File` -> `Clone Repository` select `github.com` as the repository location, then select your forked Coolify repository, choose the local path and then click `Clone` + +4. Open the cloned Coolify Repository in your chosen code editor. + + +## 4. Set up Environment Variables +1. In the Code Editor, locate the `.env.development.example` file in the root directory of your local Coolify repository. +2. Duplicate the `.env.development.example` file and rename the copy to `.env`. +3. Open the new `.env` file and review its contents. Adjust any environment variables as needed for your development setup. +4. If you encounter errors during database migrations, update the database connection settings in your `.env` file. Use the IP address or hostname of your PostgreSQL database container. You can find this information by running `docker ps` after executing `spin up`. +5. Save the changes to your `.env` file. + + +## 5. Start Coolify +1. Open a terminal in the local Coolify directory. +2. Run the following command in the terminal (leave that terminal open): + ```bash + spin up + ``` + +> [!NOTE] +> You may see some errors, but don't worry; this is expected. + +3. If you encounter permission errors, especially on macOS, use: + ```bash + sudo spin up + ``` + +> [!NOTE] +> If you change environment variables afterwards or anything seems broken, press Ctrl + C to stop the process and run `spin up` again. + + +## 6. Start Development +1. Access your Coolify instance: + - URL: `http://localhost:8000` + - Login: `test@example.com` + - Password: `password` + +2. Additional development tools: + + | Tool | URL | Note | + |------|-----|------| + | Laravel Horizon (scheduler) | `http://localhost:8000/horizon` | Only accessible when logged in as root user | + | Mailpit (email catcher) | `http://localhost:8025` | | + | Telescope (debugging tool) | `http://localhost:8000/telescope` | Disabled by default | + +> [!NOTE] +> To enable Telescope, add the following to your `.env` file: +> ```env +> TELESCOPE_ENABLED=true +> ``` + + +## Development Notes +When working on Coolify, keep the following in mind: + +1. **Database Migrations**: After switching branches or making changes to the database structure, always run migrations: + ```bash + docker exec -it coolify php artisan migrate + ``` + +2. **Resetting Development Setup**: To reset your development setup to a clean database with default values: + ```bash + docker exec -it coolify php artisan migrate:fresh --seed + ``` + +3. **Troubleshooting**: If you encounter unexpected behavior, ensure your database is up-to-date with the latest migrations and if possible reset the development setup to eliminate any environment-specific issues. + +> [!IMPORTANT] +> Forgetting to migrate the database can cause problems, so make it a habit to run migrations after pulling changes or switching branches. + + +## Resetting Development Environment +If you encounter issues or break your database or something else, follow these steps to start from a clean slate (works since `v4.0.0-beta.342`): + +1. Stop all running containers `ctrl + c`. + +2. Remove all Coolify containers: + ```bash + docker rm coolify coolify-db coolify-redis coolify-realtime coolify-testing-host coolify-minio coolify-vite-1 coolify-mail + ``` + +3. Remove Coolify volumes (it is possible that the volumes have no `coolify` prefix on your machine, in that case remove the prefix from the command): + ```bash + docker volume rm coolify_dev_backups_data coolify_dev_postgres_data coolify_dev_redis_data coolify_dev_coolify_data coolify_dev_minio_data + ``` + +4. Remove unused images: + ```bash + docker image prune -a + ``` + +5. Start Coolify again: + ```bash + spin up + ``` + +6. Run database migrations and seeders: + ```bash + docker exec -it coolify php artisan migrate:fresh --seed + ``` + +After completing these steps, you'll have a fresh development setup. + +> [!IMPORTANT] +> Always run database migrations and seeders after switching branches or pulling updates to ensure your local database structure matches the current codebase and includes necessary seed data. + + +## Additional Development Guidelines +### Adding a New Service +To add a new service to Coolify, please refer to our documentation: [Adding a New Service](https://coolify.io/docs/get-started/contribute/service) + +### Development for Documentation +To contribute to the Coolify documentation, please refer to this guide: [Contributing to the Coolify Documentation](https://coolify.io/docs/get-started/contribute/documentation) \ No newline at end of file From 84224d63666a3d66ebc25fb3f79843dcfaff7099 Mon Sep 17 00:00:00 2001 From: ShadowArcanist <162910371+ShadowArcanist@users.noreply.github.com> Date: Tue, 24 Feb 2026 00:49:45 +0530 Subject: [PATCH 03/30] chore(repo): improve bug report issue template --- .github/ISSUE_TEMPLATE/01_BUG_REPORT.yml | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml index 42df4785e..b785ba5be 100644 --- a/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml +++ b/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml @@ -1,7 +1,7 @@ name: 🐞 Bug Report description: "File a new bug report." title: "[Bug]: " -labels: ["🐛 Bug", "🔍 Triage"] +labels: ["🔍 Triage"] body: - type: markdown attributes: @@ -14,10 +14,22 @@ body: - type: textarea attributes: - label: Error Message and Logs + label: Description and Error Message description: Provide a detailed description of the error or exception you encountered, along with any relevant log output. validations: required: true + + - type: textarea + attributes: + label: Expected Behavior + description: Please describe what you expected to happen instead of the issue. Be as detailed as possible. + value: | + 1. + 2. + 3. + 4. + validations: + required: true - type: textarea attributes: @@ -58,6 +70,12 @@ body: label: Operating System and Version (self-hosted) description: Run `cat /etc/os-release` or `lsb_release -a` in your terminal and provide the operating system and version. placeholder: "Ubuntu 22.04" + + - type: textarea + attributes: + label: Screenshots / Visuals + description: If possible, provide screenshots, screen recordings, or diagrams to help illustrate the issue. + placeholder: "Attach images or provide links to recordings demonstrating the problem." - type: textarea attributes: From 2b04153dece1a131910bf2fcd4cfeb97f87e4e1f Mon Sep 17 00:00:00 2001 From: ShadowArcanist <162910371+ShadowArcanist@users.noreply.github.com> Date: Tue, 24 Feb 2026 00:50:46 +0530 Subject: [PATCH 04/30] chore(repo): improve enhancement bounty issue template --- .../ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml b/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml index ef26125e0..b71f32bd2 100644 --- a/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml +++ b/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml @@ -20,6 +20,7 @@ body: - New Feature - New Service - Improvement + - Bug Fix validations: required: true @@ -29,3 +30,25 @@ body: description: Provide a detailed description of the feature, improvement, or service you are proposing. validations: required: true + + - type: textarea + attributes: + label: Requirements / How It Should Work + description: Describe in detail how the feature, service, or improvement should function. Include user flow, expected behavior, or technical implementation notes if applicable. + value: | + 1. + 2. + 3. + validations: + required: true + + - type: textarea + attributes: + label: Criteria to Satisfy Bounty + description: Define the conditions that must be met for the PR or contribution to be considered complete and eligible for the bounty. Be specific about functionality, tests, or documentation requirements. + value: | + 1. + 2. + 3. + validations: + required: true \ No newline at end of file From fe855cf8d0930d2b0e76994b2ed72634ff8240c8 Mon Sep 17 00:00:00 2001 From: Poul Date: Mon, 25 May 2026 11:15:08 +0000 Subject: [PATCH 05/30] feat(api): add REST endpoints for destinations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Destinations section is exposed in the Coolify UI but not via the REST API. The destination_uuid field is required when creating applications via create-public-application, but no way to enumerate or create destinations programmatically existed — this blocks IaC tools (e.g. an Aspire publisher targeting Coolify). Adds, scoped to the existing v1 auth:sanctum + ApiAllowed + api.sensitive group: GET /api/v1/destinations GET /api/v1/destinations/{uuid} DELETE /api/v1/destinations/{uuid} GET /api/v1/servers/{server_uuid}/destinations POST /api/v1/servers/{server_uuid}/destinations The controller uses the existing inline-Validator convention (no Form Request classes per the API surface's house style), reuses StandaloneDocker::ownedByCurrentTeamAPI / SwarmDocker::ownedByCurrentTeamAPI for team scoping (matching ScheduledTasksController etc.), and respects the `attachedTo()` guard on delete. No migrations needed — both standalone_dockers and swarm_dockers tables already carry uuid/name/network/server_id/timestamps. OpenAPI @OA\ annotations omitted in this commit to keep the diff minimal; a follow-up can add them in the style of ServersController. --- .../Api/DestinationsController.php | 105 ++++++++++++++++++ routes/api.php | 8 ++ 2 files changed, 113 insertions(+) create mode 100644 app/Http/Controllers/Api/DestinationsController.php diff --git a/app/Http/Controllers/Api/DestinationsController.php b/app/Http/Controllers/Api/DestinationsController.php new file mode 100644 index 000000000..43fb0cba8 --- /dev/null +++ b/app/Http/Controllers/Api/DestinationsController.php @@ -0,0 +1,105 @@ + $d->id, + 'uuid' => $d->uuid, + 'name' => $d->name, + 'network' => $d->network, + 'type' => $d instanceof SwarmDocker ? 'swarm' : 'standalone', + 'server_uuid' => $d->server?->uuid, + 'created_at' => $d->created_at, + 'updated_at' => $d->updated_at, + ]; + } + + public function index(Request $request) + { + $teamId = auth()->user()->currentTeam()->id; + $standalone = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->get(); + $swarm = SwarmDocker::ownedByCurrentTeamAPI($teamId)->get(); + + return response()->json($standalone->concat($swarm)->map(fn ($d) => $this->transform($d))->values()); + } + + public function index_by_server(Request $request, string $server_uuid) + { + $teamId = auth()->user()->currentTeam()->id; + $server = Server::ownedByCurrentTeamAPI($teamId)->whereUuid($server_uuid)->firstOrFail(); + $list = $server->standaloneDockers->concat($server->swarmDockers); + + return response()->json($list->map(fn ($d) => $this->transform($d))->values()); + } + + public function show(Request $request, string $uuid) + { + $teamId = auth()->user()->currentTeam()->id; + $d = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->first() + ?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->firstOrFail(); + + return response()->json($this->transform($d)); + } + + public function create(Request $request, string $server_uuid) + { + $teamId = auth()->user()->currentTeam()->id; + $server = Server::ownedByCurrentTeamAPI($teamId)->whereUuid($server_uuid)->firstOrFail(); + + $allowed = ['name', 'network', 'type']; + $extra = array_diff(array_keys($request->all()), $allowed); + if (! empty($extra)) { + return response()->json(['message' => 'Unknown fields', 'fields' => array_values($extra)], 422); + } + + $validator = Validator::make($request->all(), [ + 'name' => 'nullable|string|max:255', + 'network' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/'], + 'type' => 'nullable|in:standalone,swarm', + ]); + if ($validator->fails()) { + return response()->json(['message' => 'Validation failed', 'errors' => $validator->errors()], 422); + } + + $type = $request->input('type', 'standalone'); + $name = $request->input('name') ?: ($server->name.'-'.$request->input('network')); + $class = $type === 'swarm' ? SwarmDocker::class : StandaloneDocker::class; + + $exists = $class::where('server_id', $server->id)->where('network', $request->input('network'))->exists(); + if ($exists) { + return response()->json(['message' => 'A destination with this network already exists on the server.'], 409); + } + + $d = $class::create([ + 'name' => $name, + 'network' => $request->input('network'), + 'server_id' => $server->id, + ]); + + return response()->json(['uuid' => $d->uuid], 201); + } + + public function delete(Request $request, string $uuid) + { + $teamId = auth()->user()->currentTeam()->id; + $d = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->first() + ?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->firstOrFail(); + if ($d->attachedTo()) { + return response()->json(['message' => 'Destination has attached resources, detach first.'], 409); + } + $d->delete(); + + return response()->json(['message' => 'Deleted.']); + } +} diff --git a/routes/api.php b/routes/api.php index cc380b2be..cd98df9ec 100644 --- a/routes/api.php +++ b/routes/api.php @@ -4,6 +4,7 @@ use App\Http\Controllers\Api\ApplicationsController; use App\Http\Controllers\Api\CloudProviderTokensController; use App\Http\Controllers\Api\DatabasesController; use App\Http\Controllers\Api\DeployController; +use App\Http\Controllers\Api\DestinationsController; use App\Http\Controllers\Api\GithubController; use App\Http\Controllers\Api\HetznerController; use App\Http\Controllers\Api\OtherController; @@ -87,6 +88,13 @@ Route::group([ Route::get('/servers/{uuid}/domains', [ServersController::class, 'domains_by_server'])->middleware(['api.ability:read']); Route::get('/servers/{uuid}/resources', [ServersController::class, 'resources_by_server'])->middleware(['api.ability:read']); + // Destinations — REST surface for the Coolify "Destinations" UI section (added). + Route::get('/destinations', [DestinationsController::class, 'index'])->middleware(['api.ability:read']); + Route::get('/destinations/{uuid}', [DestinationsController::class, 'show'])->middleware(['api.ability:read']); + Route::delete('/destinations/{uuid}', [DestinationsController::class, 'delete'])->middleware(['api.ability:write']); + Route::get('/servers/{server_uuid}/destinations', [DestinationsController::class, 'index_by_server'])->middleware(['api.ability:read']); + Route::post('/servers/{server_uuid}/destinations', [DestinationsController::class, 'create'])->middleware(['api.ability:write']); + Route::get('/servers/{uuid}/validate', [ServersController::class, 'validate_server'])->middleware(['api.ability:write']); Route::post('/servers', [ServersController::class, 'create_server'])->middleware(['api.ability:write']); From 789e2c5cab41242659b59e425671a7bc0bf9891e Mon Sep 17 00:00:00 2001 From: Poul Date: Mon, 25 May 2026 11:36:26 +0000 Subject: [PATCH 06/30] fix(api/destinations): use getTeamIdFromToken() like other Api controllers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Initial draft called auth()->user()->currentTeam() which returns null in the API context (Sanctum tokens don't carry the per-user currentTeam state — that's a session/Livewire concept). Other Api controllers (ServersController, ScheduledTasksController, etc.) use the canonical helper getTeamIdFromToken() with a null guard returning 403. This swap makes all five endpoints work against a real token. --- .../Api/DestinationsController.php | 35 ++++++++++++++++--- 1 file changed, 30 insertions(+), 5 deletions(-) diff --git a/app/Http/Controllers/Api/DestinationsController.php b/app/Http/Controllers/Api/DestinationsController.php index 43fb0cba8..cd6c187b6 100644 --- a/app/Http/Controllers/Api/DestinationsController.php +++ b/app/Http/Controllers/Api/DestinationsController.php @@ -25,9 +25,22 @@ class DestinationsController extends Controller ]; } + private function teamIdOrAbort(): int|\Illuminate\Http\JsonResponse + { + $teamId = getTeamIdFromToken(); + if (is_null($teamId)) { + return response()->json(['message' => 'You are not allowed to access the API.'], 403); + } + + return $teamId; + } + public function index(Request $request) { - $teamId = auth()->user()->currentTeam()->id; + $teamId = $this->teamIdOrAbort(); + if (! is_int($teamId)) { + return $teamId; + } $standalone = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->get(); $swarm = SwarmDocker::ownedByCurrentTeamAPI($teamId)->get(); @@ -36,7 +49,10 @@ class DestinationsController extends Controller public function index_by_server(Request $request, string $server_uuid) { - $teamId = auth()->user()->currentTeam()->id; + $teamId = $this->teamIdOrAbort(); + if (! is_int($teamId)) { + return $teamId; + } $server = Server::ownedByCurrentTeamAPI($teamId)->whereUuid($server_uuid)->firstOrFail(); $list = $server->standaloneDockers->concat($server->swarmDockers); @@ -45,7 +61,10 @@ class DestinationsController extends Controller public function show(Request $request, string $uuid) { - $teamId = auth()->user()->currentTeam()->id; + $teamId = $this->teamIdOrAbort(); + if (! is_int($teamId)) { + return $teamId; + } $d = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->first() ?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->firstOrFail(); @@ -54,7 +73,10 @@ class DestinationsController extends Controller public function create(Request $request, string $server_uuid) { - $teamId = auth()->user()->currentTeam()->id; + $teamId = $this->teamIdOrAbort(); + if (! is_int($teamId)) { + return $teamId; + } $server = Server::ownedByCurrentTeamAPI($teamId)->whereUuid($server_uuid)->firstOrFail(); $allowed = ['name', 'network', 'type']; @@ -92,7 +114,10 @@ class DestinationsController extends Controller public function delete(Request $request, string $uuid) { - $teamId = auth()->user()->currentTeam()->id; + $teamId = $this->teamIdOrAbort(); + if (! is_int($teamId)) { + return $teamId; + } $d = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->first() ?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->firstOrFail(); if ($d->attachedTo()) { From 68e9184b57962c7c5c8f30e531e9ec69a73290b9 Mon Sep 17 00:00:00 2001 From: Poul Date: Mon, 25 May 2026 11:47:10 +0000 Subject: [PATCH 07/30] fix(api/destinations): use whereHas instead of ownedByCurrentTeamAPI for back-compat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The ownedByCurrentTeamAPI scope was added to StandaloneDocker/SwarmDocker *after* 4.0.0-beta.470 — running containers on that beta hit a BadMethodCallException. Rewrites all team scoping to use whereHas('server', whereTeamId) which works against any v4.x of Coolify (StandaloneDocker.server_id -> Server.team_id has been there since the multi-team change). Also guards attachedTo() with method_exists and falls back to a manual attached-resource check covering applications + every standalone DB relation, so delete() doesn't crash on older versions either. --- .../Api/DestinationsController.php | 62 +++++++++++++++---- 1 file changed, 51 insertions(+), 11 deletions(-) diff --git a/app/Http/Controllers/Api/DestinationsController.php b/app/Http/Controllers/Api/DestinationsController.php index cd6c187b6..5db11624b 100644 --- a/app/Http/Controllers/Api/DestinationsController.php +++ b/app/Http/Controllers/Api/DestinationsController.php @@ -25,6 +25,9 @@ class DestinationsController extends Controller ]; } + /** + * Resolve the calling token's team id, or return a 403 response. + */ private function teamIdOrAbort(): int|\Illuminate\Http\JsonResponse { $teamId = getTeamIdFromToken(); @@ -35,16 +38,33 @@ class DestinationsController extends Controller return $teamId; } + /** + * StandaloneDocker / SwarmDocker scoped to a team via their parent server. + * Uses whereHas instead of the model's ownedByCurrentTeamAPI() scope so the + * controller works on Coolify versions that pre-date that scope being added + * to the destination models (e.g. 4.0.0-beta.470). + */ + private function teamScopedDockers(int $teamId) + { + return [ + 'standalone' => StandaloneDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->get(), + 'swarm' => SwarmDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->get(), + ]; + } + public function index(Request $request) { $teamId = $this->teamIdOrAbort(); if (! is_int($teamId)) { return $teamId; } - $standalone = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->get(); - $swarm = SwarmDocker::ownedByCurrentTeamAPI($teamId)->get(); + $sets = $this->teamScopedDockers($teamId); - return response()->json($standalone->concat($swarm)->map(fn ($d) => $this->transform($d))->values()); + return response()->json( + $sets['standalone']->concat($sets['swarm']) + ->map(fn ($d) => $this->transform($d)) + ->values() + ); } public function index_by_server(Request $request, string $server_uuid) @@ -53,7 +73,7 @@ class DestinationsController extends Controller if (! is_int($teamId)) { return $teamId; } - $server = Server::ownedByCurrentTeamAPI($teamId)->whereUuid($server_uuid)->firstOrFail(); + $server = Server::whereTeamId($teamId)->whereUuid($server_uuid)->firstOrFail(); $list = $server->standaloneDockers->concat($server->swarmDockers); return response()->json($list->map(fn ($d) => $this->transform($d))->values()); @@ -65,8 +85,8 @@ class DestinationsController extends Controller if (! is_int($teamId)) { return $teamId; } - $d = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->first() - ?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->firstOrFail(); + $d = StandaloneDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->first() + ?? SwarmDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->firstOrFail(); return response()->json($this->transform($d)); } @@ -77,7 +97,7 @@ class DestinationsController extends Controller if (! is_int($teamId)) { return $teamId; } - $server = Server::ownedByCurrentTeamAPI($teamId)->whereUuid($server_uuid)->firstOrFail(); + $server = Server::whereTeamId($teamId)->whereUuid($server_uuid)->firstOrFail(); $allowed = ['name', 'network', 'type']; $extra = array_diff(array_keys($request->all()), $allowed); @@ -118,10 +138,30 @@ class DestinationsController extends Controller if (! is_int($teamId)) { return $teamId; } - $d = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->first() - ?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->whereUuid($uuid)->firstOrFail(); - if ($d->attachedTo()) { - return response()->json(['message' => 'Destination has attached resources, detach first.'], 409); + $d = StandaloneDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->first() + ?? SwarmDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->firstOrFail(); + + // Guard against deleting destinations with attached resources. attachedTo() + // is recent on the destination models; fall back to a manual check for + // older Coolify versions (e.g. 4.0.0-beta.470). + if (method_exists($d, 'attachedTo')) { + if ($d->attachedTo()) { + return response()->json(['message' => 'Destination has attached resources, detach first.'], 409); + } + } else { + $hasAttached = $d->applications()->exists() + || $d->postgresqls()->exists() + || (method_exists($d, 'mysqls') && $d->mysqls()->exists()) + || (method_exists($d, 'mariadbs') && $d->mariadbs()->exists()) + || (method_exists($d, 'mongodbs') && $d->mongodbs()->exists()) + || (method_exists($d, 'redis') && $d->redis()->exists()) + || (method_exists($d, 'keydbs') && $d->keydbs()->exists()) + || (method_exists($d, 'dragonflies') && $d->dragonflies()->exists()) + || (method_exists($d, 'clickhouses') && $d->clickhouses()->exists()) + || (method_exists($d, 'services') && $d->services()->exists()); + if ($hasAttached) { + return response()->json(['message' => 'Destination has attached resources, detach first.'], 409); + } } $d->delete(); From 7b5415fdbea32bb90cecb72cdc4a0e0f99db30c7 Mon Sep 17 00:00:00 2001 From: ShadowArcanist <162910371+ShadowArcanist@users.noreply.github.com> Date: Sat, 13 Jun 2026 20:15:25 +0530 Subject: [PATCH 08/30] fix(repo): remove beta from placeholder values on issue template --- .github/ISSUE_TEMPLATE/01_BUG_REPORT.yml | 2 +- .../ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml | 54 ------------------- 2 files changed, 1 insertion(+), 55 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml diff --git a/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml index b236a07e2..d5106ab75 100644 --- a/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml +++ b/.github/ISSUE_TEMPLATE/01_BUG_REPORT.yml @@ -49,7 +49,7 @@ body: attributes: label: Coolify Version description: Please provide the Coolify version you are using. This can be found in the top left corner of your Coolify dashboard. - placeholder: "v4.0.0-beta.335" + placeholder: "v4.1.2" validations: required: true diff --git a/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml b/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml deleted file mode 100644 index b71f32bd2..000000000 --- a/.github/ISSUE_TEMPLATE/02_ENHANCEMENT_BOUNTY.yml +++ /dev/null @@ -1,54 +0,0 @@ -name: 💎 Enhancement Bounty -description: "Propose a new feature, service, or improvement with an attached bounty." -title: "[Enhancement]: " -labels: ["✨ Enhancement", "🔍 Triage"] -body: - - type: markdown - attributes: - value: | - > [!IMPORTANT] - > **This issue template is exclusively for proposing new features, services, or improvements with an attached bounty.** Enhancements without a bounty can be discussed in the appropriate category of [Github Discussions](https://github.com/coollabsio/coolify/discussions). - - # 💎 Add a Bounty (with [algora.io](https://console.algora.io/org/coollabsio/bounties/new)) - - [Click here to add the required bounty](https://console.algora.io/org/coollabsio/bounties/new) - - - type: dropdown - attributes: - label: Request Type - description: Select the type of request you are making. - options: - - New Feature - - New Service - - Improvement - - Bug Fix - validations: - required: true - - - type: textarea - attributes: - label: Description - description: Provide a detailed description of the feature, improvement, or service you are proposing. - validations: - required: true - - - type: textarea - attributes: - label: Requirements / How It Should Work - description: Describe in detail how the feature, service, or improvement should function. Include user flow, expected behavior, or technical implementation notes if applicable. - value: | - 1. - 2. - 3. - validations: - required: true - - - type: textarea - attributes: - label: Criteria to Satisfy Bounty - description: Define the conditions that must be met for the PR or contribution to be considered complete and eligible for the bounty. Be specific about functionality, tests, or documentation requirements. - value: | - 1. - 2. - 3. - validations: - required: true \ No newline at end of file From 62d9e401861384e884bf44d9ebd422d3a120a429 Mon Sep 17 00:00:00 2001 From: ShadowArcanist <162910371+ShadowArcanist@users.noreply.github.com> Date: Sat, 13 Jun 2026 20:24:44 +0530 Subject: [PATCH 09/30] fix(repo): remove bounty and beta referrences on contributors guidelines --- CONTRIBUTING.md | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6632cc68f..12a9bdf35 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,14 +27,14 @@ This is normal for a two-maintainer project. ## State of the Project -Coolify is currently at v4 and is still in beta. While v4 is stable, it has some limitations, including: +Coolify is currently at v4. While v4 is stable, it has some limitations, including: - Limited scaling support - A more complex user experience - Other smaller issues that need refinement -These limitations will be addressed in Coolify v5, which is in the planning stage. However, the maintainers are focused on releasing a stable v4 version before dedicating time to v5 development. Because of this, major features, architectural changes, or significant UI changes will not be accepted for v4 at this stage. +These limitations will be addressed in Coolify v5, which is in the planning stage. Because of this, major features, architectural changes, or significant UI changes will not be accepted for v4 at this stage. -We welcome contributions that help stabilize v4, but larger changes will be saved for v5 once we have a stable v4 release. +We welcome contributions that help stabilize v4 for a bug free experience. ## What Makes a Strong Contribution @@ -122,7 +122,7 @@ Bug reports must include: - Expected result - Actual result -Incomplete reports may be closed. +Incomplete reports and reports generated using AI may be closed. ## 3. Code Contributions @@ -177,7 +177,7 @@ AI-generated pull requests without clear understanding will be closed. ## Test Before Submitting Before submitting a pull request: -- Test your changes thoroughly +- Manually test your changes thoroughly - Verify they work in a clean environment - Provide detailed testing steps in the PR description @@ -186,22 +186,12 @@ If maintainers cannot reproduce working behavior, the PR will be closed without ## Submitting a Pull Request - GitHub will auto-populate the PR template -- The contributor agreement must remain intact +- The contributor agreement in PR description must remain intact - Pull requests without the contributor agreement will be closed - All pull requests must target the `next` branch - PRs targeting other branches will be closed without review -## Bounty Issues -Community members may create bounty issues for features or improvements. - -Important: -- Only existing contributors are eligible -- First-time contributors targeting bounty issues will be automatically closed and maybe excluded from contributing. - -This policy exists to prevent spam. We close 30+ bounty-targeted spam PRs per week. - - ## FAQ **Q: Should I ask before fixing a typo or a small bug?** A: No, small, obvious fixes like typos or narrowly-scoped bug fixes can be submitted as a PR directly. @@ -210,7 +200,7 @@ A: No, small, obvious fixes like typos or narrowly-scoped bug fixes can be submi A: Awesome! Discuss it first in GitHub Discussions or Discord. **Do not** open a PR for new features without prior alignment. **Q: My PR was closed without detailed feedback.** -A: This usually means it didn’t align with the project’s direction, required more review bandwidth than available, or targeted major changes not allowed in v4. This is normal for a two-maintainer project. +A: This usually means it didn’t align with the project’s direction, required more review bandwidth than available, or targeted major changes not allowed in v4. **Q: Can I work on an open issue?** A: Comment on the issue first to confirm it’s still relevant and that no one else is actively working on it. For anything beyond a small fix, discuss your approach before implementing. @@ -221,9 +211,6 @@ A: Focus only on your stated goal. Cleanups or refactors should be submitted as **Q: Can I use AI to help with my PR?** A: Yes, AI-assisted contributions are allowed. But you must fully understand and verify the changes. PRs that appear to be generated by AI without context understanding will be closed. -**Q: Can I work on a bounty issue as a first-time contributor?** -A: No, bounty issues are reserved for existing contributors. First-time contributors targeting bounty issues will have their PRs closed without review. This prevents spam and ensures bounties go to contributors familiar with the project. - **Q: My PR was closed without review. Can I submit a new one?** A: Yes, but keep in mind a PR closure is feedback, not a rejection of your effort. It usually means the PR didn’t match the project goals or guidelines. Address these issues first — repeating the same approach may hurt your standing with maintainers. From 9665aa292c935004781b90bec0b79270ded873d6 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Mon, 15 Jun 2026 17:03:01 +0200 Subject: [PATCH 10/30] fix(api): block invalid destination types and service deletions --- .../Api/DestinationsController.php | 16 +- app/Models/StandaloneDocker.php | 2 +- app/Models/SwarmDocker.php | 2 +- tests/Feature/Api/DestinationsApiTest.php | 200 ++++++++++++++++++ 4 files changed, 216 insertions(+), 4 deletions(-) create mode 100644 tests/Feature/Api/DestinationsApiTest.php diff --git a/app/Http/Controllers/Api/DestinationsController.php b/app/Http/Controllers/Api/DestinationsController.php index 5db11624b..8b54913e7 100644 --- a/app/Http/Controllers/Api/DestinationsController.php +++ b/app/Http/Controllers/Api/DestinationsController.php @@ -6,6 +6,7 @@ use App\Http\Controllers\Controller; use App\Models\Server; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; +use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; @@ -28,7 +29,7 @@ class DestinationsController extends Controller /** * Resolve the calling token's team id, or return a 403 response. */ - private function teamIdOrAbort(): int|\Illuminate\Http\JsonResponse + private function teamIdOrAbort(): int|JsonResponse { $teamId = getTeamIdFromToken(); if (is_null($teamId)) { @@ -97,6 +98,12 @@ class DestinationsController extends Controller if (! is_int($teamId)) { return $teamId; } + + $return = validateIncomingRequest($request); + if ($return instanceof JsonResponse) { + return $return; + } + $server = Server::whereTeamId($teamId)->whereUuid($server_uuid)->firstOrFail(); $allowed = ['name', 'network', 'type']; @@ -114,7 +121,12 @@ class DestinationsController extends Controller return response()->json(['message' => 'Validation failed', 'errors' => $validator->errors()], 422); } - $type = $request->input('type', 'standalone'); + $expectedType = $server->isSwarm() ? 'swarm' : 'standalone'; + $type = $request->input('type', $expectedType); + if ($type !== $expectedType) { + return response()->json(['message' => "Destination type must be {$expectedType} for this server."], 422); + } + $name = $request->input('name') ?: ($server->name.'-'.$request->input('network')); $class = $type === 'swarm' ? SwarmDocker::class : StandaloneDocker::class; diff --git a/app/Models/StandaloneDocker.php b/app/Models/StandaloneDocker.php index 1c5cfd342..c1dd4bf67 100644 --- a/app/Models/StandaloneDocker.php +++ b/app/Models/StandaloneDocker.php @@ -144,6 +144,6 @@ class StandaloneDocker extends BaseModel public function attachedTo() { - return $this->applications?->count() > 0 || $this->databases()->count() > 0; + return $this->applications()->exists() || $this->databases()->count() > 0 || $this->services()->exists(); } } diff --git a/app/Models/SwarmDocker.php b/app/Models/SwarmDocker.php index 0e9620457..02b8381d9 100644 --- a/app/Models/SwarmDocker.php +++ b/app/Models/SwarmDocker.php @@ -124,6 +124,6 @@ class SwarmDocker extends BaseModel public function attachedTo() { - return $this->applications?->count() > 0 || $this->databases()->count() > 0; + return $this->applications()->exists() || $this->databases()->count() > 0 || $this->services()->exists(); } } diff --git a/tests/Feature/Api/DestinationsApiTest.php b/tests/Feature/Api/DestinationsApiTest.php new file mode 100644 index 000000000..cbbd6d0a6 --- /dev/null +++ b/tests/Feature/Api/DestinationsApiTest.php @@ -0,0 +1,200 @@ + 'array', + 'session.driver' => 'array', + 'queue.default' => 'sync', + 'app.maintenance.driver' => 'file', + ]); + + InstanceSettings::unguarded(fn () => InstanceSettings::firstOrCreate( + ['id' => 0], + ['is_api_enabled' => true], + )); + + $this->team = Team::factory()->create(); + $this->user = User::factory()->create(); + $this->team->members()->attach($this->user->id, ['role' => 'owner']); + session(['currentTeam' => $this->team]); + + $this->bearerToken = destinationsApiToken($this->user, $this->team, ['*']); + $this->server = Server::factory()->create(['team_id' => $this->team->id]); + $this->destination = StandaloneDocker::where('server_id', $this->server->id)->first(); +}); + +function destinationsApiHeaders(string $bearerToken): array +{ + return [ + 'Authorization' => 'Bearer '.$bearerToken, + 'Content-Type' => 'application/json', + ]; +} + +function destinationsApiToken(User $user, Team $team, array $abilities): string +{ + $plainTextToken = Str::random(40); + $token = $user->tokens()->create([ + 'name' => 'destinations-api-test-'.Str::random(6), + 'token' => hash('sha256', $plainTextToken), + 'abilities' => $abilities, + 'team_id' => $team->id, + ]); + + return $token->getKey().'|'.$plainTextToken; +} + +describe('GET /api/v1/destinations', function () { + test('lists only destinations owned by the token team', function () { + $otherTeam = Team::factory()->create(); + $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]); + $otherDestination = StandaloneDocker::where('server_id', $otherServer->id)->first(); + + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->getJson('/api/v1/destinations'); + + $response->assertOk(); + $uuids = collect($response->json())->pluck('uuid'); + + expect($uuids)->toContain($this->destination->uuid) + ->not->toContain($otherDestination->uuid); + }); +}); + +describe('GET /api/v1/destinations/{uuid}', function () { + test('does not expose another team destination', function () { + $otherTeam = Team::factory()->create(); + $otherServer = Server::factory()->create(['team_id' => $otherTeam->id]); + $otherDestination = StandaloneDocker::where('server_id', $otherServer->id)->first(); + + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->getJson("/api/v1/destinations/{$otherDestination->uuid}"); + + $response->assertNotFound(); + }); +}); + +describe('GET /api/v1/servers/{server_uuid}/destinations', function () { + test('lists destinations for a team server', function () { + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->getJson("/api/v1/servers/{$this->server->uuid}/destinations"); + + $response->assertOk(); + expect($response->json())->toHaveCount(1) + ->and($response->json('0.uuid'))->toBe($this->destination->uuid); + }); +}); + +describe('POST /api/v1/servers/{server_uuid}/destinations', function () { + test('requires a write token', function () { + $readOnlyToken = destinationsApiToken($this->user, $this->team, ['read']); + + $response = $this->withHeaders(destinationsApiHeaders($readOnlyToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => 'new-network', + ]); + + $response->assertForbidden(); + }); + + test('rejects non-json requests before creating a destination', function () { + $response = $this->withHeaders([ + 'Authorization' => 'Bearer '.$this->bearerToken, + ])->post("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => 'api-swarm-network', + 'type' => 'swarm', + ]); + + $response->assertStatus(400); + expect(SwarmDocker::where('server_id', $this->server->id)->where('network', 'api-swarm-network')->exists())->toBeFalse(); + }); + + test('rejects unknown fields', function () { + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => 'new-network', + 'unexpected' => 'value', + ]); + + $response->assertStatus(422); + $response->assertJsonPath('fields.0', 'unexpected'); + }); + + test('rejects unsafe docker network names', function () { + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => 'bad;network', + ]); + + $response->assertStatus(422); + $response->assertJsonValidationErrors(['network']); + }); + + test('rejects a destination type that does not match the server mode', function () { + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => 'wrong-type-network', + 'type' => 'swarm', + ]); + + $response->assertStatus(422); + expect(SwarmDocker::where('server_id', $this->server->id)->where('network', 'wrong-type-network')->exists())->toBeFalse(); + }); + + test('creates a swarm destination on a swarm server', function () { + $this->server->settings()->update(['is_swarm_manager' => true]); + + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'name' => 'API Swarm', + 'network' => 'api-swarm-network', + 'type' => 'swarm', + ]); + + $response->assertCreated(); + $response->assertJsonStructure(['uuid']); + expect(SwarmDocker::where('server_id', $this->server->id)->where('network', 'api-swarm-network')->exists())->toBeTrue(); + }); + + test('rejects duplicate networks on the same server and type', function () { + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => $this->destination->network, + ]); + + $response->assertStatus(409); + }); +}); + +describe('DELETE /api/v1/destinations/{uuid}', function () { + test('blocks deleting a destination with an attached service', function () { + $project = Project::factory()->create(['team_id' => $this->team->id]); + $environment = $project->environments()->first(); + + Service::factory()->create([ + 'environment_id' => $environment->id, + 'server_id' => $this->server->id, + 'destination_id' => $this->destination->id, + 'destination_type' => $this->destination->getMorphClass(), + ]); + + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->deleteJson("/api/v1/destinations/{$this->destination->uuid}"); + + $response->assertStatus(409); + $this->assertModelExists($this->destination); + }); +}); From 9e021c4037ff9591511bb02491e9ea9413d929bd Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Mon, 15 Jun 2026 17:15:56 +0200 Subject: [PATCH 11/30] fix(api): enforce destination access and cleanup networks Require admin team membership for destination mutations, return invalid-token responses for tokenless requests, and remove standalone Docker networks when deleting destinations. --- .../RemoveStandaloneDockerNetwork.php | 16 ++ .../Api/DestinationsController.php | 139 +++++++++++------- tests/Feature/Api/DestinationsApiTest.php | 62 +++++++- 3 files changed, 162 insertions(+), 55 deletions(-) create mode 100644 app/Actions/Destination/RemoveStandaloneDockerNetwork.php diff --git a/app/Actions/Destination/RemoveStandaloneDockerNetwork.php b/app/Actions/Destination/RemoveStandaloneDockerNetwork.php new file mode 100644 index 000000000..21c40a50a --- /dev/null +++ b/app/Actions/Destination/RemoveStandaloneDockerNetwork.php @@ -0,0 +1,16 @@ +network); + + instant_remote_process(["docker network disconnect {$safeNetwork} coolify-proxy"], $destination->server, throwError: false); + instant_remote_process(["docker network rm -f {$safeNetwork}"], $destination->server); + } +} diff --git a/app/Http/Controllers/Api/DestinationsController.php b/app/Http/Controllers/Api/DestinationsController.php index 8b54913e7..26836b89a 100644 --- a/app/Http/Controllers/Api/DestinationsController.php +++ b/app/Http/Controllers/Api/DestinationsController.php @@ -2,38 +2,37 @@ namespace App\Http\Controllers\Api; +use App\Actions\Destination\RemoveStandaloneDockerNetwork; use App\Http\Controllers\Controller; use App\Models\Server; use App\Models\StandaloneDocker; use App\Models\SwarmDocker; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Illuminate\Support\Facades\Validator; class DestinationsController extends Controller { - private function transform($d): array + private function transform(StandaloneDocker|SwarmDocker $destination): array { return [ - 'id' => $d->id, - 'uuid' => $d->uuid, - 'name' => $d->name, - 'network' => $d->network, - 'type' => $d instanceof SwarmDocker ? 'swarm' : 'standalone', - 'server_uuid' => $d->server?->uuid, - 'created_at' => $d->created_at, - 'updated_at' => $d->updated_at, + 'uuid' => $destination->uuid, + 'name' => $destination->name, + 'network' => $destination->network, + 'type' => $destination instanceof SwarmDocker ? 'swarm' : 'standalone', + 'server_uuid' => $destination->server?->uuid, + 'created_at' => $destination->created_at, + 'updated_at' => $destination->updated_at, ]; } /** - * Resolve the calling token's team id, or return a 403 response. + * Resolve the calling token's team id, or return an invalid-token response. */ private function teamIdOrAbort(): int|JsonResponse { $teamId = getTeamIdFromToken(); if (is_null($teamId)) { - return response()->json(['message' => 'You are not allowed to access the API.'], 403); + return invalidTokenResponse(); } return $teamId; @@ -45,15 +44,21 @@ class DestinationsController extends Controller * controller works on Coolify versions that pre-date that scope being added * to the destination models (e.g. 4.0.0-beta.470). */ - private function teamScopedDockers(int $teamId) + private function teamScopedDockers(int $teamId): array { return [ - 'standalone' => StandaloneDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->get(), - 'swarm' => SwarmDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->get(), + 'standalone' => StandaloneDocker::with('server:id,uuid')->whereHas('server', fn ($query) => $query->whereTeamId($teamId))->get(), + 'swarm' => SwarmDocker::with('server:id,uuid')->whereHas('server', fn ($query) => $query->whereTeamId($teamId))->get(), ]; } - public function index(Request $request) + private function findDestinationForTeam(int $teamId, string $uuid): StandaloneDocker|SwarmDocker + { + return StandaloneDocker::with('server:id,uuid,team_id,ip,user,port,private_key_id')->whereHas('server', fn ($query) => $query->whereTeamId($teamId))->whereUuid($uuid)->first() + ?? SwarmDocker::with('server:id,uuid,team_id')->whereHas('server', fn ($query) => $query->whereTeamId($teamId))->whereUuid($uuid)->firstOrFail(); + } + + public function index(Request $request): JsonResponse { $teamId = $this->teamIdOrAbort(); if (! is_int($teamId)) { @@ -63,36 +68,38 @@ class DestinationsController extends Controller return response()->json( $sets['standalone']->concat($sets['swarm']) - ->map(fn ($d) => $this->transform($d)) + ->map(fn ($destination) => $this->transform($destination)) ->values() ); } - public function index_by_server(Request $request, string $server_uuid) + public function index_by_server(Request $request, string $server_uuid): JsonResponse { $teamId = $this->teamIdOrAbort(); if (! is_int($teamId)) { return $teamId; } - $server = Server::whereTeamId($teamId)->whereUuid($server_uuid)->firstOrFail(); + $server = Server::with(['standaloneDockers.server:id,uuid', 'swarmDockers.server:id,uuid']) + ->whereTeamId($teamId) + ->whereUuid($server_uuid) + ->firstOrFail(); $list = $server->standaloneDockers->concat($server->swarmDockers); - return response()->json($list->map(fn ($d) => $this->transform($d))->values()); + return response()->json($list->map(fn ($destination) => $this->transform($destination))->values()); } - public function show(Request $request, string $uuid) + public function show(Request $request, string $uuid): JsonResponse { $teamId = $this->teamIdOrAbort(); if (! is_int($teamId)) { return $teamId; } - $d = StandaloneDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->first() - ?? SwarmDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->firstOrFail(); + $destination = $this->findDestinationForTeam($teamId, $uuid); - return response()->json($this->transform($d)); + return response()->json($this->transform($destination)); } - public function create(Request $request, string $server_uuid) + public function create(Request $request, string $server_uuid): JsonResponse { $teamId = $this->teamIdOrAbort(); if (! is_int($teamId)) { @@ -107,18 +114,22 @@ class DestinationsController extends Controller $server = Server::whereTeamId($teamId)->whereUuid($server_uuid)->firstOrFail(); $allowed = ['name', 'network', 'type']; - $extra = array_diff(array_keys($request->all()), $allowed); - if (! empty($extra)) { - return response()->json(['message' => 'Unknown fields', 'fields' => array_values($extra)], 422); - } - $validator = Validator::make($request->all(), [ + $validator = customApiValidator($request->all(), [ 'name' => 'nullable|string|max:255', 'network' => ['required', 'string', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/'], 'type' => 'nullable|in:standalone,swarm', ]); - if ($validator->fails()) { - return response()->json(['message' => 'Validation failed', 'errors' => $validator->errors()], 422); + $extra = array_diff(array_keys($request->all()), $allowed); + if ($validator->fails() || ! empty($extra)) { + $errors = $validator->errors(); + if (! empty($extra)) { + foreach ($extra as $field) { + $errors->add($field, 'This field is not allowed.'); + } + } + + return response()->json(['message' => 'Validation failed.', 'errors' => $errors], 422); } $expectedType = $server->isSwarm() ? 'swarm' : 'standalone'; @@ -130,52 +141,80 @@ class DestinationsController extends Controller $name = $request->input('name') ?: ($server->name.'-'.$request->input('network')); $class = $type === 'swarm' ? SwarmDocker::class : StandaloneDocker::class; + $this->authorize('create', $class); + $exists = $class::where('server_id', $server->id)->where('network', $request->input('network'))->exists(); if ($exists) { return response()->json(['message' => 'A destination with this network already exists on the server.'], 409); } - $d = $class::create([ + $destination = $class::create([ 'name' => $name, 'network' => $request->input('network'), 'server_id' => $server->id, ]); - return response()->json(['uuid' => $d->uuid], 201); + auditLog('api.destination.created', [ + 'team_id' => $teamId, + 'destination_uuid' => $destination->uuid, + 'destination_name' => $destination->name, + 'destination_type' => $type, + 'server_uuid' => $server->uuid, + ]); + + return response()->json($this->transform($destination->load('server:id,uuid')), 201); } - public function delete(Request $request, string $uuid) + public function delete(Request $request, string $uuid): JsonResponse { $teamId = $this->teamIdOrAbort(); if (! is_int($teamId)) { return $teamId; } - $d = StandaloneDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->first() - ?? SwarmDocker::whereHas('server', fn ($q) => $q->whereTeamId($teamId))->whereUuid($uuid)->firstOrFail(); + $destination = $this->findDestinationForTeam($teamId, $uuid); + + $this->authorize('delete', $destination); // Guard against deleting destinations with attached resources. attachedTo() // is recent on the destination models; fall back to a manual check for // older Coolify versions (e.g. 4.0.0-beta.470). - if (method_exists($d, 'attachedTo')) { - if ($d->attachedTo()) { + if (method_exists($destination, 'attachedTo')) { + if ($destination->attachedTo()) { return response()->json(['message' => 'Destination has attached resources, detach first.'], 409); } } else { - $hasAttached = $d->applications()->exists() - || $d->postgresqls()->exists() - || (method_exists($d, 'mysqls') && $d->mysqls()->exists()) - || (method_exists($d, 'mariadbs') && $d->mariadbs()->exists()) - || (method_exists($d, 'mongodbs') && $d->mongodbs()->exists()) - || (method_exists($d, 'redis') && $d->redis()->exists()) - || (method_exists($d, 'keydbs') && $d->keydbs()->exists()) - || (method_exists($d, 'dragonflies') && $d->dragonflies()->exists()) - || (method_exists($d, 'clickhouses') && $d->clickhouses()->exists()) - || (method_exists($d, 'services') && $d->services()->exists()); + $hasAttached = $destination->applications()->exists() + || $destination->postgresqls()->exists() + || (method_exists($destination, 'mysqls') && $destination->mysqls()->exists()) + || (method_exists($destination, 'mariadbs') && $destination->mariadbs()->exists()) + || (method_exists($destination, 'mongodbs') && $destination->mongodbs()->exists()) + || (method_exists($destination, 'redis') && $destination->redis()->exists()) + || (method_exists($destination, 'keydbs') && $destination->keydbs()->exists()) + || (method_exists($destination, 'dragonflies') && $destination->dragonflies()->exists()) + || (method_exists($destination, 'clickhouses') && $destination->clickhouses()->exists()) + || (method_exists($destination, 'services') && $destination->services()->exists()); if ($hasAttached) { return response()->json(['message' => 'Destination has attached resources, detach first.'], 409); } } - $d->delete(); + if ($destination instanceof StandaloneDocker) { + app(RemoveStandaloneDockerNetwork::class)->handle($destination); + } + + $destinationUuid = $destination->uuid; + $destinationName = $destination->name; + $destinationType = $destination instanceof SwarmDocker ? 'swarm' : 'standalone'; + $serverUuid = $destination->server?->uuid; + + $destination->delete(); + + auditLog('api.destination.deleted', [ + 'team_id' => $teamId, + 'destination_uuid' => $destinationUuid, + 'destination_name' => $destinationName, + 'destination_type' => $destinationType, + 'server_uuid' => $serverUuid, + ]); return response()->json(['message' => 'Deleted.']); } diff --git a/tests/Feature/Api/DestinationsApiTest.php b/tests/Feature/Api/DestinationsApiTest.php index cbbd6d0a6..9639c5d9e 100644 --- a/tests/Feature/Api/DestinationsApiTest.php +++ b/tests/Feature/Api/DestinationsApiTest.php @@ -1,5 +1,6 @@ assertOk(); $uuids = collect($response->json())->pluck('uuid'); - expect($uuids)->toContain($this->destination->uuid) + expect($response->json('0'))->not->toHaveKey('id') + ->and($uuids)->toContain($this->destination->uuid) ->not->toContain($otherDestination->uuid); }); }); @@ -110,6 +112,20 @@ describe('POST /api/v1/servers/{server_uuid}/destinations', function () { $response->assertForbidden(); }); + test('rejects create requests from non-admin team members', function () { + $member = User::factory()->create(); + $this->team->members()->attach($member->id, ['role' => 'member']); + $memberToken = destinationsApiToken($member, $this->team, ['*']); + + $response = $this->withHeaders(destinationsApiHeaders($memberToken)) + ->postJson("/api/v1/servers/{$this->server->uuid}/destinations", [ + 'network' => 'member-network', + ]); + + $response->assertForbidden(); + expect(StandaloneDocker::where('server_id', $this->server->id)->where('network', 'member-network')->exists())->toBeFalse(); + }); + test('rejects non-json requests before creating a destination', function () { $response = $this->withHeaders([ 'Authorization' => 'Bearer '.$this->bearerToken, @@ -129,8 +145,8 @@ describe('POST /api/v1/servers/{server_uuid}/destinations', function () { 'unexpected' => 'value', ]); - $response->assertStatus(422); - $response->assertJsonPath('fields.0', 'unexpected'); + $response->assertUnprocessable(); + $response->assertJsonValidationErrors(['unexpected']); }); test('rejects unsafe docker network names', function () { @@ -139,7 +155,7 @@ describe('POST /api/v1/servers/{server_uuid}/destinations', function () { 'network' => 'bad;network', ]); - $response->assertStatus(422); + $response->assertUnprocessable(); $response->assertJsonValidationErrors(['network']); }); @@ -150,7 +166,7 @@ describe('POST /api/v1/servers/{server_uuid}/destinations', function () { 'type' => 'swarm', ]); - $response->assertStatus(422); + $response->assertUnprocessable(); expect(SwarmDocker::where('server_id', $this->server->id)->where('network', 'wrong-type-network')->exists())->toBeFalse(); }); @@ -180,6 +196,42 @@ describe('POST /api/v1/servers/{server_uuid}/destinations', function () { }); describe('DELETE /api/v1/destinations/{uuid}', function () { + test('requires a write token', function () { + $readOnlyToken = destinationsApiToken($this->user, $this->team, ['read']); + + $response = $this->withHeaders(destinationsApiHeaders($readOnlyToken)) + ->deleteJson("/api/v1/destinations/{$this->destination->uuid}"); + + $response->assertForbidden(); + $this->assertModelExists($this->destination); + }); + + test('rejects delete requests from non-admin team members', function () { + $member = User::factory()->create(); + $this->team->members()->attach($member->id, ['role' => 'member']); + $memberToken = destinationsApiToken($member, $this->team, ['*']); + + $response = $this->withHeaders(destinationsApiHeaders($memberToken)) + ->deleteJson("/api/v1/destinations/{$this->destination->uuid}"); + + $response->assertForbidden(); + $this->assertModelExists($this->destination); + }); + + test('deletes standalone destinations after removing the docker network', function () { + $cleanup = Mockery::mock(RemoveStandaloneDockerNetwork::class); + $cleanup->shouldReceive('handle') + ->once() + ->with(Mockery::on(fn (StandaloneDocker $destination) => $destination->is($this->destination))); + $this->app->instance(RemoveStandaloneDockerNetwork::class, $cleanup); + + $response = $this->withHeaders(destinationsApiHeaders($this->bearerToken)) + ->deleteJson("/api/v1/destinations/{$this->destination->uuid}"); + + $response->assertOk(); + $this->assertModelMissing($this->destination); + }); + test('blocks deleting a destination with an attached service', function () { $project = Project::factory()->create(['team_id' => $this->team->id]); $environment = $project->environments()->first(); From bef94a9ce285469aa4f55e44b7374f9e36018320 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 25 Jun 2026 11:42:19 +0200 Subject: [PATCH 12/30] feat(mcp): add per-team server toggle --- app/Http/Kernel.php | 2 ++ app/Http/Middleware/EnsureTeamMcpEnabled.php | 26 +++++++++++++++++++ app/Livewire/Team/Index.php | 5 ++++ app/Models/Team.php | 2 ++ ...d_is_mcp_server_enabled_to_teams_table.php | 22 ++++++++++++++++ .../livewire/settings/advanced.blade.php | 2 +- resources/views/livewire/team/index.blade.php | 2 ++ routes/ai.php | 2 +- .../Authorization/TeamAuthorizationTest.php | 12 +++++++++ tests/Feature/Mcp/McpEndpointTest.php | 10 +++++++ 10 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 app/Http/Middleware/EnsureTeamMcpEnabled.php create mode 100644 database/migrations/2026_06_25_000000_add_is_mcp_server_enabled_to_teams_table.php diff --git a/app/Http/Kernel.php b/app/Http/Kernel.php index 02a49aaa8..9e8dee83e 100644 --- a/app/Http/Kernel.php +++ b/app/Http/Kernel.php @@ -12,6 +12,7 @@ use App\Http\Middleware\CheckForcePasswordReset; use App\Http\Middleware\DecideWhatToDoWithUser; use App\Http\Middleware\EncryptCookies; use App\Http\Middleware\EnsureMcpEnabled; +use App\Http\Middleware\EnsureTeamMcpEnabled; use App\Http\Middleware\EnsureTokenBelongsToCurrentTeamMember; use App\Http\Middleware\PreventRequestsDuringMaintenance; use App\Http\Middleware\RedirectIfAuthenticated; @@ -110,5 +111,6 @@ class Kernel extends HttpKernel 'can.update.resource' => CanUpdateResource::class, 'can.access.terminal' => CanAccessTerminal::class, 'mcp.enabled' => EnsureMcpEnabled::class, + 'mcp.team.enabled' => EnsureTeamMcpEnabled::class, ]; } diff --git a/app/Http/Middleware/EnsureTeamMcpEnabled.php b/app/Http/Middleware/EnsureTeamMcpEnabled.php new file mode 100644 index 000000000..5c76d2a1b --- /dev/null +++ b/app/Http/Middleware/EnsureTeamMcpEnabled.php @@ -0,0 +1,26 @@ +user(); + $teamId = $user?->currentAccessToken()?->team_id; + + $team = $user?->teams() + ->where('teams.id', $teamId) + ->first(); + + if (! $team?->is_mcp_server_enabled) { + return response()->json(['message' => 'MCP server is disabled for this team.'], 403); + } + + return $next($request); + } +} diff --git a/app/Livewire/Team/Index.php b/app/Livewire/Team/Index.php index 140d9f5cc..406d385da 100644 --- a/app/Livewire/Team/Index.php +++ b/app/Livewire/Team/Index.php @@ -24,11 +24,14 @@ class Index extends Component public ?string $description = null; + public bool $is_mcp_server_enabled = true; + protected function rules(): array { return [ 'name' => ValidationPatterns::nameRules(), 'description' => ValidationPatterns::descriptionRules(), + 'is_mcp_server_enabled' => 'boolean', ]; } @@ -58,10 +61,12 @@ class Index extends Component // Sync TO model (before save) $this->team->name = $this->name; $this->team->description = $this->description; + $this->team->is_mcp_server_enabled = $this->is_mcp_server_enabled; } else { // Sync FROM model (on load/refresh) $this->name = $this->team->name; $this->description = $this->team->description; + $this->is_mcp_server_enabled = $this->team->is_mcp_server_enabled; } } diff --git a/app/Models/Team.php b/app/Models/Team.php index 23e2badb3..a979b44fb 100644 --- a/app/Models/Team.php +++ b/app/Models/Team.php @@ -47,10 +47,12 @@ class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, Sen 'personal_team', 'show_boarding', 'custom_server_limit', + 'is_mcp_server_enabled', ]; protected $casts = [ 'personal_team' => 'boolean', + 'is_mcp_server_enabled' => 'boolean', ]; protected static function booted() diff --git a/database/migrations/2026_06_25_000000_add_is_mcp_server_enabled_to_teams_table.php b/database/migrations/2026_06_25_000000_add_is_mcp_server_enabled_to_teams_table.php new file mode 100644 index 000000000..3162a8613 --- /dev/null +++ b/database/migrations/2026_06_25_000000_add_is_mcp_server_enabled_to_teams_table.php @@ -0,0 +1,22 @@ +boolean('is_mcp_server_enabled')->default(true); + }); + } + + public function down(): void + { + Schema::table('teams', function (Blueprint $table) { + $table->dropColumn('is_mcp_server_enabled'); + }); + } +}; diff --git a/resources/views/livewire/settings/advanced.blade.php b/resources/views/livewire/settings/advanced.blade.php index 544ed7d4c..fb7da30a7 100644 --- a/resources/views/livewire/settings/advanced.blade.php +++ b/resources/views/livewire/settings/advanced.blade.php @@ -72,7 +72,7 @@ @endif

MCP Server

-
@if ($is_mcp_server_enabled) diff --git a/resources/views/livewire/team/index.blade.php b/resources/views/livewire/team/index.blade.php index 8f54a57e3..0fbbb114f 100644 --- a/resources/views/livewire/team/index.blade.php +++ b/resources/views/livewire/team/index.blade.php @@ -13,6 +13,8 @@
+ @can('update', $team) Save diff --git a/routes/ai.php b/routes/ai.php index 3a39677ff..d79ff0eba 100644 --- a/routes/ai.php +++ b/routes/ai.php @@ -4,4 +4,4 @@ use App\Mcp\Servers\CoolifyServer; use Laravel\Mcp\Facades\Mcp; Mcp::web('/mcp', CoolifyServer::class) - ->middleware(['mcp.enabled', 'auth:sanctum', 'api.token.team']); + ->middleware(['mcp.enabled', 'auth:sanctum', 'api.token.team', 'mcp.team.enabled']); diff --git a/tests/Feature/Authorization/TeamAuthorizationTest.php b/tests/Feature/Authorization/TeamAuthorizationTest.php index e99e55a2c..6cfc26d99 100644 --- a/tests/Feature/Authorization/TeamAuthorizationTest.php +++ b/tests/Feature/Authorization/TeamAuthorizationTest.php @@ -126,6 +126,18 @@ test('member cannot submit team settings via policy', function () { expect(auth()->user()->can('update', $this->team))->toBeFalse(); }); +test('owner can update team MCP setting', function () { + $this->actingAs($this->owner); + session(['currentTeam' => $this->team]); + + Livewire::test(TeamIndex::class) + ->set('is_mcp_server_enabled', false) + ->call('submit') + ->assertDispatched('success'); + + expect($this->team->fresh()->is_mcp_server_enabled)->toBeFalse(); +}); + // --- Team Index Livewire: delete --- test('member cannot delete team via index', function () { diff --git a/tests/Feature/Mcp/McpEndpointTest.php b/tests/Feature/Mcp/McpEndpointTest.php index b8511afef..f70584ecb 100644 --- a/tests/Feature/Mcp/McpEndpointTest.php +++ b/tests/Feature/Mcp/McpEndpointTest.php @@ -90,6 +90,16 @@ test('MCP endpoint returns 404 when the instance setting is disabled', function $response->assertStatus(404); }); +test('MCP endpoint returns 403 when the token team has MCP disabled', function () { + $this->team->update(['is_mcp_server_enabled' => false]); + $token = $this->user->createToken('mcp-read', ['read'])->plainTextToken; + + $response = mcpListTools($token); + + $response->assertForbidden(); + $response->assertJson(['message' => 'MCP server is disabled for this team.']); +}); + test('MCP endpoint rejects unauthenticated requests', function () { $response = mcpPost(['jsonrpc' => '2.0', 'id' => 1, 'method' => 'tools/list']); $response->assertStatus(401); From 22b31f567149faf3db865cd0791c1867a38fc166 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Wed, 1 Jul 2026 11:14:20 +0200 Subject: [PATCH 13/30] fix(backups): require valid S3 storage selection Preserve S3 backups when a single valid storage is available, require explicit selection when multiple storages exist, and disable S3 when none are available. Make backup action controls responsive on narrow screens. --- app/Livewire/Project/Database/BackupEdit.php | 37 ++++++++-- .../components/modal-confirmation.blade.php | 6 +- .../project/database/backup-edit.blade.php | 59 ++++++++------- .../database/backup-executions.blade.php | 26 ++++--- .../database/backup/execution.blade.php | 2 +- .../database/scheduled-backups.blade.php | 2 +- .../views/livewire/settings-backup.blade.php | 2 +- tests/Feature/BackupEditValidationTest.php | 73 ++++++++++++++++++- 8 files changed, 157 insertions(+), 50 deletions(-) diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php index 99426c120..a387b6f88 100644 --- a/app/Livewire/Project/Database/BackupEdit.php +++ b/app/Livewire/Project/Database/BackupEdit.php @@ -3,10 +3,12 @@ namespace App\Livewire\Project\Database; use App\Jobs\DatabaseBackupJob; +use App\Models\S3Storage; use App\Models\ScheduledDatabaseBackup; use App\Models\ServiceDatabase; use Exception; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; +use Illuminate\Support\Collection; use Livewire\Attributes\Locked; use Livewire\Attributes\Validate; use Livewire\Component; @@ -18,7 +20,7 @@ class BackupEdit extends Component public ScheduledDatabaseBackup $backup; #[Locked] - public $s3s; + public $availableS3Storages; #[Locked] public $parameters; @@ -69,7 +71,7 @@ class BackupEdit extends Component public bool $disableLocalBackup = false; #[Validate(['nullable', 'integer'])] - public ?int $s3StorageId = 1; + public ?int $s3StorageId = null; #[Validate(['nullable', 'string'])] public ?string $databasesToBackup = null; @@ -222,10 +224,18 @@ class BackupEdit extends Component } // S3 backup cannot be enabled without a valid S3 storage owned by the team - $availableS3Ids = collect($this->s3s)->pluck('id'); + $availableS3Ids = $this->availableS3StorageIds(); if ($this->backup->save_s3 && ! $availableS3Ids->contains($this->backup->s3_storage_id)) { - $this->backup->save_s3 = $this->saveS3 = false; - $this->backup->s3_storage_id = $this->s3StorageId = null; + if ($availableS3Ids->isEmpty()) { + $this->backup->s3_storage_id = $this->s3StorageId = null; + $this->backup->save_s3 = $this->saveS3 = false; + } elseif ($this->backup->s3_storage_id === null && $availableS3Ids->count() === 1) { + $this->backup->s3_storage_id = $this->s3StorageId = $availableS3Ids->first(); + } else { + $this->backup->s3_storage_id = $this->s3StorageId = null; + + throw new Exception('Please select a valid S3 storage to enable S3 backups.'); + } } // Validate that disable_local_backup can only be true when S3 backup is enabled @@ -240,6 +250,23 @@ class BackupEdit extends Component $this->validate(); } + private function availableS3StorageIds(): Collection + { + $storages = collect($this->availableS3Storages); + $storageIds = $storages->pluck('id')->filter()->all(); + $teamIds = $storages->pluck('team_id')->reject(fn ($teamId) => $teamId === null)->unique()->values()->all(); + + if (empty($storageIds) || empty($teamIds)) { + return collect(); + } + + return S3Storage::query() + ->whereKey($storageIds) + ->whereIn('team_id', $teamIds) + ->where('is_usable', true) + ->pluck('id'); + } + public function submit() { try { diff --git a/resources/views/components/modal-confirmation.blade.php b/resources/views/components/modal-confirmation.blade.php index 4629e3b96..a25e0141f 100644 --- a/resources/views/components/modal-confirmation.blade.php +++ b/resources/views/components/modal-confirmation.blade.php @@ -129,7 +129,11 @@ } }" @keydown.escape.window="if (modalOpen) { modalOpen = false; resetModal(); }" :class="{ 'z-40': modalOpen }" - class="relative w-auto h-auto"> + @class([ + 'relative h-auto', + 'w-full' => $buttonFullWidth, + 'w-auto' => ! $buttonFullWidth, + ])> @if (isset($trigger))
{{ $trigger }} diff --git a/resources/views/livewire/project/database/backup-edit.blade.php b/resources/views/livewire/project/database/backup-edit.blade.php index 8a4b89e5b..edea7b80f 100644 --- a/resources/views/livewire/project/database/backup-edit.blade.php +++ b/resources/views/livewire/project/database/backup-edit.blade.php @@ -1,32 +1,37 @@
-
+

Scheduled Backup

- - Save - - @if (str($status)->startsWith('running')) - Backup Now - @endif - @if ($backup->database_id !== 0) - - @endif +
+ + Save + + @if (str($status)->startsWith('running')) + Backup Now + @endif + @if ($backup->database_id !== 0) +
+ +
+ @endif +
-
+
- @if ($s3s->count() > 0) + @if ($availableS3Storages->count() > 0) @else @endif - @if ($backup->save_s3) + @if ($saveS3) @else @@ -34,11 +39,11 @@ helper="When enabled, backup files will be deleted from local storage immediately after uploading to S3. This requires S3 backup to be enabled." /> @endif
- @if ($backup->save_s3) -
+ @if ($saveS3) +
- @foreach ($s3s as $s3) + @foreach ($availableS3Storages as $s3) @endforeach @@ -80,7 +85,7 @@ @endif @endif
-
+
@@ -98,7 +103,7 @@

Local Backup Retention

-
+
@@ -111,10 +116,10 @@
- @if ($backup->save_s3) + @if ($saveS3)

S3 Storage Retention

-
+
diff --git a/resources/views/livewire/project/database/backup-executions.blade.php b/resources/views/livewire/project/database/backup-executions.blade.php index b6d88a2fd..15d42a7a5 100644 --- a/resources/views/livewire/project/database/backup-executions.blade.php +++ b/resources/views/livewire/project/database/backup-executions.blade.php @@ -1,7 +1,7 @@
@isset($backup) -
-

Executions ({{ $executions_count }})

+
+

Executions ({{ $executions_count }})

@if ($executions_count > 0)
@@ -21,13 +21,15 @@
@endif - Cleanup Failed Backups - +
+ Cleanup Failed Backups + +
@@ -87,7 +89,7 @@
Location: {{ data_get($execution, 'filename', 'N/A') }}
-
+
Backup Availability:
@@ -154,9 +156,9 @@
{{ data_get($execution, 'message') }}
@endif -
+
@if (data_get($execution, 'status') === 'success') - Download @endif @php diff --git a/resources/views/livewire/project/database/backup/execution.blade.php b/resources/views/livewire/project/database/backup/execution.blade.php index 3e689645f..23c108e8c 100644 --- a/resources/views/livewire/project/database/backup/execution.blade.php +++ b/resources/views/livewire/project/database/backup/execution.blade.php @@ -6,7 +6,7 @@
- +
diff --git a/resources/views/livewire/project/database/scheduled-backups.blade.php b/resources/views/livewire/project/database/scheduled-backups.blade.php index 12b36ffa1..b8241569c 100644 --- a/resources/views/livewire/project/database/scheduled-backups.blade.php +++ b/resources/views/livewire/project/database/scheduled-backups.blade.php @@ -216,7 +216,7 @@ @if ($type === 'service-database' && $selectedBackup)
+ :available-s3-storages="$s3s" :status="data_get($database, 'status')" />
diff --git a/resources/views/livewire/settings-backup.blade.php b/resources/views/livewire/settings-backup.blade.php index 0d2fd6ceb..10fea55b7 100644 --- a/resources/views/livewire/settings-backup.blade.php +++ b/resources/views/livewire/settings-backup.blade.php @@ -27,7 +27,7 @@
- +
diff --git a/tests/Feature/BackupEditValidationTest.php b/tests/Feature/BackupEditValidationTest.php index 8894f0f69..4bd39d2c3 100644 --- a/tests/Feature/BackupEditValidationTest.php +++ b/tests/Feature/BackupEditValidationTest.php @@ -4,6 +4,7 @@ use App\Livewire\Project\Database\BackupEdit; use App\Models\Environment; use App\Models\InstanceSettings; use App\Models\Project; +use App\Models\S3Storage; use App\Models\ScheduledDatabaseBackup; use App\Models\Server; use App\Models\StandaloneDocker; @@ -43,6 +44,20 @@ function createBackupForEditValidationTest(Team $team, array $overrides = []): S ], $overrides)); } +function createS3StorageForBackupEditValidationTest(Team|int $team, string $name = 'Backup Edit S3'): S3Storage +{ + return S3Storage::create([ + 'name' => $name, + 'region' => 'us-east-1', + 'key' => 'test-key', + 'secret' => 'test-secret', + 'bucket' => 'test-bucket', + 'endpoint' => 'https://s3.example.com', + 'is_usable' => true, + 'team_id' => $team instanceof Team ? $team->id : $team, + ]); +} + beforeEach(function () { if (InstanceSettings::find(0) === null) { $settings = new InstanceSettings; @@ -60,7 +75,7 @@ beforeEach(function () { it('disables S3 backup when saved without a selected S3 storage', function () { $backup = createBackupForEditValidationTest($this->team); - Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 's3s' => $this->team->s3s]) + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) ->call('submit') ->assertDispatched('success'); @@ -74,7 +89,7 @@ it('cascades to disabling local backup deletion when S3 is force-disabled', func 'disable_local_backup' => true, ]); - Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 's3s' => $this->team->s3s]) + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) ->call('submit') ->assertDispatched('success'); @@ -83,3 +98,57 @@ it('cascades to disabling local backup deletion when S3 is force-disabled', func expect($backup->s3_storage_id)->toBeNull(); expect($backup->disable_local_backup)->toBeFalsy(); }); + +it('keeps S3 enabled by selecting the only available team storage when none is selected yet', function () { + createS3StorageForBackupEditValidationTest(Team::factory()->create()); + $s3 = createS3StorageForBackupEditValidationTest($this->team); + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->set('saveS3', true) + ->call('instantSave') + ->assertDispatched('success'); + + $backup->refresh(); + expect($backup->save_s3)->toBeTruthy(); + expect($backup->s3_storage_id)->toBe($s3->id); +}); + +it('requires an explicit S3 selection when multiple storages are available', function () { + createS3StorageForBackupEditValidationTest($this->team, 'First S3'); + createS3StorageForBackupEditValidationTest($this->team, 'Second S3'); + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->set('saveS3', true) + ->call('instantSave') + ->assertDispatched('error'); + + $backup->refresh(); + expect($backup->save_s3)->toBeFalsy(); + expect($backup->s3_storage_id)->toBeNull(); +}); + +it('accepts the S3 storage scope passed to the component', function () { + $s3 = createS3StorageForBackupEditValidationTest(0); + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => collect([$s3])]) + ->set('saveS3', true) + ->set('s3StorageId', $s3->id) + ->call('instantSave') + ->assertDispatched('success'); + + $backup->refresh(); + expect($backup->save_s3)->toBeTruthy(); + expect($backup->s3_storage_id)->toBe($s3->id); +}); From 76d429fb742d937279de7caaaf5031596e2b3267 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 12:35:28 +0200 Subject: [PATCH 14/30] fix(sidebar): center unread badge in settings menu --- resources/views/livewire/settings-dropdown.blade.php | 2 +- tests/Feature/SidebarNavigationPreferencesTest.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/resources/views/livewire/settings-dropdown.blade.php b/resources/views/livewire/settings-dropdown.blade.php index d40d6778e..7006665b5 100644 --- a/resources/views/livewire/settings-dropdown.blade.php +++ b/resources/views/livewire/settings-dropdown.blade.php @@ -114,7 +114,7 @@ What's New @if ($unreadCount > 0) {{ $unreadCount > 9 ? '9+' : $unreadCount }} diff --git a/tests/Feature/SidebarNavigationPreferencesTest.php b/tests/Feature/SidebarNavigationPreferencesTest.php index c341d9529..fd667552d 100644 --- a/tests/Feature/SidebarNavigationPreferencesTest.php +++ b/tests/Feature/SidebarNavigationPreferencesTest.php @@ -28,6 +28,7 @@ it('keeps changelog and appearance options out of the preferences dropdown', fun ->toContain('wire:click="openWhatsNewModal"') ->toContain('class="relative text-left menu-item"') ->toContain('class="text-left menu-item-label"') + ->toContain('class="absolute right-2 top-1/2 -translate-y-1/2 bg-error') ->toContain("What's New") ->toContain('M9.813 15.904 9 18.75') ->not->toContain('Changelog') From 74f4d04f53d4b80093de36b772855cbebdd034d8 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 12:47:54 +0200 Subject: [PATCH 15/30] fix(backups): default S3 storage for backup schedules Show the S3 storage selector even when S3 backups are disabled, save storage changes immediately, and improve responsive confirmation buttons. --- app/Livewire/Project/Database/BackupEdit.php | 28 +++++---- .../components/modal-confirmation.blade.php | 4 +- .../project/database/backup-edit.blade.php | 40 ++++++++---- .../database/backup-executions.blade.php | 26 +++++--- tests/Feature/BackupEditValidationTest.php | 63 +++++++++++++++++-- 5 files changed, 121 insertions(+), 40 deletions(-) diff --git a/app/Livewire/Project/Database/BackupEdit.php b/app/Livewire/Project/Database/BackupEdit.php index a387b6f88..1c1bea2f6 100644 --- a/app/Livewire/Project/Database/BackupEdit.php +++ b/app/Livewire/Project/Database/BackupEdit.php @@ -131,7 +131,7 @@ class BackupEdit extends Component $this->databaseBackupRetentionMaxStorageS3 = $this->backup->database_backup_retention_max_storage_s3; $this->saveS3 = $this->backup->save_s3; $this->disableLocalBackup = $this->backup->disable_local_backup ?? false; - $this->s3StorageId = $this->backup->s3_storage_id; + $this->s3StorageId = $this->backup->s3_storage_id ?? $this->availableS3StorageIds()->first(); $this->databasesToBackup = $this->backup->databases_to_backup; $this->dumpAll = $this->backup->dump_all; $this->timeout = $this->backup->timeout; @@ -217,6 +217,11 @@ class BackupEdit extends Component } } + public function updatedS3StorageId(): void + { + $this->instantSave(); + } + private function customValidate() { if (! is_numeric($this->backup->s3_storage_id)) { @@ -225,17 +230,13 @@ class BackupEdit extends Component // S3 backup cannot be enabled without a valid S3 storage owned by the team $availableS3Ids = $this->availableS3StorageIds(); - if ($this->backup->save_s3 && ! $availableS3Ids->contains($this->backup->s3_storage_id)) { - if ($availableS3Ids->isEmpty()) { - $this->backup->s3_storage_id = $this->s3StorageId = null; + if ($availableS3Ids->isEmpty()) { + $this->backup->s3_storage_id = $this->s3StorageId = null; + if ($this->backup->save_s3) { $this->backup->save_s3 = $this->saveS3 = false; - } elseif ($this->backup->s3_storage_id === null && $availableS3Ids->count() === 1) { - $this->backup->s3_storage_id = $this->s3StorageId = $availableS3Ids->first(); - } else { - $this->backup->s3_storage_id = $this->s3StorageId = null; - - throw new Exception('Please select a valid S3 storage to enable S3 backups.'); } + } elseif (! $availableS3Ids->contains($this->backup->s3_storage_id)) { + $this->backup->s3_storage_id = $this->s3StorageId = $availableS3Ids->first(); } // Validate that disable_local_backup can only be true when S3 backup is enabled @@ -254,9 +255,14 @@ class BackupEdit extends Component { $storages = collect($this->availableS3Storages); $storageIds = $storages->pluck('id')->filter()->all(); + + if (empty($storageIds)) { + return collect(); + } + $teamIds = $storages->pluck('team_id')->reject(fn ($teamId) => $teamId === null)->unique()->values()->all(); - if (empty($storageIds) || empty($teamIds)) { + if (empty($teamIds)) { return collect(); } diff --git a/resources/views/components/modal-confirmation.blade.php b/resources/views/components/modal-confirmation.blade.php index a25e0141f..5efc9102b 100644 --- a/resources/views/components/modal-confirmation.blade.php +++ b/resources/views/components/modal-confirmation.blade.php @@ -132,10 +132,10 @@ @class([ 'relative h-auto', 'w-full' => $buttonFullWidth, - 'w-auto' => ! $buttonFullWidth, + 'w-full sm:w-auto' => ! $buttonFullWidth, ])> @if (isset($trigger)) -
+
{{ $trigger }}
@elseif ($customButton) diff --git a/resources/views/livewire/project/database/backup-edit.blade.php b/resources/views/livewire/project/database/backup-edit.blade.php index edea7b80f..4f810d755 100644 --- a/resources/views/livewire/project/database/backup-edit.blade.php +++ b/resources/views/livewire/project/database/backup-edit.blade.php @@ -1,7 +1,7 @@ -
+

Scheduled Backup

-
+
Save @@ -9,16 +9,19 @@ Backup Now @endif @if ($backup->database_id !== 0) -
- + + shortConfirmationLabel="Database Name"> + + Delete Backups and Schedule + +
@endif
@@ -39,16 +42,27 @@ helper="When enabled, backup files will be deleted from local storage immediately after uploading to S3. This requires S3 backup to be enabled." /> @endif
- @if ($saveS3) -
- - +
+
+ S3 Storage + @if (!$saveS3) + (currently disabled) + @endif + @if ($saveS3) + + @endif +
+ + @if ($availableS3Storages->isEmpty()) + + @else @foreach ($availableS3Storages as $s3) @endforeach - -
- @endif + @endif +
+

Settings

diff --git a/resources/views/livewire/project/database/backup-executions.blade.php b/resources/views/livewire/project/database/backup-executions.blade.php index 15d42a7a5..0b7a9724a 100644 --- a/resources/views/livewire/project/database/backup-executions.blade.php +++ b/resources/views/livewire/project/database/backup-executions.blade.php @@ -1,6 +1,6 @@
@isset($backup) -
+

Executions ({{ $executions_count }})

@if ($executions_count > 0)
@@ -21,14 +21,18 @@
@endif -
+
Cleanup Failed Backups - + shortConfirmationLabel="Confirmation"> + + Cleanup Deleted + +
{{ data_get($execution, 'message') }}
@endif -
+
@if (data_get($execution, 'status') === 'success') - Download @endif @php @@ -177,11 +181,15 @@ $deleteActions[] = 'This backup execution record will be deleted.'; } @endphp - + shortConfirmationLabel="Backup Filename"> + + Delete + +
@empty diff --git a/tests/Feature/BackupEditValidationTest.php b/tests/Feature/BackupEditValidationTest.php index 4bd39d2c3..fe396b5da 100644 --- a/tests/Feature/BackupEditValidationTest.php +++ b/tests/Feature/BackupEditValidationTest.php @@ -117,8 +117,8 @@ it('keeps S3 enabled by selecting the only available team storage when none is s expect($backup->s3_storage_id)->toBe($s3->id); }); -it('requires an explicit S3 selection when multiple storages are available', function () { - createS3StorageForBackupEditValidationTest($this->team, 'First S3'); +it('defaults to the first available storage when multiple storages are available', function () { + $firstS3 = createS3StorageForBackupEditValidationTest($this->team, 'First S3'); createS3StorageForBackupEditValidationTest($this->team, 'Second S3'); $backup = createBackupForEditValidationTest($this->team, [ 'save_s3' => false, @@ -126,13 +126,14 @@ it('requires an explicit S3 selection when multiple storages are available', fun ]); Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->assertSet('s3StorageId', $firstS3->id) ->set('saveS3', true) ->call('instantSave') - ->assertDispatched('error'); + ->assertDispatched('success'); $backup->refresh(); - expect($backup->save_s3)->toBeFalsy(); - expect($backup->s3_storage_id)->toBeNull(); + expect($backup->save_s3)->toBeTruthy(); + expect($backup->s3_storage_id)->toBe($firstS3->id); }); it('accepts the S3 storage scope passed to the component', function () { @@ -152,3 +153,55 @@ it('accepts the S3 storage scope passed to the component', function () { expect($backup->save_s3)->toBeTruthy(); expect($backup->s3_storage_id)->toBe($s3->id); }); + +it('shows available S3 storages even when S3 backup is disabled', function () { + createS3StorageForBackupEditValidationTest($this->team, 'First S3'); + createS3StorageForBackupEditValidationTest($this->team, 'Second S3'); + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->assertSee('First S3') + ->assertSee('Second S3'); +}); + +it('shows disabled S3 storage dropdown when no storages are available', function () { + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->assertSee('No S3 storage available'); +}); + +it('shows when S3 backups are currently disabled', function () { + createS3StorageForBackupEditValidationTest($this->team); + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->assertSee('S3 Storage') + ->assertSee('(currently disabled)'); +}); + +it('saves selected S3 storage immediately when it changes', function () { + createS3StorageForBackupEditValidationTest($this->team, 'First S3'); + $secondS3 = createS3StorageForBackupEditValidationTest($this->team, 'Second S3'); + $backup = createBackupForEditValidationTest($this->team, [ + 'save_s3' => false, + 's3_storage_id' => null, + ]); + + Livewire::test(BackupEdit::class, ['backup' => $backup->fresh(), 'availableS3Storages' => $this->team->s3s]) + ->set('s3StorageId', $secondS3->id) + ->assertDispatched('success'); + + $backup->refresh(); + expect($backup->save_s3)->toBeFalsy(); + expect($backup->s3_storage_id)->toBe($secondS3->id); +}); From fb2d477e48764d7dd9139db13ef26f7eb7809221 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 13:05:27 +0200 Subject: [PATCH 16/30] fix: improve team resource route handling --- app/Http/Middleware/CanUpdateResource.php | 89 ++++--- app/Policies/TeamPolicy.php | 15 +- .../ApplicationConfigAuthorizationTest.php | 245 ++++++++++++++++++ .../CanUpdateResourceMiddlewareTest.php | 89 +++++++ tests/Unit/Policies/TeamPolicyTest.php | 92 +++++++ 5 files changed, 480 insertions(+), 50 deletions(-) create mode 100644 tests/Feature/Authorization/ApplicationConfigAuthorizationTest.php create mode 100644 tests/Feature/Authorization/CanUpdateResourceMiddlewareTest.php create mode 100644 tests/Unit/Policies/TeamPolicyTest.php diff --git a/app/Http/Middleware/CanUpdateResource.php b/app/Http/Middleware/CanUpdateResource.php index 372af4498..3b28ee07c 100644 --- a/app/Http/Middleware/CanUpdateResource.php +++ b/app/Http/Middleware/CanUpdateResource.php @@ -5,6 +5,7 @@ namespace App\Http\Middleware; use App\Models\Application; use App\Models\Environment; use App\Models\Project; +use App\Models\Server; use App\Models\Service; use App\Models\ServiceApplication; use App\Models\ServiceDatabase; @@ -23,53 +24,61 @@ use Symfony\Component\HttpFoundation\Response; class CanUpdateResource { + /** + * @var array> + */ + private const ROUTE_RESOURCE_MODELS = [ + 'application_uuid' => [Application::class], + 'database_uuid' => [ + StandalonePostgresql::class, + StandaloneMysql::class, + StandaloneMariadb::class, + StandaloneRedis::class, + StandaloneKeydb::class, + StandaloneDragonfly::class, + StandaloneClickhouse::class, + StandaloneMongodb::class, + ], + 'stack_service_uuid' => [ServiceApplication::class, ServiceDatabase::class], + 'service_uuid' => [Service::class], + 'server_uuid' => [Server::class], + 'environment_uuid' => [Environment::class], + 'project_uuid' => [Project::class], + ]; + public function handle(Request $request, Closure $next): Response { + $resource = $this->resourceFromRoute($request); + + if (! $resource) { + abort(404, 'Resource not found.'); + } + + if (! Gate::allows('update', $resource)) { + abort(403, 'You do not have permission to update this resource.'); + } + return $next($request); + } - // Get resource from route parameters - // $resource = null; - // if ($request->route('application_uuid')) { - // $resource = Application::where('uuid', $request->route('application_uuid'))->first(); - // } elseif ($request->route('service_uuid')) { - // $resource = Service::where('uuid', $request->route('service_uuid'))->first(); - // } elseif ($request->route('stack_service_uuid')) { - // // Handle ServiceApplication or ServiceDatabase - // $stack_service_uuid = $request->route('stack_service_uuid'); - // $resource = ServiceApplication::where('uuid', $stack_service_uuid)->first() ?? - // ServiceDatabase::where('uuid', $stack_service_uuid)->first(); - // } elseif ($request->route('database_uuid')) { - // // Try different database types - // $database_uuid = $request->route('database_uuid'); - // $resource = StandalonePostgresql::where('uuid', $database_uuid)->first() ?? - // StandaloneMysql::where('uuid', $database_uuid)->first() ?? - // StandaloneMariadb::where('uuid', $database_uuid)->first() ?? - // StandaloneRedis::where('uuid', $database_uuid)->first() ?? - // StandaloneKeydb::where('uuid', $database_uuid)->first() ?? - // StandaloneDragonfly::where('uuid', $database_uuid)->first() ?? - // StandaloneClickhouse::where('uuid', $database_uuid)->first() ?? - // StandaloneMongodb::where('uuid', $database_uuid)->first(); - // } elseif ($request->route('server_uuid')) { - // // For server routes, check if user can manage servers - // if (! auth()->user()->isAdmin()) { - // abort(403, 'You do not have permission to access this resource.'); - // } + private function resourceFromRoute(Request $request): ?object + { + foreach (self::ROUTE_RESOURCE_MODELS as $routeParameter => $models) { + $uuid = $request->route($routeParameter); - // return $next($request); - // } elseif ($request->route('environment_uuid')) { - // $resource = Environment::where('uuid', $request->route('environment_uuid'))->first(); - // } elseif ($request->route('project_uuid')) { - // $resource = Project::ownedByCurrentTeam()->where('uuid', $request->route('project_uuid'))->first(); - // } + if (! $uuid) { + continue; + } - // if (! $resource) { - // abort(404, 'Resource not found.'); - // } + foreach ($models as $model) { + $resource = $model::where('uuid', $uuid)->first(); - // if (! Gate::allows('update', $resource)) { - // abort(403, 'You do not have permission to update this resource.'); - // } + if ($resource) { + return $resource; + } + } + } - // return $next($request); + return null; } } diff --git a/app/Policies/TeamPolicy.php b/app/Policies/TeamPolicy.php index 849e23751..cc7745b64 100644 --- a/app/Policies/TeamPolicy.php +++ b/app/Policies/TeamPolicy.php @@ -37,12 +37,11 @@ class TeamPolicy */ public function update(User $user, Team $team): bool { - // Only admins and owners can update team settings if (! $user->teams->contains('id', $team->id)) { return false; } - return $user->isAdmin() || $user->isOwner(); + return $user->isAdminOfTeam($team->id); } /** @@ -50,12 +49,11 @@ class TeamPolicy */ public function delete(User $user, Team $team): bool { - // Only admins and owners can delete teams if (! $user->teams->contains('id', $team->id)) { return false; } - return $user->isAdmin() || $user->isOwner(); + return $user->isAdminOfTeam($team->id); } /** @@ -63,12 +61,11 @@ class TeamPolicy */ public function manageMembers(User $user, Team $team): bool { - // Only admins and owners can manage team members if (! $user->teams->contains('id', $team->id)) { return false; } - return $user->isAdmin() || $user->isOwner(); + return $user->isAdminOfTeam($team->id); } /** @@ -76,12 +73,11 @@ class TeamPolicy */ public function viewAdmin(User $user, Team $team): bool { - // Only admins and owners can view admin panel if (! $user->teams->contains('id', $team->id)) { return false; } - return $user->isAdmin() || $user->isOwner(); + return $user->isAdminOfTeam($team->id); } /** @@ -89,11 +85,10 @@ class TeamPolicy */ public function manageInvitations(User $user, Team $team): bool { - // Only admins and owners can manage invitations if (! $user->teams->contains('id', $team->id)) { return false; } - return $user->isAdmin() || $user->isOwner(); + return $user->isAdminOfTeam($team->id); } } diff --git a/tests/Feature/Authorization/ApplicationConfigAuthorizationTest.php b/tests/Feature/Authorization/ApplicationConfigAuthorizationTest.php new file mode 100644 index 000000000..31c30c124 --- /dev/null +++ b/tests/Feature/Authorization/ApplicationConfigAuthorizationTest.php @@ -0,0 +1,245 @@ +withoutVite(); + + InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(['id' => 0], ['id' => 0])); + + $this->team = Team::factory()->create(); + + $this->admin = User::factory()->create(); + $this->admin->teams()->attach($this->team, ['role' => 'admin']); + + $this->member = User::factory()->create(); + $this->member->teams()->attach($this->team, ['role' => 'member']); + + $keyId = DB::table('private_keys')->insertGetId([ + 'uuid' => (string) Str::uuid(), + 'name' => 'Test Key', + 'private_key' => 'test-key', + 'team_id' => $this->team->id, + 'created_at' => now(), + 'updated_at' => now(), + ]); + + $this->server = Server::factory()->create([ + 'team_id' => $this->team->id, + 'private_key_id' => $keyId, + ]); + + $this->server->settings()->update([ + 'is_reachable' => true, + 'is_usable' => true, + ]); + + StandaloneDocker::withoutEvents(function () { + $this->destination = StandaloneDocker::firstOrCreate( + ['server_id' => $this->server->id, 'network' => 'coolify'], + ['uuid' => (string) Str::uuid(), 'name' => 'test-docker'] + ); + }); + + $this->project = Project::create([ + 'uuid' => (string) Str::uuid(), + 'name' => 'Test Project', + 'team_id' => $this->team->id, + ]); + + $this->environment = $this->project->environments()->first(); + + $this->application = Application::factory()->create([ + 'uuid' => (string) Str::uuid(), + 'name' => 'Test App', + 'environment_id' => $this->environment->id, + 'destination_id' => $this->destination->id, + 'destination_type' => $this->destination->getMorphClass(), + 'status' => 'running', + ]); +}); + +// --- Application Policy: view --- + +test('admin can view application', function () { + expect($this->admin->can('view', $this->application))->toBeTrue(); +}); + +test('member can view application', function () { + expect($this->member->can('view', $this->application))->toBeTrue(); +}); + +// --- Application Policy: update --- + +test('admin can update application', function () { + expect($this->admin->can('update', $this->application))->toBeTrue(); +}); + +test('member cannot update application', function () { + expect($this->member->can('update', $this->application))->toBeFalse(); +}); + +// --- Application Policy: deploy --- + +test('admin can deploy application', function () { + expect($this->admin->can('deploy', $this->application))->toBeTrue(); +}); + +test('member cannot deploy application', function () { + expect($this->member->can('deploy', $this->application))->toBeFalse(); +}); + +// --- Application Policy: delete --- + +test('admin can delete application', function () { + expect($this->admin->can('delete', $this->application))->toBeTrue(); +}); + +test('member cannot delete application', function () { + expect($this->member->can('delete', $this->application))->toBeFalse(); +}); + +// --- Application Policy: manageEnvironment --- + +test('admin can manage application environment', function () { + expect($this->admin->can('manageEnvironment', $this->application))->toBeTrue(); +}); + +test('member cannot manage application environment', function () { + expect($this->member->can('manageEnvironment', $this->application))->toBeFalse(); +}); + +// --- Application Heading Livewire actions --- + +test('member cannot call deploy on application heading', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationHeading::class, ['application' => $this->application]) + ->call('deploy') + ->assertDispatched('error'); +}); + +test('member cannot call restart on application heading', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationHeading::class, ['application' => $this->application]) + ->call('restart') + ->assertDispatched('error'); +}); + +test('member cannot call stop on application heading', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationHeading::class, ['application' => $this->application]) + ->call('stop') + ->assertDispatched('error'); +}); + +test('member cannot call force deploy on application heading', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationHeading::class, ['application' => $this->application]) + ->call('force_deploy_without_cache') + ->assertDispatched('error'); +}); + +// --- Application General policy (Livewire mount requires full app data) --- + +test('member cannot update application general settings', function () { + expect($this->member->can('update', $this->application))->toBeFalse(); +}); + +// --- Application Advanced Livewire actions --- + +test('member cannot save application advanced settings', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationAdvanced::class, ['application' => $this->application]) + ->call('instantSave') + ->assertDispatched('error'); +}); + +test('member cannot submit application advanced settings', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationAdvanced::class, ['application' => $this->application]) + ->call('submit') + ->assertDispatched('error'); +}); + +// --- Application Rollback Livewire actions --- + +test('member cannot save rollback settings', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationRollback::class, ['application' => $this->application]) + ->call('saveSettings') + ->assertDispatched('error'); +}); + +test('member cannot rollback image', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationRollback::class, ['application' => $this->application]) + ->call('rollbackImage', 'test-image:latest') + ->assertForbidden(); +}); + +// --- Application Heading visibility --- + +test('member does not see terminal link for application', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationHeading::class, ['application' => $this->application]) + ->assertDontSee('Terminal'); +}); + +test('admin sees terminal link for application', function () { + $this->actingAs($this->admin); + session(['currentTeam' => $this->team]); + + Livewire::test(ApplicationHeading::class, ['application' => $this->application]) + ->assertSee('Terminal'); +}); + +// --- Cross-team isolation --- + +test('user from different team cannot view application', function () { + $otherTeam = Team::factory()->create(); + $otherUser = User::factory()->create(); + $otherUser->teams()->attach($otherTeam, ['role' => 'admin']); + + expect($otherUser->can('view', $this->application))->toBeFalse(); +}); + +test('user from different team cannot update application', function () { + $otherTeam = Team::factory()->create(); + $otherUser = User::factory()->create(); + $otherUser->teams()->attach($otherTeam, ['role' => 'admin']); + + expect($otherUser->can('update', $this->application))->toBeFalse(); +}); diff --git a/tests/Feature/Authorization/CanUpdateResourceMiddlewareTest.php b/tests/Feature/Authorization/CanUpdateResourceMiddlewareTest.php new file mode 100644 index 000000000..4d440b41a --- /dev/null +++ b/tests/Feature/Authorization/CanUpdateResourceMiddlewareTest.php @@ -0,0 +1,89 @@ + null, + 'database_uuid' => null, + 'stack_service_uuid' => null, + 'service_uuid' => null, + 'server_uuid' => null, + 'environment_uuid' => null, + 'project_uuid' => null, + $parameter => $value, + ]; + + $request = Mockery::mock(Request::class)->makePartial(); + $request->shouldReceive('route')->andReturnUsing(fn (string $key): ?string => $parameters[$key] ?? null); + + return $request; +} + +beforeEach(function () { + InstanceSettings::unguarded(fn () => InstanceSettings::updateOrCreate(['id' => 0], ['id' => 0])); + + $this->team = Team::factory()->create(); + $this->project = Project::factory()->create(['team_id' => $this->team->id]); + $this->server = Server::factory()->create(['team_id' => $this->team->id]); + + $this->admin = User::factory()->create(); + $this->admin->teams()->attach($this->team, ['role' => 'admin']); + + $this->member = User::factory()->create(); + $this->member->teams()->attach($this->team, ['role' => 'member']); +}); + +it('blocks members from update-only project routes before the page renders', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + (new CanUpdateResource)->handle( + requestWithCanUpdateResourceRouteParameter('project_uuid', $this->project->uuid), + fn () => response('ok') + ); +})->throws(HttpException::class, 'You do not have permission to update this resource.'); + +it('allows admins through update-only project routes', function () { + $this->actingAs($this->admin); + session(['currentTeam' => $this->team]); + + $response = (new CanUpdateResource)->handle( + requestWithCanUpdateResourceRouteParameter('project_uuid', $this->project->uuid), + fn () => response('ok') + ); + + expect($response->getContent())->toBe('ok'); +}); + +it('blocks members from update-only server routes before the page renders', function () { + $this->actingAs($this->member); + session(['currentTeam' => $this->team]); + + (new CanUpdateResource)->handle( + requestWithCanUpdateResourceRouteParameter('server_uuid', $this->server->uuid), + fn () => response('ok') + ); +})->throws(HttpException::class, 'You do not have permission to update this resource.'); + +it('returns not found when an update-only route references an unknown resource', function () { + $this->actingAs($this->admin); + session(['currentTeam' => $this->team]); + + (new CanUpdateResource)->handle( + requestWithCanUpdateResourceRouteParameter('project_uuid', 'not-a-project'), + fn () => response('ok') + ); +})->throws(NotFoundHttpException::class, 'Resource not found.'); diff --git a/tests/Unit/Policies/TeamPolicyTest.php b/tests/Unit/Policies/TeamPolicyTest.php new file mode 100644 index 000000000..3b341d488 --- /dev/null +++ b/tests/Unit/Policies/TeamPolicyTest.php @@ -0,0 +1,92 @@ +makePartial(); + $user->shouldReceive('getAttribute')->with('teams')->andReturn(collect( + array_map(fn (int $teamId): object => (object) ['id' => $teamId], $teamIds) + )); + + return $user; +} + +function teamPolicyTeam(int $teamId): Team +{ + $team = Mockery::mock(Team::class)->makePartial(); + $team->shouldReceive('getAttribute')->with('id')->andReturn($teamId); + + return $team; +} + +it('allows any authenticated user to view any teams list', function () { + $user = Mockery::mock(User::class)->makePartial(); + + expect((new TeamPolicy)->viewAny($user))->toBeTrue(); +}); + +it('allows authenticated users to create teams', function () { + $user = Mockery::mock(User::class)->makePartial(); + + expect((new TeamPolicy)->create($user))->toBeTrue(); +}); + +it('allows target team members to view the team', function () { + $user = teamPolicyUserWithTeams([1]); + $team = teamPolicyTeam(1); + + expect((new TeamPolicy)->view($user, $team))->toBeTrue(); +}); + +it('denies non-members from viewing the team', function () { + $user = teamPolicyUserWithTeams([2]); + $team = teamPolicyTeam(1); + + expect((new TeamPolicy)->view($user, $team))->toBeFalse(); +}); + +it('allows target team admins to perform privileged team actions', function (string $ability) { + $user = teamPolicyUserWithTeams([1]); + $user->shouldReceive('isAdminOfTeam')->with(1)->andReturn(true); + $team = teamPolicyTeam(1); + + expect((new TeamPolicy)->{$ability}($user, $team))->toBeTrue(); +})->with([ + 'update', + 'delete', + 'manageMembers', + 'viewAdmin', + 'manageInvitations', +]); + +it('denies target team members even when their current session role is admin elsewhere', function (string $ability) { + $user = teamPolicyUserWithTeams([1, 2]); + $user->shouldReceive('isAdmin')->andReturn(true); + $user->shouldReceive('isOwner')->andReturn(false); + $user->shouldReceive('isAdminOfTeam')->with(1)->andReturn(false); + $team = teamPolicyTeam(1); + + expect((new TeamPolicy)->{$ability}($user, $team))->toBeFalse(); +})->with([ + 'update', + 'delete', + 'manageMembers', + 'viewAdmin', + 'manageInvitations', +]); + +it('denies non-members from privileged team actions', function (string $ability) { + $user = teamPolicyUserWithTeams([2]); + $team = teamPolicyTeam(1); + + expect((new TeamPolicy)->{$ability}($user, $team))->toBeFalse(); +})->with([ + 'update', + 'delete', + 'manageMembers', + 'viewAdmin', + 'manageInvitations', +]); From c7f014017b753a53e33a4eb7d2950f7302d971b5 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 14:46:46 +0200 Subject: [PATCH 17/30] Improve outbound URL validation --- app/Jobs/SendMessageToDiscordJob.php | 19 +- app/Jobs/SendMessageToSlackJob.php | 21 +- app/Jobs/SendWebhookJob.php | 2 +- app/Models/S3Storage.php | 1 + app/Rules/SafeExternalUrl.php | 146 ++++++++++--- app/Rules/SafeWebhookUrl.php | 191 ++++++++++++++---- tests/Unit/NotificationWebhookSafetyTest.php | 36 ++++ .../Unit/S3StorageEndpointValidationTest.php | 6 +- tests/Unit/S3StorageTest.php | 2 + tests/Unit/SafeExternalUrlTest.php | 41 +++- tests/Unit/SafeWebhookUrlTest.php | 29 +++ tests/Unit/SendWebhookJobTest.php | 31 ++- 12 files changed, 440 insertions(+), 85 deletions(-) create mode 100644 tests/Unit/NotificationWebhookSafetyTest.php diff --git a/app/Jobs/SendMessageToDiscordJob.php b/app/Jobs/SendMessageToDiscordJob.php index 99aeaeea2..9ac017396 100644 --- a/app/Jobs/SendMessageToDiscordJob.php +++ b/app/Jobs/SendMessageToDiscordJob.php @@ -3,6 +3,7 @@ namespace App\Jobs; use App\Notifications\Dto\DiscordMessage; +use App\Rules\SafeWebhookUrl; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; @@ -10,6 +11,8 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Validator; class SendMessageToDiscordJob implements ShouldBeEncrypted, ShouldQueue { @@ -41,6 +44,20 @@ class SendMessageToDiscordJob implements ShouldBeEncrypted, ShouldQueue */ public function handle(): void { - Http::post($this->webhookUrl, $this->message->toPayload()); + $validator = Validator::make( + ['webhook_url' => $this->webhookUrl], + ['webhook_url' => ['required', 'url', new SafeWebhookUrl]] + ); + + if ($validator->fails()) { + Log::warning('SendMessageToDiscordJob: blocked unsafe webhook URL', [ + 'url' => $this->webhookUrl, + 'errors' => $validator->errors()->all(), + ]); + + return; + } + + Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, $this->message->toPayload()); } } diff --git a/app/Jobs/SendMessageToSlackJob.php b/app/Jobs/SendMessageToSlackJob.php index f869fd602..e5cff5818 100644 --- a/app/Jobs/SendMessageToSlackJob.php +++ b/app/Jobs/SendMessageToSlackJob.php @@ -3,6 +3,7 @@ namespace App\Jobs; use App\Notifications\Dto\SlackMessage; +use App\Rules\SafeWebhookUrl; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; use Illuminate\Contracts\Queue\ShouldQueue; @@ -10,6 +11,8 @@ use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; use Illuminate\Support\Facades\Http; +use Illuminate\Support\Facades\Log; +use Illuminate\Support\Facades\Validator; class SendMessageToSlackJob implements ShouldBeEncrypted, ShouldQueue { @@ -34,6 +37,20 @@ class SendMessageToSlackJob implements ShouldBeEncrypted, ShouldQueue public function handle(): void { + $validator = Validator::make( + ['webhook_url' => $this->webhookUrl], + ['webhook_url' => ['required', 'url', new SafeWebhookUrl]] + ); + + if ($validator->fails()) { + Log::warning('SendMessageToSlackJob: blocked unsafe webhook URL', [ + 'url' => $this->webhookUrl, + 'errors' => $validator->errors()->all(), + ]); + + return; + } + if ($this->isSlackWebhook()) { $this->sendToSlack(); @@ -64,7 +81,7 @@ class SendMessageToSlackJob implements ShouldBeEncrypted, ShouldQueue private function sendToSlack(): void { - Http::post($this->webhookUrl, [ + Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, [ 'text' => $this->message->title, 'blocks' => [ [ @@ -106,7 +123,7 @@ class SendMessageToSlackJob implements ShouldBeEncrypted, ShouldQueue { $username = config('app.name'); - Http::post($this->webhookUrl, [ + Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, [ 'username' => $username, 'attachments' => [ [ diff --git a/app/Jobs/SendWebhookJob.php b/app/Jobs/SendWebhookJob.php index 17517cebb..beee24179 100644 --- a/app/Jobs/SendWebhookJob.php +++ b/app/Jobs/SendWebhookJob.php @@ -64,7 +64,7 @@ class SendWebhookJob implements ShouldBeEncrypted, ShouldQueue ]); } - $response = Http::post($this->webhookUrl, $this->payload); + $response = Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, $this->payload); if (isDev()) { ray('Webhook response', [ diff --git a/app/Models/S3Storage.php b/app/Models/S3Storage.php index 3b344dfff..74edb5fa2 100644 --- a/app/Models/S3Storage.php +++ b/app/Models/S3Storage.php @@ -165,6 +165,7 @@ class S3Storage extends BaseModel 'http' => [ 'connect_timeout' => self::CONNECTION_TIMEOUT_SECONDS, 'timeout' => self::REQUEST_TIMEOUT_SECONDS, + 'allow_redirects' => false, ], ]); // Test the connection by listing files with ListObjectsV2 (S3) diff --git a/app/Rules/SafeExternalUrl.php b/app/Rules/SafeExternalUrl.php index 41299d6c1..5380dd5e3 100644 --- a/app/Rules/SafeExternalUrl.php +++ b/app/Rules/SafeExternalUrl.php @@ -8,6 +8,11 @@ use Illuminate\Support\Facades\Log; class SafeExternalUrl implements ValidationRule { + /** + * @param (Closure(string): array)|null $resolver + */ + public function __construct(private ?Closure $resolver = null) {} + /** * Run the validation rule. * @@ -38,44 +43,137 @@ class SafeExternalUrl implements ValidationRule } $host = strtolower($host); + $hostForIpCheck = $this->normalizeHostForIpCheck($host); + $hostForDns = rtrim($hostForIpCheck, '.'); - // Block well-known internal hostnames $internalHosts = ['localhost', '0.0.0.0', '::1']; - if (in_array($host, $internalHosts) || str_ends_with($host, '.local') || str_ends_with($host, '.internal')) { - Log::warning('External URL points to internal host', [ - 'attribute' => $attribute, - 'url' => $value, - 'host' => $host, - 'ip' => request()->ip(), - 'user_id' => auth()->id(), - ]); + if (in_array($hostForDns, $internalHosts, true) || str_ends_with($hostForDns, '.local') || str_ends_with($hostForDns, '.internal')) { + $this->logBlockedHost($attribute, $value, $host); $fail('The :attribute must not point to internal hosts.'); return; } - // Resolve hostname to IP and block private/reserved ranges - $ip = gethostbyname($host); + if (filter_var($hostForIpCheck, FILTER_VALIDATE_IP)) { + if (! $this->isPublicIp($hostForIpCheck)) { + $this->logBlockedIp($attribute, $value, $host, $hostForIpCheck); + $fail('The :attribute must not point to a private or reserved IP address.'); - // gethostbyname returns the original hostname on failure (e.g. unresolvable) - if ($ip === $host && ! filter_var($host, FILTER_VALIDATE_IP)) { + return; + } + + return; + } + + $resolvedIps = $this->resolveHost($hostForDns); + if ($resolvedIps === []) { $fail('The :attribute host could not be resolved.'); return; } - if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { - Log::warning('External URL resolves to private or reserved IP', [ - 'attribute' => $attribute, - 'url' => $value, - 'host' => $host, - 'resolved_ip' => $ip, - 'ip' => request()->ip(), - 'user_id' => auth()->id(), - ]); - $fail('The :attribute must not point to a private or reserved IP address.'); + foreach ($resolvedIps as $resolvedIp) { + if (! $this->isPublicIp($resolvedIp)) { + $this->logBlockedIp($attribute, $value, $host, $resolvedIp); + $fail('The :attribute must not point to a private or reserved IP address.'); - return; + return; + } } } + + private function normalizeHostForIpCheck(string $host): string + { + return (str_starts_with($host, '[') && str_ends_with($host, ']')) + ? substr($host, 1, -1) + : $host; + } + + /** + * @return array + */ + private function resolveHost(string $host): array + { + if ($this->resolver instanceof Closure) { + return array_values(array_filter(($this->resolver)($host), fn (string $ip): bool => filter_var($ip, FILTER_VALIDATE_IP) !== false)); + } + + $records = @dns_get_record($host, DNS_A | DNS_AAAA); + if ($records === false) { + $records = []; + } + + $ips = []; + foreach ($records as $record) { + foreach (['ip', 'ipv6'] as $key) { + if (isset($record[$key]) && filter_var($record[$key], FILTER_VALIDATE_IP)) { + $ips[] = $record[$key]; + } + } + } + + $ipv4Addresses = @gethostbynamel($host); + if (is_array($ipv4Addresses)) { + foreach ($ipv4Addresses as $ip) { + if (filter_var($ip, FILTER_VALIDATE_IP)) { + $ips[] = $ip; + } + } + } + + return array_values(array_unique($ips)); + } + + private function isPublicIp(string $ip): bool + { + $embeddedIpv4 = $this->extractIpv4FromMappedIpv6($ip); + if ($embeddedIpv4 !== null) { + return filter_var($embeddedIpv4, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false; + } + + return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false; + } + + private function extractIpv4FromMappedIpv6(string $ip): ?string + { + $packed = @inet_pton($ip); + if ($packed === false || strlen($packed) !== 16) { + return null; + } + + $prefix = substr($packed, 0, 12); + if ($prefix !== str_repeat("\0", 10)."\xff\xff") { + return null; + } + + $parts = unpack('C4', substr($packed, 12, 4)); + if ($parts === false) { + return null; + } + + return implode('.', $parts); + } + + private function logBlockedHost(string $attribute, string $url, string $host): void + { + Log::warning('External URL points to internal host', [ + 'attribute' => $attribute, + 'url' => $url, + 'host' => $host, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + } + + private function logBlockedIp(string $attribute, string $url, string $host, string $resolvedIp): void + { + Log::warning('External URL resolves to private or reserved IP', [ + 'attribute' => $attribute, + 'url' => $url, + 'host' => $host, + 'resolved_ip' => $resolvedIp, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + } } diff --git a/app/Rules/SafeWebhookUrl.php b/app/Rules/SafeWebhookUrl.php index 3723e1db5..ead03e9c0 100644 --- a/app/Rules/SafeWebhookUrl.php +++ b/app/Rules/SafeWebhookUrl.php @@ -8,6 +8,11 @@ use Illuminate\Support\Facades\Log; class SafeWebhookUrl implements ValidationRule { + /** + * @param (Closure(string): array)|null $resolver + */ + public function __construct(private ?Closure $resolver = null) {} + /** * Run the validation rule. * @@ -39,63 +44,175 @@ class SafeWebhookUrl implements ValidationRule } $host = strtolower($host); + $hostForIpCheck = $this->normalizeHostForIpCheck($host); + $hostForDns = rtrim($hostForIpCheck, '.'); - // Strip IPv6 brackets (e.g. "[::1]" -> "::1") before IP checks so bracketed - // literals can't sneak past filter_var FILTER_VALIDATE_IP. - $hostForIpCheck = (str_starts_with($host, '[') && str_ends_with($host, ']')) - ? substr($host, 1, -1) - : $host; - - // Block well-known dangerous hostnames $blockedHosts = ['localhost', '0.0.0.0', '::1']; - if (in_array($hostForIpCheck, $blockedHosts) || str_ends_with($host, '.internal')) { - Log::warning('Webhook URL points to blocked host', [ - 'attribute' => $attribute, - 'host' => $host, - 'ip' => request()->ip(), - 'user_id' => auth()->id(), - ]); + if (in_array($hostForDns, $blockedHosts, true) || str_ends_with($hostForDns, '.internal')) { + $this->logBlockedHost($attribute, $host); $fail('The :attribute must not point to localhost or internal hosts.'); return; } - // Block loopback (127.0.0.0/8) and link-local/metadata (169.254.0.0/16) when IP is provided directly - if (filter_var($hostForIpCheck, FILTER_VALIDATE_IP) && ($this->isLoopback($hostForIpCheck) || $this->isLinkLocal($hostForIpCheck))) { - Log::warning('Webhook URL points to blocked IP range', [ - 'attribute' => $attribute, - 'host' => $host, - 'ip' => request()->ip(), - 'user_id' => auth()->id(), - ]); - $fail('The :attribute must not point to loopback or link-local addresses.'); + if (filter_var($hostForIpCheck, FILTER_VALIDATE_IP)) { + if ($this->isBlockedIp($hostForIpCheck)) { + $this->logBlockedIp($attribute, $host, $hostForIpCheck); + $fail('The :attribute must not point to loopback or link-local addresses.'); + + return; + } return; } + + $resolvedIps = $this->resolveHost($hostForDns); + foreach ($resolvedIps as $resolvedIp) { + if ($this->isBlockedIp($resolvedIp)) { + $this->logBlockedIp($attribute, $host, $resolvedIp); + $fail('The :attribute must not point to loopback or link-local addresses.'); + + return; + } + } } - private function isLoopback(string $ip): bool + private function normalizeHostForIpCheck(string $host): string + { + return (str_starts_with($host, '[') && str_ends_with($host, ']')) + ? substr($host, 1, -1) + : $host; + } + + /** + * @return array + */ + private function resolveHost(string $host): array + { + if ($this->resolver instanceof Closure) { + return array_values(array_filter(($this->resolver)($host), fn (string $ip): bool => filter_var($ip, FILTER_VALIDATE_IP) !== false)); + } + + $records = @dns_get_record($host, DNS_A | DNS_AAAA); + if ($records === false) { + $records = []; + } + + $ips = []; + foreach ($records as $record) { + foreach (['ip', 'ipv6'] as $key) { + if (isset($record[$key]) && filter_var($record[$key], FILTER_VALIDATE_IP)) { + $ips[] = $record[$key]; + } + } + } + + $ipv4Addresses = @gethostbynamel($host); + if (is_array($ipv4Addresses)) { + foreach ($ipv4Addresses as $ip) { + if (filter_var($ip, FILTER_VALIDATE_IP)) { + $ips[] = $ip; + } + } + } + + return array_values(array_unique($ips)); + } + + private function isBlockedIp(string $ip): bool + { + $embeddedIpv4 = $this->extractIpv4FromMappedIpv6($ip); + if ($embeddedIpv4 !== null) { + return $this->isBlockedIpv4($embeddedIpv4); + } + + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return $this->isBlockedIpv4($ip); + } + + return $this->isBlockedIpv6($ip); + } + + private function isBlockedIpv4(string $ip): bool { - // 127.0.0.0/8, 0.0.0.0 if ($ip === '0.0.0.0' || str_starts_with($ip, '127.')) { return true; } - // IPv6 loopback - $normalized = @inet_pton($ip); - - return $normalized !== false && $normalized === inet_pton('::1'); - } - - private function isLinkLocal(string $ip): bool - { - // 169.254.0.0/16 — covers cloud metadata at 169.254.169.254 - if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + $long = ip2long($ip); + if ($long === false) { return false; } - $long = ip2long($ip); + $unsigned = sprintf('%u', $long); + $linkLocalStart = sprintf('%u', ip2long('169.254.0.0')); + $linkLocalEnd = sprintf('%u', ip2long('169.254.255.255')); - return $long !== false && ($long >> 16) === (ip2long('169.254.0.0') >> 16); + return $unsigned >= $linkLocalStart && $unsigned <= $linkLocalEnd; + } + + private function isBlockedIpv6(string $ip): bool + { + $packed = @inet_pton($ip); + if ($packed === false) { + return false; + } + + if ($packed === inet_pton('::1') || $packed === inet_pton('::')) { + return true; + } + + $bytes = unpack('C16', $packed); + if ($bytes === false) { + return false; + } + + $firstByte = $bytes[1]; + $secondByte = $bytes[2]; + + // fe80::/10 link-local and fc00::/7 unique local addresses. + return ($firstByte === 0xFE && ($secondByte & 0xC0) === 0x80) + || (($firstByte & 0xFE) === 0xFC); + } + + private function extractIpv4FromMappedIpv6(string $ip): ?string + { + $packed = @inet_pton($ip); + if ($packed === false || strlen($packed) !== 16) { + return null; + } + + $prefix = substr($packed, 0, 12); + if ($prefix !== str_repeat("\0", 10)."\xff\xff") { + return null; + } + + $parts = unpack('C4', substr($packed, 12, 4)); + if ($parts === false) { + return null; + } + + return implode('.', $parts); + } + + private function logBlockedHost(string $attribute, string $host): void + { + Log::warning('Webhook URL points to blocked host', [ + 'attribute' => $attribute, + 'host' => $host, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); + } + + private function logBlockedIp(string $attribute, string $host, string $blockedIp): void + { + Log::warning('Webhook URL points to blocked IP range', [ + 'attribute' => $attribute, + 'host' => $host, + 'resolved_ip' => $blockedIp, + 'ip' => request()->ip(), + 'user_id' => auth()->id(), + ]); } } diff --git a/tests/Unit/NotificationWebhookSafetyTest.php b/tests/Unit/NotificationWebhookSafetyTest.php new file mode 100644 index 000000000..9246c4004 --- /dev/null +++ b/tests/Unit/NotificationWebhookSafetyTest.php @@ -0,0 +1,36 @@ +handle(); + + Http::assertNothingSent(); +}); + +it('blocks queued Discord notifications to IPv4-mapped link-local URLs', function () { + Http::fake(); + + $job = new SendMessageToDiscordJob( + new DiscordMessage('Test', 'Description', DiscordMessage::infoColor()), + 'http://[::ffff:169.254.169.254]/' + ); + + $job->handle(); + + Http::assertNothingSent(); +}); diff --git a/tests/Unit/S3StorageEndpointValidationTest.php b/tests/Unit/S3StorageEndpointValidationTest.php index 054606a25..bfc2fd18b 100644 --- a/tests/Unit/S3StorageEndpointValidationTest.php +++ b/tests/Unit/S3StorageEndpointValidationTest.php @@ -23,8 +23,9 @@ it('rejects SSRF payloads on the S3 endpoint', function (string $endpoint) { expect($validator->fails())->toBeTrue("Expected rejection: {$endpoint}"); })->with([ - 'AWS IMDS' => 'http://169.254.169.254/latest/meta-data/', - 'AWS IMDS bare' => 'http://169.254.169.254', + 'link-local address' => 'http://169.254.169.254/', + 'link-local address bare' => 'http://169.254.169.254', + 'link-local address IPv4-mapped IPv6' => 'http://[::ffff:169.254.169.254]/', 'GCP metadata via link-local' => 'http://169.254.0.1', 'loopback v4' => 'http://127.0.0.1', 'loopback Redis' => 'http://127.0.0.1:6379', @@ -87,5 +88,6 @@ it('blocks testConnection() for loopback endpoints', function (string $endpoint) 'http loopback' => 'http://127.0.0.1:6379', 'localhost' => 'http://localhost:9000', 'IPv6 loopback' => 'http://[::1]', + 'IPv4-mapped IPv6 link-local' => 'http://[::ffff:169.254.169.254]', 'internal TLD' => 'http://backend.internal', ]); diff --git a/tests/Unit/S3StorageTest.php b/tests/Unit/S3StorageTest.php index ddf390443..4cf56640e 100644 --- a/tests/Unit/S3StorageTest.php +++ b/tests/Unit/S3StorageTest.php @@ -53,6 +53,7 @@ test('S3Storage model fillable attributes are configured correctly', function () $s3Storage = new S3Storage; expect($s3Storage->getFillable())->toBe([ + 'team_id', 'name', 'description', 'region', @@ -74,6 +75,7 @@ test('S3Storage connection validation uses short s3 client timeouts', function ( ->with(Mockery::on(function (array $config) { expect($config['http']['connect_timeout'])->toBe(15); expect($config['http']['timeout'])->toBe(15); + expect($config['http']['allow_redirects'])->toBeFalse(); return true; })) diff --git a/tests/Unit/SafeExternalUrlTest.php b/tests/Unit/SafeExternalUrlTest.php index b2bc13337..c047b1923 100644 --- a/tests/Unit/SafeExternalUrlTest.php +++ b/tests/Unit/SafeExternalUrlTest.php @@ -11,7 +11,7 @@ it('accepts valid public URLs', function () { $validUrls = [ 'https://api.github.com', - 'https://github.example.com/api/v3', + 'https://github.com/api/v3', 'https://example.com', 'http://example.com', ]; @@ -22,6 +22,14 @@ it('accepts valid public URLs', function () { } }); +it('accepts custom external hostnames that resolve to public IPs', function () { + $rule = new SafeExternalUrl(fn (string $host): array => ['93.184.216.34']); + + $validator = Validator::make(['url' => 'https://github.example.com/api/v3'], ['url' => $rule]); + + expect($validator->passes())->toBeTrue('Expected valid custom external hostname'); +}); + it('rejects private IPv4 addresses', function (string $url) { $rule = new SafeExternalUrl; @@ -42,6 +50,34 @@ it('rejects cloud metadata IP', function () { expect($validator->fails())->toBeTrue('Expected rejection: cloud metadata IP'); }); +it('rejects hostnames that resolve to private or reserved addresses', function (string $url, array $resolvedIps) { + $rule = new SafeExternalUrl(fn (string $host): array => $resolvedIps); + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected rejection after DNS resolution: {$url}"); +})->with([ + 'hostname to link-local IP' => ['http://169.254.169.254.nip.io/', ['169.254.169.254']], + 'hostname to loopback' => ['http://loopback.example.test/', ['127.0.0.1']], + 'hostname to private IPv4' => ['http://private.example.test/', ['10.0.0.1']], + 'hostname to IPv6 loopback' => ['http://ipv6-loopback.example.test/', ['::1']], + 'hostname to IPv6 link-local' => ['http://ipv6-link-local.example.test/', ['fe80::1']], + 'hostname to IPv6 ULA' => ['http://ipv6-ula.example.test/', ['fc00::1']], + 'hostname to mapped private IPv4' => ['http://mapped-private.example.test/', ['::ffff:10.0.0.1']], +]); + +it('rejects IPv4-mapped IPv6 literals for private or reserved IPv4 ranges', function (string $url) { + $rule = new SafeExternalUrl; + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected rejection: {$url}"); +})->with([ + 'mapped link-local IP' => 'http://[::ffff:169.254.169.254]/', + 'mapped loopback' => 'http://[::ffff:127.0.0.1]/', + 'mapped private' => 'http://[::ffff:10.0.0.1]/', +]); + it('rejects localhost and internal hostnames', function (string $url) { $rule = new SafeExternalUrl; @@ -50,9 +86,12 @@ it('rejects localhost and internal hostnames', function (string $url) { })->with([ 'localhost' => 'http://localhost', 'localhost with port' => 'http://localhost:8080', + 'localhost with trailing dot' => 'http://localhost.', 'zero address' => 'http://0.0.0.0', '.local domain' => 'http://myservice.local', + '.local domain with trailing dot' => 'http://myservice.local.', '.internal domain' => 'http://myservice.internal', + '.internal domain with trailing dot' => 'http://myservice.internal.', ]); it('rejects non-URL strings', function (string $value) { diff --git a/tests/Unit/SafeWebhookUrlTest.php b/tests/Unit/SafeWebhookUrlTest.php index bb5569ccf..69dc6fbb5 100644 --- a/tests/Unit/SafeWebhookUrlTest.php +++ b/tests/Unit/SafeWebhookUrlTest.php @@ -59,6 +59,33 @@ it('rejects link-local range', function () { expect($validator->fails())->toBeTrue('Expected rejection: link-local IP'); }); +it('rejects hostnames that resolve to blocked addresses', function (string $url, array $resolvedIps) { + $rule = new SafeWebhookUrl(fn (string $host): array => $resolvedIps); + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected rejection after DNS resolution: {$url}"); +})->with([ + 'hostname to link-local IP' => ['http://169.254.169.254.nip.io/', ['169.254.169.254']], + 'hostname to loopback' => ['http://loopback.example.test/', ['127.0.0.1']], + 'hostname to IPv6 loopback' => ['http://ipv6-loopback.example.test/', ['::1']], + 'hostname to IPv6 link-local' => ['http://ipv6-link-local.example.test/', ['fe80::1']], + 'hostname to IPv6 ULA' => ['http://ipv6-ula.example.test/', ['fc00::1']], + 'hostname to mapped link-local IP' => ['http://mapped-link-local.example.test/', ['::ffff:169.254.169.254']], +]); + +it('rejects IPv4-mapped IPv6 literals for blocked IPv4 ranges', function (string $url) { + $rule = new SafeWebhookUrl; + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected rejection: {$url}"); +})->with([ + 'mapped link-local IP' => 'http://[::ffff:169.254.169.254]/', + 'mapped loopback' => 'http://[::ffff:127.0.0.1]/', + 'mapped zero' => 'http://[::ffff:0.0.0.0]/', +]); + it('rejects localhost and internal hostnames', function (string $url) { $rule = new SafeWebhookUrl; @@ -67,7 +94,9 @@ it('rejects localhost and internal hostnames', function (string $url) { })->with([ 'localhost' => 'http://localhost', 'localhost with port' => 'http://localhost:8080', + 'localhost with trailing dot' => 'http://localhost.', '.internal domain' => 'http://myservice.internal', + '.internal domain with trailing dot' => 'http://myservice.internal.', ]); it('rejects non-http schemes', function (string $value) { diff --git a/tests/Unit/SendWebhookJobTest.php b/tests/Unit/SendWebhookJobTest.php index 688cd3bf2..dedf18e1f 100644 --- a/tests/Unit/SendWebhookJobTest.php +++ b/tests/Unit/SendWebhookJobTest.php @@ -2,7 +2,6 @@ use App\Jobs\SendWebhookJob; use Illuminate\Support\Facades\Http; -use Illuminate\Support\Facades\Log; use Tests\TestCase; uses(TestCase::class); @@ -24,11 +23,6 @@ it('sends webhook to valid URLs', function () { it('blocks webhook to loopback address', function () { Http::fake(); - Log::shouldReceive('warning') - ->once() - ->withArgs(function ($message) { - return str_contains($message, 'blocked unsafe webhook URL'); - }); $job = new SendWebhookJob( payload: ['event' => 'test'], @@ -42,15 +36,23 @@ it('blocks webhook to loopback address', function () { it('blocks webhook to cloud metadata endpoint', function () { Http::fake(); - Log::shouldReceive('warning') - ->once() - ->withArgs(function ($message) { - return str_contains($message, 'blocked unsafe webhook URL'); - }); $job = new SendWebhookJob( payload: ['event' => 'test'], - webhookUrl: 'http://169.254.169.254/latest/meta-data/' + webhookUrl: 'http://169.254.169.254/' + ); + + $job->handle(); + + Http::assertNothingSent(); +}); + +it('blocks webhook to IPv4-mapped IPv6 link-local endpoint', function () { + Http::fake(); + + $job = new SendWebhookJob( + payload: ['event' => 'test'], + webhookUrl: 'http://[::ffff:169.254.169.254]/' ); $job->handle(); @@ -60,11 +62,6 @@ it('blocks webhook to cloud metadata endpoint', function () { it('blocks webhook to localhost', function () { Http::fake(); - Log::shouldReceive('warning') - ->once() - ->withArgs(function ($message) { - return str_contains($message, 'blocked unsafe webhook URL'); - }); $job = new SendWebhookJob( payload: ['event' => 'test'], From a06c1a7bf5e30eb779d8e7bce01b6e4b1f78b624 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 14:37:39 +0200 Subject: [PATCH 18/30] Improve storage mount path handling --- .../Api/ApplicationsController.php | 61 +++++- .../Controllers/Api/DatabasesController.php | 61 +++++- .../Controllers/Api/ServicesController.php | 61 +++++- app/Jobs/ApplicationDeploymentJob.php | 2 +- app/Livewire/Project/Service/FileStorage.php | 31 ++- app/Livewire/Project/Service/Storage.php | 80 +++++-- app/Models/LocalFileVolume.php | 34 ++- bootstrap/helpers/shared.php | 201 +++++++++++++++++- ..._host_file_to_local_file_volumes_table.php | 36 ++++ database/schema/testing-schema.sql | 1 + .../project/service/file-storage.blade.php | 17 +- .../project/service/storage.blade.php | 88 +++++++- templates/service-templates-latest.json | 2 +- templates/service-templates.json | 2 +- tests/Feature/FileStorageMountPathTest.php | 123 +++++++++++ tests/Feature/StorageApiTest.php | 160 +++++++++++++- tests/Unit/FileStorageSecurityTest.php | 74 +++++++ 17 files changed, 979 insertions(+), 55 deletions(-) create mode 100644 database/migrations/2026_07_02_112425_add_is_host_file_to_local_file_volumes_table.php create mode 100644 tests/Feature/FileStorageMountPathTest.php diff --git a/app/Http/Controllers/Api/ApplicationsController.php b/app/Http/Controllers/Api/ApplicationsController.php index bdb6f8d90..9570026c1 100644 --- a/app/Http/Controllers/Api/ApplicationsController.php +++ b/app/Http/Controllers/Api/ApplicationsController.php @@ -4279,10 +4279,11 @@ class ApplicationsController extends Controller 'host_path' => ['string', 'nullable', 'regex:'.ValidationPatterns::DIRECTORY_PATH_PATTERN], 'content' => 'string|nullable', 'is_directory' => 'boolean', + 'is_host_file' => 'boolean', 'fs_path' => 'string', ]); - $allAllowedFields = ['type', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'fs_path']; + $allAllowedFields = ['type', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'is_host_file', 'fs_path']; $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); if ($validator->fails() || ! empty($extraFields)) { $errors = $validator->errors(); @@ -4306,7 +4307,7 @@ class ApplicationsController extends Controller ], 422); } - $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'fs_path'], array_keys($request->all())); + $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'is_host_file', 'fs_path'], array_keys($request->all())); if (! empty($typeSpecificInvalidFields)) { return response()->json([ 'message' => 'Validation failed.', @@ -4337,6 +4338,14 @@ class ApplicationsController extends Controller } $isDirectory = $request->boolean('is_directory', false); + $isHostFile = $request->boolean('is_host_file', false); + + if ($isDirectory && $isHostFile) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['is_host_file' => 'Host file mounts cannot also be directory mounts.'], + ], 422); + } if ($isDirectory) { if (! $request->fs_path) { @@ -4359,12 +4368,50 @@ class ApplicationsController extends Controller 'resource_id' => $application->id, 'resource_type' => get_class($application), ]); + } elseif ($isHostFile) { + if (! $request->fs_path) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['fs_path' => 'The fs_path field is required for host file mounts.'], + ], 422); + } + + if ($request->filled('content')) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['content' => 'Content is not valid for host file mounts.'], + ], 422); + } + + try { + $fsPath = validateHostFileMountPath($request->fs_path, 'host file source path'); + $mountPath = validateFileMountPath($request->mount_path, 'host file destination path'); + } catch (\Throwable $e) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['mount_path' => $e->getMessage()], + ], 422); + } + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'content' => null, + 'is_directory' => false, + 'is_host_file' => true, + 'resource_id' => $application->id, + 'resource_type' => get_class($application), + ]); } else { - $mountPath = str($request->mount_path)->trim()->start('/')->value(); - - validateShellSafePath($mountPath, 'file storage path'); - - $fsPath = application_configuration_dir().'/'.$application->uuid.$mountPath; + try { + $mountPath = validateFileMountPath($request->mount_path, 'file storage path'); + $fsPath = confineFileMountPath(application_configuration_dir().'/'.$application->uuid, $mountPath, 'file storage path'); + } catch (\Throwable $e) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['mount_path' => $e->getMessage()], + ], 422); + } $storage = LocalFileVolume::create([ 'fs_path' => $fsPath, diff --git a/app/Http/Controllers/Api/DatabasesController.php b/app/Http/Controllers/Api/DatabasesController.php index 9a463e8d3..912f81728 100644 --- a/app/Http/Controllers/Api/DatabasesController.php +++ b/app/Http/Controllers/Api/DatabasesController.php @@ -3696,10 +3696,11 @@ class DatabasesController extends Controller 'host_path' => ['string', 'nullable', 'regex:'.ValidationPatterns::DIRECTORY_PATH_PATTERN], 'content' => 'string|nullable', 'is_directory' => 'boolean', + 'is_host_file' => 'boolean', 'fs_path' => 'string', ]); - $allAllowedFields = ['type', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'fs_path']; + $allAllowedFields = ['type', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'is_host_file', 'fs_path']; $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); if ($validator->fails() || ! empty($extraFields)) { $errors = $validator->errors(); @@ -3723,7 +3724,7 @@ class DatabasesController extends Controller ], 422); } - $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'fs_path'], array_keys($request->all())); + $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'is_host_file', 'fs_path'], array_keys($request->all())); if (! empty($typeSpecificInvalidFields)) { return response()->json([ 'message' => 'Validation failed.', @@ -3754,6 +3755,14 @@ class DatabasesController extends Controller } $isDirectory = $request->boolean('is_directory', false); + $isHostFile = $request->boolean('is_host_file', false); + + if ($isDirectory && $isHostFile) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['is_host_file' => 'Host file mounts cannot also be directory mounts.'], + ], 422); + } if ($isDirectory) { if (! $request->fs_path) { @@ -3776,12 +3785,50 @@ class DatabasesController extends Controller 'resource_id' => $database->id, 'resource_type' => get_class($database), ]); + } elseif ($isHostFile) { + if (! $request->fs_path) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['fs_path' => 'The fs_path field is required for host file mounts.'], + ], 422); + } + + if ($request->filled('content')) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['content' => 'Content is not valid for host file mounts.'], + ], 422); + } + + try { + $fsPath = validateHostFileMountPath($request->fs_path, 'host file source path'); + $mountPath = validateFileMountPath($request->mount_path, 'host file destination path'); + } catch (\Throwable $e) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['mount_path' => $e->getMessage()], + ], 422); + } + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'content' => null, + 'is_directory' => false, + 'is_host_file' => true, + 'resource_id' => $database->id, + 'resource_type' => get_class($database), + ]); } else { - $mountPath = str($request->mount_path)->trim()->start('/')->value(); - - validateShellSafePath($mountPath, 'file storage path'); - - $fsPath = database_configuration_dir().'/'.$database->uuid.$mountPath; + try { + $mountPath = validateFileMountPath($request->mount_path, 'file storage path'); + $fsPath = confineFileMountPath(database_configuration_dir().'/'.$database->uuid, $mountPath, 'file storage path'); + } catch (\Throwable $e) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['mount_path' => $e->getMessage()], + ], 422); + } $storage = LocalFileVolume::create([ 'fs_path' => $fsPath, diff --git a/app/Http/Controllers/Api/ServicesController.php b/app/Http/Controllers/Api/ServicesController.php index 32137b866..6c121bcf8 100644 --- a/app/Http/Controllers/Api/ServicesController.php +++ b/app/Http/Controllers/Api/ServicesController.php @@ -2115,10 +2115,11 @@ class ServicesController extends Controller 'host_path' => ['string', 'nullable', 'regex:'.ValidationPatterns::DIRECTORY_PATH_PATTERN], 'content' => 'string|nullable', 'is_directory' => 'boolean', + 'is_host_file' => 'boolean', 'fs_path' => 'string', ]); - $allAllowedFields = ['type', 'resource_uuid', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'fs_path']; + $allAllowedFields = ['type', 'resource_uuid', 'name', 'mount_path', 'host_path', 'content', 'is_directory', 'is_host_file', 'fs_path']; $extraFields = array_diff(array_keys($request->all()), $allAllowedFields); if ($validator->fails() || ! empty($extraFields)) { $errors = $validator->errors(); @@ -2150,7 +2151,7 @@ class ServicesController extends Controller ], 422); } - $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'fs_path'], array_keys($request->all())); + $typeSpecificInvalidFields = array_intersect(['content', 'is_directory', 'is_host_file', 'fs_path'], array_keys($request->all())); if (! empty($typeSpecificInvalidFields)) { return response()->json([ 'message' => 'Validation failed.', @@ -2181,6 +2182,14 @@ class ServicesController extends Controller } $isDirectory = $request->boolean('is_directory', false); + $isHostFile = $request->boolean('is_host_file', false); + + if ($isDirectory && $isHostFile) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['is_host_file' => 'Host file mounts cannot also be directory mounts.'], + ], 422); + } if ($isDirectory) { if (! $request->fs_path) { @@ -2203,12 +2212,50 @@ class ServicesController extends Controller 'resource_id' => $subResource->id, 'resource_type' => get_class($subResource), ]); + } elseif ($isHostFile) { + if (! $request->fs_path) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['fs_path' => 'The fs_path field is required for host file mounts.'], + ], 422); + } + + if ($request->filled('content')) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['content' => 'Content is not valid for host file mounts.'], + ], 422); + } + + try { + $fsPath = validateHostFileMountPath($request->fs_path, 'host file source path'); + $mountPath = validateFileMountPath($request->mount_path, 'host file destination path'); + } catch (\Throwable $e) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['mount_path' => $e->getMessage()], + ], 422); + } + + $storage = LocalFileVolume::create([ + 'fs_path' => $fsPath, + 'mount_path' => $mountPath, + 'content' => null, + 'is_directory' => false, + 'is_host_file' => true, + 'resource_id' => $subResource->id, + 'resource_type' => get_class($subResource), + ]); } else { - $mountPath = str($request->mount_path)->trim()->start('/')->value(); - - validateShellSafePath($mountPath, 'file storage path'); - - $fsPath = service_configuration_dir().'/'.$service->uuid.$mountPath; + try { + $mountPath = validateFileMountPath($request->mount_path, 'file storage path'); + $fsPath = confineFileMountPath(service_configuration_dir().'/'.$service->uuid, $mountPath, 'file storage path'); + } catch (\Throwable $e) { + return response()->json([ + 'message' => 'Validation failed.', + 'errors' => ['mount_path' => $e->getMessage()], + ], 422); + } $storage = LocalFileVolume::create([ 'fs_path' => $fsPath, diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php index b7283550c..545735cf6 100644 --- a/app/Jobs/ApplicationDeploymentJob.php +++ b/app/Jobs/ApplicationDeploymentJob.php @@ -1031,7 +1031,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue ); } foreach ($this->application->fileStorages as $fileStorage) { - if (! $fileStorage->is_based_on_git && ! $fileStorage->is_directory) { + if (! $fileStorage->is_host_file && ! $fileStorage->is_based_on_git && ! $fileStorage->is_directory) { $fileStorage->saveStorageOnServer(); } } diff --git a/app/Livewire/Project/Service/FileStorage.php b/app/Livewire/Project/Service/FileStorage.php index 877142d8b..e869ca91b 100644 --- a/app/Livewire/Project/Service/FileStorage.php +++ b/app/Livewire/Project/Service/FileStorage.php @@ -94,6 +94,10 @@ class FileStorage extends Component try { $this->authorize('update', $this->resource); + if ($this->fileStorage->is_host_file) { + throw new \Exception('Host file mounts are bind-only and cannot be converted.'); + } + $this->fileStorage->deleteStorageOnServer(); $this->fileStorage->is_directory = true; $this->fileStorage->content = null; @@ -112,6 +116,10 @@ class FileStorage extends Component try { $this->authorize('update', $this->resource); + if ($this->fileStorage->is_host_file) { + throw new \Exception('Host file mounts are bind-only and cannot be loaded from the server.'); + } + $this->fileStorage->loadStorageOnServer(); $this->syncData(); $this->dispatch('success', 'File storage loaded from server.'); @@ -127,6 +135,10 @@ class FileStorage extends Component try { $this->authorize('update', $this->resource); + if ($this->fileStorage->is_host_file) { + throw new \Exception('Host file mounts are bind-only and cannot be converted.'); + } + $this->fileStorage->deleteStorageOnServer(); $this->fileStorage->is_directory = false; $this->fileStorage->content = null; @@ -154,8 +166,10 @@ class FileStorage extends Component $message = 'File deleted.'; if ($this->fileStorage->is_directory) { $message = 'Directory deleted.'; + } elseif ($this->fileStorage->is_host_file) { + $message = 'Host file mount removed.'; } - if ($this->permanently_delete) { + if ($this->permanently_delete && ! $this->fileStorage->is_host_file) { $message = 'Directory deleted from the server.'; $this->fileStorage->deleteStorageOnServer(); } @@ -174,6 +188,12 @@ class FileStorage extends Component { $this->authorize('update', $this->resource); + if ($this->fileStorage->is_host_file) { + $this->dispatch('error', 'Host file mounts are bind-only and cannot be edited from the UI.'); + + return; + } + if ($this->fileStorage->is_too_large) { $this->dispatch('error', 'File on server is too large to edit from the UI.'); @@ -205,6 +225,12 @@ class FileStorage extends Component public function instantSave(): void { $this->authorize('update', $this->resource); + if ($this->fileStorage->is_host_file) { + $this->dispatch('error', 'Host file mounts are bind-only and cannot be edited from the UI.'); + + return; + } + if ($this->fileStorage->is_too_large) { $this->dispatch('error', 'File on server is too large to edit from the UI.'); @@ -223,6 +249,9 @@ class FileStorage extends Component 'fileDeletionCheckboxes' => [ ['id' => 'permanently_delete', 'label' => 'The selected file will be permanently deleted form the server.'], ], + 'hostFileDeletionCheckboxes' => [ + ['id' => 'permanently_delete', 'label' => 'Only the mount configuration will be removed. The host file will not be deleted.'], + ], ]); } } diff --git a/app/Livewire/Project/Service/Storage.php b/app/Livewire/Project/Service/Storage.php index 30655691a..9b097f2e1 100644 --- a/app/Livewire/Project/Service/Storage.php +++ b/app/Livewire/Project/Service/Storage.php @@ -29,6 +29,10 @@ class Storage extends Component public ?string $file_storage_content = null; + public string $host_file_storage_source = ''; + + public string $host_file_storage_destination = ''; + public string $file_storage_directory_source = ''; public string $file_storage_directory_destination = ''; @@ -146,19 +150,9 @@ class Storage extends Component 'file_storage_content' => 'nullable|string', ]); - $this->file_storage_path = trim($this->file_storage_path); - $this->file_storage_path = str($this->file_storage_path)->start('/')->value(); + $this->file_storage_path = validateFileMountPath($this->file_storage_path, 'file storage path'); - // Validate path to prevent command injection - validateShellSafePath($this->file_storage_path, 'file storage path'); - - if ($this->resource->getMorphClass() === Application::class) { - $fs_path = application_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path; - } elseif (str($this->resource->getMorphClass())->contains('Standalone')) { - $fs_path = database_configuration_dir().'/'.$this->resource->uuid.$this->file_storage_path; - } else { - throw new \Exception('No valid resource type for file mount storage type!'); - } + $fs_path = confineFileMountPath($this->fileStorageHostPath(), $this->file_storage_path, 'file storage path'); LocalFileVolume::create([ 'fs_path' => $fs_path, @@ -178,6 +172,38 @@ class Storage extends Component } } + public function submitHostFileStorage() + { + try { + $this->authorize('update', $this->resource); + + $this->validate([ + 'host_file_storage_source' => 'required|string', + 'host_file_storage_destination' => 'required|string', + ]); + + $this->host_file_storage_source = validateHostFileMountPath($this->host_file_storage_source, 'host file source path'); + $this->host_file_storage_destination = validateFileMountPath($this->host_file_storage_destination, 'host file destination path'); + + LocalFileVolume::create([ + 'fs_path' => $this->host_file_storage_source, + 'mount_path' => $this->host_file_storage_destination, + 'content' => null, + 'is_directory' => false, + 'is_host_file' => true, + 'resource_id' => $this->resource->id, + 'resource_type' => get_class($this->resource), + ]); + + $this->dispatch('success', 'Host file mount added successfully'); + $this->dispatch('closeStorageModal', 'host-file'); + $this->clearForm(); + $this->refreshStorages(); + } catch (\Throwable $e) { + return handleError($e, $this); + } + } + public function submitFileStorageDirectory() { try { @@ -222,6 +248,8 @@ class Storage extends Component $this->file_storage_path = ''; $this->file_storage_content = null; $this->file_storage_directory_destination = ''; + $this->host_file_storage_source = ''; + $this->host_file_storage_destination = ''; if (str($this->resource->getMorphClass())->contains('Standalone')) { $this->file_storage_directory_source = database_configuration_dir()."/{$this->resource->uuid}"; @@ -230,6 +258,34 @@ class Storage extends Component } } + public function fileStorageHostPath(): string + { + if (method_exists($this->resource, 'workdir')) { + return $this->resource->workdir(); + } + + if ($this->resource->getMorphClass() === Application::class) { + return application_configuration_dir().'/'.$this->resource->uuid; + } + + if (str($this->resource->getMorphClass())->contains('Standalone')) { + return database_configuration_dir().'/'.$this->resource->uuid; + } + + throw new \Exception('No valid resource type for file mount storage type!'); + } + + public function fileStoragePreviewPath(): string + { + $path = str($this->file_storage_path)->trim(); + + if ($path->isEmpty()) { + return $this->fileStorageHostPath().'/'; + } + + return $this->fileStorageHostPath().$path->start('/')->value(); + } + public function render() { return view('livewire.project.service.storage'); diff --git a/app/Models/LocalFileVolume.php b/app/Models/LocalFileVolume.php index 627750232..b521ede3d 100644 --- a/app/Models/LocalFileVolume.php +++ b/app/Models/LocalFileVolume.php @@ -21,6 +21,7 @@ class LocalFileVolume extends BaseModel // 'mount_path' => 'encrypted', 'content' => 'encrypted', 'is_directory' => 'boolean', + 'is_host_file' => 'boolean', 'is_preview_suffix_enabled' => 'boolean', ]; @@ -33,6 +34,7 @@ class LocalFileVolume extends BaseModel 'resource_type', 'resource_id', 'is_directory', + 'is_host_file', 'chown', 'chmod', 'is_based_on_git', @@ -44,6 +46,10 @@ class LocalFileVolume extends BaseModel protected static function booted() { static::created(function (LocalFileVolume $fileVolume) { + if ($fileVolume->is_host_file) { + return; + } + $fileVolume->load(['service']); dispatch(new ServerStorageSaveJob($fileVolume)); }); @@ -70,6 +76,10 @@ class LocalFileVolume extends BaseModel public function loadStorageOnServer() { + if ($this->is_host_file) { + return; + } + $this->load(['service']); $isService = data_get($this->resource, 'service'); if ($isService) { @@ -124,6 +134,10 @@ class LocalFileVolume extends BaseModel public function deleteStorageOnServer() { + if ($this->is_host_file) { + return; + } + $this->load(['service']); $isService = data_get($this->resource, 'service'); if ($isService) { @@ -161,6 +175,10 @@ class LocalFileVolume extends BaseModel public function saveStorageOnServer() { + if ($this->is_host_file) { + return; + } + $this->load(['service']); $isService = data_get($this->resource, 'service'); if ($isService) { @@ -171,26 +189,26 @@ class LocalFileVolume extends BaseModel $server = $this->resource->destination->server; } $commands = collect([]); - - // Validate fs_path early before any shell interpolation - validateShellSafePath($this->fs_path, 'storage path'); - $escapedFsPath = escapeshellarg($this->fs_path); $escapedWorkdir = escapeshellarg($workdir); if ($this->is_directory) { + // Validate fs_path early before any shell interpolation + validateShellSafePath($this->fs_path, 'storage path'); + $escapedFsPath = escapeshellarg($this->fs_path); $commands->push("mkdir -p {$escapedFsPath} > /dev/null 2>&1 || true"); $commands->push("mkdir -p {$escapedWorkdir} > /dev/null 2>&1 || true"); $commands->push("cd {$escapedWorkdir}"); } - if (str($this->fs_path)->startsWith('.') || str($this->fs_path)->startsWith('/') || str($this->fs_path)->startsWith('~')) { - $parent_dir = str($this->fs_path)->beforeLast('/'); + $path = data_get_str($this, 'fs_path'); + $content = data_get($this, 'content'); + $pathForParentDirectory = str($this->fs_path); + if ($pathForParentDirectory->startsWith('.') || $pathForParentDirectory->startsWith('/') || $pathForParentDirectory->startsWith('~')) { + $parent_dir = $pathForParentDirectory->beforeLast('/'); if ($parent_dir != '') { $escapedParentDir = escapeshellarg($parent_dir); $commands->push("mkdir -p {$escapedParentDir} > /dev/null 2>&1 || true"); } } - $path = data_get_str($this, 'fs_path'); - $content = data_get($this, 'content'); if ($path->startsWith('.')) { $path = $path->after('.'); $path = $workdir.$path; diff --git a/bootstrap/helpers/shared.php b/bootstrap/helpers/shared.php index 7b113e7b8..ab47c067a 100644 --- a/bootstrap/helpers/shared.php +++ b/bootstrap/helpers/shared.php @@ -166,7 +166,7 @@ function validateShellSafePath(string $input, string $context = 'path'): string /** * Validate that a filename is safe for use as a plain file name (no path components). * - * Prevents path traversal attacks by rejecting directory separators, traversal + * Prevents unsafe parent directory paths by rejecting directory separators, parent directory * sequences, and null bytes, in addition to all shell metacharacters blocked by * validateShellSafePath(). Intended for user-supplied filenames such as PostgreSQL * init script names that are later written to a specific directory on the host. @@ -175,7 +175,7 @@ function validateShellSafePath(string $input, string $context = 'path'): string * @param string $context Descriptive name for error messages (e.g., 'init script filename') * @return string The validated input (unchanged if valid) * - * @throws Exception If dangerous characters or path traversal sequences are detected + * @throws Exception If dangerous characters or parent directory sequences are detected */ function validateFilenameSafe(string $input, string $context = 'filename'): string { @@ -198,10 +198,10 @@ function validateFilenameSafe(string $input, string $context = 'filename'): stri ); } - // Reject path traversal sequences (catches encoded or unusual forms) + // Reject parent directory sequences (catches encoded or unusual forms) if (str_contains($input, '..')) { throw new Exception( - "Invalid {$context}: path traversal sequence ('..') is not allowed." + "Invalid {$context}: parent directory sequence ('..') is not allowed." ); } @@ -230,6 +230,197 @@ function validateFilenameSafe(string $input, string $context = 'filename'): stri return $input; } +/** + * Validate and normalize a user supplied file mount path. + * + * File mount paths are container paths supplied by tenants. They may look like + * absolute paths (for example /etc/nginx/nginx.conf), but are later joined to a + * Coolify-managed configuration directory on the host. Therefore shell safety is + * not enough: every path segment must also be unable to traverse out of that + * managed directory. + * + * @throws Exception + */ +function validateFileMountPath(string $input, string $context = 'file mount path'): string +{ + validateShellSafePath($input, $context); + + if (str_contains($input, "\0")) { + throw new Exception( + "Invalid {$context}: contains null byte. ". + 'Null bytes are not allowed in file mount paths for security reasons.' + ); + } + + if (str_contains($input, '\\')) { + throw new Exception( + "Invalid {$context}: backslash directory separators are not allowed." + ); + } + + $path = str($input)->trim()->start('/')->replaceMatches('#/+#', '/')->value(); + + foreach (explode('/', trim($path, '/')) as $segment) { + if ($segment === '' || ($segment !== '.' && $segment !== '..')) { + continue; + } + + throw new Exception( + "Invalid {$context}: relative path segments ('.' or '..') are not allowed." + ); + } + + return $path; +} + +/** + * Validate a host file path used as a bind-only source. + * + * Unlike managed file mounts, this path is not re-based under the Coolify + * configuration directory and must never be written by Coolify. It still needs + * to be shell-safe because other storage code may pass paths through remote + * shell commands. + * + * @throws Exception + */ +function validateHostFileMountPath(string $input, string $context = 'host file path'): string +{ + validateShellSafePath($input, $context); + + if (str_contains($input, "\0")) { + throw new Exception("Invalid {$context}: contains null byte."); + } + + if (str_contains($input, '\\')) { + throw new Exception("Invalid {$context}: backslash directory separators are not allowed."); + } + + $path = str($input)->trim()->replaceMatches('#/+#', '/')->value(); + + if ($path === '' || ! str_starts_with($path, '/')) { + throw new Exception("Invalid {$context}: must be an absolute path."); + } + + if ($path === '/' || str_ends_with($path, '/')) { + throw new Exception("Invalid {$context}: must point to a file, not a directory."); + } + + foreach (explode('/', trim($path, '/')) as $segment) { + if ($segment === '' || ($segment !== '.' && $segment !== '..')) { + continue; + } + + throw new Exception("Invalid {$context}: relative path segments ('.' or '..') are not allowed."); + } + + return normalizeUnixPath($path); +} + +/** + * Resolve a tenant file mount path under a Coolify-managed base directory. + * + * This performs lexical normalization only; the target file does not need to + * exist yet. The normalized result must remain inside the given base directory. + * + * @throws Exception + */ +function confineFileMountPath(string $baseDirectory, string $path, string $context = 'file mount path'): string +{ + $baseDirectory = normalizeUnixPath($baseDirectory); + $mountPath = validateFileMountPath($path, $context); + $resolvedPath = normalizeUnixPath($baseDirectory.'/'.$mountPath); + + if ($resolvedPath !== $baseDirectory && ! str_starts_with($resolvedPath, $baseDirectory.'/')) { + throw new Exception( + "Invalid {$context}: resolved path must stay inside the resource configuration directory." + ); + } + + return $resolvedPath; +} + +/** + * Normalize an existing host path and assert it remains inside a base directory. + * + * Dot-relative paths are resolved against the base directory for legacy + * LocalFileVolume rows. Absolute paths must already point inside the base. + * + * @throws Exception + */ +function confinePathToBase(string $baseDirectory, string $path, string $context = 'path'): string +{ + $baseDirectory = normalizeUnixPath($baseDirectory); + $path = trim($path); + + if (str_starts_with($path, '.')) { + $path = $baseDirectory.'/'.str($path)->after('.')->value(); + } elseif (! str_starts_with($path, '/')) { + $path = $baseDirectory.'/'.$path; + } + + $resolvedPath = normalizeUnixPath($path); + + if ($resolvedPath !== $baseDirectory && ! str_starts_with($resolvedPath, $baseDirectory.'/')) { + throw new Exception( + "Invalid {$context}: resolved path must stay inside the resource configuration directory." + ); + } + + return $resolvedPath; +} + +/** + * Normalize a Unix path lexically without consulting the remote filesystem. + * + * @throws Exception + */ +function normalizeUnixPath(string $path): string +{ + validateShellSafePath($path, 'path'); + + if (str_contains($path, "\0")) { + throw new Exception('Invalid path: contains null byte.'); + } + + if (str_contains($path, '\\')) { + throw new Exception('Invalid path: backslash directory separators are not allowed.'); + } + + $isAbsolute = str_starts_with($path, '/'); + $segments = []; + + foreach (explode('/', $path) as $segment) { + if ($segment === '' || $segment === '.') { + continue; + } + + if ($segment === '..') { + if ($segments === [] || end($segments) === '..') { + if ($isAbsolute) { + throw new Exception('Invalid path: resolved path escapes the base directory.'); + } + $segments[] = $segment; + + continue; + } + + array_pop($segments); + + continue; + } + + $segments[] = $segment; + } + + $normalized = implode('/', $segments); + + if ($isAbsolute) { + return $normalized === '' ? '/' : '/'.$normalized; + } + + return $normalized === '' ? '.' : $normalized; +} + /** * Validate that a databases_to_backup input string is safe from command injection. * @@ -3819,7 +4010,7 @@ function formatBytes(?int $bytes, int $precision = 2): string /** * Validates that a file path is safely within the /tmp/ directory. - * Protects against path traversal attacks by resolving the real path + * Protects against unsafe parent directory paths by resolving the real path * and verifying it stays within /tmp/. * * Note: On macOS, /tmp is often a symlink to /private/tmp, which is handled. diff --git a/database/migrations/2026_07_02_112425_add_is_host_file_to_local_file_volumes_table.php b/database/migrations/2026_07_02_112425_add_is_host_file_to_local_file_volumes_table.php new file mode 100644 index 000000000..6de618632 --- /dev/null +++ b/database/migrations/2026_07_02_112425_add_is_host_file_to_local_file_volumes_table.php @@ -0,0 +1,36 @@ +boolean('is_host_file')->default(false)->after('is_directory'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + if (! Schema::hasColumn('local_file_volumes', 'is_host_file')) { + return; + } + + Schema::table('local_file_volumes', function (Blueprint $table) { + $table->dropColumn('is_host_file'); + }); + } +}; diff --git a/database/schema/testing-schema.sql b/database/schema/testing-schema.sql index edbc35db4..61c9b8e41 100644 --- a/database/schema/testing-schema.sql +++ b/database/schema/testing-schema.sql @@ -433,6 +433,7 @@ CREATE TABLE IF NOT EXISTS "local_file_volumes" ( "created_at" TEXT, "updated_at" TEXT, "is_directory" INTEGER DEFAULT false NOT NULL, + "is_host_file" INTEGER DEFAULT false NOT NULL, "chown" TEXT, "chmod" TEXT, "is_based_on_git" INTEGER DEFAULT false NOT NULL diff --git a/resources/views/livewire/project/service/file-storage.blade.php b/resources/views/livewire/project/service/file-storage.blade.php index 2a14d9350..e47d290b8 100644 --- a/resources/views/livewire/project/service/file-storage.blade.php +++ b/resources/views/livewire/project/service/file-storage.blade.php @@ -4,6 +4,10 @@
File on server exceeds 5 MB and cannot be edited from the UI. Edit it directly on the server.
+ @elseif ($fileStorage->is_host_file) +
+ This host file mount is bind-only. Coolify will not create, edit, load, chmod, or delete the source file. +
@elseif ($isReadOnly)
@if ($fileStorage->is_directory) @@ -32,7 +36,14 @@ @if (!$isReadOnly) @can('update', $resource)
- @if ($fileStorage->is_directory) + @if ($fileStorage->is_host_file) + + @elseif ($fileStorage->is_directory) @@ -99,7 +110,7 @@ @endif @else {{-- Read-only view --}} - @if (!$fileStorage->is_directory) + @if (!$fileStorage->is_directory && !$fileStorage->is_host_file) @can('update', $resource)
Load from diff --git a/resources/views/livewire/project/service/storage.blade.php b/resources/views/livewire/project/service/storage.blade.php index 9e32cd22d..2f5971842 100644 --- a/resources/views/livewire/project/service/storage.blade.php +++ b/resources/views/livewire/project/service/storage.blade.php @@ -22,11 +22,13 @@ dropdownOpen: false, volumeModalOpen: false, fileModalOpen: false, + hostFileModalOpen: false, directoryModalOpen: false }" @close-storage-modal.window=" if ($event.detail === 'volume') volumeModalOpen = false; if ($event.detail === 'file') fileModalOpen = false; + if ($event.detail === 'host-file') hostFileModalOpen = false; if ($event.detail === 'directory') directoryModalOpen = false; ">