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 1/9] 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 2/9] 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 3/9] 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 4/9] 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 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 5/9] 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 6/9] 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 @@ ## High-Level Expectations ## 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 @@ ## 2. Bug Report Contributions - 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 Usage Disclosure ## 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 @@ ## Test Before Submitting ## 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 @@ ## FAQ 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 @@ ## FAQ **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 7a853efa790fc34d2b2a833086d77c481ccfa7a8 Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 16:27:06 +0200 Subject: [PATCH 7/9] chore: inspect PR context (#10834) --- app/Jobs/ApplicationDeploymentJob.php | 9 +- ...ationDeploymentJobCommitResolutionTest.php | 121 ++++++++++++++++++ 2 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/ApplicationDeploymentJobCommitResolutionTest.php diff --git a/app/Jobs/ApplicationDeploymentJob.php b/app/Jobs/ApplicationDeploymentJob.php index 545735cf6..337562bb0 100644 --- a/app/Jobs/ApplicationDeploymentJob.php +++ b/app/Jobs/ApplicationDeploymentJob.php @@ -2327,7 +2327,7 @@ private function check_git_if_build_needed() ], ); } - if ($this->saved_outputs->get('git_commit_sha') && ! $this->rollback) { + if ($this->saved_outputs->get('git_commit_sha') && ! $this->rollback && $this->shouldResolveBranchHeadCommit()) { // Extract commit SHA from git ls-remote output, handling multi-line output (e.g., redirect warnings) // Expected format: "commit_sha\trefs/heads/branch" possibly preceded by warning lines // Note: Git warnings can be on the same line as the result (no newline) @@ -2359,6 +2359,13 @@ private function check_git_if_build_needed() } } + private function shouldResolveBranchHeadCommit(): bool + { + $commit = trim($this->commit); + + return $commit === '' || $commit === 'HEAD'; + } + private function clone_repository() { $importCommands = $this->generate_git_import_commands(); diff --git a/tests/Unit/ApplicationDeploymentJobCommitResolutionTest.php b/tests/Unit/ApplicationDeploymentJobCommitResolutionTest.php new file mode 100644 index 000000000..f11d6ac16 --- /dev/null +++ b/tests/Unit/ApplicationDeploymentJobCommitResolutionTest.php @@ -0,0 +1,121 @@ +setValue($job, $value); +} + +function getDeploymentJobProperty(object $job, string $property): mixed +{ + $reflectionProperty = new ReflectionProperty(ApplicationDeploymentJob::class, $property); + + return $reflectionProperty->getValue($job); +} + +function invokeCheckGitIfBuildNeeded(object $job): void +{ + $method = new ReflectionMethod(ApplicationDeploymentJob::class, 'check_git_if_build_needed'); + $method->invoke($job); +} + +function makeDeploymentJobForCommitCheck(string $pinnedSha, string $branchHeadSha): object +{ + $job = new class extends ApplicationDeploymentJob + { + public function __construct() {} + + public function execute_remote_command(...$commands) {} + }; + + $application = new class extends Application + { + public function generateGitImportCommands(string $deployment_uuid, int $pull_request_id = 0, ?string $git_type = null, bool $exec_in_docker = true, bool $only_checkout = false, ?string $custom_base_dir = null, ?string $commit = null) + { + return [ + 'commands' => collect([]), + 'branch' => 'main', + 'fullRepoUrl' => 'https://github.com/coollabsio/coolify.git', + ]; + } + }; + $application->forceFill([ + 'uuid' => 'application-uuid', + 'git_branch' => 'main', + ]); + $application->setRelation('settings', (object) [ + 'include_source_commit_in_build' => false, + 'use_build_secrets' => false, + ]); + $application->setRelation('private_key', null); + + $deploymentQueue = new class extends ApplicationDeploymentQueue + { + public bool $saved = false; + + public function save(array $options = []): bool + { + $this->saved = true; + + return true; + } + }; + $deploymentQueue->commit = $pinnedSha; + + setDeploymentJobProperty($job, 'application', $application); + setDeploymentJobProperty($job, 'application_deployment_queue', $deploymentQueue); + setDeploymentJobProperty($job, 'deployment_uuid', 'deployment-uuid'); + setDeploymentJobProperty($job, 'pull_request_id', 0); + setDeploymentJobProperty($job, 'commit', $pinnedSha); + setDeploymentJobProperty($job, 'rollback', false); + setDeploymentJobProperty($job, 'git_type', 'github'); + setDeploymentJobProperty($job, 'saved_outputs', collect([ + 'git_commit_sha' => str("{$branchHeadSha}\trefs/heads/main"), + ])); + + return $job; +} + +function shouldResolveBranchHeadForCommit(?string $commit): bool +{ + $job = (new ReflectionClass(ApplicationDeploymentJob::class))->newInstanceWithoutConstructor(); + + $commitProperty = new ReflectionProperty($job, 'commit'); + $commitProperty->setValue($job, $commit ?? ''); + + $method = new ReflectionMethod($job, 'shouldResolveBranchHeadCommit'); + + return $method->invoke($job); +} + +describe('ApplicationDeploymentJob commit resolution', function () { + test('resolves branch head for HEAD deployments', function () { + expect(shouldResolveBranchHeadForCommit('HEAD'))->toBeTrue(); + }); + + test('resolves branch head for blank deployments', function () { + expect(shouldResolveBranchHeadForCommit(''))->toBeTrue(); + }); + + test('keeps pinned deployment commits instead of replacing them with branch head', function () { + expect(shouldResolveBranchHeadForCommit('abc123def456abc123def456abc123def456abc1'))->toBeFalse(); + }); + + test('check git does not overwrite pinned deployment commit with branch head', function () { + $pinnedSha = 'abc123def456abc123def456abc123def456abc1'; + $branchHeadSha = '111222333444555666777888999000aaabbbccc1'; + $job = makeDeploymentJobForCommitCheck($pinnedSha, $branchHeadSha); + + invokeCheckGitIfBuildNeeded($job); + + $deploymentQueue = getDeploymentJobProperty($job, 'application_deployment_queue'); + + expect(getDeploymentJobProperty($job, 'commit'))->toBe($pinnedSha) + ->and($deploymentQueue->commit)->toBe($pinnedSha) + ->and($deploymentQueue->saved)->toBeFalse(); + }); +}); From 0bf97df9afa311f633beb01e20d060f2c32eabdb Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 16:35:39 +0200 Subject: [PATCH 8/9] feat: add internal endpoint controls --- app/Jobs/DatabaseBackupJob.php | 7 +- app/Jobs/SendMessageToDiscordJob.php | 15 +- app/Jobs/SendMessageToSlackJob.php | 31 +- app/Jobs/SendWebhookJob.php | 15 +- app/Livewire/Project/Database/ImportForm.php | 2 + app/Livewire/Settings/Advanced.php | 66 ++- app/Models/InstanceSettings.php | 8 + app/Models/S3Storage.php | 5 +- app/Rules/SafeWebhookUrl.php | 420 ++++++++++++++++-- ...l_allowlist_to_instance_settings_table.php | 23 + .../livewire/settings/advanced.blade.php | 9 + .../Unit/S3StorageEndpointValidationTest.php | 31 +- tests/Unit/SafeWebhookUrlTest.php | 167 ++++++- 13 files changed, 713 insertions(+), 86 deletions(-) create mode 100644 database/migrations/2026_07_02_142003_add_webhook_internal_allowlist_to_instance_settings_table.php diff --git a/app/Jobs/DatabaseBackupJob.php b/app/Jobs/DatabaseBackupJob.php index 9878e0a38..6bc6e48db 100644 --- a/app/Jobs/DatabaseBackupJob.php +++ b/app/Jobs/DatabaseBackupJob.php @@ -16,6 +16,7 @@ use App\Notifications\Database\BackupFailed; use App\Notifications\Database\BackupSuccess; use App\Notifications\Database\BackupSuccessWithS3Warning; +use App\Rules\SafeWebhookUrl; use Carbon\Carbon; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeEncrypted; @@ -716,8 +717,12 @@ private function upload_to_s3(): void $escapedSecret = escapeshellarg($secret); $escapedBackupLocation = escapeshellarg($this->backup_location); $escapedS3Destination = escapeshellarg("temporary/{$bucket}{$this->backup_dir}/"); + $resolveOptions = collect(SafeWebhookUrl::minioClientResolveOptions($endpoint)) + ->map(fn (string $resolveOption): string => '--resolve '.escapeshellarg($resolveOption)) + ->implode(' '); + $resolveOptions = $resolveOptions === '' ? '' : ' '.$resolveOptions; - $commands[] = "docker exec backup-of-{$this->backup_log_uuid} mc alias set temporary {$escapedEndpoint} {$escapedKey} {$escapedSecret}"; + $commands[] = "docker exec backup-of-{$this->backup_log_uuid} mc alias set{$resolveOptions} temporary {$escapedEndpoint} {$escapedKey} {$escapedSecret}"; $commands[] = "docker exec backup-of-{$this->backup_log_uuid} mc cp {$escapedBackupLocation} {$escapedS3Destination}"; instant_remote_process($commands, $this->server, true, false, null, disableMultiplexing: true); diff --git a/app/Jobs/SendMessageToDiscordJob.php b/app/Jobs/SendMessageToDiscordJob.php index 9ac017396..d5c29efb0 100644 --- a/app/Jobs/SendMessageToDiscordJob.php +++ b/app/Jobs/SendMessageToDiscordJob.php @@ -51,13 +51,24 @@ public function handle(): void if ($validator->fails()) { Log::warning('SendMessageToDiscordJob: blocked unsafe webhook URL', [ - 'url' => $this->webhookUrl, + 'url' => SafeWebhookUrl::redactedUrlForLog($this->webhookUrl), 'errors' => $validator->errors()->all(), ]); return; } - Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, $this->message->toPayload()); + try { + $httpOptions = SafeWebhookUrl::httpClientOptions($this->webhookUrl); + } catch (\RuntimeException $e) { + Log::warning('SendMessageToDiscordJob: blocked unsafe webhook URL at send time', [ + 'url' => SafeWebhookUrl::redactedUrlForLog($this->webhookUrl), + 'error' => $e->getMessage(), + ]); + + return; + } + + Http::withOptions($httpOptions)->post($this->webhookUrl, $this->message->toPayload()); } } diff --git a/app/Jobs/SendMessageToSlackJob.php b/app/Jobs/SendMessageToSlackJob.php index e5cff5818..3a306c23d 100644 --- a/app/Jobs/SendMessageToSlackJob.php +++ b/app/Jobs/SendMessageToSlackJob.php @@ -44,15 +44,26 @@ public function handle(): void if ($validator->fails()) { Log::warning('SendMessageToSlackJob: blocked unsafe webhook URL', [ - 'url' => $this->webhookUrl, + 'url' => SafeWebhookUrl::redactedUrlForLog($this->webhookUrl), 'errors' => $validator->errors()->all(), ]); return; } + try { + $httpOptions = SafeWebhookUrl::httpClientOptions($this->webhookUrl); + } catch (\RuntimeException $e) { + Log::warning('SendMessageToSlackJob: blocked unsafe webhook URL at send time', [ + 'url' => SafeWebhookUrl::redactedUrlForLog($this->webhookUrl), + 'error' => $e->getMessage(), + ]); + + return; + } + if ($this->isSlackWebhook()) { - $this->sendToSlack(); + $this->sendToSlack($httpOptions); return; } @@ -62,7 +73,7 @@ public function handle(): void * * @see https://github.com/coollabsio/coolify/pull/6139#issuecomment-3756777708 */ - $this->sendToMattermost(); + $this->sendToMattermost($httpOptions); } private function isSlackWebhook(): bool @@ -79,9 +90,12 @@ private function isSlackWebhook(): bool return $scheme === 'https' && $host === 'hooks.slack.com'; } - private function sendToSlack(): void + /** + * @param array $httpOptions + */ + private function sendToSlack(array $httpOptions): void { - Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, [ + Http::withOptions($httpOptions)->post($this->webhookUrl, [ 'text' => $this->message->title, 'blocks' => [ [ @@ -119,11 +133,14 @@ private function sendToSlack(): void /** * @todo v5 refactor: Extract this into a separate SendMessageToMattermostJob.php triggered via the "mattermost" notification channel type. */ - private function sendToMattermost(): void + /** + * @param array $httpOptions + */ + private function sendToMattermost(array $httpOptions): void { $username = config('app.name'); - Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, [ + Http::withOptions($httpOptions)->post($this->webhookUrl, [ 'username' => $username, 'attachments' => [ [ diff --git a/app/Jobs/SendWebhookJob.php b/app/Jobs/SendWebhookJob.php index beee24179..accbf906f 100644 --- a/app/Jobs/SendWebhookJob.php +++ b/app/Jobs/SendWebhookJob.php @@ -50,7 +50,7 @@ public function handle(): void if ($validator->fails()) { Log::warning('SendWebhookJob: blocked unsafe webhook URL', [ - 'url' => $this->webhookUrl, + 'url' => SafeWebhookUrl::redactedUrlForLog($this->webhookUrl), 'errors' => $validator->errors()->all(), ]); @@ -64,7 +64,18 @@ public function handle(): void ]); } - $response = Http::withOptions(['allow_redirects' => false])->post($this->webhookUrl, $this->payload); + try { + $httpOptions = SafeWebhookUrl::httpClientOptions($this->webhookUrl); + } catch (\RuntimeException $e) { + Log::warning('SendWebhookJob: blocked unsafe webhook URL at send time', [ + 'url' => SafeWebhookUrl::redactedUrlForLog($this->webhookUrl), + 'error' => $e->getMessage(), + ]); + + return; + } + + $response = Http::withOptions($httpOptions)->post($this->webhookUrl, $this->payload); if (isDev()) { ray('Webhook response', [ diff --git a/app/Livewire/Project/Database/ImportForm.php b/app/Livewire/Project/Database/ImportForm.php index 2f6bcb3b4..f97e78fa7 100644 --- a/app/Livewire/Project/Database/ImportForm.php +++ b/app/Livewire/Project/Database/ImportForm.php @@ -14,6 +14,7 @@ use App\Models\StandaloneMysql; use App\Models\StandalonePostgresql; use App\Models\StandaloneRedis; +use App\Rules\SafeWebhookUrl; use App\Support\DatabaseBackupFileValidator; use App\Support\ValidationPatterns; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; @@ -598,6 +599,7 @@ public function checkS3File() 'bucket' => $s3Storage->bucket, 'endpoint' => $s3Storage->endpoint, 'use_path_style_endpoint' => true, + 'http' => SafeWebhookUrl::httpClientOptions($s3Storage->endpoint), ]); // Check if file exists diff --git a/app/Livewire/Settings/Advanced.php b/app/Livewire/Settings/Advanced.php index 5be066c7f..bbe397819 100644 --- a/app/Livewire/Settings/Advanced.php +++ b/app/Livewire/Settings/Advanced.php @@ -43,6 +43,11 @@ class Advanced extends Component #[Validate('boolean')] public bool $is_mcp_server_enabled; + public ?string $webhook_allowed_internal_hosts = null; + + #[Validate('boolean')] + public bool $webhook_allow_localhost; + public function rules() { return [ @@ -56,6 +61,8 @@ public function rules() 'disable_two_step_confirmation' => 'boolean', 'is_wire_navigate_enabled' => 'boolean', 'is_mcp_server_enabled' => 'boolean', + 'webhook_allowed_internal_hosts' => 'nullable|string', + 'webhook_allow_localhost' => 'boolean', ]; } @@ -75,6 +82,8 @@ public function mount() $this->is_sponsorship_popup_enabled = $this->settings->is_sponsorship_popup_enabled; $this->is_wire_navigate_enabled = $this->settings->is_wire_navigate_enabled ?? true; $this->is_mcp_server_enabled = $this->settings->is_mcp_server_enabled ?? false; + $this->webhook_allowed_internal_hosts = collect($this->settings->webhook_allowed_internal_hosts ?? [])->implode(','); + $this->webhook_allow_localhost = $this->settings->webhook_allow_localhost ?? false; } public function submit() @@ -141,13 +150,21 @@ public function submit() $this->allowed_ips = implode(',', $validEntries); } - $this->instantSave(); + $webhookAllowedInternalHosts = $this->normalizeWebhookAllowedInternalHosts(); + if ($webhookAllowedInternalHosts === false) { + return; + } + + $this->instantSave($webhookAllowedInternalHosts); } catch (\Exception $e) { return handleError($e, $this); } } - public function instantSave() + /** + * @param array|null $webhookAllowedInternalHosts + */ + public function instantSave(?array $webhookAllowedInternalHosts = null) { try { $this->authorize('update', $this->settings); @@ -161,6 +178,8 @@ public function instantSave() $this->settings->disable_two_step_confirmation = $this->disable_two_step_confirmation; $this->settings->is_wire_navigate_enabled = $this->is_wire_navigate_enabled; $this->settings->is_mcp_server_enabled = $this->is_mcp_server_enabled; + $this->settings->webhook_allowed_internal_hosts = $webhookAllowedInternalHosts ?? $this->settings->webhook_allowed_internal_hosts ?? []; + $this->settings->webhook_allow_localhost = $this->webhook_allow_localhost; $this->settings->save(); $this->dispatch('success', 'Settings updated!'); } catch (\Exception $e) { @@ -168,6 +187,49 @@ public function instantSave() } } + /** + * @return array|false + */ + private function normalizeWebhookAllowedInternalHosts(): array|false + { + $entries = collect(preg_split('/[,\r\n]+/', $this->webhook_allowed_internal_hosts ?? '') ?: []) + ->map(fn (string $entry): string => rtrim(strtolower(trim($entry)), '.')) + ->filter() + ->unique() + ->values(); + + $invalidEntries = $entries->reject(fn (string $entry): bool => $this->isValidWebhookAllowlistEntry($entry)); + if ($invalidEntries->isNotEmpty()) { + $this->dispatch('error', 'Invalid webhook internal allowlist entries: '.$invalidEntries->implode(', ')); + + return false; + } + + $this->webhook_allowed_internal_hosts = $entries->implode(','); + + return $entries->all(); + } + + private function isValidWebhookAllowlistEntry(string $entry): bool + { + if (filter_var($entry, FILTER_VALIDATE_IP)) { + return true; + } + + if (str_contains($entry, '/')) { + [$ip, $mask] = array_pad(explode('/', $entry, 2), 2, null); + $isIpv6 = filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) !== false; + $maxMask = $isIpv6 ? 128 : 32; + + return filter_var($ip, FILTER_VALIDATE_IP) !== false + && is_numeric($mask) + && (int) $mask >= 0 + && (int) $mask <= $maxMask; + } + + return filter_var($entry, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) !== false; + } + public function toggleRegistration($password): bool { if (! verifyPasswordConfirmation($password, $this)) { diff --git a/app/Models/InstanceSettings.php b/app/Models/InstanceSettings.php index d5c3bfa28..57d3e6ae6 100644 --- a/app/Models/InstanceSettings.php +++ b/app/Models/InstanceSettings.php @@ -46,6 +46,8 @@ class InstanceSettings extends Model 'dev_helper_version', 'is_wire_navigate_enabled', 'is_mcp_server_enabled', + 'webhook_allowed_internal_hosts', + 'webhook_allow_localhost', ]; protected $casts = [ @@ -69,10 +71,16 @@ class InstanceSettings extends Model 'sentinel_token' => 'encrypted', 'is_wire_navigate_enabled' => 'boolean', 'is_mcp_server_enabled' => 'boolean', + 'webhook_allowed_internal_hosts' => 'array', + 'webhook_allow_localhost' => 'boolean', ]; protected static function booted(): void { + static::created(function () { + Once::flush(); + }); + static::updated(function ($settings) { // Clear once() cache so subsequent calls get fresh data Once::flush(); diff --git a/app/Models/S3Storage.php b/app/Models/S3Storage.php index 3ffac87e1..fe08984ed 100644 --- a/app/Models/S3Storage.php +++ b/app/Models/S3Storage.php @@ -173,11 +173,10 @@ public function testConnection(bool $shouldSave = false) 'bucket' => $this['bucket'], 'endpoint' => $this['endpoint'], 'use_path_style_endpoint' => true, - 'http' => [ + 'http' => array_merge(SafeWebhookUrl::httpClientOptions($this['endpoint']), [ 'connect_timeout' => self::CONNECTION_TIMEOUT_SECONDS, 'timeout' => self::REQUEST_TIMEOUT_SECONDS, - 'allow_redirects' => false, - ], + ]), ]); // Test the connection by listing files with ListObjectsV2 (S3) $disk->files(); diff --git a/app/Rules/SafeWebhookUrl.php b/app/Rules/SafeWebhookUrl.php index ead03e9c0..e171ba46c 100644 --- a/app/Rules/SafeWebhookUrl.php +++ b/app/Rules/SafeWebhookUrl.php @@ -2,9 +2,11 @@ namespace App\Rules; +use App\Models\InstanceSettings; use Closure; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use Throwable; class SafeWebhookUrl implements ValidationRule { @@ -18,8 +20,8 @@ public function __construct(private ?Closure $resolver = null) {} * * Validates that a webhook URL is safe for server-side requests. * Blocks loopback addresses, cloud metadata endpoints (link-local), - * and dangerous hostnames while allowing private network IPs - * for self-hosted deployments. + * private/reserved ranges, and dangerous hostnames unless the + * instance operator explicitly allowlists the intranet target. */ public function validate(string $attribute, mixed $value, Closure $fail): void { @@ -43,12 +45,17 @@ public function validate(string $attribute, mixed $value, Closure $fail): void return; } + if (str_ends_with($host, '.')) { + $fail('The :attribute host must not end with a trailing dot.'); + + return; + } + $host = strtolower($host); $hostForIpCheck = $this->normalizeHostForIpCheck($host); $hostForDns = rtrim($hostForIpCheck, '.'); - $blockedHosts = ['localhost', '0.0.0.0', '::1']; - if (in_array($hostForDns, $blockedHosts, true) || str_ends_with($hostForDns, '.internal')) { + if ($this->isBlockedHostname($hostForDns) && ! $this->isAllowedHostname($hostForDns)) { $this->logBlockedHost($attribute, $host); $fail('The :attribute must not point to localhost or internal hosts.'); @@ -56,9 +63,9 @@ public function validate(string $attribute, mixed $value, Closure $fail): void } if (filter_var($hostForIpCheck, FILTER_VALIDATE_IP)) { - if ($this->isBlockedIp($hostForIpCheck)) { + if (! $this->isAllowedIp($hostForIpCheck, $hostForDns)) { $this->logBlockedIp($attribute, $host, $hostForIpCheck); - $fail('The :attribute must not point to loopback or link-local addresses.'); + $fail('The :attribute must not point to private, reserved, loopback, or link-local addresses.'); return; } @@ -67,16 +74,124 @@ public function validate(string $attribute, mixed $value, Closure $fail): void } $resolvedIps = $this->resolveHost($hostForDns); + if ($resolvedIps === []) { + $fail('The :attribute host could not be resolved.'); + + return; + } + foreach ($resolvedIps as $resolvedIp) { - if ($this->isBlockedIp($resolvedIp)) { + if (! $this->isAllowedIp($resolvedIp, $hostForDns)) { $this->logBlockedIp($attribute, $host, $resolvedIp); - $fail('The :attribute must not point to loopback or link-local addresses.'); + $fail('The :attribute must not point to private, reserved, loopback, or link-local addresses.'); return; } } } + /** + * Build HTTP client options that pin the validated host to the resolved IPs. + * + * @return array + */ + public static function httpClientOptions(string $url): array + { + $options = ['allow_redirects' => false]; + + if (! defined('CURLOPT_RESOLVE')) { + throw new \RuntimeException('Webhook URL DNS pinning is unavailable.'); + } + + $target = self::resolveUrlForRequest($url); + + if ($target['ips'] === [] || filter_var($target['host'], FILTER_VALIDATE_IP)) { + return $options; + } + + $options['curl'] = [ + CURLOPT_RESOLVE => array_map( + fn (string $ip): string => sprintf('%s:%d:%s', $target['host'], $target['port'], filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? '['.$ip.']' : $ip), + $target['ips'], + ), + ]; + + return $options; + } + + /** + * Build mc --resolve mappings that pin the endpoint host for S3 backups. + * + * @return array + */ + public static function minioClientResolveOptions(string $url): array + { + $target = self::resolveUrlForRequest($url); + + if ($target['ips'] === [] || filter_var($target['host'], FILTER_VALIDATE_IP)) { + return []; + } + + return array_map( + fn (string $ip): string => sprintf('%s:%d=%s', $target['host'], $target['port'], filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) ? '['.$ip.']' : $ip), + $target['ips'], + ); + } + + public static function redactedUrlForLog(string $url): string + { + $scheme = parse_url($url, PHP_URL_SCHEME); + $host = parse_url($url, PHP_URL_HOST); + $port = parse_url($url, PHP_URL_PORT); + + if (! is_string($scheme) || ! is_string($host)) { + return '[invalid-url]'; + } + + return strtolower($scheme).'://'.strtolower($host).($port ? ':'.$port : ''); + } + + /** + * @return array{host: string, port: int, ips: array} + */ + private static function resolveUrlForRequest(string $url): array + { + $rule = new self; + $host = parse_url($url, PHP_URL_HOST); + if (! is_string($host) || $host === '') { + throw new \RuntimeException('Webhook URL host could not be resolved.'); + } + + if (str_ends_with($host, '.')) { + throw new \RuntimeException('Webhook URL host must not end with a trailing dot.'); + } + + $scheme = strtolower(parse_url($url, PHP_URL_SCHEME) ?? ''); + $port = parse_url($url, PHP_URL_PORT) ?: ($scheme === 'https' ? 443 : 80); + $hostForDns = rtrim($rule->normalizeHostForIpCheck(strtolower($host)), '.'); + + if (filter_var($hostForDns, FILTER_VALIDATE_IP)) { + if (! $rule->isAllowedIp($hostForDns, $hostForDns)) { + throw new \RuntimeException('Webhook URL resolved to an unsafe IP address.'); + } + + return ['host' => $hostForDns, 'port' => $port, 'ips' => []]; + } + + $resolvedIps = $rule->resolveHost($hostForDns); + if ($resolvedIps === []) { + throw new \RuntimeException('Webhook URL host could not be resolved.'); + } + + foreach ($resolvedIps as $resolvedIp) { + if (! $rule->isAllowedIp($resolvedIp, $hostForDns)) { + throw new \RuntimeException('Webhook URL resolved to an unsafe IP address.'); + } + } + + return ['host' => $hostForDns, 'port' => $port, 'ips' => $resolvedIps]; + } + private function normalizeHostForIpCheck(string $host): string { return (str_starts_with($host, '[') && str_ends_with($host, ']')) @@ -119,60 +234,271 @@ private function resolveHost(string $host): array return array_values(array_unique($ips)); } - private function isBlockedIp(string $ip): bool + private function isAllowedIp(string $ip, string $host): bool { $embeddedIpv4 = $this->extractIpv4FromMappedIpv6($ip); if ($embeddedIpv4 !== null) { - return $this->isBlockedIpv4($embeddedIpv4); + $ip = $embeddedIpv4; + } + + if ($this->isPublicIp($ip)) { + return true; + } + + if ($this->isLocalhostIp($ip)) { + return $this->allowLocalhost() + && ($this->isAllowedHostname($host) || $this->isAllowlistedIp($ip)); + } + + if ($this->isPrivateIp($ip)) { + return $this->isAllowedHostname($host) || $this->isAllowlistedIp($ip); + } + + return $this->isAllowlistedIp($ip); + } + + 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 + && ! $this->isSpecialUseIpv4($embeddedIpv4); + } + + return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false + && ! $this->isSpecialUseIp($ip); + } + + private function isLocalhostIp(string $ip): bool + { + $embeddedIpv4 = $this->extractIpv4FromMappedIpv6($ip); + if ($embeddedIpv4 !== null) { + return $this->isLocalhostIp($embeddedIpv4); } if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { - return $this->isBlockedIpv4($ip); + return $this->ipv4InCidr($ip, '127.0.0.0/8'); } - return $this->isBlockedIpv6($ip); + return @inet_pton($ip) === @inet_pton('::1'); } - private function isBlockedIpv4(string $ip): bool + private function isPrivateIp(string $ip): bool { - if ($ip === '0.0.0.0' || str_starts_with($ip, '127.')) { + $embeddedIpv4 = $this->extractIpv4FromMappedIpv6($ip); + if ($embeddedIpv4 !== null) { + $ip = $embeddedIpv4; + } + + return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false + && filter_var($ip, FILTER_VALIDATE_IP) !== false; + } + + private function isSpecialUseIp(string $ip): bool + { + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return $this->isSpecialUseIpv4($ip); + } + + return $this->isSpecialUseIpv6($ip); + } + + private function isSpecialUseIpv4(string $ip): bool + { + foreach ([ + '0.0.0.0/8', + '100.64.0.0/10', + '127.0.0.0/8', + '169.254.0.0/16', + '192.0.0.0/24', + '192.0.2.0/24', + '198.18.0.0/15', + '198.51.100.0/24', + '203.0.113.0/24', + '224.0.0.0/4', + '240.0.0.0/4', + '255.255.255.255/32', + ] as $cidr) { + if ($this->ipv4InCidr($ip, $cidr)) { + return true; + } + } + + return false; + } + + private function isSpecialUseIpv6(string $ip): bool + { + $ipBytes = @inet_pton($ip); + if ($ipBytes === false) { + return false; + } + + foreach ([ + '::/128', + '::1/128', + '::ffff:0:0/96', + '64:ff9b::/96', + '100::/64', + '2001::/23', + '2001:2::/48', + '2001:db8::/32', + '2002::/16', + 'fc00::/7', + 'fe80::/10', + 'ff00::/8', + ] as $cidr) { + [$network, $prefix] = explode('/', $cidr, 2); + $networkBytes = @inet_pton($network); + if ($networkBytes !== false && $this->binaryInCidr($ipBytes, $networkBytes, (int) $prefix)) { + return true; + } + } + + return false; + } + + private function isBlockedHostname(string $host): bool + { + return in_array($host, ['localhost'], true) + || str_ends_with($host, '.local') + || str_ends_with($host, '.internal') + || str_ends_with($host, '.cluster.local'); + } + + private function isAllowedHostname(string $host): bool + { + foreach ($this->allowlistEntries() as $entry) { + if (! str_contains($entry, '/') && strtolower($entry) === $host) { + return true; + } + } + + return false; + } + + private function isAllowlistedIp(string $ip): bool + { + foreach ($this->allowlistEntries() as $entry) { + if (str_contains($entry, '/')) { + if ($this->ipInCidr($ip, $entry)) { + return true; + } + + continue; + } + + if (filter_var($entry, FILTER_VALIDATE_IP) && @inet_pton($entry) === @inet_pton($ip)) { + return true; + } + } + + return false; + } + + /** + * @return array + */ + private function allowlistEntries(): array + { + $entries = $this->instanceSettings()?->webhook_allowed_internal_hosts ?? []; + + if (is_string($entries)) { + $entries = explode(',', $entries); + } + + if (! is_array($entries)) { + return []; + } + + return array_values(array_filter(array_map( + fn (mixed $entry): string => rtrim(strtolower(trim((string) $entry)), '.'), + $entries, + ))); + } + + private function allowLocalhost(): bool + { + return (bool) ($this->instanceSettings()?->webhook_allow_localhost ?? false); + } + + private function instanceSettings(): ?InstanceSettings + { + try { + return InstanceSettings::query()->find(0); + } catch (Throwable) { + return null; + } + } + + private function ipInCidr(string $ip, string $cidr): bool + { + [$network, $prefix] = array_pad(explode('/', $cidr, 2), 2, null); + if ($network === null || $prefix === null || ! is_numeric($prefix)) { + return false; + } + + if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) && filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + return $this->ipv4InCidr($ip, $cidr); + } + + if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) || ! filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { + return false; + } + + $prefix = (int) $prefix; + if ($prefix < 0 || $prefix > 128) { + return false; + } + + $ipBytes = @inet_pton($ip); + $networkBytes = @inet_pton($network); + if ($ipBytes === false || $networkBytes === false) { + return false; + } + + return $this->binaryInCidr($ipBytes, $networkBytes, $prefix); + } + + private function ipv4InCidr(string $ip, string $cidr): bool + { + [$network, $prefix] = array_pad(explode('/', $cidr, 2), 2, null); + if ($network === null || $prefix === null || ! is_numeric($prefix)) { + return false; + } + + $prefix = (int) $prefix; + if ($prefix < 0 || $prefix > 32) { + return false; + } + + $ipLong = ip2long($ip); + $networkLong = ip2long($network); + if ($ipLong === false || $networkLong === false) { + return false; + } + + $mask = $prefix === 0 ? 0 : (-1 << (32 - $prefix)); + + return ($ipLong & $mask) === ($networkLong & $mask); + } + + private function binaryInCidr(string $ipBytes, string $networkBytes, int $prefix): bool + { + $bytes = intdiv($prefix, 8); + $bits = $prefix % 8; + + if ($bytes > 0 && substr($ipBytes, 0, $bytes) !== substr($networkBytes, 0, $bytes)) { + return false; + } + + if ($bits === 0) { return true; } - $long = ip2long($ip); - if ($long === false) { - return false; - } + $mask = 0xFF << (8 - $bits) & 0xFF; - $unsigned = sprintf('%u', $long); - $linkLocalStart = sprintf('%u', ip2long('169.254.0.0')); - $linkLocalEnd = sprintf('%u', ip2long('169.254.255.255')); - - 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); + return (ord($ipBytes[$bytes]) & $mask) === (ord($networkBytes[$bytes]) & $mask); } private function extractIpv4FromMappedIpv6(string $ip): ?string diff --git a/database/migrations/2026_07_02_142003_add_webhook_internal_allowlist_to_instance_settings_table.php b/database/migrations/2026_07_02_142003_add_webhook_internal_allowlist_to_instance_settings_table.php new file mode 100644 index 000000000..ea34d74fa --- /dev/null +++ b/database/migrations/2026_07_02_142003_add_webhook_internal_allowlist_to_instance_settings_table.php @@ -0,0 +1,23 @@ +json('webhook_allowed_internal_hosts')->nullable(); + $table->boolean('webhook_allow_localhost')->default(false); + }); + } + + public function down(): void + { + Schema::table('instance_settings', function (Blueprint $table) { + $table->dropColumn(['webhook_allowed_internal_hosts', 'webhook_allow_localhost']); + }); + } +}; diff --git a/resources/views/livewire/settings/advanced.blade.php b/resources/views/livewire/settings/advanced.blade.php index fb7da30a7..3a49d0cfa 100644 --- a/resources/views/livewire/settings/advanced.blade.php +++ b/resources/views/livewire/settings/advanced.blade.php @@ -70,6 +70,15 @@ class="flex flex-col h-full gap-8 sm:flex-row"> environments! @endif +

Webhook/S3 Endpoint Controls

+ +
+ +

MCP Server

$endpoint], ['endpoint' => ['required', 'max:255', new SafeWebhookUrl]], @@ -43,19 +45,15 @@ it('accepts real-world S3 endpoints', function (string $endpoint) { $validator = Validator::make( ['endpoint' => $endpoint], - ['endpoint' => ['required', 'max:255', new SafeWebhookUrl]], + ['endpoint' => ['required', 'max:255', new SafeWebhookUrl(fn (string $host): array => ['93.184.216.34'])]], ); expect($validator->passes())->toBeTrue("Expected accepted: {$endpoint}"); })->with([ 'AWS S3' => 'https://s3.us-east-1.amazonaws.com', - 'Cloudflare R2' => 'https://fake.r2.cloudflarestorage.com', 'DigitalOcean Spaces' => 'https://nyc3.digitaloceanspaces.com', 'Backblaze B2' => 'https://s3.us-west-001.backblazeb2.com', - 'Self-hosted MinIO on 10.x' => 'http://10.0.0.5:9000', - 'Self-hosted MinIO on 172.16.x' => 'http://172.16.0.10:9000', - 'Self-hosted MinIO on 192.168.x' => 'http://192.168.1.50:9000', - 'Custom domain MinIO' => 'https://minio.example.com', + 'Custom public domain S3-compatible endpoint' => 'https://example.com', ]); it('blocks testConnection() on an unsafe endpoint without issuing HTTP', function () { @@ -91,3 +89,18 @@ 'IPv4-mapped IPv6 link-local' => 'http://[::ffff:169.254.169.254]', 'internal TLD' => 'http://backend.internal', ]); + +it('accepts explicitly allowlisted intranet S3 endpoints', function (string $endpoint, array $allowlist) { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['webhook_allowed_internal_hosts' => $allowlist])); + + $validator = Validator::make( + ['endpoint' => $endpoint], + ['endpoint' => ['required', 'max:255', new SafeWebhookUrl]], + ); + + expect($validator->passes())->toBeTrue("Expected allowlisted intranet S3 endpoint: {$endpoint}"); +})->with([ + 'Self-hosted MinIO on 10.x CIDR' => ['http://10.0.0.5:9000', ['10.0.0.0/8']], + 'Self-hosted MinIO on 172.16.x CIDR' => ['http://172.16.0.10:9000', ['172.16.0.0/12']], + 'Self-hosted MinIO on 192.168.x exact IP' => ['http://192.168.1.50:9000', ['192.168.1.50']], +]); diff --git a/tests/Unit/SafeWebhookUrlTest.php b/tests/Unit/SafeWebhookUrlTest.php index 69dc6fbb5..957ee5da9 100644 --- a/tests/Unit/SafeWebhookUrlTest.php +++ b/tests/Unit/SafeWebhookUrlTest.php @@ -1,13 +1,15 @@ ['93.184.216.34']); $validUrls = [ 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXX', @@ -22,17 +24,6 @@ } }); -it('accepts private network IPs for self-hosted deployments', function (string $url) { - $rule = new SafeWebhookUrl; - - $validator = Validator::make(['url' => $url], ['url' => $rule]); - expect($validator->passes())->toBeTrue("Expected valid (private IP): {$url}"); -})->with([ - '10.x range' => 'http://10.0.0.5/webhook', - '172.16.x range' => 'http://172.16.0.1:8080/hook', - '192.168.x range' => 'http://192.168.1.50:8080/webhook', -]); - it('rejects loopback addresses', function (string $url) { $rule = new SafeWebhookUrl; @@ -117,3 +108,153 @@ $validator = Validator::make(['url' => 'http://[::1]'], ['url' => $rule]); expect($validator->fails())->toBeTrue('Expected rejection: IPv6 loopback'); }); + +it('rejects private and reserved network targets by default', function (string $url) { + $rule = new SafeWebhookUrl; + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected default rejection: {$url}"); +})->with([ + 'private 10/8' => 'http://10.0.0.5/webhook', + 'private 172.16/12' => 'http://172.16.0.1:8080/hook', + 'private 192.168/16' => 'http://192.168.1.50:8080/webhook', + 'shared address space' => 'http://100.64.0.1/webhook', + 'zero network peer alias' => 'http://0.0.0.1/webhook', + 'multicast' => 'http://224.0.0.1/webhook', + 'benchmark range' => 'http://198.18.0.1/webhook', + 'documentation range' => 'http://192.0.2.10/webhook', +]); + +it('rejects hostname forms that resolve to loopback', function (string $url) { + $rule = new SafeWebhookUrl; + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected loopback hostname-form rejection: {$url}"); +})->with([ + 'decimal IPv4' => 'http://2130706433:8888/exfil', + 'hex IPv4' => 'http://0x7f000001:8888/exfil', + 'octal IPv4' => 'http://017700000001:8888/exfil', + 'short dotted IPv4' => 'http://127.1:8888/exfil', + 'IPv4-mapped IPv6 hex loopback' => 'http://[::ffff:7f00:1]:8888/exfil', +]); + +it('rejects internal DNS suffixes by default', function (string $url) { + $rule = new SafeWebhookUrl(fn (string $host): array => ['93.184.216.34']); + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected default rejection: {$url}"); +})->with([ + '.local host' => 'http://receiver.local/webhook', + '.cluster.local host' => 'http://service.cluster.local/webhook', +]); + +it('rejects unresolvable hostnames by default', function () { + $rule = new SafeWebhookUrl(fn (string $host): array => []); + + $validator = Validator::make(['url' => 'http://does-not-resolve.example.test/webhook'], ['url' => $rule]); + + expect($validator->fails())->toBeTrue('Expected default rejection for unresolvable host'); +}); + +it('allows explicitly configured intranet webhook targets', function (string $url, array $resolvedIps, array $allowlist) { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['webhook_allowed_internal_hosts' => $allowlist])); + + $rule = new SafeWebhookUrl(fn (string $host): array => $resolvedIps); + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->passes())->toBeTrue("Expected configured intranet target to pass: {$url}"); +})->with([ + 'exact .local hostname' => ['http://receiver.local/webhook', ['192.168.10.20'], ['receiver.local']], + 'private CIDR' => ['http://hooks.example.test/webhook', ['10.50.10.20'], ['10.50.0.0/16']], +]); + +it('requires explicit localhost opt in in addition to allowlist', function () { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['webhook_allowed_internal_hosts' => ['localhost']])); + + $rule = new SafeWebhookUrl; + + $validator = Validator::make(['url' => 'http://localhost:8080/webhook'], ['url' => $rule]); + + expect($validator->fails())->toBeTrue('Expected localhost to remain blocked without explicit localhost opt in'); + + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['webhook_allow_localhost' => true])); + + $validator = Validator::make(['url' => 'http://localhost:8080/webhook'], ['url' => $rule]); + + expect($validator->passes())->toBeTrue('Expected localhost to pass only after explicit localhost opt in'); +}); + +it('builds HTTP client options that pin resolved DNS for the request', function () { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], [ + 'webhook_allowed_internal_hosts' => ['localhost'], + 'webhook_allow_localhost' => true, + ])); + + $options = SafeWebhookUrl::httpClientOptions('http://localhost:8080/webhook'); + + expect($options['allow_redirects'])->toBeFalse(); + + if (defined('CURLOPT_RESOLVE')) { + expect($options['curl'][CURLOPT_RESOLVE])->toContain('localhost:8080:127.0.0.1'); + } +}); + +it('fails closed while building HTTP options when the send-time resolution is unsafe', function () { + expect(fn () => SafeWebhookUrl::httpClientOptions('http://localhost:8080/webhook')) + ->toThrow(RuntimeException::class, 'unsafe IP address'); +}); + +it('builds MinIO client resolve options for S3 backup uploads', function () { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], [ + 'webhook_allowed_internal_hosts' => ['localhost'], + 'webhook_allow_localhost' => true, + ])); + + $options = SafeWebhookUrl::minioClientResolveOptions('http://localhost:9000'); + + expect($options)->toContain('localhost:9000=127.0.0.1'); +}); + +it('rejects trailing-dot hostnames to avoid DNS pinning mismatch', function () { + $rule = new SafeWebhookUrl(fn (string $host): array => ['93.184.216.34']); + + $validator = Validator::make(['url' => 'http://example.com./webhook'], ['url' => $rule]); + + expect($validator->fails())->toBeTrue('Expected trailing-dot hostname rejection'); + + expect(fn () => SafeWebhookUrl::httpClientOptions('http://example.com./webhook')) + ->toThrow(RuntimeException::class, 'trailing dot'); +}); + +it('rejects reserved IPv6 ranges by default', function (string $url) { + $rule = new SafeWebhookUrl; + + $validator = Validator::make(['url' => $url], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected reserved IPv6 rejection: {$url}"); +})->with([ + 'documentation IPv6' => 'http://[2001:db8::1]/webhook', + 'IPv4/IPv6 translation prefix' => 'http://[64:ff9b::1]/webhook', + '6to4' => 'http://[2002::1]/webhook', +]); + +it('rejects hostnames that resolve to reserved IPv6 ranges by default', function (string $resolvedIp) { + $rule = new SafeWebhookUrl(fn (string $host): array => [$resolvedIp]); + + $validator = Validator::make(['url' => 'http://ipv6-reserved.example.test/webhook'], ['url' => $rule]); + + expect($validator->fails())->toBeTrue("Expected reserved IPv6 resolution rejection: {$resolvedIp}"); +})->with([ + '2001:db8::1', + '64:ff9b::1', + '2002::1', +]); + +it('redacts webhook URLs for logs', function () { + expect(SafeWebhookUrl::redactedUrlForLog('https://hooks.slack.com/services/T000/B000/secret-token?foo=bar')) + ->toBe('https://hooks.slack.com'); +}); From 3988ad6921a5415782eb323d6347831cbe96194a Mon Sep 17 00:00:00 2001 From: Andras Bacsai <5845193+andrasbacsai@users.noreply.github.com> Date: Thu, 2 Jul 2026 16:47:55 +0200 Subject: [PATCH 9/9] fix(webhooks): resolve hostnames using custom DNS servers Keep webhook SSRF DNS checks active when general DNS validation is disabled, and include localhost loopback resolution in safe URL validation. --- app/Rules/SafeWebhookUrl.php | 60 +++++++++++++++++++++++++++++++ tests/Unit/SafeWebhookUrlTest.php | 20 +++++++++++ 2 files changed, 80 insertions(+) diff --git a/app/Rules/SafeWebhookUrl.php b/app/Rules/SafeWebhookUrl.php index e171ba46c..478b05197 100644 --- a/app/Rules/SafeWebhookUrl.php +++ b/app/Rules/SafeWebhookUrl.php @@ -6,6 +6,8 @@ use Closure; use Illuminate\Contracts\Validation\ValidationRule; use Illuminate\Support\Facades\Log; +use PurplePixie\PhpDns\DNSQuery; +use PurplePixie\PhpDns\DNSTypes; use Throwable; class SafeWebhookUrl implements ValidationRule @@ -208,6 +210,15 @@ private function resolveHost(string $host): array return array_values(array_filter(($this->resolver)($host), fn (string $ip): bool => filter_var($ip, FILTER_VALIDATE_IP) !== false)); } + if ($host === 'localhost') { + return ['127.0.0.1', '::1']; + } + + $customDnsServers = $this->customDnsServers(); + if ($customDnsServers !== []) { + return $this->resolveHostWithCustomDnsServers($host, $customDnsServers); + } + $records = @dns_get_record($host, DNS_A | DNS_AAAA); if ($records === false) { $records = []; @@ -234,6 +245,55 @@ private function resolveHost(string $host): array return array_values(array_unique($ips)); } + /** + * @param array $dnsServers + * @return array + */ + private function resolveHostWithCustomDnsServers(string $host, array $dnsServers): array + { + $ips = []; + + foreach ($dnsServers as $dnsServer) { + foreach ([DNSTypes::NAME_A, DNSTypes::NAME_AAAA] as $type) { + try { + $query = new DNSQuery($dnsServer, 53, 5); + $records = $query->query($host, $type); + + if ($records === false || $query->hasError()) { + continue; + } + + foreach ($records as $record) { + if ($record->getType() === $type && filter_var($record->getData(), FILTER_VALIDATE_IP)) { + $ips[] = $record->getData(); + } + } + } catch (Throwable) { + continue; + } + } + } + + return array_values(array_unique($ips)); + } + + /** + * @return array + */ + private function customDnsServers(): array + { + $servers = $this->instanceSettings()?->custom_dns_servers ?? ''; + + if (! is_string($servers)) { + return []; + } + + return array_values(array_filter(array_map( + fn (string $server): string => trim($server), + explode(',', $servers), + ), fn (string $server): bool => filter_var($server, FILTER_VALIDATE_IP) !== false)); + } + private function isAllowedIp(string $ip, string $host): bool { $embeddedIpv4 = $this->extractIpv4FromMappedIpv6($ip); diff --git a/tests/Unit/SafeWebhookUrlTest.php b/tests/Unit/SafeWebhookUrlTest.php index 957ee5da9..de0c06260 100644 --- a/tests/Unit/SafeWebhookUrlTest.php +++ b/tests/Unit/SafeWebhookUrlTest.php @@ -159,6 +159,26 @@ expect($validator->fails())->toBeTrue('Expected default rejection for unresolvable host'); }); +it('keeps webhook DNS resolution enabled when general DNS validation is disabled', function () { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['is_dns_validation_enabled' => false])); + + $rule = new SafeWebhookUrl(fn (string $host): array => ['127.0.0.1']); + + $validator = Validator::make(['url' => 'http://rebinding.example.test/webhook'], ['url' => $rule]); + + expect($validator->fails())->toBeTrue('Expected webhook SSRF DNS checks to remain enabled'); +}); + +it('reads configured custom DNS servers for webhook hostname resolution', function () { + InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['custom_dns_servers' => '1.1.1.1, invalid, 2606:4700:4700::1111'])); + + $method = new ReflectionMethod(SafeWebhookUrl::class, 'customDnsServers'); + $method->setAccessible(true); + + expect($method->invoke(new SafeWebhookUrl)) + ->toBe(['1.1.1.1', '2606:4700:4700::1111']); +}); + it('allows explicitly configured intranet webhook targets', function (string $url, array $resolvedIps, array $allowlist) { InstanceSettings::unguarded(fn () => InstanceSettings::query()->updateOrCreate(['id' => 0], ['webhook_allowed_internal_hosts' => $allowlist]));