Merge remote-tracking branch 'origin/next' into improve-application-url-handling

This commit is contained in:
Andras Bacsai 2026-07-02 16:57:14 +02:00
commit ed6352682e
18 changed files with 1340 additions and 338 deletions

View file

@ -1,7 +1,7 @@
name: 🐞 Bug Report
description: "File a new bug report."
title: "[Bug]: "
labels: ["🐛 Bug", "🔍 Triage"]
labels: ["🔍 Triage"]
body:
- type: markdown
attributes:
@ -11,10 +11,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:
@ -37,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
@ -55,6 +67,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:

View file

@ -1,289 +1,226 @@
# Contributing to Coolify
Were happy that youre 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:
<details>
<summary><strong>Windows</strong></summary>
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)
</details>
<details>
<summary><strong>MacOS</strong></summary>
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)
</details>
<details>
<summary><strong>Linux</strong></summary>
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)
</details>
## 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. 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. 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 for a bug free experience.
#### 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 and Testing
All contributions must adhere to the highest standards of code quality and testing:
- **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.
## 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 and reports generated using AI 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:
- Manually 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 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
## 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 didnt align with the projects 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 its 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: 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 didnt 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

212
DEVELOPMENT.md Normal file
View file

@ -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:
<details>
<summary><strong>Windows</strong></summary>
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)
</details>
<details>
<summary><strong>MacOS</strong></summary>
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)
</details>
<details>
<summary><strong>Linux</strong></summary>
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)
</details>
## 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)

View file

@ -2343,7 +2343,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)
@ -2375,6 +2375,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();

View file

@ -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);

View file

@ -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());
}
}

View file

@ -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<string, mixed> $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<string, mixed> $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' => [
[

View file

@ -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', [

View file

@ -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

View file

@ -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<int, string>|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<int, string>|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)) {

View file

@ -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();

View file

@ -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();

View file

@ -2,9 +2,13 @@
namespace App\Rules;
use App\Models\InstanceSettings;
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
{
@ -18,8 +22,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 +47,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 +65,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 +76,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<string, mixed>
*/
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<int, string>
*/
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<int, string>}
*/
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, ']'))
@ -93,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 = [];
@ -119,60 +245,320 @@ private function resolveHost(string $host): array
return array_values(array_unique($ips));
}
private function isBlockedIp(string $ip): bool
/**
* @param array<int, string> $dnsServers
* @return array<int, string>
*/
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<int, string>
*/
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);
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<int, string>
*/
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

View file

@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::table('instance_settings', function (Blueprint $table) {
$table->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']);
});
}
};

View file

@ -70,6 +70,15 @@ class="flex flex-col h-full gap-8 sm:flex-row">
environments!
</x-callout>
@endif
<h4 class="pt-4">Webhook/S3 Endpoint Controls</h4>
<x-forms.textarea id="webhook_allowed_internal_hosts" rows="4"
label="Allowed Internal Webhook/S3 Targets"
helper="Optional instance-level allowlist for webhook and S3 endpoint destinations. Supports exact hostnames, IPs, and CIDR ranges separated by commas or new lines."
placeholder="hooks.company.local, 10.50.0.0/16, 192.168.10.20" />
<div class="md:w-96">
<x-forms.checkbox id="webhook_allow_localhost" label="Allow Localhost Webhook/S3 Targets"
helper="Allows localhost/loopback targets only when they are also listed above. Use only for local development or trusted single-instance setups." />
</div>
<h4 class="pt-4">MCP Server</h4>
<div class="md:w-96">
<x-forms.checkbox instantSave id="is_mcp_server_enabled" label="Enable MCP Server Instance-wide"

View file

@ -0,0 +1,121 @@
<?php
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
function setDeploymentJobProperty(object $job, string $property, mixed $value): void
{
$reflectionProperty = new ReflectionProperty(ApplicationDeploymentJob::class, $property);
$reflectionProperty->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();
});
});

View file

@ -1,21 +1,23 @@
<?php
use App\Models\InstanceSettings;
use App\Models\S3Storage;
use App\Rules\SafeWebhookUrl;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
uses(TestCase::class);
uses(TestCase::class, RefreshDatabase::class);
/**
* Regression tests for SSRF via S3 Storage endpoint.
* Regression tests for S3 Storage endpoint validation.
*
* The Livewire forms (Create.php, Form.php) and the model-level defense in
* S3Storage::testConnection() share the same SafeWebhookUrl rule. These tests
* assert the rule rejects the concrete payloads and that the model refuses to
* build an S3 client for an unsafe endpoint.
*/
it('rejects SSRF payloads on the S3 endpoint', function (string $endpoint) {
it('rejects disallowed targets on the S3 endpoint', function (string $endpoint) {
$validator = Validator::make(
['endpoint' => $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']],
]);

View file

@ -1,13 +1,15 @@
<?php
use App\Models\InstanceSettings;
use App\Rules\SafeWebhookUrl;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Validator;
use Tests\TestCase;
uses(TestCase::class);
uses(TestCase::class, RefreshDatabase::class);
it('accepts valid public URLs', function () {
$rule = new SafeWebhookUrl;
$rule = new SafeWebhookUrl(fn (string $host): array => ['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,173 @@
$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('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]));
$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');
});