This commit is contained in:
Andras Bacsai
2026-08-11 12:26:16 +02:00
committed by GitHub
1229 changed files with 147549 additions and 26137 deletions
+267
View File
@@ -0,0 +1,267 @@
---
name: shadcn
description: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".
user-invocable: false
allowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)
---
# shadcn/ui
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
## Current Project Context
```json
!`npx shadcn@latest info --json`
```
The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
## Principles
1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.
2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.
3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.
4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
## Critical Rules
These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
### Styling & Tailwind → [styling.md](./rules/styling.md)
- **`className` for layout, not styling.** Never override component colors or typography.
- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.
- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.
- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.
- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).
- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.
- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
### Forms & Inputs → [forms.md](./rules/forms.md)
- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.
- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.
- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**
- **Option sets (27 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.
- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.
- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
### Component Structure → [composition.md](./rules/composition.md)
- **Items always inside their Group.** `SelectItem``SelectGroup`. `DropdownMenuItem``DropdownMenuGroup`. `CommandItem``CommandGroup`.
- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)
- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.
- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.
- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.
- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.
- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.
- **Callouts use `Alert`.** Don't build custom styled divs.
- **Empty states use `Empty`.** Don't build custom empty state markup.
- **Toast via `sonner`.** Use `toast()` from `sonner`.
- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.
- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.
- **Use `Badge`** instead of custom styled spans.
### Icons → [icons.md](./rules/icons.md)
- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.
- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.
- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
### CLI
- **Never decode preset codes or build preset URLs manually.** Use `npx shadcn@latest preset decode <code>`, `preset url <code>`, or `preset open <code>`. For project-aware preset detection, use `npx shadcn@latest preset resolve`.
- **Apply preset codes directly with the CLI.** Use `npx shadcn@latest apply <code>` for existing projects, or `npx shadcn@latest init --preset <code>` when initializing.
## Key Patterns
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
```tsx
// Form layout: FieldGroup + Field, not div + Label.
<FieldGroup>
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" />
</Field>
</FieldGroup>
// Validation: data-invalid on Field, aria-invalid on the control.
<Field data-invalid>
<FieldLabel>Email</FieldLabel>
<Input aria-invalid />
<FieldDescription>Invalid email.</FieldDescription>
</Field>
// Icons in buttons: data-icon, no sizing classes.
<Button>
<SearchIcon data-icon="inline-start" />
Search
</Button>
// Spacing: gap-*, not space-y-*.
<div className="flex flex-col gap-4"> // correct
<div className="space-y-4"> // wrong
// Equal dimensions: size-*, not w-* h-*.
<Avatar className="size-10"> // correct
<Avatar className="w-10 h-10"> // wrong
// Status colors: Badge variants or semantic tokens, not raw colors.
<Badge variant="secondary">+20.1%</Badge> // correct
<span className="text-emerald-600">+20.1%</span> // wrong
```
## Component Selection
| Need | Use |
| -------------------------- | --------------------------------------------------------------------------------------------------- |
| Button/action | `Button` with appropriate variant |
| Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` |
| Toggle between 25 options | `ToggleGroup` + `ToggleGroupItem` |
| Data display | `Table`, `Card`, `Badge`, `Avatar` |
| Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` |
| Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) |
| Feedback | `sonner` (toast), `Alert`, `Progress`, `Skeleton`, `Spinner` |
| Command palette | `Command` inside `Dialog` |
| Charts | `Chart` (wraps Recharts) |
| Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` |
| Empty states | `Empty` |
| Menus | `DropdownMenu`, `ContextMenu`, `Menubar` |
| Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
## Key Fields
The injected project context contains these key fields:
- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.
- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.
- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.
- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.
- **`style`** → component visual treatment (e.g. `nova`, `vega`).
- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.
- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.
- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.
- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).
- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
- **`preset`** → resolved preset code and values for the current project. Use `npx shadcn@latest preset resolve --json` when you only need preset information.
See [cli.md — `info` command](./cli.md) for the full field reference.
## Component Docs, Examples, and Usage
Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
```bash
npx shadcn@latest docs button dialog select
```
**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
## Workflow
1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.
2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.
3. **Find components**`npx shadcn@latest search`.
4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.
5. **Install or update**`npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).
6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.
7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.
8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, `owner/repo`, etc.), ask which registry to use. Never default to a registry on behalf of the user.
9. **Switching presets** — Ask the user first: **overwrite**, **partial**, **merge**, or **skip**?
- **Inspect current preset**: `npx shadcn@latest preset resolve`. Use `--json` when you need structured values.
- **Inspect incoming preset**: `npx shadcn@latest preset decode <code>`. Use `preset url <code>` or `preset open <code>` to share or open the preset builder.
- **Overwrite**: `npx shadcn@latest apply <code>`. Overwrites detected components, fonts, and CSS variables.
- **Partial**: `npx shadcn@latest apply <code> --only theme,font`. Updates only the selected preset parts without reinstalling UI components. Supported values are `theme` and `font`; comma-separated combinations are allowed. `icon` is intentionally not supported, because icon changes may require full component reinstall and transforms.
- **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually.
- **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is.
- **Important**: Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
## Updating Components
When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.
2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.
3. Decide per file based on the diff:
- No local changes → safe to overwrite.
- Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications.
- User says "just update everything" → use `--overwrite`, but confirm first.
4. **Never use `--overwrite` without the user's explicit approval.**
## Quick Reference
```bash
# Create a new project.
npx shadcn@latest init --name my-app --preset base-nova
npx shadcn@latest init --name my-app --preset a2r6bw --template vite
# Create a monorepo project.
npx shadcn@latest init --name my-app --preset base-nova --monorepo
npx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
# Initialize existing project.
npx shadcn@latest init --preset base-nova
npx shadcn@latest init --defaults # shortcut: --template=next --preset=nova (base style implied)
# Apply a preset to an existing project.
npx shadcn@latest apply a2r6bw
npx shadcn@latest apply a2r6bw --only theme
npx shadcn@latest apply a2r6bw --only font
npx shadcn@latest apply a2r6bw --only theme,font
# Inspect preset codes and project preset state.
npx shadcn@latest preset decode a2r6bw
npx shadcn@latest preset url a2r6bw
npx shadcn@latest preset open a2r6bw
npx shadcn@latest preset resolve
npx shadcn@latest preset resolve --json
# Add components.
npx shadcn@latest add button card dialog
npx shadcn@latest add @magicui/shimmer-button
npx shadcn@latest add owner/repo/item
npx shadcn@latest add --all
# Preview changes before adding/updating.
npx shadcn@latest add button --dry-run
npx shadcn@latest add button --diff button.tsx
npx shadcn@latest add @acme/form --view button.tsx
npx shadcn@latest add owner/repo/item --dry-run
# Search registries.
npx shadcn@latest search @shadcn -q "sidebar"
npx shadcn@latest search @tailark -q "stats"
npx shadcn@latest search owner/repo -q "login"
npx shadcn@latest search # all configured registries
npx shadcn@latest search @shadcn -q "menu" -t ui # filter by item type
# Get component docs and example URLs.
npx shadcn@latest docs button dialog select
# View registry item details (for items not yet installed).
npx shadcn@latest view @shadcn/button
npx shadcn@latest view owner/repo/item
```
**Named presets:** `nova`, `vega`, `maia`, `lyra`, `mira`, `luma`
**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)
**Preset codes:** Version-prefixed base62 strings (e.g. `a2r6bw` or `b0`), from [ui.shadcn.com](https://ui.shadcn.com).
## Detailed References
- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states
- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading
- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects
- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index
- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion
- [cli.md](./cli.md) — Commands, flags, presets, templates
- [registry.md](./registry.md) — Authoring source registries, `include`, item definitions, dependencies, GitHub registry rules
- [customization.md](./customization.md) — Theming, CSS variables, extending components
+5
View File
@@ -0,0 +1,5 @@
interface:
display_name: "shadcn/ui"
short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI."
icon_small: "./assets/shadcn-small.png"
icon_large: "./assets/shadcn.png"
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+290
View File
@@ -0,0 +1,290 @@
# shadcn CLI Reference
Configuration is read from `components.json`.
> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
## Contents
- Commands: init, apply, add (dry-run, smart merge), search, view, docs, info, build
- Templates: next, vite, start, react-router, astro
- Presets: named, code, URL formats and fields
- Switching presets
---
## Commands
### `init` — Initialize or create a project
```bash
npx shadcn@latest init [components...] [options]
```
Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
| Flag | Short | Description | Default |
| ----------------------- | ----- | --------------------------------------------------------- | ------- |
| `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — |
| `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — |
| `--yes` | `-y` | Skip confirmation prompt | `true` |
| `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` |
| `--force` | `-f` | Force overwrite existing configuration | `false` |
| `--cwd <cwd>` | `-c` | Working directory | current |
| `--name <name>` | `-n` | Name for new project | — |
| `--silent` | `-s` | Mute output | `false` |
| `--rtl` | | Enable RTL support | — |
| `--reinstall` | | Re-install existing UI components | `false` |
| `--monorepo` | | Scaffold a monorepo project | — |
| `--no-monorepo` | | Skip the monorepo prompt | — |
`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
### `apply` — Apply a preset to an existing project
```bash
npx shadcn@latest apply [preset] [options]
```
Applies a preset to an existing project, overwriting preset-driven config, fonts, CSS variables, and detected UI components.
| Flag | Short | Description | Default |
| ------------------- | ----- | ------------------------------------------ | ------- |
| `--preset <preset>` | — | Preset configuration (named, code, or URL) | — |
| `--yes` | `-y` | Skip confirmation prompt | `false` |
| `--cwd <cwd>` | `-c` | Working directory | current |
| `--silent` | `-s` | Mute output | `false` |
`[preset]` is a shorthand for `--preset <preset>`. If both are provided, they must match.
If no preset is provided, the CLI offers to open the custom preset builder on `ui.shadcn.com/create`.
### `add` — Add components
> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
```bash
npx shadcn@latest add [components...] [options]
```
Accepts component names, registry-prefixed names (`@magicui/shimmer-button`),
GitHub item addresses (`owner/repo/item`), URLs, or local paths.
| Flag | Short | Description | Default |
| --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- |
| `--yes` | `-y` | Skip confirmation prompt | `false` |
| `--overwrite` | `-o` | Overwrite existing files | `false` |
| `--cwd <cwd>` | `-c` | Working directory | current |
| `--all` | `-a` | Add all available components | `false` |
| `--path <path>` | `-p` | Target path for the component | — |
| `--silent` | `-s` | Mute output | `false` |
| `--dry-run` | | Preview all changes without writing files | `false` |
| `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
| `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
#### Dry-Run Mode
Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
```bash
# Preview all changes.
npx shadcn@latest add button --dry-run
# Show diffs for all files (top 5).
npx shadcn@latest add button --diff
# Show the diff for a specific file.
npx shadcn@latest add button --diff button.tsx
# Show contents for all files (top 5).
npx shadcn@latest add button --view
# Show the full content of a specific file.
npx shadcn@latest add button --view button.tsx
# Works with URLs too.
npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
# Works with public GitHub registries too.
npx shadcn@latest add owner/repo/item --dry-run
# CSS diffs.
npx shadcn@latest add button --diff globals.css
```
**When to use dry-run:**
- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.
- Before overwriting existing components — use `--diff` to preview the changes first.
- When the user wants to inspect component source code without installing — use `--view`.
- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.
- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
#### Smart Merge from Upstream
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
### `search` — Search registries
```bash
npx shadcn@latest search [registries...] [options]
```
Fuzzy search across registries. Also aliased as `npx shadcn@latest list`.
Supports namespaces (`@acme`), public GitHub registry sources (`owner/repo`),
and registry catalog URLs. Without `-q`, lists all items. When no registries are
passed, searches every registry configured in `components.json`.
| Flag | Short | Description | Default |
| ------------------- | ----- | ------------------------------------------------- | ------- |
| `--query <query>` | `-q` | Search query | — |
| `--type <type>` | `-t` | Filter by item type (e.g. `ui`, `block`, `hook`); comma-separated | — |
| `--limit <number>` | `-l` | Max items to display | `100` |
| `--offset <number>` | `-o` | Items to skip | `0` |
| `--json` | | Output as JSON | `false` |
| `--cwd <cwd>` | `-c` | Working directory | current |
### `view` — View item details
```bash
npx shadcn@latest view <items...> [options]
```
Displays item info including file contents. Examples:
`npx shadcn@latest view @shadcn/button`,
`npx shadcn@latest view owner/repo/item`.
### `docs` — Get component documentation URLs
```bash
npx shadcn@latest docs <components...> [options]
```
Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
Example output for `npx shadcn@latest docs input button`:
```
base radix
input
docs https://ui.shadcn.com/docs/components/radix/input
examples https://raw.githubusercontent.com/.../examples/input-example.tsx
button
docs https://ui.shadcn.com/docs/components/radix/button
examples https://raw.githubusercontent.com/.../examples/button-example.tsx
```
Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
### `diff` — Check for updates
Do not use this command. Use `npx shadcn@latest add --diff` instead.
### `info` — Project information
```bash
npx shadcn@latest info [options]
```
Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
| Flag | Short | Description | Default |
| ------------- | ----- | ----------------- | ------- |
| `--cwd <cwd>` | `-c` | Working directory | current |
**Project Info fields:**
| Field | Type | Meaning |
| -------------------- | --------- | ------------------------------------------------------------------ |
| `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) |
| `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) |
| `isSrcDir` | `boolean` | Whether the project uses a `src/` directory |
| `isRSC` | `boolean` | Whether React Server Components are enabled |
| `isTsx` | `boolean` | Whether the project uses TypeScript |
| `tailwindVersion` | `string` | `"v3"` or `"v4"` |
| `tailwindConfigFile` | `string` | Path to the Tailwind config file |
| `tailwindCssFile` | `string` | Path to the global CSS file |
| `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) |
| `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
**Components.json fields:**
| Field | Type | Meaning |
| -------------------- | --------- | ------------------------------------------------------------------------------------------ |
| `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props |
| `style` | `string` | Visual style (e.g. `nova`, `vega`) |
| `rsc` | `boolean` | RSC flag from config |
| `tsx` | `boolean` | TypeScript flag |
| `tailwind.config` | `string` | Tailwind config path |
| `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go |
| `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) |
| `aliases.components` | `string` | Component import alias (e.g. `@/components`) |
| `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) |
| `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) |
| `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) |
| `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) |
| `resolvedPaths` | `object` | Absolute file-system paths for each alias |
| `registries` | `object` | Configured custom registries |
**Links fields:**
The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
### `build` — Build a custom registry
```bash
npx shadcn@latest build [registry] [options]
```
Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
For authoring rules, `include`, item definitions, `registryDependencies`, and
GitHub registry behavior, see [registry.md](./registry.md).
| Flag | Short | Description | Default |
| ----------------- | ----- | ----------------- | ------------ |
| `--output <path>` | `-o` | Output directory | `./public/r` |
| `--cwd <cwd>` | `-c` | Working directory | current |
---
## Templates
| Value | Framework | Monorepo support |
| -------------- | -------------- | ---------------- |
| `next` | Next.js | Yes |
| `vite` | Vite | Yes |
| `start` | TanStack Start | Yes |
| `react-router` | React Router | Yes |
| `astro` | Astro | Yes |
| `laravel` | Laravel | No |
All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
---
## Presets
Three ways to specify a preset via `--preset`:
1. **Named:** `--preset nova` or `--preset lyra`
2. **Code:** `--preset a2r6bw` (version-prefixed base62 string, e.g. `a2r6bw` or `b0`)
3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.
> Use `npx shadcn@latest apply --preset <code>` when overwriting an existing project's preset.
## Switching Presets
Ask the user first: **overwrite**, **merge**, or **skip** existing components?
- **Overwrite / Re-install**`npx shadcn@latest apply --preset <code>`. Overwrites all detected component files with the new preset styles. Use when the user hasn't customized components.
- **Merge**`npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.
- **Skip**`npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
+209
View File
@@ -0,0 +1,209 @@
# Customization & Theming
Components reference semantic CSS variable tokens. Change the variables to change every component.
## Contents
- How it works (CSS variables → Tailwind utilities → components)
- Color variables and OKLCH format
- Dark mode setup
- Changing the theme (presets, CSS variables)
- Adding custom colors (Tailwind v3 and v4)
- Border radius
- Customizing components (variants, className, wrappers)
- Checking for updates
---
## How It Works
1. CSS variables defined in `:root` (light) and `.dark` (dark mode).
2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.
3. Components use these utilities — changing a variable changes all components that reference it.
---
## Color Variables
Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
| Variable | Purpose |
| -------------------------------------------- | -------------------------------- |
| `--background` / `--foreground` | Page background and default text |
| `--card` / `--card-foreground` | Card surfaces |
| `--primary` / `--primary-foreground` | Primary buttons and actions |
| `--secondary` / `--secondary-foreground` | Secondary actions |
| `--muted` / `--muted-foreground` | Muted/disabled states |
| `--accent` / `--accent-foreground` | Hover and accent states |
| `--destructive` / `--destructive-foreground` | Error and destructive actions |
| `--border` | Default border color |
| `--input` | Form input borders |
| `--ring` | Focus ring color |
| `--chart-1` through `--chart-5` | Chart/data visualization |
| `--sidebar-*` | Sidebar-specific colors |
| `--surface` / `--surface-foreground` | Secondary surface |
Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (01), chroma (0 = gray), and hue (0360).
---
## Dark Mode
Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
```tsx
import { ThemeProvider } from "next-themes"
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
</ThemeProvider>
```
---
## Changing the Theme
```bash
# Apply a preset code from ui.shadcn.com.
npx shadcn@latest apply --preset a2r6bw
# Positional shorthand also works.
npx shadcn@latest apply a2r6bw
# Switch to a named preset and overwrite existing components.
npx shadcn@latest apply --preset nova
# Preserve existing components instead.
npx shadcn@latest init --preset nova --force --no-reinstall
# Use a custom theme URL.
npx shadcn@latest apply --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..."
```
Or edit CSS variables directly in `globals.css`.
---
## Adding Custom Colors
Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
```css
/* 1. Define in the global CSS file. */
:root {
--warning: oklch(0.84 0.16 84);
--warning-foreground: oklch(0.28 0.07 46);
}
.dark {
--warning: oklch(0.41 0.11 46);
--warning-foreground: oklch(0.99 0.02 95);
}
```
```css
/* 2a. Register with Tailwind v4 (@theme inline). */
@theme inline {
--color-warning: var(--warning);
--color-warning-foreground: var(--warning-foreground);
}
```
When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
```js
// 2b. Register with Tailwind v3 (tailwind.config.js).
module.exports = {
theme: {
extend: {
colors: {
warning: "oklch(var(--warning) / <alpha-value>)",
"warning-foreground":
"oklch(var(--warning-foreground) / <alpha-value>)",
},
},
},
}
```
```tsx
// 3. Use in components.
<div className="bg-warning text-warning-foreground">Warning</div>
```
---
## Border Radius
`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
---
## Customizing Components
See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
Prefer these approaches in order:
### 1. Built-in variants
```tsx
<Button variant="outline" size="sm">
Click
</Button>
```
### 2. Tailwind classes via `className`
```tsx
<Card className="mx-auto max-w-md">...</Card>
```
### 3. Add a new variant
Edit the component source to add a variant via `cva`:
```tsx
// components/ui/button.tsx
warning: "bg-warning text-warning-foreground hover:bg-warning/90",
```
### 4. Wrapper components
Compose shadcn/ui primitives into higher-level components:
```tsx
export function ConfirmDialog({ title, description, onConfirm, children }) {
return (
<AlertDialog>
<AlertDialogTrigger asChild>{children}</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
)
}
```
---
## Checking for Updates
```bash
npx shadcn@latest add button --diff
```
To preview exactly what would change before updating, use `--dry-run` and `--diff`:
```bash
npx shadcn@latest add button --dry-run # see all affected files
npx shadcn@latest add button --diff button.tsx # see the diff for a specific file
```
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.
+47
View File
@@ -0,0 +1,47 @@
{
"skill_name": "shadcn",
"evals": [
{
"id": 1,
"prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.",
"expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.",
"files": [],
"expectations": [
"Uses FieldGroup and Field components for form layout instead of raw div with space-y",
"Uses Switch for independent on/off notification toggles (not looping Button with manual active state)",
"Uses data-invalid on Field and aria-invalid on the input control for validation states",
"Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing",
"Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500",
"No manual dark: color overrides"
]
},
{
"id": 2,
"prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.",
"expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.",
"files": [],
"expectations": [
"Includes DialogTitle for accessibility (visible or with sr-only class)",
"Avatar component includes AvatarFallback",
"Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")",
"No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)",
"Uses tabler icons (@tabler/icons-react) instead of lucide-react",
"Uses asChild for custom triggers (radix preset)"
]
},
{
"id": 3,
"prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.",
"expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.",
"files": [],
"expectations": [
"Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)",
"Uses Skeleton component for loading placeholders instead of custom animate-pulse divs",
"Uses Badge component for percentage change instead of custom styled spans",
"Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600",
"Uses gap-* instead of space-y-* or space-x-* for spacing",
"Uses size-* when width and height are equal instead of separate w-* h-*"
]
}
]
}
+105
View File
@@ -0,0 +1,105 @@
# shadcn MCP Server
The CLI includes an MCP server that lets AI assistants search, browse, view, and install items from registries.
---
## Setup
```bash
shadcn mcp # start the MCP server (stdio)
shadcn mcp init # write config for your editor
```
Editor config files:
| Editor | Config file |
| ----------- | ------------------------------- |
| Claude Code | `.mcp.json` |
| Cursor | `.cursor/mcp.json` |
| VS Code | `.vscode/mcp.json` |
| OpenCode | `opencode.json` |
| Codex | `~/.codex/config.toml` (manual) |
---
## Tools
> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
### `shadcn:get_project_registries`
Returns registry names from `components.json`. Errors if no `components.json` exists.
**Input:** none
### `shadcn:list_items_in_registries`
Lists all items from one or more registries. Registries can be configured
namespaces such as `@acme`, public GitHub sources such as `owner/repo`, or
registry catalog URLs. Omit `registries` to list from every registry configured
in `components.json`.
**Input:** `registries` (string[], optional — omit for all configured), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
### `shadcn:search_items_in_registries`
Fuzzy search across registries. Registries can be configured namespaces, public
GitHub sources, or registry catalog URLs. Omit `registries` to search every
registry configured in `components.json` — e.g. "find me a hero" across all
configured registries.
**Input:** `registries` (string[], optional — omit for all configured), `query` (string), `types` (string[], optional — e.g. `["ui", "block"]`), `limit` (number, optional, defaults to 100), `offset` (number, optional)
### `shadcn:view_items_in_registries`
View item details including full file contents.
**Input:** `items` (string[]) — e.g.
`["@shadcn/button", "@shadcn/card", "owner/repo/item"]`
### `shadcn:get_item_examples_from_registries`
Find usage examples and demos with source code. Omit `registries` to search
every registry configured in `components.json`.
**Input:** `registries` (string[], optional — omit for all configured), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
### `shadcn:get_add_command_for_items`
Returns the CLI install command.
**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
### `shadcn:get_audit_checklist`
Returns a checklist for verifying components (imports, deps, lint, TypeScript).
**Input:** none
---
## Configuring Registries
Namespaced and authenticated registries are set in `components.json`. The
`@shadcn` registry is always built-in. Public GitHub registries can also be used
directly as `owner/repo` registry sources when the repository has a root
`registry.json`; they do not need `components.json` configuration.
```json
{
"registries": {
"@acme": "https://acme.com/r/{name}.json",
"@private": {
"url": "https://private.com/r/{name}.json",
"headers": { "Authorization": "Bearer ${MY_TOKEN}" }
}
}
}
```
- Names must start with `@`.
- URLs must contain `{name}`.
- `${VAR}` references are resolved from environment variables.
Community registry index: `https://ui.shadcn.com/r/registries.json`
+277
View File
@@ -0,0 +1,277 @@
# Registry Authoring and Addresses
Use this reference when the user wants to create, fix, publish, or reason about
a shadcn registry.
## Mental Model
A registry has two forms:
- **Source registry**: an authored `registry.json` in a project or repository.
It may use `include` and file paths that point at source files.
- **Built registry**: generated JSON files served to CLI consumers, usually
from `public/r`. Use `npx shadcn@latest build` to create this form.
The CLI installer consumes registry item payloads. A source registry is a way to
author those payloads from real files.
Registry items are not limited to React components. They can distribute
components, hooks, utilities, design tokens, pages, config files, docs, rules,
workflows, templates, MCP files, and other project files.
## Root `registry.json`
The root registry file should define registry metadata and either `items` or
`include`.
```json
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "acme",
"homepage": "https://acme.com",
"items": [
{
"name": "absolute-url",
"type": "registry:lib",
"title": "Absolute URL",
"description": "A utility to turn any path into an absolute URL.",
"files": [
{
"path": "lib/absolute-url.ts",
"type": "registry:lib"
}
]
}
]
}
```
Root registry rules:
- Root `registry.json` must include `name` and `homepage`.
- `items` is an array of registry item definitions.
- `include` may be used to split the source registry into multiple files.
- Included registry files may omit `name` and `homepage`.
## Include
Use `include` to keep large registries modular.
```json
{
"$schema": "https://ui.shadcn.com/schema/registry.json",
"name": "acme",
"homepage": "https://acme.com",
"include": ["registry/ui/registry.json", "registry/blocks/registry.json"]
}
```
Include rules:
- Include paths are relative to the `registry.json` that declares them.
- Include paths must explicitly point to a `registry.json` file.
- Do not use remote URLs, absolute paths, or parent traversal (`..`).
- Item file paths are relative to the registry file that declares the item.
- Duplicate item names fail across the resolved registry.
Example included file:
```json
{
"items": [
{
"name": "button",
"type": "registry:ui",
"files": [
{
"path": "button.tsx",
"type": "registry:ui"
}
]
}
]
}
```
If this file is at `registry/ui/registry.json`, then `button.tsx` is read from
`registry/ui/button.tsx`, and the built item path is emitted relative to the
root registry.
## Item Definitions
Common item fields:
```json
{
"name": "login-form",
"type": "registry:block",
"title": "Login Form",
"description": "A login form with email and password fields.",
"dependencies": ["zod"],
"registryDependencies": ["button", "input", "label"],
"files": [
{
"path": "blocks/login-form.tsx",
"type": "registry:block"
}
],
"cssVars": {
"light": {
"brand": "oklch(0.62 0.18 250)"
},
"dark": {
"brand": "oklch(0.72 0.16 250)"
}
}
}
```
Important fields:
- `name`: the installable item name. It is not necessarily a file path.
- `type`: one of the registry item types, such as `registry:ui`,
`registry:block`, `registry:lib`, `registry:hook`, `registry:file`,
`registry:page`, `registry:theme`, `registry:style`, `registry:font`, or
`registry:item`.
- `files`: source files copied or generated by the item.
- `dependencies`: npm runtime dependencies.
- `devDependencies`: npm development dependencies.
- `registryDependencies`: other registry items required by this item.
- `cssVars`, `css`, `tailwind`, `envVars`, and `docs`: optional install-time
additions.
File rules:
- File paths are relative to the declaring `registry.json`.
- `registry:file` and `registry:page` files require a `target`.
- Do not use remote file URLs in source registry file paths.
- Keep source files copy-pasteable: no hidden app-only imports.
## Registry Dependencies
`registryDependencies` entries are item addresses, not file paths.
```json
{
"name": "login-form",
"type": "registry:block",
"registryDependencies": ["button", "@acme/input", "acme/ui/card#v1.2.0"],
"files": [
{
"path": "blocks/login-form.tsx",
"type": "registry:block"
}
]
}
```
Dependency rules:
- Bare names such as `"button"` mean official shadcn items.
- Bare names never mean same-registry or same-repository items.
- Namespaced dependencies use `@namespace/item-name`.
- GitHub dependencies use `owner/repo/item-name`.
- Pin GitHub dependencies with `owner/repo/item-name#ref` when needed.
- Refs are not inherited. If `owner/repo/foo#v2` depends on `bar` from the same
repo at `v2`, write `owner/repo/bar#v2`.
- Do not use relative dependencies such as `"./bar"`.
## Address Schemes
When reasoning about a registry item string, classify it first.
| Address | Scheme | Meaning |
| ----------------------------------- | --------- | ------------------------------------------------------------ |
| `button` | shadcn | Official shadcn item named `button`. |
| `@acme/button` | namespace | Item `button` from configured registry `@acme`. |
| `@acme/ui/button` | namespace | Item `ui/button` from configured registry `@acme`. |
| `https://example.com/r/button.json` | url | Built registry item JSON at that URL. |
| `./button.json` | file | Built registry item JSON on disk. |
| `acme/ui/button` | github | Item `button` from GitHub repo `acme/ui`. |
| `acme/ui/forms/login#main` | github | Item `forms/login` from GitHub repo `acme/ui` at ref `main`. |
For namespace and GitHub addresses, slashful item names are allowed and are item
names, not file paths. Addresses ending in `.json` keep file-address
precedence, so `acme/ui/data/schema.json` is treated as a file path, not a
GitHub item address.
## GitHub Registries
A public GitHub repository can act as a source registry when it has a root
`registry.json`.
```txt
owner/repo/item-name[#ref]
```
Rules:
- The first two path segments are GitHub owner and repo.
- All remaining path segments are the registry item name.
- The source entrypoint is always root `registry.json`.
- GitHub registries are source registries consumed directly by the CLI. They do
not require `shadcn build` or generated item JSON files.
- `include` follows the same source-registry rules as local registries.
- Currently, GitHub addresses support public `github.com` repositories only.
- Private repos and GitHub Enterprise require explicit product decisions.
When implementing GitHub registry fetching, resolve refs to a commit SHA before
reading source files. Do not read moving refs directly from
`raw.githubusercontent.com`, because branch-like refs can be cached for several
minutes.
Preferred flow:
```txt
owner/repo[#ref]
-> resolve ref with git ls-remote
-> commit SHA
-> read https://raw.githubusercontent.com/{owner}/{repo}/{sha}/registry.json
-> read includes and item files from the same SHA
```
This keeps a command on one consistent repository snapshot.
Full 40-character commit SHAs are already stable and can be used directly.
Branches, tags, and short refs require Git so the CLI can resolve them to a
commit SHA first.
## Build and Verify
Use the CLI to build source registries:
```bash
npx shadcn@latest build
npx shadcn@latest build registry.json --output public/r
```
Use CLI commands to inspect the result:
```bash
npx shadcn@latest list @acme
npx shadcn@latest search @acme -q "login"
npx shadcn@latest view @acme/login-form
npx shadcn@latest add @acme/login-form --dry-run
npx shadcn@latest registry validate ./registry.json
```
Use GitHub addresses directly for public GitHub registries:
```bash
npx shadcn@latest list owner/repo
npx shadcn@latest search owner/repo -q "login"
npx shadcn@latest view owner/repo/item
npx shadcn@latest add owner/repo/item --dry-run
npx shadcn@latest registry validate owner/repo
```
When working on registry implementation in the shadcn/ui codebase:
- Keep address parsing pure and testable.
- Do not add side effects to validators.
- Preserve existing behavior for official shadcn, namespace, URL, and file
schemes.
- Add tests for address parsing, source loading, dependency resolution, list,
search, view, and add paths.
- Prefer small source-reader abstractions over a plugin system until there are
multiple real providers.
@@ -0,0 +1,306 @@
# Base vs Radix
API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
## Contents
- Composition: asChild vs render
- Button / trigger as non-button element
- Select (items prop, placeholder, positioning, multiple, object values)
- ToggleGroup (type vs multiple)
- Slider (scalar vs array)
- Accordion (type and defaultValue)
---
## Composition: asChild (radix) vs render (base)
Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
**Incorrect:**
```tsx
<DialogTrigger>
<div>
<Button>Open</Button>
</div>
</DialogTrigger>
```
**Correct (radix):**
```tsx
<DialogTrigger asChild>
<Button>Open</Button>
</DialogTrigger>
```
**Correct (base):**
```tsx
<DialogTrigger render={<Button />}>Open</DialogTrigger>
```
This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
---
## Button / trigger as non-button element (base only)
When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
**Incorrect (base):** missing `nativeButton={false}`.
```tsx
<Button render={<a href="/docs" />}>Read the docs</Button>
```
**Correct (base):**
```tsx
<Button render={<a href="/docs" />} nativeButton={false}>
Read the docs
</Button>
```
**Correct (radix):**
```tsx
<Button asChild>
<a href="/docs">Read the docs</a>
</Button>
```
Same for triggers whose `render` is not a `Button`:
```tsx
// base.
<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}>
Pick date
</PopoverTrigger>
```
---
## Select
**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
**Incorrect (base):**
```tsx
<Select>
<SelectTrigger><SelectValue placeholder="Select a fruit" /></SelectTrigger>
</Select>
```
**Correct (base):**
```tsx
const items = [
{ label: "Select a fruit", value: null },
{ label: "Apple", value: "apple" },
{ label: "Banana", value: "banana" },
]
<Select items={items}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
{items.map((item) => (
<SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>
))}
</SelectGroup>
</SelectContent>
</Select>
```
**Correct (radix):**
```tsx
<Select>
<SelectTrigger>
<SelectValue placeholder="Select a fruit" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="apple">Apple</SelectItem>
<SelectItem value="banana">Banana</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
```
**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
```tsx
// base.
<SelectContent alignItemWithTrigger={false} side="bottom">
// radix.
<SelectContent position="popper">
```
---
## Select — multiple selection and object values (base only)
Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
**Correct (base — multiple selection):**
```tsx
<Select items={items} multiple defaultValue={[]}>
<SelectTrigger>
<SelectValue>
{(value: string[]) => value.length === 0 ? "Select fruits" : `${value.length} selected`}
</SelectValue>
</SelectTrigger>
...
</Select>
```
**Correct (base — object values):**
```tsx
<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}>
<SelectTrigger>
<SelectValue>{(value) => value.name}</SelectValue>
</SelectTrigger>
...
</Select>
```
---
## ToggleGroup
Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
**Incorrect (base):**
```tsx
<ToggleGroup type="single" defaultValue="daily">
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
</ToggleGroup>
```
**Correct (base):**
```tsx
// Single (no prop needed), defaultValue is always an array.
<ToggleGroup defaultValue={["daily"]} spacing={2}>
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
</ToggleGroup>
// Multi-selection.
<ToggleGroup multiple>
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
</ToggleGroup>
```
**Correct (radix):**
```tsx
// Single, defaultValue is a string.
<ToggleGroup type="single" defaultValue="daily" spacing={2}>
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
</ToggleGroup>
// Multi-selection.
<ToggleGroup type="multiple">
<ToggleGroupItem value="bold">Bold</ToggleGroupItem>
<ToggleGroupItem value="italic">Italic</ToggleGroupItem>
</ToggleGroup>
```
**Controlled single value:**
```tsx
// base — wrap/unwrap arrays.
const [value, setValue] = React.useState("normal")
<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
// radix — plain string.
const [value, setValue] = React.useState("normal")
<ToggleGroup type="single" value={value} onValueChange={setValue}>
```
---
## Slider
Base accepts a plain number for a single thumb. Radix always requires an array.
**Incorrect (base):**
```tsx
<Slider defaultValue={[50]} max={100} step={1} />
```
**Correct (base):**
```tsx
<Slider defaultValue={50} max={100} step={1} />
```
**Correct (radix):**
```tsx
<Slider defaultValue={[50]} max={100} step={1} />
```
Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
```tsx
// base.
const [value, setValue] = React.useState([0.3, 0.7])
<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
// radix.
const [value, setValue] = React.useState([0.3, 0.7])
<Slider value={value} onValueChange={setValue} />
```
---
## Accordion
Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
**Incorrect (base):**
```tsx
<Accordion type="single" collapsible defaultValue="item-1">
<AccordionItem value="item-1">...</AccordionItem>
</Accordion>
```
**Correct (base):**
```tsx
<Accordion defaultValue={["item-1"]}>
<AccordionItem value="item-1">...</AccordionItem>
</Accordion>
// Multi-select.
<Accordion multiple defaultValue={["item-1", "item-2"]}>
<AccordionItem value="item-1">...</AccordionItem>
<AccordionItem value="item-2">...</AccordionItem>
</Accordion>
```
**Correct (radix):**
```tsx
<Accordion type="single" collapsible defaultValue="item-1">
<AccordionItem value="item-1">...</AccordionItem>
</Accordion>
```
+195
View File
@@ -0,0 +1,195 @@
# Component Composition
## Contents
- Items always inside their Group component
- Callouts use Alert
- Empty states use Empty component
- Toast notifications use sonner
- Choosing between overlay components
- Dialog, Sheet, and Drawer always need a Title
- Card structure
- Button has no isPending or isLoading prop
- TabsTrigger must be inside TabsList
- Avatar always needs AvatarFallback
- Use Separator instead of raw hr or border divs
- Use Skeleton for loading placeholders
- Use Badge instead of custom styled spans
---
## Items always inside their Group component
Never render items directly inside the content container.
**Incorrect:**
```tsx
<SelectContent>
<SelectItem value="apple">Apple</SelectItem>
<SelectItem value="banana">Banana</SelectItem>
</SelectContent>
```
**Correct:**
```tsx
<SelectContent>
<SelectGroup>
<SelectItem value="apple">Apple</SelectItem>
<SelectItem value="banana">Banana</SelectItem>
</SelectGroup>
</SelectContent>
```
This applies to all group-based components:
| Item | Group |
|------|-------|
| `SelectItem`, `SelectLabel` | `SelectGroup` |
| `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` |
| `MenubarItem` | `MenubarGroup` |
| `ContextMenuItem` | `ContextMenuGroup` |
| `CommandItem` | `CommandGroup` |
---
## Callouts use Alert
```tsx
<Alert>
<AlertTitle>Warning</AlertTitle>
<AlertDescription>Something needs attention.</AlertDescription>
</Alert>
```
---
## Empty states use Empty component
```tsx
<Empty>
<EmptyHeader>
<EmptyMedia variant="icon"><FolderIcon /></EmptyMedia>
<EmptyTitle>No projects yet</EmptyTitle>
<EmptyDescription>Get started by creating a new project.</EmptyDescription>
</EmptyHeader>
<EmptyContent>
<Button>Create Project</Button>
</EmptyContent>
</Empty>
```
---
## Toast notifications use sonner
```tsx
import { toast } from "sonner"
toast.success("Changes saved.")
toast.error("Something went wrong.")
toast("File deleted.", {
action: { label: "Undo", onClick: () => undoDelete() },
})
```
---
## Choosing between overlay components
| Use case | Component |
|----------|-----------|
| Focused task that requires input | `Dialog` |
| Destructive action confirmation | `AlertDialog` |
| Side panel with details or filters | `Sheet` |
| Mobile-first bottom panel | `Drawer` |
| Quick info on hover | `HoverCard` |
| Small contextual content on click | `Popover` |
---
## Dialog, Sheet, and Drawer always need a Title
`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
```tsx
<DialogContent>
<DialogHeader>
<DialogTitle>Edit Profile</DialogTitle>
<DialogDescription>Update your profile.</DialogDescription>
</DialogHeader>
...
</DialogContent>
```
---
## Card structure
Use full composition — don't dump everything into `CardContent`:
```tsx
<Card>
<CardHeader>
<CardTitle>Team Members</CardTitle>
<CardDescription>Manage your team.</CardDescription>
</CardHeader>
<CardContent>...</CardContent>
<CardFooter>
<Button>Invite</Button>
</CardFooter>
</Card>
```
---
## Button has no isPending or isLoading prop
Compose with `Spinner` + `data-icon` + `disabled`:
```tsx
<Button disabled>
<Spinner data-icon="inline-start" />
Saving...
</Button>
```
---
## TabsTrigger must be inside TabsList
Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
```tsx
<Tabs defaultValue="account">
<TabsList>
<TabsTrigger value="account">Account</TabsTrigger>
<TabsTrigger value="password">Password</TabsTrigger>
</TabsList>
<TabsContent value="account">...</TabsContent>
</Tabs>
```
---
## Avatar always needs AvatarFallback
Always include `AvatarFallback` for when the image fails to load:
```tsx
<Avatar>
<AvatarImage src="/avatar.png" alt="User" />
<AvatarFallback>JD</AvatarFallback>
</Avatar>
```
---
## Use existing components instead of custom markup
| Instead of | Use |
|---|---|
| `<hr>` or `<div className="border-t">` | `<Separator />` |
| `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` |
| `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |
+192
View File
@@ -0,0 +1,192 @@
# Forms & Inputs
## Contents
- Forms use FieldGroup + Field
- InputGroup requires InputGroupInput/InputGroupTextarea
- Buttons inside inputs use InputGroup + InputGroupAddon
- Option sets (27 choices) use ToggleGroup
- FieldSet + FieldLegend for grouping related fields
- Field validation and disabled states
---
## Forms use FieldGroup + Field
Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
```tsx
<FieldGroup>
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" type="email" />
</Field>
<Field>
<FieldLabel htmlFor="password">Password</FieldLabel>
<Input id="password" type="password" />
</Field>
</FieldGroup>
```
Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
**Choosing form controls:**
- Simple text input → `Input`
- Dropdown with predefined options → `Select`
- Searchable dropdown → `Combobox`
- Native HTML select (no JS) → `native-select`
- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)
- Single choice from few options → `RadioGroup`
- Toggle between 25 options → `ToggleGroup` + `ToggleGroupItem`
- OTP/verification code → `InputOTP`
- Multi-line text → `Textarea`
---
## InputGroup requires InputGroupInput/InputGroupTextarea
Never use raw `Input` or `Textarea` inside an `InputGroup`.
**Incorrect:**
```tsx
<InputGroup>
<Input placeholder="Search..." />
</InputGroup>
```
**Correct:**
```tsx
import { InputGroup, InputGroupInput } from "@/components/ui/input-group"
<InputGroup>
<InputGroupInput placeholder="Search..." />
</InputGroup>
```
---
## Buttons inside inputs use InputGroup + InputGroupAddon
Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
**Incorrect:**
```tsx
<div className="relative">
<Input placeholder="Search..." className="pr-10" />
<Button className="absolute right-0 top-0" size="icon">
<SearchIcon />
</Button>
</div>
```
**Correct:**
```tsx
import { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group"
<InputGroup>
<InputGroupInput placeholder="Search..." />
<InputGroupAddon>
<Button size="icon">
<SearchIcon data-icon="inline-start" />
</Button>
</InputGroupAddon>
</InputGroup>
```
---
## Option sets (27 choices) use ToggleGroup
Don't manually loop `Button` components with active state.
**Incorrect:**
```tsx
const [selected, setSelected] = useState("daily")
<div className="flex gap-2">
{["daily", "weekly", "monthly"].map((option) => (
<Button
key={option}
variant={selected === option ? "default" : "outline"}
onClick={() => setSelected(option)}
>
{option}
</Button>
))}
</div>
```
**Correct:**
```tsx
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"
<ToggleGroup spacing={2}>
<ToggleGroupItem value="daily">Daily</ToggleGroupItem>
<ToggleGroupItem value="weekly">Weekly</ToggleGroupItem>
<ToggleGroupItem value="monthly">Monthly</ToggleGroupItem>
</ToggleGroup>
```
Combine with `Field` for labelled toggle groups:
```tsx
<Field orientation="horizontal">
<FieldTitle id="theme-label">Theme</FieldTitle>
<ToggleGroup aria-labelledby="theme-label" spacing={2}>
<ToggleGroupItem value="light">Light</ToggleGroupItem>
<ToggleGroupItem value="dark">Dark</ToggleGroupItem>
<ToggleGroupItem value="system">System</ToggleGroupItem>
</ToggleGroup>
</Field>
```
> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
---
## FieldSet + FieldLegend for grouping related fields
Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
```tsx
<FieldSet>
<FieldLegend variant="label">Preferences</FieldLegend>
<FieldDescription>Select all that apply.</FieldDescription>
<FieldGroup className="gap-3">
<Field orientation="horizontal">
<Checkbox id="dark" />
<FieldLabel htmlFor="dark" className="font-normal">Dark mode</FieldLabel>
</Field>
</FieldGroup>
</FieldSet>
```
---
## Field validation and disabled states
Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
```tsx
// Invalid.
<Field data-invalid>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" aria-invalid />
<FieldDescription>Invalid email address.</FieldDescription>
</Field>
// Disabled.
<Field data-disabled>
<FieldLabel htmlFor="email">Email</FieldLabel>
<Input id="email" disabled />
</Field>
```
Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.
+101
View File
@@ -0,0 +1,101 @@
# Icons
**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide``lucide-react`, `tabler``@tabler/icons-react`, etc. Never assume `lucide-react`.
---
## Icons in Button use data-icon attribute
Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
**Incorrect:**
```tsx
<Button>
<SearchIcon className="mr-2 size-4" />
Search
</Button>
```
**Correct:**
```tsx
<Button>
<SearchIcon data-icon="inline-start"/>
Search
</Button>
<Button>
Next
<ArrowRightIcon data-icon="inline-end"/>
</Button>
```
---
## No sizing classes on icons inside components
Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
**Incorrect:**
```tsx
<Button>
<SearchIcon className="size-4" data-icon="inline-start" />
Search
</Button>
<DropdownMenuItem>
<SettingsIcon className="mr-2 size-4" />
Settings
</DropdownMenuItem>
```
**Correct:**
```tsx
<Button>
<SearchIcon data-icon="inline-start" />
Search
</Button>
<DropdownMenuItem>
<SettingsIcon />
Settings
</DropdownMenuItem>
```
---
## Pass icons as component objects, not string keys
Use `icon={CheckIcon}`, not a string key to a lookup map.
**Incorrect:**
```tsx
const iconMap = {
check: CheckIcon,
alert: AlertIcon,
}
function StatusBadge({ icon }: { icon: string }) {
const Icon = iconMap[icon]
return <Icon />
}
<StatusBadge icon="check" />
```
**Correct:**
```tsx
// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).
import { CheckIcon } from "lucide-react"
function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) {
return <Icon />
}
<StatusBadge icon={CheckIcon} />
```
+162
View File
@@ -0,0 +1,162 @@
# Styling & Customization
See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
## Contents
- Semantic colors
- Built-in variants first
- className for layout only
- No space-x-* / space-y-*
- Prefer size-* over w-* h-* when equal
- Prefer truncate shorthand
- No manual dark: color overrides
- Use cn() for conditional classes
- No manual z-index on overlay components
---
## Semantic colors
**Incorrect:**
```tsx
<div className="bg-blue-500 text-white">
<p className="text-gray-600">Secondary text</p>
</div>
```
**Correct:**
```tsx
<div className="bg-primary text-primary-foreground">
<p className="text-muted-foreground">Secondary text</p>
</div>
```
---
## No raw color values for status/state indicators
For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
**Incorrect:**
```tsx
<span className="text-emerald-600">+20.1%</span>
<span className="text-green-500">Active</span>
<span className="text-red-600">-3.2%</span>
```
**Correct:**
```tsx
<Badge variant="secondary">+20.1%</Badge>
<Badge>Active</Badge>
<span className="text-destructive">-3.2%</span>
```
If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
---
## Built-in variants first
**Incorrect:**
```tsx
<Button className="border border-input bg-transparent hover:bg-accent">
Click me
</Button>
```
**Correct:**
```tsx
<Button variant="outline">Click me</Button>
```
---
## className for layout only
Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
**Incorrect:**
```tsx
<Card className="bg-blue-100 text-blue-900 font-bold">
<CardContent>Dashboard</CardContent>
</Card>
```
**Correct:**
```tsx
<Card className="max-w-md mx-auto">
<CardContent>Dashboard</CardContent>
</Card>
```
To customize a component's appearance, prefer these approaches in order:
1. **Built-in variants**`variant="outline"`, `variant="destructive"`, etc.
2. **Semantic color tokens**`bg-primary`, `text-muted-foreground`.
3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
---
## No space-x-* / space-y-*
Use `gap-*` instead. `space-y-4``flex flex-col gap-4`. `space-x-2``flex gap-2`.
```tsx
<div className="flex flex-col gap-4">
<Input />
<Input />
<Button>Submit</Button>
</div>
```
---
## Prefer size-* over w-* h-* when equal
`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
---
## Prefer truncate shorthand
`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
---
## No manual dark: color overrides
Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
---
## Use cn() for conditional classes
Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
**Incorrect:**
```tsx
<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>
```
**Correct:**
```tsx
import { cn } from "@/lib/utils"
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>
```
---
## No manual z-index on overlay components
`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.
+7
View File
@@ -0,0 +1,7 @@
# Lessons
## Alpine x-transition + tw-animate-css exit animations flash at the end
- Symptom: a modal/overlay fades out, then flashes fully visible for 1-2 frames before it disappears.
- Cause: `animate-out` keyframes default to `animation-fill-mode: none`. The element snaps back to its natural state when the keyframe ends. Alpine hides the element (display: none) only after its own timer (read from `transition-duration`), which starts ~2 rAF later than the animation. The gap shows the element at full opacity.
- Rule: every `x-transition:leave` that uses tw-animate-css `animate-out` MUST also include `fill-mode-forwards`.
- Rule: when a user reports UI flicker, check ALL layers of the animation stack (state reset timing, spinner flash, keyframe fill mode, focus restore) before you report the fix as complete. My first fix covered state reset and spinner only; the fill-mode snap was the visible one.
+64
View File
@@ -0,0 +1,64 @@
# V5 Architecture Fix Plan
Source: /Users/heyandras/.claude/plans/what-do-you-think-soft-firefly.md
## Wave 1 (parallel) — DONE
- [x] 1. Split DashboardController into domain controllers + Laravel policies (denyAsNotFound), dedupe cluster serializer
- [x] 6. Frontend: extract Dashboard.tsx components, useCallback/memo, unified optimistic rollback, use-pending-ids reuse, mid-drag snap-back fix, types.ts drift, env-scoped merge
- [x] 5. Hot-path index migration (wireguard_management_ip, node_address, host, runtime_container_id, last_seen_at)
## Wave 2 (parallel, after wave 1) — DONE
- [x] 2. Status enums (ApplicationStatus/ServerStatus/IngressStatus/ContainerState) + observed_at ordered ingestion
- [x] 3. Reconcile + prune scheduled jobs (V5ReconcileServersJob every 5m + per-server V5ReconcileServerStateJob, 24h container-status prune)
- [x] 4. Job uniqueness (ShouldBeUnique deploy+bootstrap) + queued broadcasts (ShouldBroadcast, afterCommit, null-safe payloads)
- [x] 7. Laravel↔coold verb handshake: UnsupportedCooldVerb detection (flux 501), graceful ingress degradation, coold_version persisted
## Wave 3 (everything else) — DONE
- [x] Morph map (v5.application alias) + uuid collision retry + drop per-insert Schema::hasColumn + defaults dedup
- [x] v5_servers.uuid non-null; capabilities → indexed has_coold/is_ingress booleans (wire format preserved)
- [x] Firewall vs DB atomicity (DB=desired state, flux converge, compensating rollback; revoke-first destroy)
- [x] Deploy failure compensation (stop+force-remove orphaned container, original error preserved)
- [x] Caddyfile hostname/port validation + ValidHostname newline-bypass fix
- [x] Ambiguous host_id resolution warning
## Wave 4 — DONE
- [x] Full V5 suite: 262 passed (1901 assertions); tsc clean; npm build ok; pint clean
## Wave 5 (deep dives)
- [ ] Clusters.tsx + remaining frontend audit
- [ ] coold/flux Rust internals + security audit
- [ ] V5 test quality/coverage audit
## Skipped (product decisions, documented)
- Soft deletes on infra rows (changes cascade semantics — needs product call)
- TLS in v5 ingress (feature, not fix)
- config coold.php/flux.php merge (cosmetic)
## Wave 5 (deep dives) — DONE
- [x] coold/flux Rust audit → findings reported (NOT fixed — separate repo, see session recap: no-TLS gRPC, wildcard cap profiles, lost status updates on outage, exec exit_code always 0, mount-allowlist gaps, unauthenticated Corrosion gossip)
- [x] Frontend audit → all MUST/SHOULD-FIX applied (stale connections on env switch, deleteCluster shadow null-deref, persistSelection ok-guard, useTeamChannel extraction, apiRequest timeouts in Clusters, echo logging gated)
- [x] Test-quality audit → all applied (shared V5TestSchema helper killed schema drift, DashboardTest 174-test monolith split into 12 files, substring tests quarantined in V5FrontendSourceContractTest, +20 new tests: policies, RemoveBootstrapMarker, broadcast payloads, channel auth)
## Wave 6 (audit fixes) — DONE
- [x] v4/v5 currentTeam session cross-contamination (full Team model, write-on-change only)
- [x] flux_url preflight 422 before bootstrap dispatch
- [x] Bootstrap marker/coold_version ordering
- [x] Enum literals sweep (jobs + StopCaddyIngress)
- [x] ManagesConnectionFirewallRules + SerializesResourceConnections → app/Support/V5 classes
## Final state
289 V5 tests passed (2005 assertions) + 333 v4 unit slice green; tsc clean; npm build ok; pint clean. Nothing committed.
## Wave 7 (security + JWT, cut off by session limit, then recovered) — DONE
- [x] JWT: mint explicit 21-primitive caps (config flux.host_capabilities), NOT the host-agent:default wildcard that flux treats as authorize-all; escape-hatch profile config; jti claim + persisted agent_token_jti; kid header; TTL 24h→1h (config); RevokedAgentToken model + migration + isRevoked API; inbound bearer array (laravel_api_tokens) for rotation
- [x] Authz: V5 policies role-gate mutations via isAdminOfTeam (403), keep denyAsNotFound (404) for cross-team; ClusterController::store authorize
- [x] Input: ValidServerIp rejects private/reserved ranges behind config('coold.allow_private_server_ips'); error-detail leak → generic messages + Log::warning; throttle:v5 limiter (RouteServiceProvider)
- [x] Stability: reconcile+refresh honor/advance status_observed_at (shared StatusObservation); Configured + full podman states in enums; deploy persists runtime_container_id after create; reconcile jobs on v5-reconcile queue; status_message churn fixed
- [x] Team-delete teardown: Team::deleting → V5TeardownTeamJob (best-effort per-server container/ingress/marker teardown, self-contained payload)
## Wave 7 recovery fix (post-cutoff)
- [x] FATAL: V5ReconcileServersJob + V5ReconcileServerStateJob redeclared `public $queue = 'v5-reconcile'` — incompatible with Queueable trait's `public $queue;` on PHP 8.5 → hard fatal crashing BOTH pest suite and `php artisan test` bootstrap (job discovery). Moved queue assignment to onQueue() in constructor.
- [x] Stale test: ResourceConnectionControllerTest asserted old snapshot-fail detail; scenario hits the restore path → updated to "The previous rules were restored." (correct behavior)
## Final state (Wave 7)
322 V5 tests passed (2124 assertions) via BOTH vendor/bin/pest AND php artisan test; v4 slice 308 passed; tsc clean; npm build ok; pint clean.
+1
View File
@@ -0,0 +1 @@
../../.agents/skills/shadcn
+32
View File
@@ -0,0 +1,32 @@
vmType: "vz"
arch: "default"
cpus: 2
memory: "2GiB"
disk: "20GiB"
containerd:
system: false
user: false
ssh:
localPort: 60003
images:
- location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-amd64.img"
arch: "x86_64"
- location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-arm64.img"
arch: "aarch64"
mounts: []
provision:
- mode: system
script: |
#!/usr/bin/env bash
set -euxo pipefail
export DEBIAN_FRONTEND=noninteractive
install -d -m 700 /root/.ssh
cat >/root/.ssh/authorized_keys <<'KEYS'
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFuGmoeGq/pojrsyP1pszcNVuZx9iFkCELtxrh31QJ68 sail@76ff66d2e2dd
KEYS
chmod 600 /root/.ssh/authorized_keys
sed -i 's/^#\?PermitRootLogin.*/PermitRootLogin prohibit-password/' /etc/ssh/sshd_config
sed -i 's/^#\?PubkeyAuthentication.*/PubkeyAuthentication yes/' /etc/ssh/sshd_config
systemctl restart ssh || systemctl restart sshd
apt-get update
apt-get install -y --no-install-recommends ca-certificates curl openssh-server sudo
+7
View File
@@ -0,0 +1,7 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi/QySHv0Mk
hwAAAAtzc2gtZWQyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevA
AAAECBQw4jg1WRT2IGHMncCiZhURCts2s24HoDS0thHnnRKVuGmoeGq/pojrsyP1pszcNV
uZx9iFkCELtxrh31QJ68AAAAEXNhaWxANzZmZjY2ZDJlMmRkAQIDBA==
-----END OPENSSH PRIVATE KEY-----
+1
View File
@@ -0,0 +1 @@
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIFuGmoeGq/pojrsyP1pszcNVuZx9iFkCELtxrh31QJ68 sail@76ff66d2e2dd
+8 -4
View File
@@ -3,10 +3,13 @@ APP_ENV=local
APP_NAME=Coolify
APP_ID=development
APP_KEY=
COOLIFY_FLUX_LARAVEL_API_TOKEN=development-flux-token
APP_URL=http://localhost
APP_PORT=8000
APP_DEBUG=true
SSH_MUX_ENABLED=true
COOLIFY_CONTAINER_ROLE=all
DEV_SENTINEL_URL=
# PostgreSQL Database Configuration
DB_DATABASE=coolify
@@ -27,11 +30,12 @@ DB_PORT=5432
# DB_WRITE_PASSWORD=
# DB_STICKY=true
# Enable Laravel Telescope for debugging
TELESCOPE_ENABLED=false
# Enable Laravel Debugbar (disabled by default; set true when needed)
DEBUGBAR_ENABLED=false
# Server-Timing headers + on-screen HUD (defaults ON when APP_ENV=local).
# Force on in any environment (including production): SERVER_TIMING_ENABLED=true
# Force off even in local: SERVER_TIMING_ENABLED=false
# SERVER_TIMING_ENABLED=true
# Vite dev server. Defaults to localhost. For phone/LAN/Tailscale access, set to
# the host machine's reachable IP (e.g. VITE_HOST=100.75.155.70), then recreate vite.
+1
View File
@@ -2,6 +2,7 @@ APP_ENV=production
APP_NAME="Coolify Staging"
APP_ID=development
APP_KEY=
COOLIFY_FLUX_LARAVEL_API_TOKEN=test-flux-token
APP_URL=http://localhost
APP_PORT=8000
SSH_MUX_ENABLED=true
+1 -1
View File
@@ -1,5 +1,6 @@
APP_ENV=testing
APP_KEY=base64:8VEfVNVkXQ9mH2L33WBWNMF4eQ0BWD5CTzB8mIxcl+k=
COOLIFY_FLUX_LARAVEL_API_TOKEN=test-flux-token
APP_DEBUG=true
DB_CONNECTION=testing
@@ -8,7 +9,6 @@ CACHE_DRIVER=array
SESSION_DRIVER=array
QUEUE_CONNECTION=sync
MAIL_MAILER=array
TELESCOPE_ENABLED=false
REDIS_HOST=127.0.0.1
+12
View File
@@ -38,5 +38,17 @@ docker/coolify-realtime/node_modules
.DS_Store
CHANGELOG.md
/.workspaces
/.superpowers/
tests/Browser/Screenshots
tests/v4/Browser/Screenshots
ref
# Local generated Lima configs
.dev/bin/
.dev/coold-assets/
.dev/lima/ssh.config
.dev/lima/ssh_key
.dev/lima/hosts
# Multi-instance local Coolify env files (scripts/dev-instances)
.dev-instances/
+10 -3
View File
@@ -8,7 +8,7 @@ Coolify is an open-source, self-hostable PaaS (alternative to Heroku/Netlify/Ver
## Design Reference
For UI/UX design specifications, principles, and visual standards, consult `DESIGN.md` in the [coollabsio/architecture](https://github.com/coollabsio/architecture) repo.
For UI/UX design specifications, principles, and visual standards, consult the local [`DESIGN.md`](DESIGN.md). It is the source of truth for frontend design work in this repository.
## Development Environment
@@ -18,9 +18,17 @@ Docker Compose-based dev setup with services: coolify (app), postgres, redis, so
# Start dev environment (uses docker-compose.dev.yml)
spin up # or: docker compose -f docker-compose.dev.yml up -d
spin down # stop services
# Two local Coolify instances (isolated stacks; server transfer / multi-control-plane)
./scripts/dev-instances up # a:8000 + b:8001 (uses npm run build for CSS/JS)
./scripts/dev-instances up a --with vite # HMR only when starting a single instance
./scripts/dev-instances urls
./scripts/dev-instances down
# Compose: docker-compose.dev-multi.yml Env: .dev-instances/{a,b}.env (gitignored)
# Note: dual Vite HMR is unsupported (shared public/hot); multi-instance always uses public/build.
```
The app runs at `localhost:8000` by default. Vite dev server on port 5173.
The app runs at `localhost:8000` by default. Instance **b** is on `8001` (db `5433`, redis `6380`, …); see `./scripts/dev-instances`.
## Common Commands
@@ -167,7 +175,6 @@ This application is a Laravel application and its main Laravel ecosystems packag
- laravel/boost (BOOST) - v2
- laravel/dusk (DUSK) - v8
- laravel/pint (PINT) - v1
- laravel/telescope (TELESCOPE) - v5
- pestphp/pest (PEST) - v4
- phpunit/phpunit (PHPUNIT) - v12
- rector/rector (RECTOR) - v2
+714
View File
@@ -0,0 +1,714 @@
# Coolify UI design system
This document defines Coolify's UI design system for its Livewire + Blade +
Alpine + Tailwind v4 frontend. The visual system covers the global shell,
project and environment pages, application navigation, settings surfaces,
tables, modals, toasts, terminals, and metrics.
Use this file as the source of truth for frontend design work. Update it in the
same change whenever a new shared visual pattern or component is introduced.
Onboarding validation and live server validation checkpoints share
`<x-checkpoint-item>` (idle / pending / running / success / error) inside a
compact divided list, not legacy green check SVGs or fixed-width status rows.
> **Maintainer rules**
>
> - Keep the work frontend-focused unless existing data must be exposed to the
> view.
> - Preserve routes, Livewire bindings, permissions, confirmations, and working
> interactions while changing layout and presentation.
> - Add or update tests when a UI change affects behavior. Follow the testing
> requirements in `AGENTS.md`.
> - Validate Blade with `docker exec coolify php artisan view:cache`, then clear
> it with `docker exec coolify php artisan view:clear`.
> - Build frontend assets in the Vite container with
> `docker exec coolify-vite npm run build`.
> - Use existing components before adding another styling abstraction.
---
## 1. Visual direction
The interface is compact and product-focused:
- near-neutral layered surfaces instead of large bordered boxes;
- 1314px UI typography and 32px controls;
- hairline rings instead of heavy borders;
- full-width data tables for dense collections;
- outline Reicon glyphs through `<x-reicon>`;
- the Coolify purple brand accent in light mode;
- the readable Coolify yellow accent in dark mode;
- solid active-item fills (neutral black/white opacity), not accent gradients;
active state is the left accent rail plus a flat selected surface;
- sentence-case labels and headings;
- never use the em dash (`—`) in UI copy. Prefer a period, colon, comma, or
ASCII hyphen (`-`) for empty cells and separators.
Avoid oversized titles, generic dashboard cards, strong shadows, thick
dividers, native browser selects, and isolated colored buttons that do not
match the current action styles.
---
## 2. Development and cascade notes
PHP runs in the `coolify` container. The development app is normally available
at `http://localhost:8000`, with Vite on port `5173`.
`resources/css/app.css` still contains unlayered global element rules for
headings, labels, and tables. Tailwind utilities are layered, so the
unlayered rules can win unexpectedly.
The settings and dense-surface CSS therefore lives as plain unlayered CSS near
the end of `resources/css/app.css`, beginning at:
```css
/* Coollabs layer-card settings surfaces */
```
Important consequences:
- scope settings forms with `.application-settings-form` or
`.application-settings-workspace`;
- add shared surface overrides to the unlayered block instead of stacking
`!important` utilities;
- listbox panels require ancestors with `overflow: visible`;
- anchored cards use `scroll-margin-top: 7rem` to clear both fixed navigation
layers;
- modal shells reuse the layer-card classes but keep content-width sizing on
desktop;
- Alpine code inside quoted Blade attributes must not introduce conflicting
quote characters.
---
## 3. Tokens and color behavior
The surface ladder is defined in `resources/css/app.css`.
| Token | Light | Dark | Use |
|---|---|---|---|
| `--coollabs-canvas` | near white | 10% neutral | page canvas |
| `--coollabs-elevated` | 98% neutral | 15% neutral | shells and card headers |
| `--coollabs-base` | white | 17% neutral | nested card bodies |
| `--coollabs-recessed` | 96% neutral | 20% neutral | inputs and listboxes |
| `--coollabs-fill` | 92.2% neutral | 26.9% neutral | dividers and passive fills |
| `--coollabs-line` | translucent dark | 32% neutral | control borders |
| `--coollabs-hairline` | 93.5% neutral | 26.9% neutral | shell rings |
| `--coollabs-subtle` | 55.6% neutral | 70.8% neutral | labels and muted titles |
Accent behavior is intentionally theme-aware:
- **Light mode:** Coolify purple (`coollabs`) for active controls, focus,
primary actions, and navigation accents.
- **Dark mode:** Coolify yellow (`warning`) for the same states because the
original purple did not provide sufficient text and ring contrast.
Do not hard-code blue focus rings or leave yellow accent utilities active in
light mode. Primary action patterns should normally follow:
```html
bg-coollabs/10 text-coollabs ring-coollabs/25
dark:bg-warning/15 dark:text-warning dark:ring-warning/25
```
The filled top-level action/tab treatment uses the same palette at a restrained
opacity rather than a fully saturated fill.
---
## 4. Page shells and navigation
### Global shell
- Main sidebar groups are compact, use outline Reicons, and keep a 32px row
height.
- Active sidebar rows are rounded pills (`rounded-md`) with an accent rail on
the left plus a solid neutral selected fill (`bg-black/5` light,
`bg-white/6` dark). Hover rows use the same radius. Do not use accent-tinted
gradients on nav rows; yellow washes look muddy on dark UI.
- Nested items use a thin guide line with a visible active segment, not a thick
box border.
- The update badge sits on the version row and uses a tiny fully rounded
primary-action pill.
### Layer-2 navigation
Application and server pages use the same fixed second navigation layer
directly below the global topbar. Do not keep a large in-flow resource heading
or legacy `.navbar-main` tabs on one resource type while using the compact
layer-2 bar on another. Active tabs are a light brand fill:
- purple tint in light mode;
- yellow tint in dark mode;
- no fully saturated tab background.
Keep route-derived active state in Blade/Livewire. Do not rely only on Alpine
state because it can disappear after polling or a Livewire morph.
The global topbar owns the current resource identity and its compact status
badges. Layer 2 owns route tabs, resource links, and contextual action buttons
only. If a resource is missing from `x-top-breadcrumb`, extend the global
topbar instead of repeating its name or status summary in layer 2. Mobile
resource navigation may repeat this context because the desktop global topbar
is hidden there.
Only add layer-2 tabs when they represent real sibling routes inside one
context. Never repeat main-sidebar destinations such as Dashboard, Projects,
Terminal, Servers, Sources, Destinations, or Storage as a second tab row. A
single collection page does not need a tab just to fill the bar; keep its
primary action in the page header instead. When tabs are useful, their left edge
uses the same compact `pl-2` alignment as application navigation rather than
the content container's wide horizontal padding.
The dashboard is a compact overview, not a metrics wall. Use two full-width
sections that follow the projects-page grid pattern: projects first, then
servers. Keep one `New` action in the page header and let its modal choose the
resource type. Place active deployments above the resource grids as a compact,
live-updating table rather than a metric card. Communicate server health with
the shared status badge.
### Top-level dashboard destinations
Every page opened directly from the main sidebar uses the same compact content
shell:
- 24px page title and a 13px muted summary;
- the primary action at the top right using the restrained brand fill;
- no legacy `coolbox`, `.navbar-main`, or oversized subtitle block;
- four-column compact cards for small browsable collections;
- a dense table instead of cards when the collection is expected to grow;
- `x-empty` anatomy for empty states;
- `x-status-badge` for state and `x-reicon` for all interface icons.
Collection cards are `min-h-28` or `min-h-32`, use a 32px icon tile, and keep
secondary metadata at 11px. They must not grow into dashboard-sized summary
cards. Sources, destinations, S3 storage, private keys, and shared-variable
scopes use this pattern.
Top-level settings families such as Team, Notifications, Keys & Tokens, and
instance Settings use a compact header followed by a small route-derived tab
strip. The active tab uses the same purple-light/yellow-dark tint as resource
tabs. Do not nest `<button>` elements inside tab links.
### Route-family consistency
Treat every route family as one cohesive experience rather than styling only
its index or most visible route:
- index, create, detail, settings, logs, metrics, backup, execution, and danger
routes must share the same navigation hierarchy and surface language;
- main-sidebar collection routes use the global shell without duplicating those
destinations in a layer-2 tab row;
- resource detail families use resource identity and status in the global
topbar, route tabs and actions in layer 2, and the grouped settings sidebar
only for the third level;
- create and edit routes stay inside the same layer-2 family instead of
falling back to an isolated legacy page;
- reusable partials, empty states, confirmation flows, and row editors must be
updated with the page that exposes them;
- audit the whole family for native selects, legacy heading blocks, old Save
buttons, old status chips, and `coolbox`/`navbar-main`/`sub-menu-wrapper`
to keep the family consistent.
Do not leave a sibling route using old tabs, a large in-flow title, a browser
select, or a different modal anatomy.
The New Resource page keeps its filter controls in the top layer card, then
renders Applications, Databases, and Services as separate layer-card sections.
Do not leave category headings and resource grids floating as uncontained
content below the filter card.
### Settings workspace
Application and server configuration pages use the same 210px grouped,
icon-led sidebar and a full-width content column. The workspace is capped at
1180px, the sidebar becomes sticky at `xl`, and the sidebar label and first
content card start on the same visual line. Do not use the legacy
`sub-menu-wrapper`, native mobile page selects, or an in-flow row of top-level
tabs. Only show nested section anchors when a page has at least four useful
sections.
The shared workspace grid is:
```blade
<div
class="application-settings-workspace mt-8 grid min-w-0 gap-8
xl:mt-0 xl:grid-cols-[210px_minmax(0,1fr)] xl:gap-10">
<aside class="application-settings-navigation min-w-0 xl:sticky xl:top-26 xl:self-start">
...
</aside>
<div class="min-w-0 xl:mt-3">
...
</div>
</div>
```
Instance Settings constrains both `x-settings.navbar` and the workspace to the
same `max-w-[1180px]` shell.
**Page titles (global):** family H1s (`x-dashboard.navbar` with
`titleOnDesktop="false"`, the default) hide at **lg+**, the same breakpoint as
the desktop shell (main sidebar + fixed layer-2 tabs). Below `lg` the mobile
topbar is used and the page title stays visible. Collection indexes (Servers,
Projects, …) always keep their H1; stack title above actions on narrow widths
so they never overlap. Resource in-flow names only render below `md` (when the
fixed resource tab bar is hidden). Fixed layer-2 spacers must be `lg:h-12` to
match the bar height. Do not put the H1 beside the settings sidebar.
Standard content stack:
```blade
<div class="application-settings-workspace flex flex-col gap-6">
<x-application.settings-section ... />
<x-application.settings-section ... />
</div>
```
The current cross-page section gap is `gap-6`. Do not introduce extra top
padding on an individual page unless its toolbar is intentionally separated
from the first card.
Use a flex or grid stack with `gap-6`; do not use `space-y-*` between layer
cards. The layer-card root intentionally resets its own margin, so margin-based
spacing utilities can silently collapse.
---
## 5. Layer cards
Use `resources/views/components/application/settings-section.blade.php`.
Older manual shells may use `.application-settings-section-header` and
`.application-settings-section-body`; both must retain the same padded,
action-aligned anatomy as the component. Use the component for new work and
replace a manual shell when modifying it instead of creating another variant.
```blade
<x-application.settings-section
id="public-access-section"
title="Public access"
helper="How this section affects the resource.">
<x-slot:actions>
<x-forms.button>Action</x-forms.button>
</x-slot:actions>
...
</x-application.settings-section>
```
Anatomy:
- 8px shell radius;
- elevated header strip;
- no divider below the header;
- nested base-color body with its own fill ring;
- 16px body padding;
- optional `flush` mode for full-bleed tables;
- card-level actions belong in the header slot.
Header actions use an 8px top/right inset while the title keeps its 16px left
inset. Do not leave a larger empty strip between the final action and the
card's top-right corner.
Do not split one collection into a summary card followed by a table or log
card. Keep its status/action in the header, its view switcher or toolbar at the
top of a flush body, and its data in that same layer card. Repeated file
editors are the opposite case: each file gets its own titled layer card so its
content and actions remain clearly associated.
### Nested radii
Concentric boxes must follow:
```text
outer radius = inner radius + visible inset
```
Examples:
- a 6px tab or listbox option inside 4px padding uses a 10px outer well;
- an 8px button inside the unsaved pill's 8px padding uses a 16px outer pill.
Do not give visibly inset parent and child boxes the same radius. Flush or
edge-to-edge children are exempt because there is no visible inset to add.
Use an empty state when the section has no usable controls:
```blade
<x-empty size="sm" title="Nothing here" description="Explain what enables it.">
<x-slot:icon>
<x-reicon name="layers" class="size-8" />
</x-slot:icon>
</x-empty>
```
---
## 6. Controls
All normal controls are 32px high with an 8px radius.
### Field grids
The grid must match the controls visible in the current state:
- two visible peer controls use two columns, not a three-column grid with an
empty track;
- three visible peer controls may use three columns when their content stays
readable;
- conditional fields remain in the same grid when they are part of that field
group, so a URL or text input does not become wider than its peer column;
- collapse to one column at smaller breakpoints.
Do not pick a column count from the maximum possible state if the normal state
shows fewer controls.
### Inputs
Use `x-forms.input` and `x-forms.textarea`. Fields need visible vertical spacing
between the label and control. Password visibility uses the outline Reicon
`eye`/`eye-off` treatment from the shared input component.
### Dropdowns
Do not use native `<select>` on application routes, including mobile fallbacks.
Use:
```blade
<x-forms.listbox id="property" label="Setting" :options="[
['value' => true, 'label' => 'Enabled'],
['value' => false, 'label' => 'Disabled'],
]" onChange="instantSave" />
```
Boolean checkboxes should normally become descriptive two-option listboxes.
Use `.live` behavior only when the selection needs an immediate server
rerender.
Keep checkboxes for compact permission matrices and multi-select lists. Those
controls must use the shared `x-forms.checkbox` anatomy: an 18px rounded custom
box, purple checked fill in light mode, yellow checked fill in dark mode, and a
high-contrast check mark. Never expose the browser or Tailwind Forms default
checkbox on application pages.
The popup panel uses a 10px radius around 6px options with a 4px inset. Keep
the option content left-aligned and size the panel to its content or trigger;
do not create an unnecessarily wide menu.
Toolbar filter and sort buttons keep static labels (`Filter`, `Sort`). The
selected option is indicated inside the menu, not repeated on the trigger.
#### Livewire dropdown state synchronization
Instant-save listboxes must not flash back to an older value while Livewire is
saving or morphing the DOM. Treat the Alpine selection as the current visual
state until its request finishes:
- await the Livewire change handler and prevent overlapping selections while
it is running;
- when a client-managed listbox can be rerendered by an unrelated or stale
Livewire response, use the listbox's `preserveValue` option so the morph does
not replace its newer Alpine value;
- scope `preserveValue` to controls whose value is owned by that interaction;
do not use it when external server events must replace the displayed value;
- after saving through a related model, refresh the parent component's loaded
relationship before rendering the response. A database write alone does not
update an already-loaded Eloquent collection;
- use stable `wire:key` values for rows containing listboxes. Do not include the
selected value in the key, because recreating the Alpine component causes a
visible reset;
- remember that a portalled options panel is teleported outside its visual
wrapper. Guard selection in the Alpine handler itself rather than relying
only on `pointer-events` or a disabled wrapper.
The failure mode to avoid is: selection B is shown optimistically, selection A
is chosen next, the response for B morphs the listbox back to B, then the later
response finally shows A. The control should remain on the newest accepted
selection throughout the save sequence.
#### Multi-select filter dropdowns
Toolbar filters that can combine criteria use one multi-select listbox rather
than separate dropdowns or a single selected value. Follow the deployment
history filter in
`resources/views/livewire/project/application/deployment/index.blade.php`:
- set `aria-multiselectable="true"` on the listbox;
- group related options under compact uppercase labels;
- keep the dropdown open while options are toggled;
- use the shared 16px custom checkbox treatment: purple checked fill in light
mode, yellow checked fill in dark mode, and a high-contrast check mark;
- show the number of active selections in a small count pill on the static
`Filter` trigger;
- combine selections within one group with OR logic and combine different
groups with AND logic;
- constrain only the options area with `max-h-80 overflow-y-auto`;
- place a persistent `Reset filters` action in a separate footer below the
scrollable options, divided by a top border;
- disable the reset action when no filter is active, and close the dropdown
after resetting.
Do not represent the empty state as a selectable `All` option. The footer reset
action is the single way to return the multi-select to its unfiltered state.
### Standard table controls
Dense tables use the shared `x-table.*` components so search, filters, sorting,
and backend loading states remain visually and behaviorally consistent:
- `<x-table.toolbar>` owns the responsive search-left/actions-right layout;
- `<x-table.search>` owns the search icon, optional loading indicator, clear
action, sizing, and input anatomy;
- `<x-table.filter>` owns the static Filter trigger, active-count pill,
multi-select panel, scrollable options area, and Reset filters footer;
- `<x-table.sort>` owns the static Sort trigger and single-select panel;
- `<x-table.loading>` overlays only the changing table data for backend search,
filter, sort, and pagination requests.
Tables continue to own their filter options, sort choices, headers, rows,
queries, permissions, and empty states. Backend-filtered or paginated tables
must use `x-table.loading`; frontend-only Alpine tables reuse the same toolbar
and control anatomy but do not show an artificial loading state.
### Buttons
- neutral actions use the shared `.button`;
- primary actions use the theme-aware purple/yellow tint;
- destructive actions use the existing error treatment;
- use outline Reicons where a matching glyph exists;
- avoid raw browser-default buttons and old dark-mode purple fills.
### Unsaved changes
`resources/views/components/unsaved-bar.blade.php` is a compact floating
bottom-center pill. It contains:
- “You have changes that haven't been saved yet.”
- a subtle Reset action;
- a theme-aware Save changes button matching the tab accent.
On small viewports the pill is inset (`inset-x-3`) and stacks: full label on
the first line, Reset / Save on the second (right-aligned). From `sm` up it
returns to the centered single-row nowrap pill.
Do not restore the old full-width footer.
Deferred fields in one Livewire component use one floating unsaved bar and one
submit action. Do not add a separate “Save configuration” button to every
card. Selectors that are safe to persist independently should use the existing
instant-save pattern.
---
## 7. Dense tables
Collections with many rows should use the Cloudflare-inspired table pattern:
- toolbar above the table;
- search on the left;
- filters, sort, view toggles, and Add on the right;
- 40px header row and roughly 48px data rows;
- subtle row hover;
- plain text or the shared status badge rather than large colored chips;
- compact action at the far right;
- no separate layer card for each item.
Do not add a summary card above a table when it only repeats the row count,
current page, or refresh interval. Keep counts and pagination in the footer.
Background polling stays silent unless its state is actionable; do not add a
“Live updates” badge just to explain that a table refreshes. Filters only
render meaningful values; use the shared listbox instead of a number input or
browser-native control.
The footer is always inside the table shell:
- `Showing XY of Z` on the left;
- first, previous, current page, next, and last controls on the right.
Hide the entire pagination footer when there is only one page (`totalPages > 1`).
A lone “12 of 2” bar with disabled controls adds noise and is unnecessary.
Use `x-status-badge` for resource and execution state. It is a small neutral
pill with a semantic dot, not a full colored rectangle.
Relevant classes:
- `.data-table`
- `.data-table-header`
- `.data-table-row`
- `.table-badge`
Create a page-specific grid class when columns differ. Add responsive rules
that hide secondary columns before allowing horizontal overflow.
---
## 8. Modals, confirmations, and toasts
### Modals
`x-modal-input` and confirmation dialogs reuse the layer-card shell:
- compact elevated header;
- nested base-color body;
- content-width desktop sizing;
- shared 32px controls;
- no redundant description below a self-explanatory title;
- custom listboxes instead of native browser selects;
- listbox and dropdown panels must render above the modal body and escape its
scroll container. Never clip a panel at the modal boundary or make users
scroll the modal to see its options;
- when there is not enough viewport space below the trigger, open the panel
above it while keeping the panel visually on top of the modal;
- right-aligned footer actions below a divider;
- compact action buttons, never a submit button stretched by a column layout.
Edit modals should use the same field layout and option set as their matching
create modal.
### Command palette
The global search command palette (`livewire:global-search`) is a compact
top-anchored overlay:
- elevated shell with hairline ring and modal shadow (not a heavy floating card);
- recessed-neutral header strip with outline search glyph and 14px input;
- compact OS-aware mod+K (`⌘K` on macOS, `Ctrl+K` on Windows/Linux) / `/` / `ESC` kbd chips matching the sidebar search trigger;
- nested base-color results body with group labels in sentence case;
- dense result rows as inset 6px-radius pills (listbox anatomy), not full-bleed
bars with global focus rings;
- hover uses neutral fill; keyboard focus uses a soft accent wash plus a 2px
left rail — never the global `ring-2` / ring-offset treatment;
- create rows use a neutral plus tile that only picks up the accent when the
row is focused;
- type pills and quickcommand chips stay recessed; they tint with the accent
only on the focused row;
- neutral thin scrollbar inside the results body (not brand-colored);
- create-resource modals opened from the palette reuse the standard
`application-settings-section` layer-card shell.
Preserve keyboard navigation (arrow keys, Enter via focused links, Escape to
clear then close), `/` and mod+K (⌘K / Ctrl+K by OS) open shortcuts, and the multi-step
server → destination → project → environment create flow.
### Toasts
`resources/views/components/toast.blade.php` provides the global
`window.toast(message, options)` API and Livewire event handling.
Current toast behavior:
- compact layered card, maximum width 26rem;
- Reicon status tile for success, info, warning, danger, or default;
- title plus optional description;
- dismiss and copy-details actions;
- up to four stacked notifications;
- four-second dismissal, paused while hovered;
- support for all six screen positions and sanitized custom HTML.
Do not bring back the old oversized dark rectangle.
---
## 9. Terminals, logs, and metrics
### Terminals
Application and server browser terminals use the same browser-oriented console
shell, theme picker, compact header controls, and outline `browser-terminal`
Reicon. Hide a container switcher when only one container exists.
### Logs
Runtime and deployment logs should feel like a clean terminal surface:
- keep a single log stream inside one layer card instead of adding an
introductory card above it;
- one compact toolbar;
- a recessed monospace log viewport;
- search and line-count controls aligned with icon actions;
- clear live/follow state;
- fullscreen support without changing the control language;
- custom listbox-style menus instead of browser dropdowns.
### Metrics
Metrics pages use separate layer cards for range selection, CPU, and memory.
Charts follow the application metrics implementation:
- 240px area chart;
- smooth 2px stroke and restrained gradient fill;
- dashed neutral grid;
- no ApexCharts toolbar;
- tooltip positioned at the hovered point;
- UTC on both axes and tooltip;
- 20% headroom above observed values;
- downsample long time ranges before rendering.
Only add a metric if Sentinel exposes historical data for it. Current Sentinel
history endpoints store CPU and memory. Root filesystem usage is included in
the periodic push payload for threshold notifications, but it is not stored as
a historical Sentinel metric and has no history endpoint, so it cannot power a
disk-usage graph yet.
---
## 10. Current reference surfaces
Use these as implementation references:
| Surface | Reference |
|---|---|
| Dashboard overview | `resources/views/livewire/dashboard.blade.php` |
| Top-level collection cards | `resources/views/livewire/project/index.blade.php`, `resources/views/source/all.blade.php` |
| Top-level family tabs | `resources/views/components/team/navbar.blade.php`, `resources/views/components/notification/navbar.blade.php` |
| General settings and form anatomy | `resources/views/livewire/project/application/general.blade.php` |
| Advanced settings | `resources/views/livewire/project/application/advanced.blade.php` |
| Fixed layer-2 resource navigation | `resources/views/livewire/project/application/heading.blade.php`, `resources/views/livewire/server/navbar.blade.php` |
| Grouped settings sidebar | `resources/views/livewire/project/application/configuration.blade.php`, `resources/views/components/server/sidebar.blade.php` |
| Dense environment table and footer | `resources/views/livewire/project/shared/environment-variable/all.blade.php` |
| Standard table toolbar controls | `resources/views/components/table/*` |
| Application metrics charts | `resources/views/livewire/project/shared/metrics.blade.php` |
| Browser terminal workspace | `resources/views/livewire/terminal/index.blade.php` |
| Layer card | `resources/views/components/application/settings-section.blade.php` |
| Custom dropdown | `resources/views/components/forms/listbox.blade.php` |
| Empty state | `resources/views/components/empty.blade.php` |
| Status pill | `resources/views/components/status-badge.blade.php` |
| Floating save pill | `resources/views/components/unsaved-bar.blade.php` |
| Global toast | `resources/views/components/toast.blade.php` |
| Command palette / global search | `resources/views/livewire/global-search.blade.php` |
| Outline icons | `resources/views/components/reicon.blade.php` |
| Shared styling | `resources/css/app.css`, `resources/css/utilities.css` |
| HTTP error pages | `resources/views/components/error-page.blade.php`, `resources/views/errors/*` |
HTTP error pages (400, 401, 402, 403, 404, 419, 429, 500, 503) use the shared
`<x-error-page>` component on the public auth-style canvas: theme-aware status
code, compact title and muted description, neutral `.button` actions, and an
`auth-text-link`-style Contact support link. Keep copy sentence-case and avoid
oversized 200px status numbers.
---
## 11. UI implementation checklist
1. Inventory every route and reusable partial in the family before editing.
2. Read the current Blade and Livewire class before changing presentation.
3. Preserve every existing action, authorization check, loading state, and
confirmation.
4. Add the correct dual navigation and scoped workspace/form class.
5. Convert meaningful groups to layer cards and use `gap-6`.
6. Make the responsive column count match the controls visible in every state.
7. Replace native selects and checkbox-style configuration with listboxes.
8. Use one save model per component: instant-save or one floating dirty bar.
9. Check nested radii using `outer = inner + inset`.
10. Keep modal descriptions purposeful and footer actions compact/right-aligned.
11. Use tables for dense collections and cards for forms or summaries.
12. Use `x-status-badge`, `x-empty`, and `x-reicon`.
13. Confirm light and dark accent behavior.
14. Check fixed-nav anchor offsets and responsive stacking.
15. Sweep every sibling route for legacy controls and shells.
16. Run `git diff --check`.
17. Compile Blade views in the `coolify` container.
18. Build assets in `coolify-vite`.
19. Hard-refresh and inspect the family routes in both themes.
+14 -8
View File
@@ -140,13 +140,19 @@ After installing Docker (or Orbstack) and Spin, verify the installation:
|------|-----|------|
| 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
> ```
**Server-Timing + HUD** (headers + bottom-right pill on full HTML pages):
| Setting | Effect |
|---------|--------|
| `APP_ENV=local` and `SERVER_TIMING_ENABLED` unset | **On** (default in dev) |
| `SERVER_TIMING_ENABLED=true` | **On** in any env, including production |
| `SERVER_TIMING_ENABLED=false` | **Off** even when `APP_ENV=local` |
Metrics: `app` / `db` / `php` / `dbslow` (ms), `queries`, `html` (bytes), `mem` (MB).
HUD keeps a request log (click row → AI-ready dump). Production: enable only
temporarily (`SERVER_TIMING_ENABLED=true`); if you use `config:cache`, rebuild
or clear config after changing the env var.
## Development Notes
@@ -173,9 +179,9 @@ If you encounter issues or break your database or something else, follow these s
1. Stop all running containers `ctrl + c`.
2. Remove all Coolify containers:
2. Force-remove all Coolify dev containers:
```bash
docker rm coolify coolify-db coolify-redis coolify-realtime coolify-testing-host coolify-minio coolify-vite-1 coolify-mail
npm run clean
```
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):
+4 -1
View File
@@ -24,6 +24,9 @@ class CleanupDocker
$helperImageWithVersion = "$helperImage:$helperImageVersion";
$helperImageWithoutPrefix = 'coollabsio/coolify-helper';
$helperImageWithoutPrefixVersion = "coollabsio/coolify-helper:$helperImageVersion";
$buildxMetadataVolume = isDev() && $server->isLocalhost()
? 'coolify-buildx'
: '$HOME/.docker/buildx';
$cleanupLog = [];
@@ -51,7 +54,7 @@ class CleanupDocker
'docker container prune -f --filter "label=coolify.managed=true" --filter "label!=coolify.proxy=true" --filter "label!=coolify.type=database" --filter "label!=coolify.type=application" --filter "label!=coolify.type=service"',
$imagePruneCmd,
'docker builder prune -af',
"docker run --rm -v \$HOME/.docker/buildx:/root/.docker/buildx -v /var/run/docker.sock:/var/run/docker.sock {$helperImageWithVersion} docker buildx prune --builder coolify-railpack -af 2>/dev/null || true",
"docker run --rm -v {$buildxMetadataVolume}:/root/.docker/buildx -v /var/run/docker.sock:/var/run/docker.sock {$helperImageWithVersion} docker buildx prune --builder coolify-railpack -af 2>/dev/null || true",
"docker images --filter before=$helperImageWithVersion --filter reference=$helperImage | grep $helperImage | awk '{print $3}' | xargs -r docker rmi -f",
"docker images --filter before=$realtimeImageWithVersion --filter reference=$realtimeImage | grep $realtimeImage | awk '{print $3}' | xargs -r docker rmi -f",
"docker images --filter before=$helperImageWithoutPrefixVersion --filter reference=$helperImageWithoutPrefix | grep $helperImageWithoutPrefix | awk '{print $3}' | xargs -r docker rmi -f",
+1 -4
View File
@@ -23,13 +23,10 @@ class StartSentinel
$refreshRate = data_get($server, 'settings.sentinel_metrics_refresh_rate_seconds');
$pushInterval = data_get($server, 'settings.sentinel_push_interval_seconds');
$token = $server->settings->ensureValidSentinelToken();
$endpoint = data_get($server, 'settings.sentinel_custom_url');
$endpoint = $server->settings->ensureSentinelUrl();
$debug = data_get($server, 'settings.is_sentinel_debug_enabled');
$mountDir = '/data/coolify/sentinel';
$image = coolifyRegistryUrl().'/coollabsio/sentinel:'.$version;
if (! $endpoint) {
throw new \RuntimeException('You should set FQDN in Instance Settings.');
}
$environments = [
'TOKEN' => $token,
'DEBUG' => $debug ? 'true' : 'false',
+9
View File
@@ -25,6 +25,15 @@ class ValidateServer
public function handle(Server $server)
{
if (! $server->canBeValidated()) {
$this->error = 'This server was transferred to another Coolify instance and cannot be revalidated here.';
$server->update([
'validation_logs' => $this->error,
'is_validating' => false,
]);
throw new \Exception($this->error);
}
$server->update([
'validation_logs' => null,
]);
@@ -59,6 +59,11 @@ class UpdateServiceApplicationFromApi
$serviceApplication->fqdn = $parsed['normalized'];
}
if (array_key_exists('noindex_domains', $payload)) {
// Must run after fqdn is set above: flags are kept only for current domains.
$serviceApplication->setNoindexDomains($payload['noindex_domains'] ?? []);
}
if (array_key_exists('human_name', $payload)) {
$serviceApplication->human_name = $payload['human_name'];
}
@@ -0,0 +1,290 @@
<?php
namespace App\Actions\Shared;
use App\Actions\Application\StopApplication;
use App\Actions\Database\StopDatabase;
use App\Actions\Service\StopService;
use App\Jobs\FinalizeResourceMigrationJob;
use App\Jobs\HostPathCloneJob;
use App\Jobs\ServerStorageSaveJob;
use App\Jobs\VolumeCloneJob;
use App\Models\Application;
use App\Models\LocalPersistentVolume;
use App\Models\Service;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDocker;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\SwarmDocker;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Bus;
use Illuminate\Validation\ValidationException;
use Lorisleiva\Actions\Concerns\AsAction;
class MigrateResourceToDestination
{
use AsAction;
/**
* @return array{async: bool, volume_jobs: int, message: string}
*/
public function handle(
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
StandaloneDocker|SwarmDocker $destination,
bool $migrateVolumes = true,
): array {
if (! isDev()) {
throw ValidationException::withMessages([
'destination_id' => 'Resource migration is only available in development mode.',
]);
}
$resource->loadMissing(['destination.server']);
$sourceDestination = $resource->destination;
if (! $sourceDestination) {
throw ValidationException::withMessages([
'destination_id' => 'Resource has no destination to migrate from.',
]);
}
if (
(int) $sourceDestination->id === (int) $destination->id
&& $sourceDestination->getMorphClass() === $destination->getMorphClass()
) {
throw ValidationException::withMessages([
'destination_id' => 'Resource is already on the selected destination.',
]);
}
$sourceServer = $sourceDestination->server;
$targetServer = $destination->server;
if (! $targetServer) {
throw ValidationException::withMessages([
'destination_id' => 'Target destination has no server.',
]);
}
if (! $targetServer->canHostResources()) {
throw ValidationException::withMessages([
'destination_id' => 'The selected server cannot host resources.',
]);
}
$targetServer->refresh();
if (! $targetServer->isFunctional()) {
throw ValidationException::withMessages([
'destination_id' => 'Target server is not validated and reachable.',
]);
}
$crossServer = $sourceServer && (int) $sourceServer->id !== (int) $targetServer->id;
if (! $crossServer) {
throw ValidationException::withMessages([
'destination_id' => 'Migration requires a different server. Choose another server destination.',
]);
}
if ($migrateVolumes) {
if (! $sourceServer?->isFunctional()) {
throw ValidationException::withMessages([
'destination_id' => 'Source server is not functional. Cannot migrate volume data.',
]);
}
}
$this->stopResource($resource);
$jobs = [];
if ($migrateVolumes) {
$jobs = $this->buildVolumeJobs($resource, $sourceServer, $targetServer);
}
if ($jobs !== []) {
Bus::chain([
...$jobs,
new FinalizeResourceMigrationJob($resource, $destination),
])->dispatch();
return [
'async' => true,
'volume_jobs' => count($jobs),
'message' => 'Migration started. The resource was stopped and volume data is being transferred. Destination will update when transfer completes. Redeploy afterwards.',
];
}
$this->applyDestination($resource, $destination);
return [
'async' => false,
'volume_jobs' => 0,
'message' => $migrateVolumes
? 'Resource migrated to the new server. Redeploy when ready.'
: 'Resource migrated to the new server. Volume data was not transferred. Redeploy when ready.',
];
}
public function applyDestination(
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
StandaloneDocker|SwarmDocker $destination,
): void {
$payload = [
'destination_id' => $destination->id,
'destination_type' => $destination->getMorphClass(),
];
if ($resource instanceof Service) {
$payload['server_id'] = $destination->server_id;
} else {
// Service status is computed from child containers, not a DB column.
$payload['status'] = 'exited';
$payload['started_at'] = null;
}
$resource->fill($payload)->save();
if ($resource instanceof Application) {
$resource->additional_networks()->detach();
$this->regenerateApplicationLabels($resource->fresh(['destination.server', 'settings']));
}
if ($resource instanceof Service) {
foreach ($resource->applications() as $application) {
$application->fill(['status' => 'exited'])->save();
}
foreach ($resource->databases() as $database) {
$database->fill(['status' => 'exited'])->save();
}
}
$this->resaveFileStorages($resource->fresh());
}
protected function stopResource(
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
): void {
try {
if ($resource instanceof Application) {
StopApplication::run($resource, previewDeployments: false, dockerCleanup: false);
} elseif ($resource instanceof Service) {
StopService::run($resource, deleteConnectedNetworks: false, dockerCleanup: false);
} else {
StopDatabase::run($resource, dockerCleanup: false);
}
} catch (\Throwable $e) {
\Log::warning('Failed to stop resource during migration: '.$e->getMessage(), [
'resource_type' => $resource->getMorphClass(),
'resource_uuid' => $resource->uuid ?? null,
]);
}
}
/**
* @return array<int, VolumeCloneJob|HostPathCloneJob>
*/
protected function buildVolumeJobs(
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
$sourceServer,
$targetServer,
): array {
$jobs = [];
$seenNamedVolumes = [];
$seenHostPaths = [];
foreach ($this->collectPersistentVolumes($resource) as $volume) {
if (! $volume instanceof LocalPersistentVolume) {
continue;
}
$hostPath = filled($volume->host_path) ? (string) $volume->host_path : null;
if ($hostPath) {
if (isset($seenHostPaths[$hostPath])) {
continue;
}
$seenHostPaths[$hostPath] = true;
$jobs[] = new HostPathCloneJob($hostPath, $hostPath, $sourceServer, $targetServer);
continue;
}
$name = (string) $volume->name;
if ($name === '' || isset($seenNamedVolumes[$name])) {
continue;
}
$seenNamedVolumes[$name] = true;
$jobs[] = new VolumeCloneJob($name, $name, $sourceServer, $targetServer, $volume);
}
return $jobs;
}
/**
* @return Collection<int, LocalPersistentVolume>
*/
protected function collectPersistentVolumes(
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
) {
if ($resource instanceof Service) {
$volumes = collect();
foreach ($resource->applications() as $application) {
$volumes = $volumes->merge($application->persistentStorages()->get());
}
foreach ($resource->databases() as $database) {
$volumes = $volumes->merge($database->persistentStorages()->get());
}
return $volumes;
}
return $resource->persistentStorages()->get();
}
protected function regenerateApplicationLabels(Application $application): void
{
$settings = $application->settings;
if (! $settings || ! $settings->is_container_label_readonly_enabled) {
return;
}
if ($application->destination?->server?->proxyType() === 'NONE') {
return;
}
$customLabels = str(implode('|coolify|', generateLabelsApplication($application)))->replace('|coolify|', "\n");
$application->custom_labels = base64_encode($customLabels);
$application->save();
}
protected function resaveFileStorages(
Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
): void {
$fileStorages = collect();
if ($resource instanceof Service) {
foreach ($resource->applications() as $application) {
$fileStorages = $fileStorages->merge($application->fileStorages()->get());
}
foreach ($resource->databases() as $database) {
$fileStorages = $fileStorages->merge($database->fileStorages()->get());
}
} elseif (method_exists($resource, 'fileStorages')) {
$fileStorages = $resource->fileStorages()->get();
}
foreach ($fileStorages as $storage) {
if ($storage->is_host_file) {
continue;
}
ServerStorageSaveJob::dispatch($storage);
}
}
}
@@ -0,0 +1,168 @@
<?php
namespace App\Actions\V5\Application;
use App\Enums\V5\ApplicationStatus;
use App\Enums\V5\ContainerState;
use App\Enums\V5\ServerStatus;
use App\Models\V5\Application;
use App\Services\Flux\FluxClient;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
class DeployNginxApplication
{
use AsAction;
public function __construct(private readonly FluxClient $fluxClient) {}
public function handle(Application $application): Application
{
$application->loadMissing('server');
$server = $application->server;
if ($server === null) {
return $this->markFailed($application, 'No server is attached to this application.');
}
if ($server->status !== ServerStatus::Installed->value || $server->last_bootstrapped_at === null) {
return $this->markFailed($application, "Bootstrap server {$server->name} before deploying to it.");
}
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
return $this->markFailed($application, 'No Flux host ID is available for this server.');
}
$containerId = null;
try {
$this->fluxClient->pullImage($hostId, $application->image);
$containerId = $this->fluxClient->createContainer($hostId, $this->containerSpec($application));
// Persist the runtime id the instant the container exists, before
// start/inspect. A worker SIGKILL at the job timeout would otherwise
// orphan a created container whose id only lived in this local var,
// leaving failed()/reconcile unable to find and clean it by id.
$application->update([
'status' => ApplicationStatus::Created->value,
'status_message' => 'Container created.',
'runtime_container_id' => $containerId,
]);
$this->fluxClient->startContainer($hostId, $containerId);
$inspect = $this->fluxClient->inspectContainer($hostId, $containerId);
if (! $this->isContainerRunning($inspect)) {
$this->cleanUpContainer($application, $hostId, $containerId);
return $this->markFailed($application, 'Container did not stay running.');
}
$application->update([
'status' => ApplicationStatus::Running->value,
'status_message' => 'Container started.',
'runtime_container_id' => $containerId,
]);
return $application->refresh()->load('server');
} catch (\Throwable $e) {
if (is_string($containerId) && $containerId !== '') {
$this->cleanUpContainer($application, $hostId, $containerId);
}
return $this->markFailed($application, $e->getMessage());
}
}
/**
* Best-effort compensation for a failed deploy: stop and force-remove the
* container this run created so it is never left orphaned on the node, then
* null the runtime id we persisted right after create so a cleaned-up
* failure never leaves a dangling id that reconcile would try to reap.
* Cleanup failures only log a warning and never mask the original error.
*/
private function cleanUpContainer(Application $application, string $hostId, string $containerId): void
{
try {
$this->fluxClient->stopContainer($hostId, $containerId);
} catch (\Throwable $e) {
Log::warning('Could not stop the container created by a failed v5 deploy.', [
'application_id' => $application->getKey(),
'container_id' => $containerId,
'error' => $e->getMessage(),
]);
}
try {
$this->fluxClient->removeContainer($hostId, $containerId, force: true);
} catch (\Throwable $e) {
Log::warning('Could not remove the container created by a failed v5 deploy.', [
'application_id' => $application->getKey(),
'container_id' => $containerId,
'error' => $e->getMessage(),
]);
}
if ($application->runtime_container_id === $containerId) {
$application->update(['runtime_container_id' => null]);
}
}
/**
* @return array<string, mixed>
*/
private function containerSpec(Application $application): array
{
$network = $this->meshNetwork($application);
$containerName = $application->container_name;
return [
'name' => $containerName,
'image' => $application->image,
'networks' => [$network],
'network_aliases' => [$containerName],
'dns_search' => [$this->meshDnsSearchDomain($application)],
'restart_policy' => 'unless-stopped',
];
}
private function meshNetwork(Application $application): string
{
$namespace = $application->mesh_namespace ?: 'default';
return "coolify-{$namespace}-mesh";
}
private function meshDnsSearchDomain(Application $application): string
{
$namespace = $application->mesh_namespace ?: 'default';
return "{$namespace}.coolify.internal";
}
/**
* @param array<string, mixed> $inspect
*/
private function isContainerRunning(array $inspect): bool
{
$state = $inspect['State'] ?? [];
if (is_array($state) && ($state['Running'] ?? null) === true) {
return true;
}
return is_string($inspect['state'] ?? null) && $inspect['state'] === ContainerState::Running->value;
}
private function markFailed(Application $application, string $message): Application
{
$application->update([
'status' => ApplicationStatus::Failed->value,
'status_message' => str($message)->limit(10000)->toString(),
]);
return $application->refresh()->load('server');
}
}
@@ -0,0 +1,96 @@
<?php
namespace App\Actions\V5\Application;
use App\Models\PrivateKey;
use App\Models\V5\Application;
use Illuminate\Contracts\Process\ProcessResult;
use Illuminate\Support\Facades\Process;
use Lorisleiva\Actions\Concerns\AsAction;
class DestroyNginxApplication
{
use AsAction;
public function handle(Application $application): ?string
{
$application->loadMissing('server.privateKey');
$server = $application->server;
if ($server === null || ! $server->privateKey instanceof PrivateKey) {
return null;
}
$keyLocation = $this->writeTemporaryPrivateKey($server->privateKey);
try {
$result = Process::timeout(120)->run([
'ssh',
'-o',
'BatchMode=yes',
'-o',
'LogLevel=ERROR',
'-o',
'StrictHostKeyChecking=no',
'-o',
'UserKnownHostsFile=/dev/null',
'-o',
'ConnectTimeout=10',
'-o',
'IdentitiesOnly=yes',
'-i',
$keyLocation,
'-p',
(string) $server->ssh_port,
"{$server->ssh_user}@{$server->host}",
$this->remoteCommand($application),
]);
if (! $result->successful()) {
return $this->processOutput($result);
}
return null;
} catch (\Throwable $e) {
return $e->getMessage();
} finally {
@unlink($keyLocation);
}
}
private function remoteCommand(Application $application): string
{
$containerName = escapeshellarg($application->container_name);
return implode(PHP_EOL, [
'set -e',
'if [ "$(id -u)" = "0" ]; then podman=podman; else podman="sudo -n podman"; fi',
"\$podman rm -f {$containerName} >/dev/null 2>&1 || true",
]);
}
private function processOutput(ProcessResult $result): string
{
$output = trim($result->output()."\n".$result->errorOutput());
return $output !== '' ? $output : 'Could not delete nginx container.';
}
private function writeTemporaryPrivateKey(PrivateKey $privateKey): string
{
$keyDirectory = storage_path('app/ssh/keys');
if (! is_dir($keyDirectory)) {
mkdir($keyDirectory, 0700, true);
}
$keyLocation = tempnam($keyDirectory, 'v5_nginx_destroy_key_');
if ($keyLocation === false) {
throw new \RuntimeException('Could not create a temporary SSH key file.');
}
file_put_contents($keyLocation, $privateKey->private_key);
chmod($keyLocation, 0600);
return $keyLocation;
}
}
@@ -0,0 +1,366 @@
<?php
namespace App\Actions\V5\Flux;
use App\Enums\V5\ApplicationStatus;
use App\Enums\V5\ContainerState;
use App\Enums\V5\IngressStatus;
use App\Enums\V5\ServerStatus;
use App\Models\V5\Application as V5Application;
use App\Models\V5\ContainerStatus;
use App\Models\V5\Server as V5Server;
use App\Support\V5\StatusObservation;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
class ApplyFluxResourceStatusUpdate
{
use AsAction;
/**
* @param array<string, mixed> $payload
*/
public function handle(array $payload): ?Model
{
$resourceType = strtolower((string) data_get($payload, 'resource_type', data_get($payload, 'type', '')));
$containerStatus = $resourceType === 'container' ? $this->upsertContainerStatus($payload) : null;
if ($this->isCaddyIngressStatusUpdate($payload, $resourceType)) {
return $this->updateCaddyIngress($payload) ?? $containerStatus;
}
if (in_array($resourceType, ['server', 'node', 'host'], true)) {
return $this->updateServer($payload);
}
return $this->updateApplication($payload) ?? $containerStatus;
}
/**
* @param array<string, mixed> $payload
*/
private function upsertContainerStatus(array $payload): ?ContainerStatus
{
$status = $this->status($payload, ContainerState::class);
$containerId = $this->stringValue($payload, 'container_id') ?? $this->stringValue($payload, 'runtime_container_id');
$server = $this->findServer($payload);
if ($status === null || $containerId === null || ! $server instanceof V5Server) {
return null;
}
$observedAt = $this->observedAt($payload);
$existing = ContainerStatus::query()
->where('server_id', $server->id)
->where('container_id', $containerId)
->first();
if ($this->isStaleObservation($observedAt, $existing?->status_observed_at, 'container status', [
'server_id' => $server->id,
'container_id' => $containerId,
])) {
return $existing;
}
$attributes = [
'team_id' => $server->team_id,
'container_name' => $this->stringValue($payload, 'container_name') ?? $this->stringValue($payload, 'name'),
'image' => $this->stringValue($payload, 'image'),
'status' => $status,
'status_message' => $this->statusMessage($payload, 'Container state received from coold.'),
'last_seen_at' => now(),
];
if ($observedAt !== null) {
$attributes['status_observed_at'] = $observedAt;
}
ContainerStatus::query()->updateOrCreate([
'server_id' => $server->id,
'container_id' => $containerId,
], $attributes);
return ContainerStatus::query()
->where('server_id', $server->id)
->where('container_id', $containerId)
->first();
}
/**
* @param array<string, mixed> $payload
*/
private function updateApplication(array $payload): ?V5Application
{
$status = $this->status($payload, ApplicationStatus::class);
if ($status === null) {
return null;
}
$application = $this->findApplication($payload);
if (! $application instanceof V5Application) {
return null;
}
$observedAt = $this->observedAt($payload);
if ($this->isStaleObservation($observedAt, $application->status_observed_at, 'application status', [
'application_id' => $application->id,
])) {
return $application;
}
$payloadContainerId = $this->stringValue($payload, 'runtime_container_id')
?? $this->stringValue($payload, 'container_id');
// Payloads may carry no timestamp, so the container id remains an
// ordering signal as a second layer: an update for a superseded
// container is stale and must not overwrite the current one's state.
if (
$payloadContainerId !== null
&& $application->runtime_container_id !== null
&& $payloadContainerId !== $application->runtime_container_id
) {
return $application;
}
$attributes = [
'status' => $status,
'status_message' => $this->statusMessage($payload, 'Status updated by flux.'),
'runtime_container_id' => $payloadContainerId ?? $application->runtime_container_id,
];
if ($observedAt !== null) {
$attributes['status_observed_at'] = $observedAt;
}
$application->update($attributes);
return $application->refresh();
}
/**
* @param array<string, mixed> $payload
*/
private function updateServer(array $payload): ?V5Server
{
$status = $this->status($payload, ServerStatus::class);
if ($status === null) {
return null;
}
$server = $this->findServer($payload);
if (! $server instanceof V5Server) {
return null;
}
$observedAt = $this->observedAt($payload);
if ($this->isStaleObservation($observedAt, $server->status_observed_at, 'server status', [
'server_id' => $server->id,
])) {
return $server;
}
$attributes = [
'status' => $status,
'last_status_check' => 'flux',
'last_status_output' => $this->statusMessage($payload, 'Status updated by flux.'),
'last_status_checked_at' => now(),
];
if ($observedAt !== null) {
$attributes['status_observed_at'] = $observedAt;
}
$server->update($attributes);
return $server->refresh();
}
/**
* The ingress state shares the server row but describes a different
* resource, so it deliberately does not read or write the server's
* `status_observed_at` watermark.
*
* @param array<string, mixed> $payload
*/
private function updateCaddyIngress(array $payload): ?V5Server
{
$status = $this->status($payload, IngressStatus::class);
if ($status === null) {
return null;
}
$server = $this->findServer($payload);
if (! $server instanceof V5Server || ! $server->isIngress()) {
return null;
}
$server->update([
'ingress_type' => 'caddy',
'ingress_status' => $status,
'last_status_check' => 'flux',
'last_status_output' => $this->statusMessage($payload, 'Status updated by flux.'),
'last_status_checked_at' => now(),
]);
return $server->refresh();
}
/**
* @param array<string, mixed> $payload
*/
private function findApplication(array $payload): ?V5Application
{
$server = $this->findServer($payload);
if (! $server instanceof V5Server) {
return null;
}
$query = V5Application::query()
->with('server')
->where('server_id', $server->id)
->where('team_id', $server->team_id);
$applicationUuid = $this->stringValue($payload, 'application_uuid') ?? $this->stringValue($payload, 'resource_uuid');
if ($applicationUuid !== null) {
return $query->where('uuid', $applicationUuid)->first();
}
$containerName = $this->stringValue($payload, 'container_name') ?? $this->stringValue($payload, 'name');
if ($containerName !== null) {
return $query->where('container_name', $containerName)->first();
}
$containerId = $this->stringValue($payload, 'runtime_container_id') ?? $this->stringValue($payload, 'container_id');
if ($containerId !== null) {
return $query->where('runtime_container_id', $containerId)->first();
}
return null;
}
/**
* @param array<string, mixed> $payload
*/
private function isCaddyIngressStatusUpdate(array $payload, string $resourceType): bool
{
if (in_array($resourceType, ['caddy_ingress', 'caddy-ingress'], true)) {
return true;
}
return $this->stringValue($payload, 'container_name') === 'coolify-v5-caddy'
|| $this->stringValue($payload, 'name') === 'coolify-v5-caddy';
}
/**
* @param array<string, mixed> $payload
*/
private function findServer(array $payload): ?V5Server
{
$serverUuid = $this->stringValue($payload, 'server_uuid') ?? $this->stringValue($payload, 'host_server_uuid');
if ($serverUuid !== null) {
return V5Server::query()->where('uuid', $serverUuid)->first();
}
$hostId = $this->stringValue($payload, 'host_id')
?? $this->stringValue($payload, 'node_id')
?? $this->stringValue($payload, 'server_host');
if ($hostId === null) {
return null;
}
$matches = V5Server::query()
->where('uuid', $hostId)
->limit(2)
->get();
if ($matches->count() > 1) {
Log::warning('Dropping flux resource status update: host id matches multiple v5 servers.', [
'host_id' => $hostId,
'server_ids' => $matches->pluck('id')->all(),
]);
return null;
}
return $matches->first();
}
/**
* Map the raw payload status onto the given status enum. Unknown values
* are never written to the database: they fall back to the enum's
* Unknown case and are logged.
*
* @param array<string, mixed> $payload
* @param class-string<ApplicationStatus|ContainerState|IngressStatus|ServerStatus> $enumClass
*/
private function status(array $payload, string $enumClass): ?string
{
$raw = $this->stringValue($payload, 'status') ?? $this->stringValue($payload, 'state');
return StatusObservation::normalize($raw, $enumClass);
}
/**
* @param array<string, mixed> $payload
*/
private function observedAt(array $payload): ?CarbonInterface
{
$observedAt = $this->stringValue($payload, 'observed_at');
if ($observedAt === null) {
return null;
}
return rescue(fn (): CarbonImmutable => CarbonImmutable::parse($observedAt), null, false);
}
/**
* A payload that carries an observation timestamp older than the one
* already persisted is stale (delivered out of order) and must not
* clobber the newer state.
*
* @param array<string, mixed> $logContext
*/
private function isStaleObservation(?CarbonInterface $observedAt, ?CarbonInterface $currentObservedAt, string $context, array $logContext): bool
{
return StatusObservation::isStale($observedAt, $currentObservedAt, $context, $logContext);
}
/**
* @param array<string, mixed> $payload
*/
private function statusMessage(array $payload, string $fallback): string
{
return $this->stringValue($payload, 'status_message')
?? $this->stringValue($payload, 'message')
?? $fallback;
}
/**
* @param array<string, mixed> $payload
*/
private function stringValue(array $payload, string $key): ?string
{
$value = data_get($payload, $key);
return is_string($value) && $value !== '' ? $value : null;
}
}
@@ -0,0 +1,157 @@
<?php
namespace App\Actions\V5\Proxy;
use App\Models\V5\Application;
use App\Models\V5\ApplicationDomain;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class GenerateCaddyIngressConfiguration
{
use AsAction;
/**
* Strict RFC 1123 hostname: dot-separated alphanumeric labels with inner
* hyphens, max 253 characters. Anchored with \A/\z (never $) so values
* containing newlines, braces, quotes, whitespace, or control characters
* can never inject extra directives into the generated Caddyfile.
*/
private const HOSTNAME_PATTERN = '/\A(?=.{1,253}\z)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*\z/i';
/**
* @param Collection<int, Application>|null $applications
* @return array{compose: string, caddyfile: string, apps: array<int, array{name: string, caddyfile: string}>}
*/
public function handle(?Collection $applications = null): array
{
return [
'compose' => $this->compose(),
'caddyfile' => $this->rootCaddyfile(),
'apps' => $this->appCaddyfiles($applications ?? collect()),
];
}
private function compose(): string
{
return Yaml::dump([
'services' => [
'caddy' => [
'image' => 'docker.io/library/caddy:2-alpine',
'container_name' => 'coolify-v5-caddy',
'restart' => 'unless-stopped',
'ports' => [
'80:80',
],
'volumes' => [
'./Caddyfile:/etc/caddy/Caddyfile:ro',
'./apps:/etc/caddy/apps:ro',
'./data:/data',
'./config:/config',
],
],
],
], 8, 2);
}
private function rootCaddyfile(): string
{
return <<<'CADDY'
:80 {
respond /coolify-health 200
respond 404
}
import apps/*.caddy
CADDY;
}
/**
* @param Collection<int, Application> $applications
* @return array<int, array{name: string, caddyfile: string}>
*/
private function appCaddyfiles(Collection $applications): array
{
return $applications
->each(fn (Application $application) => $application->loadMissing('domains'))
->map(fn (Application $application) => [
'name' => $this->appFileName($application),
'caddyfile' => $this->applicationCaddyfile($application),
])
->filter(fn (array $file) => $file['caddyfile'] !== '')
->sortBy('name')
->values()
->all();
}
private function applicationCaddyfile(Application $application): string
{
if (! $application->ingress_enabled || ! $application->internal_port) {
return '';
}
return $application->domains
->map(fn (ApplicationDomain $domain) => $this->applicationRoute($application, $domain))
->filter()
->sort()
->implode("\n\n");
}
private function applicationRoute(Application $application, ApplicationDomain $domain): ?string
{
if ($domain->domain === null || $domain->domain === '') {
return null;
}
$namespace = $application->mesh_namespace ?: 'default';
$internalPort = (int) $application->internal_port;
if (! $this->isSafeHostname($domain->domain)) {
Log::warning('Skipping a caddy ingress route with an unsafe domain.', [
'application_id' => $application->getKey(),
'domain' => $domain->domain,
]);
return null;
}
if (! $this->isSafeHostname($application->container_name) || ! $this->isSafeHostname($namespace)) {
Log::warning('Skipping a caddy ingress route with an unsafe container name or namespace.', [
'application_id' => $application->getKey(),
'container_name' => $application->container_name,
'namespace' => $namespace,
]);
return null;
}
if ($internalPort < 1 || $internalPort > 65535) {
Log::warning('Skipping a caddy ingress route with an out-of-range internal port.', [
'application_id' => $application->getKey(),
'internal_port' => $application->internal_port,
]);
return null;
}
$upstream = "{$application->container_name}.{$namespace}.coolify.internal:{$internalPort}";
return implode("\n", [
"http://{$domain->domain} {",
" reverse_proxy {$upstream}",
'}',
]);
}
private function isSafeHostname(mixed $value): bool
{
return is_string($value) && preg_match(self::HOSTNAME_PATTERN, $value) === 1;
}
private function appFileName(Application $application): string
{
return 'app_'.$application->getKey();
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace App\Actions\V5\Proxy;
use App\Exceptions\V5\UnsupportedCooldVerb;
use App\Models\V5\Application;
use App\Models\V5\Server;
use App\Services\Flux\FluxClient;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
class StartCaddyIngress
{
use AsAction;
private const FIREWALL_PORTS = [80];
public function __construct(private readonly FluxClient $fluxClient) {}
public function handle(Server $server): string
{
if (! $server->isIngress()) {
return 'Server is not an ingress server.';
}
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
throw new \RuntimeException('Server is missing its Flux host id.');
}
$configuration = GenerateCaddyIngressConfiguration::run($this->applications($server));
$output = $this->fluxClient->applyIngress($hostId, 'caddy', $configuration['caddyfile'], $this->ingressApps($configuration['apps']));
$firewallWarning = null;
foreach (self::FIREWALL_PORTS as $port) {
try {
$this->fluxClient->applyFirewallRule($hostId, [
'id' => "v5-caddy-ingress:{$port}",
'namespace' => 'default',
'src' => '0.0.0.0/0',
'dst' => 'coolify-v5-caddy',
'proto' => 'tcp',
'port' => $port,
]);
} catch (UnsupportedCooldVerb $exception) {
$firewallWarning = "Caddy ingress is running, but this node's coold does not support {$exception->verb}, so the managed firewall was not updated for port {$port}.";
Log::warning('V5 caddy ingress firewall rule skipped: coold verb unsupported', [
'server_id' => $server->id,
'port' => $port,
'verb' => $exception->verb,
'message' => $exception->getMessage(),
]);
break;
}
}
if ($server->exists) {
$server->update([
'ingress_type' => 'caddy',
'ingress_status' => 'running',
...($firewallWarning === null ? [] : [
'last_status_check' => 'flux',
'last_status_output' => $firewallWarning,
]),
]);
}
return $output;
}
/**
* @param array<int, array{name: string, caddyfile: string}> $apps
* @return array<int, array{name: string, config: string}>
*/
private function ingressApps(array $apps): array
{
return array_map(
fn (array $app): array => [
'name' => $app['name'],
'config' => $app['caddyfile'],
],
$apps
);
}
/**
* @return Collection<int, Application>
*/
private function applications(Server $server): Collection
{
if (! $server->exists) {
return collect();
}
return Application::query()
->where('team_id', $server->team_id)
->where('server_id', $server->id)
->with('domains')
->orderBy('name')
->get();
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Actions\V5\Proxy;
use App\Enums\V5\IngressStatus;
use App\Exceptions\V5\UnsupportedCooldVerb;
use App\Models\V5\Server;
use App\Services\Flux\FluxClient;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Lorisleiva\Actions\Concerns\AsAction;
class StopCaddyIngress
{
use AsAction;
private const FIREWALL_PORTS = [80];
public function __construct(private readonly FluxClient $fluxClient) {}
public function handle(Server $server): string
{
if (! $server->isIngress() && $server->ingress_type === null) {
return 'Server is not an ingress server.';
}
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
throw new \RuntimeException('Server is missing its Flux host id.');
}
// Revoke first: if stopping the container fails the allow rules must not
// stay orphaned on the host.
foreach (self::FIREWALL_PORTS as $port) {
$this->revokeFirewallRuleIfPresent($hostId, "v5-caddy-ingress:{$port}");
}
$output = $this->fluxClient->stopIngress($hostId, 'caddy');
if ($server->exists) {
$server->update(['ingress_status' => IngressStatus::Exited->value]);
}
return $output;
}
private function revokeFirewallRuleIfPresent(string $hostId, string $ruleId): void
{
try {
$this->fluxClient->revokeFirewallRule($hostId, $ruleId);
} catch (UnsupportedCooldVerb $exception) {
Log::warning('V5 caddy ingress firewall revoke skipped: coold verb unsupported', [
'host_id' => $hostId,
'rule_id' => $ruleId,
'verb' => $exception->verb,
'message' => $exception->getMessage(),
]);
} catch (\RuntimeException $exception) {
if (! str_contains(Str::lower($exception->getMessage()), 'not found')) {
throw $exception;
}
}
}
}
@@ -0,0 +1,101 @@
<?php
namespace App\Actions\V5\Server;
use App\Models\PrivateKey;
use App\Models\V5\Server;
use Illuminate\Support\Facades\Process;
use Lorisleiva\Actions\Concerns\AsAction;
class PushHostAgentToken
{
use AsAction;
/**
* Best-effort SSH push of a freshly minted host JWT to the on-host jwt path.
*
* coold re-reads the JWT file on every reconnect and flux drops the stream
* at the token's exp, so overwriting the file in place is enough for the
* next reconnect to pick up the new token coold is intentionally NOT
* restarted here (a restart would force an unnecessary disconnect of a
* stream that is still valid on the current token).
*
* Mirrors V5BootstrapServerJob::enrollCooldIntoFlux for the write mechanics
* (printf %s <token> | sudo tee <path>; chmod 600) and RemoveBootstrapMarker
* for the SSH/temp-key mechanics. Returns whether the write succeeded;
* every failure path (missing key, SSH error, exception) resolves to false
* and always cleans up the temporary key file.
*/
public function handle(Server $server, string $token): bool
{
$server->loadMissing('privateKey');
if (! $server->privateKey instanceof PrivateKey) {
return false;
}
$jwtPath = trim((string) config('coold.flux_host_jwt_path', '/etc/coolify/host-jwt'));
if ($jwtPath === '') {
$jwtPath = '/etc/coolify/host-jwt';
}
$jwtPath = str_replace(["\r", "\n"], '', $jwtPath);
$token = str_replace(["\r", "\n"], '', $token);
$keyDirectory = storage_path('app/ssh/keys');
if (! is_dir($keyDirectory)) {
mkdir($keyDirectory, 0700, true);
}
$keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');
if ($keyLocation === false) {
return false;
}
file_put_contents($keyLocation, $server->privateKey->private_key);
chmod($keyLocation, 0600);
$tokenArgument = escapeshellarg($token);
$jwtPathArgument = $this->shellPathArg($jwtPath);
$script = <<<SH
set -e
SUDO=''
if [ "\$(id -u)" != "0" ]; then SUDO='sudo'; fi
\$SUDO mkdir -p /etc/coolify
printf %s {$tokenArgument} | \$SUDO tee {$jwtPathArgument} >/dev/null
\$SUDO chmod 600 {$jwtPathArgument}
SH;
try {
$result = Process::timeout(30)->run([
'ssh',
'-o', 'BatchMode=yes',
'-o', 'LogLevel=ERROR',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ConnectTimeout=10',
'-o', 'IdentitiesOnly=yes',
'-i', $keyLocation,
'-p', (string) $server->ssh_port,
"{$server->ssh_user}@{$server->host}",
$script,
]);
return $result->successful();
} catch (\Throwable) {
return false;
} finally {
@unlink($keyLocation);
}
}
private function shellPathArg(string $value): string
{
if (preg_match('/^[A-Za-z0-9_\/:.,@%+=-]+$/', $value) === 1) {
return $value;
}
return escapeshellarg($value);
}
}
@@ -0,0 +1,75 @@
<?php
namespace App\Actions\V5\Server;
use App\Models\PrivateKey;
use App\Models\V5\Server;
use App\Services\Flux\AgentTokenIssuer;
use Illuminate\Support\Facades\Process;
use Lorisleiva\Actions\Concerns\AsAction;
class RemoveBootstrapMarker
{
use AsAction;
/**
* Best-effort removal of the on-host bootstrap identity (marker, host JWT and
* Flux drop-in) so a re-added server can never silently adopt stale state.
*
* The host token jti is revoked first (a local DB write plus a best-effort
* push to the flux revocation store) so a captured or pre-copied token is
* recorded revoked even when the host is unreachable see
* AgentTokenIssuer::revoke.
*/
public function handle(Server $server): bool
{
app(AgentTokenIssuer::class)->revoke($server);
$server->loadMissing('privateKey');
if (! $server->privateKey instanceof PrivateKey) {
return false;
}
$keyDirectory = storage_path('app/ssh/keys');
if (! is_dir($keyDirectory)) {
mkdir($keyDirectory, 0700, true);
}
$keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');
if ($keyLocation === false) {
return false;
}
file_put_contents($keyLocation, $server->privateKey->private_key);
chmod($keyLocation, 0600);
$script = implode("\n", [
"SUDO=''",
'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',
'$SUDO rm -f /etc/coolify/v5-node.json /etc/coolify/host-jwt /etc/systemd/system/coold.service.d/10-flux.conf',
]);
try {
$result = Process::timeout(15)->run([
'ssh',
'-o', 'BatchMode=yes',
'-o', 'LogLevel=ERROR',
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-o', 'ConnectTimeout=10',
'-o', 'IdentitiesOnly=yes',
'-i', $keyLocation,
'-p', (string) $server->ssh_port,
"{$server->ssh_user}@{$server->host}",
$script,
]);
return $result->successful();
} catch (\Throwable) {
return false;
} finally {
@unlink($keyLocation);
}
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Actions\V5\Server;
use App\Enums\V5\ServerStatus;
use App\Models\PrivateKey;
use App\Models\Team;
use App\Models\User;
use App\Models\V5\Cluster;
use App\Models\V5\Server;
use Lorisleiva\Actions\Concerns\AsAction;
/**
* Registers local Lima development VMs (provisioned by scripts/dev.sh) as
* cluster servers. They are intentionally seeded as Installed with
* last_bootstrapped_at already set but has_coold=false, so they skip the real
* bootstrap flow by design: V5BootstrapServerJob early-returns on a non-null
* last_bootstrapped_at, and V5ReconcileServersJob ignores them until
* something marks has_coold=true.
*/
class SyncDevLimaServers
{
use AsAction;
/**
* @param array<int, array{
* name: string,
* host: string,
* ssh_user: string,
* ssh_port: int,
* wireguard_management_ip?: ?string,
* wireguard_listen_port_override?: ?int,
* wireguard_endpoint_override?: ?string
* }> $servers
*/
public function handle(
Team $team,
User $user,
?PrivateKey $privateKey,
string $clusterName,
array $servers,
): Cluster {
$cluster = Cluster::query()->updateOrCreate([
'team_id' => $team->id,
'name' => $clusterName,
], [
'created_by_user_id' => $user->id,
'description' => 'Local Lima development cluster managed by scripts/dev.sh.',
]);
foreach ($servers as $server) {
$wireguardManagementIp = $server['wireguard_management_ip'] ?? null;
$values = [
'created_by_user_id' => $user->id,
'private_key_id' => $privateKey?->id,
'host' => $server['host'],
'ssh_user' => $server['ssh_user'],
'ssh_port' => $server['ssh_port'],
'status' => ServerStatus::Installed->value,
'has_coold' => false,
'is_ingress' => false,
'builder_enabled' => false,
'builder_capacity' => 0,
'node_address' => $wireguardManagementIp ?: $server['host'],
'wireguard_management_ip' => $wireguardManagementIp,
'last_bootstrapped_at' => now(),
];
if (array_key_exists('wireguard_listen_port_override', $server)) {
$values['wireguard_listen_port_override'] = $server['wireguard_listen_port_override'];
}
if (array_key_exists('wireguard_endpoint_override', $server)) {
$values['wireguard_endpoint_override'] = $server['wireguard_endpoint_override'];
}
Server::query()->updateOrCreate([
'team_id' => $team->id,
'cluster_id' => $cluster->id,
'name' => $server['name'],
], $values);
}
return $cluster->refresh();
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Console\Commands;
use App\Services\Flux\AgentTokenIssuer;
use App\Support\V5\V5Feature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class FluxDev extends Command
{
protected $signature = 'flux:dev
{host_id=coold-dev : Stable coold host id}
{--caps= : Comma-separated host capabilities}
{--ttl=3600 : Token lifetime in seconds}
{--output= : Optional path to write the token with 0600 permissions}';
protected $description = 'Run Flux development helpers.';
/**
* @return array<int, string>
*/
private function defaultCapabilities(): array
{
return [
'host-agent:dev',
];
}
public function handle(AgentTokenIssuer $agentTokenIssuer): int
{
if (! V5Feature::enabled()) {
$this->error('V5 is only available in development environments.');
return self::FAILURE;
}
$hostId = (string) $this->argument('host_id');
$ttl = max(60, (int) $this->option('ttl'));
$caps = collect(explode(',', (string) $this->option('caps')))
->map(fn (string $cap) => trim($cap))
->filter()
->unique()
->values()
->all();
if ($caps === []) {
$caps = $this->defaultCapabilities();
}
try {
$token = $agentTokenIssuer->issue($hostId, $caps, $ttl);
} catch (\RuntimeException $exception) {
$this->error($exception->getMessage());
return self::FAILURE;
}
$output = $this->option('output');
if (is_string($output) && $output !== '') {
$outputPath = Str::startsWith($output, '/') ? $output : base_path($output);
File::ensureDirectoryExists(dirname($outputPath));
File::put($outputPath, $token.PHP_EOL);
chmod($outputPath, 0600);
$this->info("Host JWT written to {$outputPath}.");
return self::SUCCESS;
}
$this->line($token);
return self::SUCCESS;
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Console\Commands;
use App\Services\Flux\AgentTokenIssuer;
use App\Support\V5\V5Feature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
/**
* Generates the ES256 (EC P-256) keypair used to authorize coold host agents
* against flux. Laravel signs the per-host JWT with the private key
* (config('flux.jwt_private_key_path')); flux verifies it with the matching
* public key (config('flux.jwt_public_key_path')). Without this keypair a fresh
* install cannot mint host tokens, so this command is a bootstrap prerequisite.
*
* @see AgentTokenIssuer
*/
class V5FluxGenerateKeys extends Command
{
protected $signature = 'v5:flux-generate-keys
{--force : Overwrite an existing private key instead of refusing}
{--show-public : Print the generated public key PEM so it can be provisioned to flux}';
protected $description = 'Generate the ES256 keypair Flux uses to sign and verify coold host agent JWTs.';
public function handle(AgentTokenIssuer $agentTokenIssuer): int
{
if (! V5Feature::enabled()) {
$this->error('V5 is only available in development environments.');
return self::FAILURE;
}
$privateKeyPath = (string) config('flux.jwt_private_key_path');
$publicKeyPath = (string) config('flux.jwt_public_key_path');
if ($privateKeyPath === '' || $publicKeyPath === '') {
$this->error('Flux JWT key paths are not configured (flux.jwt_private_key_path / flux.jwt_public_key_path).');
return self::FAILURE;
}
// Idempotent by default: re-running during provisioning must not clobber
// a live key (which would instantly invalidate every host token on
// disk). Refuse unless --force is passed, and exit SUCCESS so a
// provisioning script can call this unconditionally on every deploy.
if (File::exists($privateKeyPath) && ! $this->option('force')) {
$this->warn("A Flux JWT private key already exists at {$privateKeyPath}.");
$this->line('Refusing to overwrite it. Re-run with --force to replace it (this invalidates every host token currently on disk).');
return self::SUCCESS;
}
// curve_name drives the actual EC key (P-256). private_key_bits is
// still validated by PHP's generic length check (>= 384) even though it
// is irrelevant to EC, so it must be present or openssl_pkey_new fails
// with "Private key length must be at least 384 bits, configured to 0".
$keyPair = openssl_pkey_new([
'private_key_type' => OPENSSL_KEYTYPE_EC,
'curve_name' => 'prime256v1',
'private_key_bits' => 384,
]);
if ($keyPair === false) {
$this->error('Failed to generate an EC P-256 keypair: '.openssl_error_string());
return self::FAILURE;
}
$privatePem = '';
if (! openssl_pkey_export($keyPair, $privatePem)) {
$this->error('Failed to export the private key PEM: '.openssl_error_string());
return self::FAILURE;
}
$details = openssl_pkey_get_details($keyPair);
if ($details === false || ! isset($details['key'])) {
$this->error('Failed to read the generated public key PEM.');
return self::FAILURE;
}
$publicPem = (string) $details['key'];
$this->writeKeyFile($privateKeyPath, $privatePem, 0600);
$this->writeKeyFile($publicKeyPath, $publicPem, 0644);
// Self-check: the whole point of this command is that AgentTokenIssuer
// can mint with the key we just wrote. If the format were wrong (e.g.
// not a PEM EC private key Firebase\JWT accepts for ES256) this fails
// loudly here instead of silently at the first real host bootstrap.
try {
$token = $agentTokenIssuer->issue('flux-keygen-selfcheck');
} catch (\Throwable $exception) {
$this->error('Generated a keypair but AgentTokenIssuer could not mint a token with it: '.$exception->getMessage());
return self::FAILURE;
}
if (substr_count($token, '.') !== 2) {
$this->error('Generated key produced a malformed JWT (expected 3 segments).');
return self::FAILURE;
}
$this->info('Generated a fresh ES256 (EC P-256) Flux keypair.');
$this->line(" Private key (0600): {$privateKeyPath}");
$this->line(" Public key (0644): {$publicKeyPath}");
$this->newLine();
$this->line('Provision the PUBLIC key to flux — flux verifies every host JWT with it.');
$this->line('Keep the PRIVATE key secret and on the Laravel host only.');
if ($this->option('show-public')) {
$this->newLine();
$this->line(rtrim($publicPem));
}
return self::SUCCESS;
}
/**
* Write a key file with exact permissions, creating the parent directory at
* 0700 if missing. chmod is applied after the write because umask can
* loosen both the mkdir mode and the created file mode.
*/
private function writeKeyFile(string $path, string $contents, int $mode): void
{
$directory = dirname($path);
if (! is_dir($directory)) {
File::makeDirectory($directory, 0700, true);
@chmod($directory, 0700);
}
File::put($path, $contents);
@chmod($path, $mode);
}
}
@@ -0,0 +1,93 @@
<?php
namespace App\Console\Commands;
use App\Actions\V5\Server\SyncDevLimaServers;
use App\Models\PrivateKey;
use App\Models\Team;
use App\Models\User;
use App\Support\V5\V5Feature;
use Illuminate\Console\Command;
class V5SyncDevLimaServers extends Command
{
protected $signature = 'v5:sync-dev-lima-servers
{--team-id=0 : Team that owns the dev servers}
{--user-id=0 : User recorded as creator}
{--private-key-id= : Optional private key used by the dev servers}
{--cluster=Development-Lima : Cluster name for the dev Lima servers}
{--server=* : Server as name|host|ssh_user|ssh_port|wireguard_management_ip}';
protected $description = 'Sync development Lima VMs into the v5 server/cluster tables.';
public function handle(): int
{
if (! V5Feature::enabled()) {
$this->error('V5 is only available in development environments.');
return self::FAILURE;
}
$team = Team::query()->find((int) $this->option('team-id')) ?? Team::query()->orderBy('id')->first();
$user = User::query()->find((int) $this->option('user-id')) ?? User::query()->orderBy('id')->first();
$privateKeyId = $this->option('private-key-id');
$privateKey = is_numeric($privateKeyId)
? PrivateKey::query()->find((int) $privateKeyId)
: PrivateKey::query()
->where('team_id', $team?->id)
->where('is_git_related', false)
->orderBy('id')
->first();
if (! $team instanceof Team || ! $user instanceof User) {
$this->warn('Cannot sync dev Lima servers without an existing team and user.');
return self::SUCCESS;
}
$servers = $this->option('server');
if (! is_array($servers) || $servers === []) {
$this->warn('No dev Lima servers were provided.');
return self::SUCCESS;
}
$parsedServers = [];
foreach ($servers as $server) {
$parts = explode('|', (string) $server);
if (! in_array(count($parts), [4, 5], true)) {
$this->error("Invalid server '{$server}'. Expected name|host|ssh_user|ssh_port|wireguard_management_ip.");
return self::FAILURE;
}
[$name, $host, $sshUser, $sshPort] = array_slice($parts, 0, 4);
$wireguardManagementIp = ($parts[4] ?? null) ?: null;
$parsedServers[] = [
'name' => $name,
'host' => $host,
'ssh_user' => $sshUser,
'ssh_port' => (int) $sshPort,
'wireguard_management_ip' => $wireguardManagementIp,
];
}
SyncDevLimaServers::run(
team: $team,
user: $user,
privateKey: $privateKey,
clusterName: (string) $this->option('cluster'),
servers: $parsedServers,
);
foreach ($parsedServers as $server) {
$this->info("Synced {$server['name']} ({$server['host']}:{$server['ssh_port']}).");
}
return self::SUCCESS;
}
}
+8
View File
@@ -15,7 +15,10 @@ use App\Jobs\RegenerateSslCertJob;
use App\Jobs\ScheduledJobManager;
use App\Jobs\ServerManagerJob;
use App\Jobs\UpdateCoolifyJob;
use App\Jobs\V5ReconcileServersJob;
use App\Jobs\V5RotateAgentTokensJob;
use App\Models\InstanceSettings;
use App\Support\V5\V5Feature;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
@@ -49,6 +52,11 @@ class Kernel extends ConsoleKernel
$this->scheduleInstance->command('sanctum:prune-expired --hours=1')->hourly()->onOneServer();
$this->scheduleInstance->job(new ApiTokenExpirationWarningJob)->hourly()->onOneServer();
if (V5Feature::enabled()) {
$this->scheduleInstance->job(new V5ReconcileServersJob)->everyFiveMinutes()->withoutOverlapping()->onOneServer();
$this->scheduleInstance->job(new V5RotateAgentTokensJob)->everyFifteenMinutes()->withoutOverlapping()->onOneServer();
}
if (isDev()) {
// Instance Jobs
$this->scheduleInstance->command('horizon:snapshot')->everyMinute();
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums\V5;
/**
* Lifecycle states persisted on `v5_applications.status`.
*
* Besides Coolify's own states (creating, failed, unknown), the column also
* receives raw container runtime states reported by coold, so the Docker and
* Podman container states are part of the catalog.
*/
enum ApplicationStatus: string
{
case Creating = 'creating';
case Configured = 'configured';
case Created = 'created';
case Starting = 'starting';
case Running = 'running';
case Restarting = 'restarting';
case Paused = 'paused';
case Removing = 'removing';
case Stopping = 'stopping';
case Stopped = 'stopped';
case Exited = 'exited';
case Dead = 'dead';
case Failed = 'failed';
case Unknown = 'unknown';
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Enums\V5;
/**
* Runtime states persisted on `v5_container_statuses.status`.
*
* Named ContainerState (not ContainerStatus) to avoid clashing with the
* App\Models\V5\ContainerStatus Eloquent model. Covers the Docker and Podman
* container states reported by coold.
*/
enum ContainerState: string
{
case Configured = 'configured';
case Created = 'created';
case Starting = 'starting';
case Running = 'running';
case Restarting = 'restarting';
case Paused = 'paused';
case Removing = 'removing';
case Stopping = 'stopping';
case Stopped = 'stopped';
case Exited = 'exited';
case Dead = 'dead';
case Unknown = 'unknown';
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Enums\V5;
/**
* States persisted on `v5_servers.ingress_status`.
*
* The value mirrors the ingress proxy container's runtime state as reported
* by coold, so the Docker and Podman container states are part of the catalog.
*/
enum IngressStatus: string
{
case Configured = 'configured';
case Created = 'created';
case Starting = 'starting';
case Running = 'running';
case Restarting = 'restarting';
case Paused = 'paused';
case Removing = 'removing';
case Stopping = 'stopping';
case Stopped = 'stopped';
case Exited = 'exited';
case Dead = 'dead';
case Unknown = 'unknown';
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace App\Enums\V5;
/**
* Lifecycle states persisted on `v5_servers.status`.
*/
enum ServerStatus: string
{
case Added = 'added';
case Installed = 'installed';
case Failed = 'failed';
case Unreachable = 'unreachable';
case Unknown = 'unknown';
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Events;
use App\Models\V5\Application as V5Application;
use App\Models\V5\Server as V5Server;
use App\Support\V5\CanvasResourceSerializer;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class V5CanvasResourceUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Push the queued broadcast job only after the dispatching database
* transaction commits, so workers never serialize pre-commit state.
*/
public bool $afterCommit = true;
public function __construct(
public int $teamId,
public ?int $applicationId = null,
public ?int $caddyIngressServerId = null,
public ?int $serverId = null,
) {}
public function broadcastOn(): array
{
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
public function broadcastAs(): string
{
return 'v5.canvas.resource.updated';
}
/**
* @return array{application: array<string, mixed>|null, applications: array<int, array<string, mixed>>, caddyIngress: array<string, mixed>|null}
*/
public function broadcastWith(): array
{
$serializer = app(CanvasResourceSerializer::class);
$application = $this->applicationId !== null
? V5Application::query()->with(['server', 'domains'])->find($this->applicationId)
: null;
$applications = $this->serverId !== null
? V5Application::query()
->where('server_id', $this->serverId)
->with(['server', 'domains'])
->get()
: collect();
$caddyIngress = $this->caddyIngressServerId !== null
? V5Server::query()->find($this->caddyIngressServerId)
: null;
return [
'application' => $application instanceof V5Application ? $serializer->serializeApplication($application) : null,
'applications' => $applications
->map(fn (V5Application $application) => $serializer->serializeApplication($application))
->values()
->all(),
'caddyIngress' => $caddyIngress instanceof V5Server && $caddyIngress->isIngress()
? $serializer->serializeCaddyIngress($caddyIngress)
: null,
];
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Events;
use App\Models\V5\Cluster as V5Cluster;
use App\Support\V5\ClusterSerializer;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class V5ClusterUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Push the queued broadcast job only after the dispatching database
* transaction commits, so workers never serialize pre-commit state.
*/
public bool $afterCommit = true;
public function __construct(public int $teamId, public int $clusterId) {}
public function broadcastOn(): array
{
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
public function broadcastAs(): string
{
return 'v5.cluster.updated';
}
/**
* @return array{cluster: array<string, mixed>|null}
*/
public function broadcastWith(): array
{
$cluster = V5Cluster::query()
->where('team_id', $this->teamId)
->with(['servers' => fn ($query) => $query
->with('privateKey')
->orderBy('name')])
->withCount('servers')
->find($this->clusterId);
return [
'cluster' => $cluster instanceof V5Cluster ? app(ClusterSerializer::class)->serialize($cluster) : null,
];
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Events;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class V5RealtimeTestEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public string $sentAt;
public function __construct(public int $teamId, public string $message)
{
$this->sentAt = now()->toJSON();
}
public function broadcastOn(): array
{
return [
new PrivateChannel("team.{$this->teamId}"),
];
}
public function broadcastAs(): string
{
return 'v5.realtime.test';
}
/**
* @return array{message: string, teamId: int, sentAt: string}
*/
public function broadcastWith(): array
{
return [
'message' => $this->message,
'teamId' => $this->teamId,
'sentAt' => $this->sentAt,
];
}
}
+3 -2
View File
@@ -69,8 +69,9 @@ class Handler extends ExceptionHandler
*/
public function render($request, Throwable $e)
{
// Handle authorization exceptions for API routes
if ($e instanceof AuthorizationException) {
// Handle authorization exceptions for API routes. Exceptions carrying
// an explicit status (e.g. denyAsNotFound) keep it via parent::render.
if ($e instanceof AuthorizationException && ! $e->hasStatus()) {
if ($request->is('api/*') || $request->expectsJson()) {
if ($request->is('api/*')) {
auditLog('api.auth.policy_denied', [
@@ -0,0 +1,18 @@
<?php
namespace App\Exceptions\V5;
use RuntimeException;
/**
* The per-node coold agent does not implement the dispatched verb. Flux
* rejects these before they reach the node, so callers can degrade
* gracefully instead of treating the miss as an operational failure.
*/
class UnsupportedCooldVerb extends RuntimeException
{
public function __construct(public readonly string $verb, string $message = '')
{
parent::__construct($message !== '' ? $message : "The node's coold agent does not support the {$verb} verb.");
}
}
+41
View File
@@ -127,6 +127,7 @@ class SshMultiplexingHelper
$scpCommand .= self::getCommonSshOptions($server, $sshKeyLocation, self::getConnectionTimeout($server), config('constants.ssh.server_interval'), isScp: true);
// Upload: local source -> remote dest
if ($server->isIpv6()) {
return $scpCommand.escapeshellarg($source).' '.escapeshellarg($server->user).'@['.escapeshellarg($server->ip).']:'.escapeshellarg($dest);
}
@@ -134,6 +135,46 @@ class SshMultiplexingHelper
return $scpCommand.escapeshellarg($source).' '.self::escapedUserAtHost($server).':'.escapeshellarg($dest);
}
/**
* Build an SCP command that downloads a remote file onto the Coolify host.
*/
public static function generateScpDownloadCommand(Server $server, string $remoteSource, string $localDest): string
{
$sshConfig = self::serverSshConfiguration($server);
$sshKeyLocation = $sshConfig['sshKeyLocation'];
$scpCommand = 'timeout '.config('constants.ssh.command_timeout').' scp ';
if ($server->isIpv6()) {
$scpCommand .= '-6 ';
}
if (self::isMultiplexingEnabled()) {
try {
if (self::ensureMultiplexedConnection($server)) {
$scpCommand .= self::multiplexingOptions($server);
}
} catch (\Throwable $e) {
Log::warning('SSH multiplexing failed for SCP download, falling back to non-multiplexed connection', [
'server' => $server->name ?? $server->ip,
'error' => $e->getMessage(),
]);
}
}
if (data_get($server, 'settings.is_cloudflare_tunnel')) {
$scpCommand .= '-o ProxyCommand="cloudflared access ssh --hostname %h" ';
}
$scpCommand .= self::getCommonSshOptions($server, $sshKeyLocation, self::getConnectionTimeout($server), config('constants.ssh.server_interval'), isScp: true);
// Download: remote source -> local dest
if ($server->isIpv6()) {
return $scpCommand.escapeshellarg($server->user).'@['.escapeshellarg($server->ip).']:'.escapeshellarg($remoteSource).' '.escapeshellarg($localDest);
}
return $scpCommand.self::escapedUserAtHost($server).':'.escapeshellarg($remoteSource).' '.escapeshellarg($localDest);
}
public static function generateSshCommand(Server $server, string $command, bool $disableMultiplexing = false, ?int $commandTimeout = null): string
{
if ($server->settings->force_disabled) {
@@ -17,6 +17,8 @@ use App\Models\LocalPersistentVolume;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use App\Rules\DockerImageFormat;
use App\Rules\ValidGitBranch;
use App\Rules\ValidGitRepositoryUrl;
@@ -49,6 +51,14 @@ class ApplicationsController extends Controller
'is_gzip_enabled',
'is_stripprefix_enabled',
'is_raw_compose_deployment_enabled',
'is_log_drain_enabled',
'is_gpu_enabled',
'gpu_driver',
'gpu_count',
'gpu_device_ids',
'gpu_options',
'is_consistent_container_name_enabled',
'custom_internal_name',
];
private const BOOLEAN_APPLICATION_SETTING_FIELDS = [
@@ -63,6 +73,9 @@ class ApplicationsController extends Controller
'is_gzip_enabled',
'is_stripprefix_enabled',
'is_raw_compose_deployment_enabled',
'is_log_drain_enabled',
'is_gpu_enabled',
'is_consistent_container_name_enabled',
];
protected function findTaggableResource(string $uuid, int|string $teamId): mixed
@@ -289,6 +302,7 @@ class ApplicationsController extends Controller
'name' => ['type' => 'string', 'description' => 'The application name.'],
'description' => ['type' => 'string', 'description' => 'The application description.'],
'domains' => ['type' => 'string', 'description' => 'The application URLs in a comma-separated list.'],
'noindex_domains' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'The subset of the application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the application domains are ignored.'],
'git_commit_sha' => ['type' => 'string', 'description' => 'The git commit SHA.'],
'docker_registry_image_name' => ['type' => 'string', 'description' => 'The docker registry image name.'],
'docker_registry_image_tag' => ['type' => 'string', 'description' => 'The docker registry image tag.'],
@@ -349,6 +363,7 @@ class ApplicationsController extends Controller
properties: [
'name' => ['type' => 'string', 'description' => 'The service name as defined in docker-compose.'],
'domain' => ['type' => 'string', 'description' => 'Comma-separated list of URLs (e.g. "https://app.coolify.io,https://app2.coolify.io")'],
'redirect' => ['type' => 'string', 'nullable' => true, 'description' => 'Per-service www/non-www redirect for this compose service.', 'enum' => ['www', 'non-www', 'both']],
],
),
],
@@ -368,6 +383,16 @@ class ApplicationsController extends Controller
'is_gzip_enabled' => ['type' => 'boolean', 'description' => 'Enable gzip compression.'],
'is_stripprefix_enabled' => ['type' => 'boolean', 'description' => 'Enable path prefix stripping.'],
'is_raw_compose_deployment_enabled' => ['type' => 'boolean', 'description' => 'Deploy the raw Docker Compose definition.'],
'is_log_drain_enabled' => ['type' => 'boolean', 'description' => 'Enable log drain for the application.'],
'is_gpu_enabled' => ['type' => 'boolean', 'description' => 'Enable GPU support.'],
'gpu_driver' => ['type' => 'string', 'nullable' => true, 'description' => 'GPU driver name.'],
'gpu_count' => ['type' => 'string', 'nullable' => true, 'description' => 'Number of GPUs to allocate.'],
'gpu_device_ids' => ['type' => 'string', 'nullable' => true, 'description' => 'Comma-separated GPU device IDs.'],
'gpu_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Additional GPU options.'],
'is_consistent_container_name_enabled' => ['type' => 'boolean', 'description' => 'Use a consistent container name across deployments.'],
'custom_internal_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom internal container name.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'max_restart_count' => ['type' => 'integer', 'minimum' => 0, 'description' => 'Maximum container restart count before stopping.'],
'is_http_basic_auth_enabled' => ['type' => 'boolean', 'description' => 'HTTP Basic Authentication enabled.'],
'http_basic_auth_username' => ['type' => 'string', 'nullable' => true, 'description' => 'Username for HTTP Basic Authentication'],
'http_basic_auth_password' => ['type' => 'string', 'nullable' => true, 'description' => 'Password for HTTP Basic Authentication'],
@@ -472,6 +497,7 @@ class ApplicationsController extends Controller
'name' => ['type' => 'string', 'description' => 'The application name.'],
'description' => ['type' => 'string', 'description' => 'The application description.'],
'domains' => ['type' => 'string', 'description' => 'The application URLs in a comma-separated list.'],
'noindex_domains' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'The subset of the application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the application domains are ignored.'],
'git_commit_sha' => ['type' => 'string', 'description' => 'The git commit SHA.'],
'docker_registry_image_name' => ['type' => 'string', 'description' => 'The docker registry image name.'],
'docker_registry_image_tag' => ['type' => 'string', 'description' => 'The docker registry image tag.'],
@@ -531,6 +557,7 @@ class ApplicationsController extends Controller
properties: [
'name' => ['type' => 'string', 'description' => 'The service name as defined in docker-compose.'],
'domain' => ['type' => 'string', 'description' => 'Comma-separated list of URLs (e.g. "https://app.coolify.io,https://app2.coolify.io")'],
'redirect' => ['type' => 'string', 'nullable' => true, 'description' => 'Per-service www/non-www redirect for this compose service.', 'enum' => ['www', 'non-www', 'both']],
],
),
],
@@ -550,6 +577,16 @@ class ApplicationsController extends Controller
'is_gzip_enabled' => ['type' => 'boolean', 'description' => 'Enable gzip compression.'],
'is_stripprefix_enabled' => ['type' => 'boolean', 'description' => 'Enable path prefix stripping.'],
'is_raw_compose_deployment_enabled' => ['type' => 'boolean', 'description' => 'Deploy the raw Docker Compose definition.'],
'is_log_drain_enabled' => ['type' => 'boolean', 'description' => 'Enable log drain for the application.'],
'is_gpu_enabled' => ['type' => 'boolean', 'description' => 'Enable GPU support.'],
'gpu_driver' => ['type' => 'string', 'nullable' => true, 'description' => 'GPU driver name.'],
'gpu_count' => ['type' => 'string', 'nullable' => true, 'description' => 'Number of GPUs to allocate.'],
'gpu_device_ids' => ['type' => 'string', 'nullable' => true, 'description' => 'Comma-separated GPU device IDs.'],
'gpu_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Additional GPU options.'],
'is_consistent_container_name_enabled' => ['type' => 'boolean', 'description' => 'Use a consistent container name across deployments.'],
'custom_internal_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom internal container name.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'max_restart_count' => ['type' => 'integer', 'minimum' => 0, 'description' => 'Maximum container restart count before stopping.'],
'is_http_basic_auth_enabled' => ['type' => 'boolean', 'description' => 'HTTP Basic Authentication enabled.'],
'http_basic_auth_username' => ['type' => 'string', 'nullable' => true, 'description' => 'Username for HTTP Basic Authentication'],
'http_basic_auth_password' => ['type' => 'string', 'nullable' => true, 'description' => 'Password for HTTP Basic Authentication'],
@@ -654,6 +691,7 @@ class ApplicationsController extends Controller
'name' => ['type' => 'string', 'description' => 'The application name.'],
'description' => ['type' => 'string', 'description' => 'The application description.'],
'domains' => ['type' => 'string', 'description' => 'The application URLs in a comma-separated list.'],
'noindex_domains' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'The subset of the application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the application domains are ignored.'],
'git_commit_sha' => ['type' => 'string', 'description' => 'The git commit SHA.'],
'docker_registry_image_name' => ['type' => 'string', 'description' => 'The docker registry image name.'],
'docker_registry_image_tag' => ['type' => 'string', 'description' => 'The docker registry image tag.'],
@@ -713,6 +751,7 @@ class ApplicationsController extends Controller
properties: [
'name' => ['type' => 'string', 'description' => 'The service name as defined in docker-compose.'],
'domain' => ['type' => 'string', 'description' => 'Comma-separated list of URLs (e.g. "https://app.coolify.io,https://app2.coolify.io")'],
'redirect' => ['type' => 'string', 'nullable' => true, 'description' => 'Per-service www/non-www redirect for this compose service.', 'enum' => ['www', 'non-www', 'both']],
],
),
],
@@ -732,6 +771,16 @@ class ApplicationsController extends Controller
'is_gzip_enabled' => ['type' => 'boolean', 'description' => 'Enable gzip compression.'],
'is_stripprefix_enabled' => ['type' => 'boolean', 'description' => 'Enable path prefix stripping.'],
'is_raw_compose_deployment_enabled' => ['type' => 'boolean', 'description' => 'Deploy the raw Docker Compose definition.'],
'is_log_drain_enabled' => ['type' => 'boolean', 'description' => 'Enable log drain for the application.'],
'is_gpu_enabled' => ['type' => 'boolean', 'description' => 'Enable GPU support.'],
'gpu_driver' => ['type' => 'string', 'nullable' => true, 'description' => 'GPU driver name.'],
'gpu_count' => ['type' => 'string', 'nullable' => true, 'description' => 'Number of GPUs to allocate.'],
'gpu_device_ids' => ['type' => 'string', 'nullable' => true, 'description' => 'Comma-separated GPU device IDs.'],
'gpu_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Additional GPU options.'],
'is_consistent_container_name_enabled' => ['type' => 'boolean', 'description' => 'Use a consistent container name across deployments.'],
'custom_internal_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom internal container name.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'max_restart_count' => ['type' => 'integer', 'minimum' => 0, 'description' => 'Maximum container restart count before stopping.'],
'is_http_basic_auth_enabled' => ['type' => 'boolean', 'description' => 'HTTP Basic Authentication enabled.'],
'http_basic_auth_username' => ['type' => 'string', 'nullable' => true, 'description' => 'Username for HTTP Basic Authentication'],
'http_basic_auth_password' => ['type' => 'string', 'nullable' => true, 'description' => 'Password for HTTP Basic Authentication'],
@@ -834,6 +883,7 @@ class ApplicationsController extends Controller
'name' => ['type' => 'string', 'description' => 'The application name.'],
'description' => ['type' => 'string', 'description' => 'The application description.'],
'domains' => ['type' => 'string', 'description' => 'The application URLs in a comma-separated list.'],
'noindex_domains' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'The subset of the application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the application domains are ignored.'],
'docker_registry_image_name' => ['type' => 'string', 'description' => 'The docker registry image name.'],
'docker_registry_image_tag' => ['type' => 'string', 'description' => 'The docker registry image tag.'],
'ports_mappings' => ['type' => 'string', 'description' => 'The ports mappings.'],
@@ -886,6 +936,16 @@ class ApplicationsController extends Controller
'is_gzip_enabled' => ['type' => 'boolean', 'description' => 'Enable gzip compression.'],
'is_stripprefix_enabled' => ['type' => 'boolean', 'description' => 'Enable path prefix stripping.'],
'is_raw_compose_deployment_enabled' => ['type' => 'boolean', 'description' => 'Deploy the raw Docker Compose definition.'],
'is_log_drain_enabled' => ['type' => 'boolean', 'description' => 'Enable log drain for the application.'],
'is_gpu_enabled' => ['type' => 'boolean', 'description' => 'Enable GPU support.'],
'gpu_driver' => ['type' => 'string', 'nullable' => true, 'description' => 'GPU driver name.'],
'gpu_count' => ['type' => 'string', 'nullable' => true, 'description' => 'Number of GPUs to allocate.'],
'gpu_device_ids' => ['type' => 'string', 'nullable' => true, 'description' => 'Comma-separated GPU device IDs.'],
'gpu_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Additional GPU options.'],
'is_consistent_container_name_enabled' => ['type' => 'boolean', 'description' => 'Use a consistent container name across deployments.'],
'custom_internal_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom internal container name.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'max_restart_count' => ['type' => 'integer', 'minimum' => 0, 'description' => 'Maximum container restart count before stopping.'],
'is_http_basic_auth_enabled' => ['type' => 'boolean', 'description' => 'HTTP Basic Authentication enabled.'],
'http_basic_auth_username' => ['type' => 'string', 'nullable' => true, 'description' => 'Username for HTTP Basic Authentication'],
'http_basic_auth_password' => ['type' => 'string', 'nullable' => true, 'description' => 'Password for HTTP Basic Authentication'],
@@ -987,6 +1047,7 @@ class ApplicationsController extends Controller
'name' => ['type' => 'string', 'description' => 'The application name.'],
'description' => ['type' => 'string', 'description' => 'The application description.'],
'domains' => ['type' => 'string', 'description' => 'The application URLs in a comma-separated list.'],
'noindex_domains' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'The subset of the application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the application domains are ignored.'],
'ports_mappings' => ['type' => 'string', 'description' => 'The ports mappings.'],
'health_check_enabled' => ['type' => 'boolean', 'description' => 'Health check enabled.'],
'health_check_path' => ['type' => 'string', 'description' => 'Health check path.'],
@@ -1036,6 +1097,16 @@ class ApplicationsController extends Controller
'is_gzip_enabled' => ['type' => 'boolean', 'description' => 'Enable gzip compression.'],
'is_stripprefix_enabled' => ['type' => 'boolean', 'description' => 'Enable path prefix stripping.'],
'is_raw_compose_deployment_enabled' => ['type' => 'boolean', 'description' => 'Deploy the raw Docker Compose definition.'],
'is_log_drain_enabled' => ['type' => 'boolean', 'description' => 'Enable log drain for the application.'],
'is_gpu_enabled' => ['type' => 'boolean', 'description' => 'Enable GPU support.'],
'gpu_driver' => ['type' => 'string', 'nullable' => true, 'description' => 'GPU driver name.'],
'gpu_count' => ['type' => 'string', 'nullable' => true, 'description' => 'Number of GPUs to allocate.'],
'gpu_device_ids' => ['type' => 'string', 'nullable' => true, 'description' => 'Comma-separated GPU device IDs.'],
'gpu_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Additional GPU options.'],
'is_consistent_container_name_enabled' => ['type' => 'boolean', 'description' => 'Use a consistent container name across deployments.'],
'custom_internal_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom internal container name.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'max_restart_count' => ['type' => 'integer', 'minimum' => 0, 'description' => 'Maximum container restart count before stopping.'],
'is_http_basic_auth_enabled' => ['type' => 'boolean', 'description' => 'HTTP Basic Authentication enabled.'],
'http_basic_auth_username' => ['type' => 'string', 'nullable' => true, 'description' => 'Username for HTTP Basic Authentication'],
'http_basic_auth_password' => ['type' => 'string', 'nullable' => true, 'description' => 'Password for HTTP Basic Authentication'],
@@ -1120,7 +1191,7 @@ class ApplicationsController extends Controller
if ($return instanceof JsonResponse) {
return $return;
}
$allowedFields = ['project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'is_preview_deployments_enabled', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'private_key_uuid', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'custom_network_aliases', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_type', 'health_check_command', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'redirect', 'github_app_uuid', 'instant_deploy', 'dockerfile', 'dockerfile_location', 'docker_compose_location', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'watch_paths', 'use_build_server', 'use_build_secrets', 'static_image', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'autogenerate_domain', 'is_container_label_escape_enabled', 'tags', 'is_preserve_repository_enabled', ...self::APPLICATION_SETTING_FIELDS];
$allowedFields = ['project_uuid', 'environment_name', 'environment_uuid', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'is_preview_deployments_enabled', 'domains', 'noindex_domains', 'git_repository', 'git_branch', 'git_commit_sha', 'private_key_uuid', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'custom_network_aliases', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_type', 'health_check_command', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'redirect', 'github_app_uuid', 'instant_deploy', 'dockerfile', 'dockerfile_location', 'docker_compose_location', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'watch_paths', 'use_build_server', 'use_build_secrets', 'static_image', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'autogenerate_domain', 'is_container_label_escape_enabled', 'tags', 'is_preserve_repository_enabled', 'preview_url_template', 'max_restart_count', ...self::APPLICATION_SETTING_FIELDS];
$validator = customApiValidator($request->all(), [
'name' => 'string|max:255',
@@ -1269,9 +1340,10 @@ class ApplicationsController extends Controller
'build_pack' => ['required', Rule::enum(BuildPackTypes::class)],
'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_domains.*' => 'array:name,domain',
'docker_compose_domains.*' => 'array:name,domain,redirect',
'docker_compose_domains.*.name' => 'string|required',
'docker_compose_domains.*.domain' => ValidationPatterns::applicationDomainRules(),
'docker_compose_domains.*.redirect' => 'nullable|string|in:www,non-www,both',
];
// ports_exposes is not required for dockercompose
if ($request->build_pack === 'dockercompose') {
@@ -1280,7 +1352,7 @@ class ApplicationsController extends Controller
}
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validationMessages = [
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only a name and domain field are supported.',
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only name, domain, and redirect fields are supported.',
];
$validator = Validator::make($request->all(), $validationRules, $validationMessages);
if ($validator->fails()) {
@@ -1372,7 +1444,12 @@ class ApplicationsController extends Controller
}
$dockerComposeDomains->each(function ($domain) use ($dockerComposeDomainsJson) {
$dockerComposeDomainsJson->put(data_get($domain, 'name'), ['domain' => data_get($domain, 'domain')]);
$entry = ['domain' => data_get($domain, 'domain')];
$redirect = data_get($domain, 'redirect');
if (in_array($redirect, ['www', 'non-www', 'both'], true)) {
$entry['redirect'] = $redirect;
}
$dockerComposeDomainsJson->put(data_get($domain, 'name'), $entry);
});
$request->offsetUnset('docker_compose_domains');
}
@@ -1489,13 +1566,14 @@ class ApplicationsController extends Controller
'github_app_uuid' => 'string|required',
'watch_paths' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_domains.*' => 'array:name,domain',
'docker_compose_domains.*' => 'array:name,domain,redirect',
'docker_compose_domains.*.name' => 'string|required',
'docker_compose_domains.*.domain' => ValidationPatterns::applicationDomainRules(),
'docker_compose_domains.*.redirect' => 'nullable|string|in:www,non-www,both',
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validationMessages = [
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only a name and domain field are supported.',
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only name, domain, and redirect fields are supported.',
];
$validator = Validator::make($request->all(), $validationRules, $validationMessages);
if ($validator->fails()) {
@@ -1625,7 +1703,12 @@ class ApplicationsController extends Controller
}
$dockerComposeDomains->each(function ($domain) use ($dockerComposeDomainsJson) {
$dockerComposeDomainsJson->put(data_get($domain, 'name'), ['domain' => data_get($domain, 'domain')]);
$entry = ['domain' => data_get($domain, 'domain')];
$redirect = data_get($domain, 'redirect');
if (in_array($redirect, ['www', 'non-www', 'both'], true)) {
$entry['redirect'] = $redirect;
}
$dockerComposeDomainsJson->put(data_get($domain, 'name'), $entry);
});
$request->offsetUnset('docker_compose_domains');
}
@@ -1741,14 +1824,15 @@ class ApplicationsController extends Controller
'private_key_uuid' => 'string|required',
'watch_paths' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_domains.*' => 'array:name,domain',
'docker_compose_domains.*' => 'array:name,domain,redirect',
'docker_compose_domains.*.name' => 'string|required',
'docker_compose_domains.*.domain' => ValidationPatterns::applicationDomainRules(),
'docker_compose_domains.*.redirect' => 'nullable|string|in:www,non-www,both',
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validationMessages = [
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only a name and domain field are supported.',
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only name, domain, and redirect fields are supported.',
];
$validator = Validator::make($request->all(), $validationRules, $validationMessages);
@@ -1850,7 +1934,12 @@ class ApplicationsController extends Controller
}
$dockerComposeDomains->each(function ($domain) use ($dockerComposeDomainsJson) {
$dockerComposeDomainsJson->put(data_get($domain, 'name'), ['domain' => data_get($domain, 'domain')]);
$entry = ['domain' => data_get($domain, 'domain')];
$redirect = data_get($domain, 'redirect');
if (in_array($redirect, ['www', 'non-www', 'both'], true)) {
$entry['redirect'] = $redirect;
}
$dockerComposeDomainsJson->put(data_get($domain, 'name'), $entry);
});
$request->offsetUnset('docker_compose_domains');
}
@@ -2526,6 +2615,7 @@ class ApplicationsController extends Controller
'name' => ['type' => 'string', 'description' => 'The application name.'],
'description' => ['type' => 'string', 'description' => 'The application description.'],
'domains' => ['type' => 'string', 'description' => 'The application URLs in a comma-separated list.'],
'noindex_domains' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'The subset of the application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the application domains are ignored.'],
'git_commit_sha' => ['type' => 'string', 'description' => 'The git commit SHA.'],
'docker_registry_image_name' => ['type' => 'string', 'description' => 'The docker registry image name.'],
'docker_registry_image_tag' => ['type' => 'string', 'description' => 'The docker registry image tag.'],
@@ -2584,6 +2674,7 @@ class ApplicationsController extends Controller
properties: [
'name' => ['type' => 'string', 'description' => 'The service name as defined in docker-compose.'],
'domain' => ['type' => 'string', 'description' => 'Comma-separated list of URLs (e.g. "https://app.coolify.io,https://app2.coolify.io")'],
'redirect' => ['type' => 'string', 'nullable' => true, 'description' => 'Per-service www/non-www redirect for this compose service.', 'enum' => ['www', 'non-www', 'both']],
],
),
],
@@ -2603,6 +2694,16 @@ class ApplicationsController extends Controller
'is_gzip_enabled' => ['type' => 'boolean', 'description' => 'Enable gzip compression.'],
'is_stripprefix_enabled' => ['type' => 'boolean', 'description' => 'Enable path prefix stripping.'],
'is_raw_compose_deployment_enabled' => ['type' => 'boolean', 'description' => 'Deploy the raw Docker Compose definition.'],
'is_log_drain_enabled' => ['type' => 'boolean', 'description' => 'Enable log drain for the application.'],
'is_gpu_enabled' => ['type' => 'boolean', 'description' => 'Enable GPU support.'],
'gpu_driver' => ['type' => 'string', 'nullable' => true, 'description' => 'GPU driver name.'],
'gpu_count' => ['type' => 'string', 'nullable' => true, 'description' => 'Number of GPUs to allocate.'],
'gpu_device_ids' => ['type' => 'string', 'nullable' => true, 'description' => 'Comma-separated GPU device IDs.'],
'gpu_options' => ['type' => 'string', 'nullable' => true, 'description' => 'Additional GPU options.'],
'is_consistent_container_name_enabled' => ['type' => 'boolean', 'description' => 'Use a consistent container name across deployments.'],
'custom_internal_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Custom internal container name.'],
'preview_url_template' => ['type' => 'string', 'description' => 'Preview URL template.'],
'max_restart_count' => ['type' => 'integer', 'minimum' => 0, 'description' => 'Maximum container restart count before stopping.'],
'connect_to_docker_network' => ['type' => 'boolean', 'description' => 'The flag to connect the service to the predefined Docker network.'],
'force_domain_override' => ['type' => 'boolean', 'description' => 'Force domain usage even if conflicts are detected. Default is false.'],
'is_container_label_escape_enabled' => ['type' => 'boolean', 'default' => true, 'description' => 'Escape special characters in labels. By default, $ (and other chars) is escaped. So if you write $ in the labels, it will be saved as $$. If you want to use env variables inside the labels, turn this off.'],
@@ -2692,7 +2793,7 @@ class ApplicationsController extends Controller
$this->authorize('update', $application);
$server = $application->destination->server;
$allowedFields = ['name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'is_preview_deployments_enabled', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'static_image', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'custom_network_aliases', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_type', 'health_check_command', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'watch_paths', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'dockerfile_location', 'dockerfile_target_build', 'docker_compose_location', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'redirect', 'instant_deploy', 'use_build_server', 'use_build_secrets', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'is_container_label_escape_enabled', 'is_preserve_repository_enabled', ...self::APPLICATION_SETTING_FIELDS];
$allowedFields = ['name', 'description', 'is_static', 'is_spa', 'is_auto_deploy_enabled', 'is_force_https_enabled', 'is_preview_deployments_enabled', 'domains', 'noindex_domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'static_image', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'custom_network_aliases', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_type', 'health_check_command', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'watch_paths', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'dockerfile_location', 'dockerfile_target_build', 'docker_compose_location', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'redirect', 'instant_deploy', 'use_build_server', 'use_build_secrets', 'custom_nginx_configuration', 'is_http_basic_auth_enabled', 'http_basic_auth_username', 'http_basic_auth_password', 'connect_to_docker_network', 'force_domain_override', 'is_container_label_escape_enabled', 'is_preserve_repository_enabled', 'preview_url_template', 'max_restart_count', ...self::APPLICATION_SETTING_FIELDS];
$validationRules = [
'name' => 'string|max:255',
@@ -2700,9 +2801,10 @@ class ApplicationsController extends Controller
'static_image' => 'string',
'watch_paths' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_domains.*' => 'array:name,domain',
'docker_compose_domains.*' => 'array:name,domain,redirect',
'docker_compose_domains.*.name' => 'string|required',
'docker_compose_domains.*.domain' => ValidationPatterns::applicationDomainRules(),
'docker_compose_domains.*.redirect' => 'nullable|string|in:www,non-www,both',
'custom_nginx_configuration' => 'string|nullable',
'is_http_basic_auth_enabled' => 'boolean|nullable',
'is_preview_deployments_enabled' => 'boolean|nullable',
@@ -2712,7 +2814,7 @@ class ApplicationsController extends Controller
];
$validationRules = array_merge(sharedDataApplications(), $validationRules);
$validationMessages = [
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only a name and domain field are supported.',
'docker_compose_domains.*.array' => 'An item in the docker_compose_domains array has invalid fields. Only name, domain, and redirect fields are supported.',
];
$validator = Validator::make($request->all(), $validationRules, $validationMessages);
@@ -2920,10 +3022,18 @@ class ApplicationsController extends Controller
$yaml = Yaml::parse($application->docker_compose_raw);
$services = data_get($yaml, 'services', []);
$dockerComposeDomains->each(function ($domain) use ($services, $dockerComposeDomainsJson) {
$existingDockerComposeDomains = json_decode($application->docker_compose_domains ?? '[]', true) ?? [];
$dockerComposeDomains->each(function ($domain) use ($services, $dockerComposeDomainsJson, $existingDockerComposeDomains) {
$name = data_get($domain, 'name');
if ($name && is_array($services) && isset($services[$name])) {
$dockerComposeDomainsJson->put($name, ['domain' => data_get($domain, 'domain')]);
$entry = ['domain' => data_get($domain, 'domain')];
$redirect = array_key_exists('redirect', $domain)
? data_get($domain, 'redirect')
: data_get($existingDockerComposeDomains[$name] ?? [], 'redirect');
if (in_array($redirect, ['www', 'non-www', 'both'], true)) {
$entry['redirect'] = $redirect;
}
$dockerComposeDomainsJson->put($name, $entry);
}
});
$request->offsetUnset('docker_compose_domains');
@@ -3002,8 +3112,14 @@ class ApplicationsController extends Controller
if ($dockerComposeDomainsJson->count() > 0) {
data_set($data, 'docker_compose_domains', json_encode($dockerComposeDomainsJson));
}
$requestHasNoindexDomains = $request->has('noindex_domains');
data_forget($data, 'noindex_domains');
$application->fill($data);
if ($application->settings->is_container_label_readonly_enabled && $requestHasDomains && $server->isProxyShouldRun()) {
if ($requestHasNoindexDomains) {
// Must run after fqdn is filled: flags are kept only for domains the app still has.
$application->setNoindexDomains($request->input('noindex_domains') ?? []);
}
if ($application->settings->is_container_label_readonly_enabled && ($requestHasDomains || $requestHasNoindexDomains) && $server->isProxyShouldRun()) {
$application->custom_labels = str(implode('|coolify|', generateLabelsApplication($application)))->replace('|coolify|', "\n");
}
$application->save();
@@ -4257,6 +4373,54 @@ class ApplicationsController extends Controller
return moveResourceToEnvironment($request, $application, 'Application', $teamId);
}
#[OA\Post(
summary: 'Migrate to Server',
description: 'Migrate an application to another destination/server owned by the authenticated team. Stops the application, optionally transfers persistent volume data when both servers are managed by Coolify, and updates database records. Redeploy after migration completes.',
path: '/applications/{uuid}/migrate',
operationId: 'migrate-application-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string', description: 'UUID of the target destination.'),
new OA\Property(property: 'migrate_volumes', type: 'boolean', default: true, description: 'Whether to transfer persistent volume data when migrating across servers.'),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Application migration started or completed.'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function migrate_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->uuid)->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('update', $application);
return migrateResourceToDestination($request, $application, 'Application', $teamId);
}
private function validateDataApplications(Request $request, Server $server)
{
$teamId = getTeamIdFromToken();
@@ -5149,4 +5313,548 @@ class ApplicationsController extends Controller
{
return $this->deleteTag($request);
}
#[OA\Post(
summary: 'Clone',
description: 'Clone an application to a destination owned by the authenticated team.',
path: '/applications/{uuid}/clone',
operationId: 'clone-application-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string', description: 'UUID of the destination to clone into.'),
new OA\Property(property: 'name', type: 'string', nullable: true, description: 'Optional name for the cloned application.'),
new OA\Property(property: 'clone_volumes', type: 'boolean', default: false, description: 'Whether to clone volume data.'),
]
)
),
responses: [
new OA\Response(
response: 201,
description: 'Application cloned.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'uuid', type: 'string'),
new OA\Property(property: 'message', type: 'string', example: 'Application cloned.'),
]
)
),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function clone_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'destination_uuid' => 'required|string',
'name' => 'string|max:255|nullable',
'clone_volumes' => 'boolean',
]);
$allowedFields = ['destination_uuid', 'name', 'clone_volumes'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('update', $application);
$destination = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first()
?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first();
if (! $destination || ! $destination->server?->canHostResources()) {
return response()->json(['message' => 'Destination not found.'], 404);
}
$overrides = ['uuid' => new_public_id()];
if ($request->filled('name')) {
$overrides['name'] = $request->string('name')->toString();
}
$newApplication = clone_application(
$application,
$destination,
$overrides,
$request->boolean('clone_volumes', false),
);
auditLog('api.application.cloned', [
'team_id' => $teamId,
'source_uuid' => $application->uuid,
'application_uuid' => $newApplication->uuid,
'application_name' => $newApplication->name,
'destination_uuid' => $destination->uuid,
'clone_volumes' => $request->boolean('clone_volumes', false),
]);
return response()->json([
'uuid' => $newApplication->uuid,
'message' => 'Application cloned.',
], 201);
}
#[OA\Get(
summary: 'List Rollback Images',
description: 'List available Docker images for rolling back an application. Returns an empty list when the server is unavailable or remote inspection is not possible.',
path: '/applications/{uuid}/rollback-images',
operationId: 'list-application-rollback-images',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Rollback images.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'current', type: 'string', nullable: true),
new OA\Property(
property: 'images',
type: 'array',
items: new OA\Items(
type: 'object',
properties: [
new OA\Property(property: 'tag', type: 'string'),
new OA\Property(property: 'created_at', type: 'string'),
new OA\Property(property: 'is_current', type: 'boolean'),
]
)
),
]
)
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function rollback_images(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('view', $application);
$current = null;
$images = [];
try {
$server = $application->destination?->server;
if ($server && $server->isFunctional()) {
$image = $application->docker_registry_image_name ?? $application->uuid;
$output = instant_remote_process([
"docker inspect --format='{{.Config.Image}}' {$application->uuid}",
], $server, throwError: false);
$current = self::currentRollbackImageTag(str($output)->trim()->toString());
$output = instant_remote_process([
"docker images --format '{{.Repository}}#{{.Tag}}#{{.CreatedAt}}'",
], $server);
$images = str($output)->trim()->explode("\n")->filter(function ($item) use ($image) {
$repository = str($item)->before('#')->toString();
// Exact repository match only — avoid substring collisions across images.
return $repository === $image;
})->map(function ($item) use ($current) {
$parts = str($item)->explode('#');
return [
'tag' => $parts[1] ?? null,
'created_at' => $parts[2] ?? null,
'is_current' => ($parts[1] ?? null) === $current,
];
})->values()->all();
}
} catch (\Throwable) {
$current = null;
$images = [];
}
return response()->json([
'current' => $current,
'images' => $images,
]);
}
private static function currentRollbackImageTag(string $imageReference): ?string
{
if (str_contains($imageReference, '@')) {
return null;
}
$lastColon = strrpos($imageReference, ':');
$lastSlash = strrpos($imageReference, '/');
if ($lastColon === false || ($lastSlash !== false && $lastColon < $lastSlash)) {
return null;
}
return substr($imageReference, $lastColon + 1) ?: null;
}
#[OA\Post(
summary: 'Rollback',
description: 'Queue a rollback deployment for an application to a previous image commit/tag.',
path: '/applications/{uuid}/rollback',
operationId: 'rollback-application-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['commit'],
properties: [
new OA\Property(property: 'commit', type: 'string', description: 'Image tag / commit to roll back to.'),
]
)
),
responses: [
new OA\Response(
response: 200,
description: 'Rollback deployment queued.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'message', type: 'string'),
new OA\Property(property: 'deployment_uuid', type: 'string'),
]
)
),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function rollback_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'commit' => 'required|string',
]);
$allowedFields = ['commit'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('deploy', $application);
try {
$commit = validateGitRef($request->string('commit')->toString(), 'rollback commit');
} catch (\Throwable $e) {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['commit' => [$e->getMessage()]],
], 422);
}
$deployment_uuid = new_public_id();
$result = queue_application_deployment(
application: $application,
deployment_uuid: $deployment_uuid,
commit: $commit,
rollback: true,
force_rebuild: false,
is_api: true,
);
if ($result['status'] === 'queue_full') {
return response()->json(['message' => $result['message'] ?? 'Deployment queue full.'], 400);
}
if ($result['status'] === 'skipped') {
return response()->json(['message' => $result['message']], 200);
}
auditLog('api.application.rollback', [
'team_id' => $teamId,
'application_uuid' => $application->uuid,
'application_name' => $application->name,
'deployment_uuid' => $deployment_uuid,
'commit' => $commit,
]);
return response()->json([
'message' => 'Rollback deployment queued.',
'deployment_uuid' => $deployment_uuid,
]);
}
#[OA\Get(
summary: 'List Destinations',
description: 'List primary and additional destinations for a standalone application.',
path: '/applications/{uuid}/destinations',
operationId: 'list-application-destinations',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Application destinations.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function destinations(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('view', $application);
$destinations = collect();
$primary = $application->destination;
if ($primary) {
$destinations->push([
'uuid' => $primary->uuid,
'name' => $primary->name,
'network' => $primary->network ?? null,
'server_uuid' => $primary->server?->uuid,
'server_id' => $primary->server_id,
'is_primary' => true,
]);
}
foreach ($application->additional_networks as $network) {
$destinations->push([
'uuid' => $network->uuid,
'name' => $network->name,
'network' => $network->network ?? null,
'server_uuid' => $network->server?->uuid,
'server_id' => $network->pivot->server_id ?? $network->server_id,
'is_primary' => false,
]);
}
return response()->json($destinations->values());
}
#[OA\Post(
summary: 'Add Destination',
description: 'Attach an additional standalone Docker destination to an application.',
path: '/applications/{uuid}/destinations',
operationId: 'add-application-destination',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string'),
]
)
),
responses: [
new OA\Response(response: 201, description: 'Destination attached.'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function add_destination(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'destination_uuid' => 'required|string',
]);
$extraFields = array_diff(array_keys($request->all()), ['destination_uuid']);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('update', $application);
$destination = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first();
if (! $destination || ! $destination->server?->canHostResources()) {
return response()->json(['message' => 'Destination not found.'], 404);
}
if ($application->destination_id === $destination->id && $application->destination_type === $destination->getMorphClass()) {
return response()->json(['message' => 'Destination is already the primary destination.'], 422);
}
if ($application->additional_networks()->where('standalone_dockers.id', $destination->id)->exists()) {
return response()->json(['message' => 'Destination is already attached.'], 422);
}
if ($application->destination?->server_id === $destination->server_id) {
return response()->json(['message' => 'Cannot attach a destination on the same server as the primary destination.'], 422);
}
if ($application->additional_servers?->pluck('id')->contains($destination->server_id)) {
return response()->json(['message' => 'A destination on this server is already attached.'], 422);
}
$application->additional_networks()->attach($destination->id, ['server_id' => $destination->server_id]);
auditLog('api.application.destination_added', [
'team_id' => $teamId,
'application_uuid' => $application->uuid,
'destination_uuid' => $destination->uuid,
]);
return response()->json([
'message' => 'Destination attached.',
'uuid' => $destination->uuid,
], 201);
}
#[OA\Delete(
summary: 'Remove Destination',
description: 'Detach an additional destination from an application.',
path: '/applications/{uuid}/destinations/{destination_uuid}',
operationId: 'remove-application-destination',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'destination_uuid', in: 'path', required: true, description: 'UUID of the destination.', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Destination detached.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function remove_destination(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$application = Application::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->route('uuid'))->first();
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
$this->authorize('update', $application);
$destinationUuid = $request->route('destination_uuid');
$destination = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $destinationUuid)->first();
if (! $destination) {
return response()->json(['message' => 'Destination not found.'], 404);
}
if ($application->destination_id === $destination->id && $application->destination_type === $destination->getMorphClass()) {
return response()->json(['message' => 'Cannot remove the primary destination.'], 422);
}
$attached = $application->additional_networks()->where('standalone_dockers.id', $destination->id)->first();
if (! $attached) {
return response()->json(['message' => 'Destination not found.'], 404);
}
$application->additional_networks()
->wherePivot('server_id', $attached->pivot->server_id)
->detach($destination->id);
auditLog('api.application.destination_removed', [
'team_id' => $teamId,
'application_uuid' => $application->uuid,
'destination_uuid' => $destination->uuid,
]);
return response()->json(['message' => 'Destination detached.']);
}
}
@@ -0,0 +1,281 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\CloudInitScript;
use App\Rules\ValidCloudInitYaml;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class CloudInitScriptsController extends Controller
{
private function removeSensitiveData(CloudInitScript $script): array
{
$script->makeHidden(['id', 'team_id']);
if (request()->attributes->get('can_read_sensitive', false) === true) {
$script->makeVisible(['script']);
}
return serializeApiResponse($script)->all();
}
#[OA\Get(
summary: 'List Cloud-init Scripts',
description: 'List all cloud-init scripts for the authenticated team.',
path: '/cloud-init-scripts',
operationId: 'list-cloud-init-scripts',
security: [['bearerAuth' => []]],
tags: ['Cloud-init Scripts'],
responses: [
new OA\Response(response: 200, description: 'Cloud-init scripts for the team.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 403, description: 'Forbidden.'),
]
)]
public function index(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$this->authorize('viewAny', CloudInitScript::class);
$scripts = CloudInitScript::where('team_id', $teamId)
->orderByDesc('created_at')
->get()
->map(fn (CloudInitScript $script) => $this->removeSensitiveData($script));
return response()->json($scripts);
}
#[OA\Post(
summary: 'Create Cloud-init Script',
description: 'Create a new cloud-init script for the authenticated team.',
path: '/cloud-init-scripts',
operationId: 'create-cloud-init-script',
security: [['bearerAuth' => []]],
tags: ['Cloud-init Scripts'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['name', 'script'],
properties: [
new OA\Property(property: 'name', type: 'string'),
new OA\Property(property: 'script', type: 'string', description: 'Bash script (#!) or cloud-config YAML.'),
]
)
),
responses: [
new OA\Response(response: 201, description: 'Cloud-init script created.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function store(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$this->authorize('create', CloudInitScript::class);
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'name' => 'required|string|max:255',
'script' => ['required', 'string', new ValidCloudInitYaml],
]);
$extraFields = array_diff(array_keys($request->all()), ['name', 'script']);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$script = CloudInitScript::create([
'team_id' => $teamId,
'name' => $request->string('name')->toString(),
'script' => $request->string('script')->toString(),
]);
auditLog('api.cloud_init_script.created', [
'team_id' => $teamId,
'cloud_init_script_uuid' => $script->uuid,
'cloud_init_script_name' => $script->name,
]);
return response()->json($this->removeSensitiveData($script), 201);
}
#[OA\Get(
summary: 'Get Cloud-init Script',
description: 'Get a cloud-init script by UUID.',
path: '/cloud-init-scripts/{uuid}',
operationId: 'get-cloud-init-script-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Cloud-init Scripts'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Cloud-init script.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function show(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$script = CloudInitScript::where('team_id', $teamId)->where('uuid', $request->route('uuid'))->first();
if (! $script) {
return response()->json(['message' => 'Cloud-init script not found.'], 404);
}
$this->authorize('view', $script);
return response()->json($this->removeSensitiveData($script));
}
#[OA\Patch(
summary: 'Update Cloud-init Script',
description: 'Update a cloud-init script by UUID.',
path: '/cloud-init-scripts/{uuid}',
operationId: 'update-cloud-init-script-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Cloud-init Scripts'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'name', type: 'string'),
new OA\Property(property: 'script', type: 'string'),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Cloud-init script updated.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
if ($request->all() === []) {
return response()->json(['message' => 'At least one field must be provided.'], 422);
}
$script = CloudInitScript::where('team_id', $teamId)->where('uuid', $request->route('uuid'))->first();
if (! $script) {
return response()->json(['message' => 'Cloud-init script not found.'], 404);
}
$this->authorize('update', $script);
$validator = customApiValidator($request->all(), [
'name' => 'string|max:255',
'script' => ['string', new ValidCloudInitYaml],
]);
$extraFields = array_diff(array_keys($request->all()), ['name', 'script']);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$script->update($request->only(['name', 'script']));
auditLog('api.cloud_init_script.updated', [
'team_id' => $teamId,
'cloud_init_script_uuid' => $script->uuid,
'cloud_init_script_name' => $script->name,
'changed_fields' => array_values(array_intersect(['name', 'script'], array_keys($request->all()))),
]);
return response()->json($this->removeSensitiveData($script->fresh()));
}
#[OA\Delete(
summary: 'Delete Cloud-init Script',
description: 'Delete a cloud-init script by UUID.',
path: '/cloud-init-scripts/{uuid}',
operationId: 'delete-cloud-init-script-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Cloud-init Scripts'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Cloud-init script deleted.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function destroy(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$script = CloudInitScript::where('team_id', $teamId)->where('uuid', $request->route('uuid'))->first();
if (! $script) {
return response()->json(['message' => 'Cloud-init script not found.'], 404);
}
$this->authorize('delete', $script);
$uuid = $script->uuid;
$name = $script->name;
$script->delete();
auditLog('api.cloud_init_script.deleted', [
'team_id' => $teamId,
'cloud_init_script_uuid' => $uuid,
'cloud_init_script_name' => $name,
]);
return response()->json(['message' => 'Cloud-init script deleted.']);
}
}
@@ -11,6 +11,7 @@ use App\Enums\NewDatabaseTypes;
use App\Http\Controllers\Controller;
use App\Jobs\DatabaseBackupJob;
use App\Jobs\DeleteResourceJob;
use App\Jobs\VolumeCloneJob;
use App\Models\EnvironmentVariable;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
@@ -18,11 +19,14 @@ use App\Models\Project;
use App\Models\S3Storage;
use App\Models\ScheduledDatabaseBackup;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\StandalonePostgresql;
use App\Models\SwarmDocker;
use App\Support\ValidationPatterns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\DB;
use OpenApi\Attributes as OA;
@@ -3050,6 +3054,54 @@ class DatabasesController extends Controller
return moveResourceToEnvironment($request, $database, 'Database', $teamId);
}
#[OA\Post(
summary: 'Migrate to Server',
description: 'Migrate a database to another destination/server owned by the authenticated team. Stops the database, optionally transfers persistent volume data when both servers are managed by Coolify, and updates database records. Redeploy after migration completes.',
path: '/databases/{uuid}/migrate',
operationId: 'migrate-database-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Databases'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the database.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string', description: 'UUID of the target destination.'),
new OA\Property(property: 'migrate_volumes', type: 'boolean', default: true, description: 'Whether to transfer persistent volume data when migrating across servers.'),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Database migration started or completed.'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function migrate_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
$database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId);
if (! $database) {
return response()->json(['message' => 'Database not found.'], 404);
}
$this->authorize('update', $database);
return migrateResourceToDestination($request, $database, 'Database', $teamId);
}
#[OA\Post(
summary: 'Start',
description: 'Start database.',
@@ -4648,4 +4700,220 @@ class DatabasesController extends Controller
{
return $this->deleteTag($request);
}
#[OA\Post(
summary: 'Clone',
description: 'Clone a database to a destination owned by the authenticated team.',
path: '/databases/{uuid}/clone',
operationId: 'clone-database-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Databases'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the database.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string'),
new OA\Property(property: 'name', type: 'string', nullable: true),
new OA\Property(property: 'clone_volumes', type: 'boolean', default: false),
]
)
),
responses: [
new OA\Response(response: 201, description: 'Database cloned.'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function clone_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'destination_uuid' => 'required|string',
'name' => 'string|max:255|nullable',
'clone_volumes' => 'boolean',
]);
$allowedFields = ['destination_uuid', 'name', 'clone_volumes'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$database = queryDatabaseByUuidWithinTeam($request->route('uuid'), $teamId);
if (! $database) {
return response()->json(['message' => 'Database not found.'], 404);
}
$this->authorize('update', $database);
$destination = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first()
?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first();
if (! $destination || ! $destination->server?->canHostResources()) {
return response()->json(['message' => 'Destination not found.'], 404);
}
$uuid = new_public_id();
$name = $request->filled('name')
? $request->string('name')->toString()
: $database->name.'-clone-'.$uuid;
$cloneVolumeData = $request->boolean('clone_volumes', false);
$newDatabase = $database->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => $uuid,
'name' => $name,
'status' => 'exited',
'started_at' => null,
'destination_id' => $destination->id,
'destination_type' => $destination->getMorphClass(),
]);
$newDatabase->save();
foreach ($database->tags as $tag) {
$newDatabase->tags()->attach($tag->id);
}
$newDatabase->persistentStorages()->delete();
$pendingVolumeClones = [];
$sourceServer = $database->destination?->server;
$targetServer = $newDatabase->destination?->server;
foreach ($database->persistentStorages()->get() as $volume) {
$originalName = $volume->name;
$newName = match (true) {
str_starts_with($originalName, 'postgres-data-') => 'postgres-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'mysql-data-') => 'mysql-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'redis-data-') => 'redis-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'clickhouse-data-') => 'clickhouse-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'mariadb-data-') => 'mariadb-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'mongodb-data-') => 'mongodb-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'keydb-data-') => 'keydb-data-'.$newDatabase->uuid,
str_starts_with($originalName, 'dragonfly-data-') => 'dragonfly-data-'.$newDatabase->uuid,
str_starts_with($volume->name, $database->uuid) => str($volume->name)->replace($database->uuid, $newDatabase->uuid)->toString(),
default => $newDatabase->uuid.'-'.$volume->name,
};
$newPersistentVolume = $volume->replicate([
'id',
'created_at',
'updated_at',
'uuid',
])->fill([
'name' => $newName,
'resource_id' => $newDatabase->id,
]);
$newPersistentVolume->save();
if ($cloneVolumeData) {
$pendingVolumeClones[] = [
'source' => $volume->name,
'target' => $newPersistentVolume->name,
'model' => $newPersistentVolume,
];
}
}
// Stop once, clone all volumes, then start once — avoids per-volume stop/start races.
if ($pendingVolumeClones !== [] && $sourceServer && $targetServer) {
try {
$chain = [
function () use ($database) {
StopDatabase::run($database);
},
];
foreach ($pendingVolumeClones as $clone) {
$chain[] = new VolumeCloneJob(
$clone['source'],
$clone['target'],
$sourceServer,
$targetServer,
$clone['model'],
);
}
$chain[] = function () use ($database) {
StartDatabase::run($database);
};
Bus::chain($chain)->onQueue('high')->dispatch();
} catch (\Exception $e) {
\Log::error('Failed to queue database volume clone for '.$database->uuid.': '.$e->getMessage());
}
}
foreach ($database->fileStorages()->get() as $storage) {
$storage->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'resource_id' => $newDatabase->id,
])->save();
}
foreach ($database->scheduledBackups()->get() as $backup) {
$backup->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => new_public_id(),
'database_id' => $newDatabase->id,
'database_type' => $newDatabase->getMorphClass(),
'team_id' => $teamId,
])->save();
}
foreach ($database->environment_variables()->get() as $environmentVariable) {
$environmentVariable->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'resourceable_id' => $newDatabase->id,
'resourceable_type' => $newDatabase->getMorphClass(),
])->save();
}
auditLog('api.database.cloned', [
'team_id' => $teamId,
'source_uuid' => $database->uuid,
'database_uuid' => $newDatabase->uuid,
'database_name' => $newDatabase->name,
'destination_uuid' => $destination->uuid,
'clone_volumes' => $cloneVolumeData,
]);
return response()->json([
'uuid' => $newDatabase->uuid,
'message' => 'Database cloned.',
], 201);
}
}
@@ -274,6 +274,84 @@ class DestinationsController extends Controller
|| in_array($driverCode, ['19', '1062', '2067'], true);
}
#[OA\Patch(
summary: 'Update destination',
description: 'Update a Docker network destination name. Network cannot be changed via the API.',
path: '/destinations/{uuid}',
operationId: 'update-destination-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Destinations'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Destination UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'name', type: 'string', maxLength: 255),
],
type: 'object',
),
),
responses: [
new OA\Response(
response: 200,
description: 'Destination updated.',
content: new OA\JsonContent(ref: '#/components/schemas/Destination'),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function update(Request $request, string $uuid): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$allowed = ['name'];
$validator = customApiValidator($request->all(), [
'name' => 'required|string|max:255',
]);
$extra = array_diff(array_keys($request->all()), $allowed);
if ($validator->fails() || ! empty($extra)) {
$errors = $validator->errors();
if (! empty($extra)) {
foreach ($extra as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json(['message' => 'Validation failed.', 'errors' => $errors], 422);
}
$destination = $this->findDestinationForTeam($teamId, $uuid);
$this->authorize('update', $destination);
$destination->update(['name' => $request->input('name')]);
$destination->load('server:id,uuid');
auditLog('api.destination.updated', [
'team_id' => $teamId,
'destination_uuid' => $destination->uuid,
'destination_name' => $destination->name,
'destination_type' => $destination instanceof SwarmDocker ? 'swarm' : 'standalone',
'server_uuid' => $destination->server?->uuid,
'changed_fields' => ['name'],
]);
return response()->json($this->transform($destination));
}
#[OA\Delete(
summary: 'Delete destination',
description: 'Delete an unused Docker network destination.',
@@ -0,0 +1,540 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\GitlabApp;
use App\Rules\SafeExternalUrl;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use OpenApi\Attributes as OA;
class GitlabController extends Controller
{
private function removeSensitiveData(GitlabApp $gitlabApp)
{
if (request()->attributes->get('can_read_sensitive', false) === true) {
$gitlabApp->makeVisible([
'client_secret',
'webhook_token',
'access_token',
'refresh_token',
]);
} else {
$gitlabApp->makeHidden([
'client_secret',
'webhook_token',
'access_token',
'refresh_token',
]);
}
return serializeApiResponse($gitlabApp);
}
private function findTeamGitlabApp(int|string $gitlabAppId, int $teamId): GitlabApp
{
return GitlabApp::where('id', $gitlabAppId)
->where('team_id', $teamId)
->firstOrFail();
}
private function gitlabApiUrlFromHtmlUrl(string $htmlUrl): string
{
return rtrim($htmlUrl, '/').'/api/v4';
}
#[OA\Get(
summary: 'List',
description: 'List all GitLab apps for the current team (and system-wide sources).',
path: '/gitlab-apps',
operationId: 'list-gitlab-apps',
security: [
['bearerAuth' => []],
],
tags: ['GitLab Apps'],
responses: [
new OA\Response(
response: 200,
description: 'List of GitLab apps.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'array',
items: new OA\Items(
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'uuid' => ['type' => 'string'],
'name' => ['type' => 'string'],
'api_url' => ['type' => 'string'],
'html_url' => ['type' => 'string'],
'custom_user' => ['type' => 'string'],
'custom_port' => ['type' => 'integer'],
'client_id' => ['type' => 'string', 'nullable' => true],
'group_name' => ['type' => 'string', 'nullable' => true],
'redirect_uri' => ['type' => 'string', 'nullable' => true],
'is_system_wide' => ['type' => 'boolean'],
'is_public' => ['type' => 'boolean'],
'team_id' => ['type' => 'integer'],
]
)
)
),
]
),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 400,
ref: '#/components/responses/400',
),
]
)]
public function list_gitlab_apps(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$gitlabApps = GitlabApp::where(function ($query) use ($teamId) {
$query->where('team_id', $teamId)
->orWhere('is_system_wide', true);
})->get();
$gitlabApps = $gitlabApps->map(function ($app) {
return $this->removeSensitiveData($app);
});
return response()->json($gitlabApps);
}
#[OA\Post(
summary: 'Create GitLab App',
description: 'Create a new GitLab app (OAuth source). Credentials may be supplied later via the UI or update endpoint.',
path: '/gitlab-apps',
operationId: 'create-gitlab-app',
security: [
['bearerAuth' => []],
],
tags: ['GitLab Apps'],
requestBody: new OA\RequestBody(
description: 'GitLab app creation payload.',
required: true,
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'name' => ['type' => 'string', 'description' => 'Name of the GitLab app.'],
'html_url' => ['type' => 'string', 'description' => 'GitLab instance URL (e.g., https://gitlab.com).'],
'api_url' => ['type' => 'string', 'description' => 'GitLab API URL (defaults to {html_url}/api/v4).'],
'custom_user' => ['type' => 'string', 'description' => 'Custom user for SSH access (default: git).'],
'custom_port' => ['type' => 'integer', 'description' => 'Custom port for SSH access (default: 22).'],
'group_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional comma-separated group names to filter repositories.'],
'client_id' => ['type' => 'string', 'nullable' => true, 'description' => 'GitLab OAuth Application ID.'],
'client_secret' => ['type' => 'string', 'nullable' => true, 'description' => 'GitLab OAuth Application Secret.'],
'webhook_token' => ['type' => 'string', 'nullable' => true, 'description' => 'Webhook secret token (auto-generated when omitted).'],
'redirect_uri' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth redirect URI registered in GitLab.'],
'is_system_wide' => ['type' => 'boolean', 'description' => 'Is this app system-wide (non-cloud instances only).'],
],
required: ['name', 'html_url'],
),
),
],
),
responses: [
new OA\Response(
response: 201,
description: 'GitLab app created successfully.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'uuid' => ['type' => 'string'],
'name' => ['type' => 'string'],
'api_url' => ['type' => 'string'],
'html_url' => ['type' => 'string'],
'custom_user' => ['type' => 'string'],
'custom_port' => ['type' => 'integer'],
'client_id' => ['type' => 'string', 'nullable' => true],
'group_name' => ['type' => 'string', 'nullable' => true],
'redirect_uri' => ['type' => 'string', 'nullable' => true],
'is_system_wide' => ['type' => 'boolean'],
'team_id' => ['type' => 'integer'],
]
)
),
]
),
new OA\Response(
response: 400,
ref: '#/components/responses/400',
),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 422,
ref: '#/components/responses/422',
),
]
)]
public function create_gitlab_app(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$this->authorize('create', [GitlabApp::class]);
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$allowedFields = [
'name',
'html_url',
'api_url',
'custom_user',
'custom_port',
'group_name',
'client_id',
'client_secret',
'webhook_token',
'redirect_uri',
'is_system_wide',
];
$validator = customApiValidator($request->all(), [
'name' => 'required|string|max:255',
'html_url' => ['required', 'string', 'url', new SafeExternalUrl],
'api_url' => ['nullable', 'string', 'url', new SafeExternalUrl],
'custom_user' => 'nullable|string|max:255',
'custom_port' => 'nullable|integer|min:1|max:65535',
'group_name' => 'nullable|string|max:255',
'client_id' => 'nullable|string|max:255',
'client_secret' => 'nullable|string',
'webhook_token' => 'nullable|string',
// Callback to this Coolify instance — may be a private/LAN URL; do not use SafeExternalUrl.
'redirect_uri' => ['nullable', 'string', 'url'],
'is_system_wide' => 'boolean',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
try {
$htmlUrl = rtrim((string) $request->input('html_url'), '/');
$apiUrl = filled($request->input('api_url'))
? rtrim((string) $request->input('api_url'), '/')
: $this->gitlabApiUrlFromHtmlUrl($htmlUrl);
$payload = [
'name' => $request->input('name'),
'html_url' => $htmlUrl,
'api_url' => $apiUrl,
'custom_user' => $request->input('custom_user', 'git'),
'custom_port' => $request->input('custom_port', 22),
'group_name' => $request->input('group_name'),
'client_id' => $request->input('client_id'),
'client_secret' => $request->input('client_secret'),
'webhook_token' => $request->input('webhook_token') ?: Str::random(32),
'redirect_uri' => $request->input('redirect_uri'),
'is_public' => false,
'team_id' => $teamId,
];
if (! isCloud()) {
$payload['is_system_wide'] = $request->boolean('is_system_wide', false);
}
$gitlabApp = GitlabApp::create($payload);
auditLog('api.gitlab_app.created', [
'team_id' => $teamId,
'gitlab_app_uuid' => $gitlabApp->uuid,
'gitlab_app_name' => $gitlabApp->name,
]);
return response()->json($this->removeSensitiveData($gitlabApp->fresh()), 201);
} catch (\Throwable $e) {
return handleError($e);
}
}
#[OA\Patch(
path: '/gitlab-apps/{gitlab_app_id}',
operationId: 'updateGitlabApp',
security: [
['bearerAuth' => []],
],
tags: ['GitLab Apps'],
summary: 'Update GitLab App',
description: 'Update an existing GitLab app.',
parameters: [
new OA\Parameter(
name: 'gitlab_app_id',
in: 'path',
required: true,
schema: new OA\Schema(type: 'integer'),
description: 'GitLab App ID'
),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'name' => ['type' => 'string', 'description' => 'GitLab App name'],
'html_url' => ['type' => 'string', 'description' => 'GitLab HTML URL'],
'api_url' => ['type' => 'string', 'description' => 'GitLab API URL'],
'custom_user' => ['type' => 'string', 'description' => 'Custom user for SSH'],
'custom_port' => ['type' => 'integer', 'description' => 'Custom port for SSH'],
'group_name' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional group filter'],
'client_id' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth Application ID'],
'client_secret' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth Application Secret'],
'webhook_token' => ['type' => 'string', 'nullable' => true, 'description' => 'Webhook secret token'],
'redirect_uri' => ['type' => 'string', 'nullable' => true, 'description' => 'OAuth redirect URI'],
'is_system_wide' => ['type' => 'boolean', 'description' => 'Is system wide (non-cloud instances only)'],
]
)
)
),
responses: [
new OA\Response(
response: 200,
description: 'GitLab app updated successfully',
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'message' => ['type' => 'string', 'example' => 'GitLab app updated successfully'],
'data' => ['type' => 'object', 'description' => 'Updated GitLab app data'],
]
)
)
),
new OA\Response(response: 401, description: 'Unauthorized'),
new OA\Response(response: 404, description: 'GitLab app not found'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_gitlab_app(Request $request, $gitlab_app_id)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
try {
$gitlabApp = $this->findTeamGitlabApp($gitlab_app_id, $teamId);
$this->authorize('update', $gitlabApp);
$allowedFields = [
'name',
'html_url',
'api_url',
'custom_user',
'custom_port',
'group_name',
'client_id',
'client_secret',
'webhook_token',
'redirect_uri',
];
if (! isCloud()) {
$allowedFields[] = 'is_system_wide';
}
$payload = $request->only($allowedFields);
$rules = [];
if (isset($payload['name'])) {
$rules['name'] = 'string|max:255';
}
if (isset($payload['html_url'])) {
$rules['html_url'] = ['url', new SafeExternalUrl];
}
if (isset($payload['api_url'])) {
$rules['api_url'] = ['url', new SafeExternalUrl];
}
if (isset($payload['custom_user'])) {
$rules['custom_user'] = 'string|max:255';
}
if (isset($payload['custom_port'])) {
$rules['custom_port'] = 'integer|min:1|max:65535';
}
if (array_key_exists('group_name', $payload)) {
$rules['group_name'] = 'nullable|string|max:255';
}
if (array_key_exists('client_id', $payload)) {
$rules['client_id'] = 'nullable|string|max:255';
}
if (array_key_exists('client_secret', $payload)) {
$rules['client_secret'] = 'nullable|string';
}
if (array_key_exists('webhook_token', $payload)) {
$rules['webhook_token'] = 'nullable|string';
}
if (array_key_exists('redirect_uri', $payload)) {
// Callback to this Coolify instance — may be a private/LAN URL.
$rules['redirect_uri'] = 'nullable|url';
}
if (! isCloud() && isset($payload['is_system_wide'])) {
$rules['is_system_wide'] = 'boolean';
}
$validator = customApiValidator($payload, $rules);
if ($validator->fails()) {
return response()->json([
'message' => 'Validation error',
'errors' => $validator->errors(),
], 422);
}
if (isset($payload['html_url'])) {
$payload['html_url'] = rtrim((string) $payload['html_url'], '/');
if (! filled($payload['api_url'] ?? null)) {
$payload['api_url'] = $this->gitlabApiUrlFromHtmlUrl($payload['html_url']);
}
}
if (isset($payload['api_url'])) {
$payload['api_url'] = rtrim((string) $payload['api_url'], '/');
}
$gitlabApp->update($payload);
auditLog('api.gitlab_app.updated', [
'team_id' => $teamId,
'gitlab_app_uuid' => $gitlabApp->uuid,
'gitlab_app_name' => $gitlabApp->name,
'changed_fields' => array_values(array_diff(array_keys($payload), ['client_secret', 'webhook_token'])),
]);
return response()->json([
'message' => 'GitLab app updated successfully',
'data' => $this->removeSensitiveData($gitlabApp->fresh()),
]);
} catch (ModelNotFoundException $e) {
return response()->json([
'message' => 'GitLab app not found',
], 404);
}
}
#[OA\Delete(
path: '/gitlab-apps/{gitlab_app_id}',
operationId: 'deleteGitlabApp',
security: [
['bearerAuth' => []],
],
tags: ['GitLab Apps'],
summary: 'Delete GitLab App',
description: 'Delete a GitLab app if it is not being used by any applications.',
parameters: [
new OA\Parameter(
name: 'gitlab_app_id',
in: 'path',
required: true,
schema: new OA\Schema(type: 'integer'),
description: 'GitLab App ID'
),
],
responses: [
new OA\Response(
response: 200,
description: 'GitLab app deleted successfully',
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'message' => ['type' => 'string', 'example' => 'GitLab app deleted successfully'],
]
)
)
),
new OA\Response(response: 401, description: 'Unauthorized'),
new OA\Response(response: 404, description: 'GitLab app not found'),
new OA\Response(
response: 409,
description: 'Conflict - GitLab app is in use',
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'message' => ['type' => 'string', 'example' => 'This GitLab app is being used by 5 application(s). Please delete all applications first.'],
]
)
)
),
]
)]
public function delete_gitlab_app($gitlab_app_id)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
try {
$gitlabApp = $this->findTeamGitlabApp($gitlab_app_id, $teamId);
$this->authorize('delete', $gitlabApp);
if ($gitlabApp->applications->isNotEmpty()) {
$count = $gitlabApp->applications->count();
return response()->json([
'message' => "This GitLab app is being used by {$count} application(s). Please delete all applications first.",
], 409);
}
$deletedUuid = $gitlabApp->uuid;
$deletedName = $gitlabApp->name;
$gitlabApp->delete();
auditLog('api.gitlab_app.deleted', [
'team_id' => $teamId,
'gitlab_app_uuid' => $deletedUuid,
'gitlab_app_name' => $deletedName,
]);
return response()->json([
'message' => 'GitLab app deleted successfully',
]);
} catch (ModelNotFoundException $e) {
return response()->json([
'message' => 'GitLab app not found',
], 404);
}
}
}
@@ -0,0 +1,111 @@
<?php
namespace App\Http\Controllers\Api\Internal;
use App\Actions\V5\Flux\ApplyFluxResourceStatusUpdate;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class FluxResourceStatusController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
if (! $this->authorizedBearer($request)) {
abort(401);
}
$validated = Validator::make($request->all(), [
'resource_type' => ['required', 'string', 'max:64'],
'team_id' => ['prohibited'],
'application_id' => ['prohibited'],
'resource_id' => ['prohibited'],
'server_id' => ['prohibited'],
'host_server_id' => ['prohibited'],
'application_uuid' => ['nullable', 'string', 'max:255'],
'resource_uuid' => ['nullable', 'string', 'max:255'],
'server_uuid' => ['nullable', 'string', 'max:255'],
'host_server_uuid' => ['nullable', 'string', 'max:255'],
'host_id' => ['nullable', 'string', 'max:255'],
'node_id' => ['nullable', 'string', 'max:255'],
'server_host' => ['nullable', 'string', 'max:255'],
'container_id' => ['nullable', 'string', 'max:255'],
'runtime_container_id' => ['nullable', 'string', 'max:255'],
'container_name' => ['nullable', 'string', 'max:255'],
'name' => ['nullable', 'string', 'max:255'],
'status' => ['required_without:state', 'string', 'max:64'],
'state' => ['required_without:status', 'string', 'max:64'],
'status_message' => ['nullable', 'string', 'max:1000'],
'message' => ['nullable', 'string', 'max:1000'],
'observed_at' => ['nullable', 'string', 'date'],
])->validate();
$resource = ApplyFluxResourceStatusUpdate::run($validated);
if ($resource === null) {
if (($validated['resource_type'] ?? null) === 'container') {
return response()->json([
'message' => 'Container status accepted.',
], 202);
}
return response()->json([
'message' => 'No matching v5 resource was found.',
], 404);
}
return response()->json([
'message' => 'Resource status updated.',
]);
}
/**
* Constant-time match the presented bearer token against every accepted
* inbound token. Accepting an array (config('flux.laravel_api_tokens'),
* falling back to the single config('flux.laravel_api_token')) lets an
* operator rotate by serving old+new tokens simultaneously.
*
* SECURITY: this is still a shared global secret every flux instance
* presents the same token, so it cannot be scoped or revoked per-flux, and
* a leak forces a fleet-wide rotation. The target design is per-flux,
* individually rotatable tokens; until then the array support above is the
* mitigation that makes rotation possible without downtime.
*/
private function authorizedBearer(Request $request): bool
{
$presented = (string) $request->bearerToken();
if ($presented === '') {
return false;
}
foreach ($this->acceptedTokens() as $token) {
if (hash_equals($token, $presented)) {
return true;
}
}
return false;
}
/**
* @return array<int, string>
*/
private function acceptedTokens(): array
{
$tokens = config('flux.laravel_api_tokens', []);
$tokens = is_array($tokens) ? $tokens : [];
$single = config('flux.laravel_api_token');
if (is_string($single) && $single !== '') {
$tokens[] = $single;
}
return array_values(array_filter(
array_map(fn ($token): string => is_string($token) ? $token : '', $tokens),
fn (string $token): bool => $token !== ''
));
}
}
@@ -0,0 +1,511 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\DiscordNotificationSettings;
use App\Models\EmailNotificationSettings;
use App\Models\PushoverNotificationSettings;
use App\Models\SlackNotificationSettings;
use App\Models\Team;
use App\Models\TelegramNotificationSettings;
use App\Models\WebhookNotificationSettings;
use App\Rules\SafeWebhookUrl;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class NotificationsController extends Controller
{
/**
* @return array{model: class-string<Model>, rules: array<string, mixed>}
*/
private function channelConfig(string $channel): array
{
return match ($channel) {
'email' => [
'model' => EmailNotificationSettings::class,
'rules' => [
'smtp_enabled' => 'sometimes|boolean',
'smtp_from_address' => 'sometimes|nullable|email',
'smtp_from_name' => 'sometimes|nullable|string|max:255',
'smtp_recipients' => 'sometimes|nullable|string|max:1000',
'smtp_host' => 'sometimes|nullable|string|max:255',
'smtp_port' => 'sometimes|nullable|integer|min:1|max:65535',
'smtp_encryption' => 'sometimes|nullable|string|in:starttls,tls,none',
'smtp_username' => 'sometimes|nullable|string|max:255',
'smtp_password' => 'sometimes|nullable|string|max:255',
'smtp_timeout' => 'sometimes|nullable|integer|min:0',
'resend_enabled' => 'sometimes|boolean',
'resend_api_key' => 'sometimes|nullable|string|max:255',
'use_instance_email_settings' => 'sometimes|boolean',
'deployment_success_email_notifications' => 'sometimes|boolean',
'deployment_failure_email_notifications' => 'sometimes|boolean',
'status_change_email_notifications' => 'sometimes|boolean',
'backup_success_email_notifications' => 'sometimes|boolean',
'backup_failure_email_notifications' => 'sometimes|boolean',
'scheduled_task_success_email_notifications' => 'sometimes|boolean',
'scheduled_task_failure_email_notifications' => 'sometimes|boolean',
'docker_cleanup_success_email_notifications' => 'sometimes|boolean',
'docker_cleanup_failure_email_notifications' => 'sometimes|boolean',
'server_disk_usage_email_notifications' => 'sometimes|boolean',
'server_reachable_email_notifications' => 'sometimes|boolean',
'server_unreachable_email_notifications' => 'sometimes|boolean',
'server_patch_email_notifications' => 'sometimes|boolean',
'traefik_outdated_email_notifications' => 'sometimes|boolean',
],
],
'discord' => [
'model' => DiscordNotificationSettings::class,
'rules' => [
'discord_enabled' => 'sometimes|boolean',
'discord_webhook_url' => ['sometimes', 'nullable', 'string', new SafeWebhookUrl],
'deployment_success_discord_notifications' => 'sometimes|boolean',
'deployment_failure_discord_notifications' => 'sometimes|boolean',
'status_change_discord_notifications' => 'sometimes|boolean',
'backup_success_discord_notifications' => 'sometimes|boolean',
'backup_failure_discord_notifications' => 'sometimes|boolean',
'scheduled_task_success_discord_notifications' => 'sometimes|boolean',
'scheduled_task_failure_discord_notifications' => 'sometimes|boolean',
'docker_cleanup_success_discord_notifications' => 'sometimes|boolean',
'docker_cleanup_failure_discord_notifications' => 'sometimes|boolean',
'server_disk_usage_discord_notifications' => 'sometimes|boolean',
'server_reachable_discord_notifications' => 'sometimes|boolean',
'server_unreachable_discord_notifications' => 'sometimes|boolean',
'server_patch_discord_notifications' => 'sometimes|boolean',
'traefik_outdated_discord_notifications' => 'sometimes|boolean',
'discord_ping_enabled' => 'sometimes|boolean',
],
],
'slack' => [
'model' => SlackNotificationSettings::class,
'rules' => [
'slack_enabled' => 'sometimes|boolean',
'slack_webhook_url' => ['sometimes', 'nullable', 'string', new SafeWebhookUrl],
'deployment_success_slack_notifications' => 'sometimes|boolean',
'deployment_failure_slack_notifications' => 'sometimes|boolean',
'status_change_slack_notifications' => 'sometimes|boolean',
'backup_success_slack_notifications' => 'sometimes|boolean',
'backup_failure_slack_notifications' => 'sometimes|boolean',
'scheduled_task_success_slack_notifications' => 'sometimes|boolean',
'scheduled_task_failure_slack_notifications' => 'sometimes|boolean',
'docker_cleanup_success_slack_notifications' => 'sometimes|boolean',
'docker_cleanup_failure_slack_notifications' => 'sometimes|boolean',
'server_disk_usage_slack_notifications' => 'sometimes|boolean',
'server_reachable_slack_notifications' => 'sometimes|boolean',
'server_unreachable_slack_notifications' => 'sometimes|boolean',
'server_patch_slack_notifications' => 'sometimes|boolean',
'traefik_outdated_slack_notifications' => 'sometimes|boolean',
],
],
'telegram' => [
'model' => TelegramNotificationSettings::class,
'rules' => [
'telegram_enabled' => 'sometimes|boolean',
'telegram_token' => 'sometimes|nullable|string|max:255',
'telegram_chat_id' => 'sometimes|nullable|string|max:255',
'deployment_success_telegram_notifications' => 'sometimes|boolean',
'deployment_failure_telegram_notifications' => 'sometimes|boolean',
'status_change_telegram_notifications' => 'sometimes|boolean',
'backup_success_telegram_notifications' => 'sometimes|boolean',
'backup_failure_telegram_notifications' => 'sometimes|boolean',
'scheduled_task_success_telegram_notifications' => 'sometimes|boolean',
'scheduled_task_failure_telegram_notifications' => 'sometimes|boolean',
'docker_cleanup_success_telegram_notifications' => 'sometimes|boolean',
'docker_cleanup_failure_telegram_notifications' => 'sometimes|boolean',
'server_disk_usage_telegram_notifications' => 'sometimes|boolean',
'server_reachable_telegram_notifications' => 'sometimes|boolean',
'server_unreachable_telegram_notifications' => 'sometimes|boolean',
'server_patch_telegram_notifications' => 'sometimes|boolean',
'traefik_outdated_telegram_notifications' => 'sometimes|boolean',
'telegram_notifications_deployment_success_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_deployment_failure_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_status_change_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_backup_success_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_backup_failure_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_scheduled_task_success_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_scheduled_task_failure_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_docker_cleanup_success_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_docker_cleanup_failure_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_server_disk_usage_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_server_reachable_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_server_unreachable_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_server_patch_thread_id' => 'sometimes|nullable|string|max:255',
'telegram_notifications_traefik_outdated_thread_id' => 'sometimes|nullable|string|max:255',
],
],
'pushover' => [
'model' => PushoverNotificationSettings::class,
'rules' => [
'pushover_enabled' => 'sometimes|boolean',
'pushover_user_key' => 'sometimes|nullable|string|max:255',
'pushover_api_token' => 'sometimes|nullable|string|max:255',
'deployment_success_pushover_notifications' => 'sometimes|boolean',
'deployment_failure_pushover_notifications' => 'sometimes|boolean',
'status_change_pushover_notifications' => 'sometimes|boolean',
'backup_success_pushover_notifications' => 'sometimes|boolean',
'backup_failure_pushover_notifications' => 'sometimes|boolean',
'scheduled_task_success_pushover_notifications' => 'sometimes|boolean',
'scheduled_task_failure_pushover_notifications' => 'sometimes|boolean',
'docker_cleanup_success_pushover_notifications' => 'sometimes|boolean',
'docker_cleanup_failure_pushover_notifications' => 'sometimes|boolean',
'server_disk_usage_pushover_notifications' => 'sometimes|boolean',
'server_reachable_pushover_notifications' => 'sometimes|boolean',
'server_unreachable_pushover_notifications' => 'sometimes|boolean',
'server_patch_pushover_notifications' => 'sometimes|boolean',
'traefik_outdated_pushover_notifications' => 'sometimes|boolean',
],
],
'webhook' => [
'model' => WebhookNotificationSettings::class,
'rules' => [
'webhook_enabled' => 'sometimes|boolean',
'webhook_url' => ['sometimes', 'nullable', 'string', new SafeWebhookUrl],
'deployment_success_webhook_notifications' => 'sometimes|boolean',
'deployment_failure_webhook_notifications' => 'sometimes|boolean',
'status_change_webhook_notifications' => 'sometimes|boolean',
'backup_success_webhook_notifications' => 'sometimes|boolean',
'backup_failure_webhook_notifications' => 'sometimes|boolean',
'scheduled_task_success_webhook_notifications' => 'sometimes|boolean',
'scheduled_task_failure_webhook_notifications' => 'sometimes|boolean',
'docker_cleanup_success_webhook_notifications' => 'sometimes|boolean',
'docker_cleanup_failure_webhook_notifications' => 'sometimes|boolean',
'server_disk_usage_webhook_notifications' => 'sometimes|boolean',
'server_reachable_webhook_notifications' => 'sometimes|boolean',
'server_unreachable_webhook_notifications' => 'sometimes|boolean',
'server_patch_webhook_notifications' => 'sometimes|boolean',
'traefik_outdated_webhook_notifications' => 'sometimes|boolean',
],
],
default => throw new \InvalidArgumentException("Unknown notification channel [{$channel}]."),
};
}
/**
* @return list<string>
*/
private function allowedFields(string $channel): array
{
$config = $this->channelConfig($channel);
/** @var Model $model */
$model = new $config['model'];
return array_values(array_filter(
$model->getFillable(),
fn (string $field): bool => $field !== 'team_id'
));
}
private function serializeSettings(Model $settings): array
{
exposeSensitiveFields($settings);
$settings->makeHidden(['team']);
return serializeApiResponse($settings)->toArray();
}
private function resolveSettings(string $channel, int $teamId): Model
{
$config = $this->channelConfig($channel);
$modelClass = $config['model'];
/** @var Model $settings */
$settings = $modelClass::query()->firstOrCreate(['team_id' => $teamId]);
$settings->setRelation('team', Team::query()->findOrFail($teamId));
return $settings;
}
private function showChannel(string $channel): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$settings = $this->resolveSettings($channel, $teamId);
$this->authorize('view', $settings);
return response()->json($this->serializeSettings($settings));
}
private function updateChannel(Request $request, string $channel): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$allowedFields = $this->allowedFields($channel);
$body = $request->json()->all();
$config = $this->channelConfig($channel);
$validator = customApiValidator($body, $config['rules']);
$extraFields = array_diff(array_keys($body), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$settings = $this->resolveSettings($channel, $teamId);
$this->authorize('update', $settings);
$settings->fill(array_intersect_key($body, array_flip($allowedFields)));
$settings->save();
auditLog("api.notifications.{$channel}.updated", [
'team_id' => $teamId,
'changed_fields' => array_values(array_intersect($allowedFields, array_keys($body))),
]);
$settings->refresh();
$settings->setRelation('team', Team::query()->findOrFail($teamId));
return response()->json($this->serializeSettings($settings));
}
#[OA\Get(
summary: 'Get email notification settings',
description: 'Get the current team email notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
path: '/notifications/email',
operationId: 'get-current-team-email-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Email notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
]
)]
public function email(Request $request): JsonResponse
{
return $this->showChannel('email');
}
#[OA\Patch(
summary: 'Update email notification settings',
description: 'Update the current team email notification settings.',
path: '/notifications/email',
operationId: 'update-current-team-email-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Updated email notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_email(Request $request): JsonResponse
{
return $this->updateChannel($request, 'email');
}
#[OA\Get(
summary: 'Get Discord notification settings',
description: 'Get the current team Discord notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
path: '/notifications/discord',
operationId: 'get-current-team-discord-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Discord notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
]
)]
public function discord(Request $request): JsonResponse
{
return $this->showChannel('discord');
}
#[OA\Patch(
summary: 'Update Discord notification settings',
description: 'Update the current team Discord notification settings.',
path: '/notifications/discord',
operationId: 'update-current-team-discord-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Updated Discord notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_discord(Request $request): JsonResponse
{
return $this->updateChannel($request, 'discord');
}
#[OA\Get(
summary: 'Get Slack notification settings',
description: 'Get the current team Slack notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
path: '/notifications/slack',
operationId: 'get-current-team-slack-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Slack notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
]
)]
public function slack(Request $request): JsonResponse
{
return $this->showChannel('slack');
}
#[OA\Patch(
summary: 'Update Slack notification settings',
description: 'Update the current team Slack notification settings.',
path: '/notifications/slack',
operationId: 'update-current-team-slack-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Updated Slack notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_slack(Request $request): JsonResponse
{
return $this->updateChannel($request, 'slack');
}
#[OA\Get(
summary: 'Get Telegram notification settings',
description: 'Get the current team Telegram notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
path: '/notifications/telegram',
operationId: 'get-current-team-telegram-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Telegram notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
]
)]
public function telegram(Request $request): JsonResponse
{
return $this->showChannel('telegram');
}
#[OA\Patch(
summary: 'Update Telegram notification settings',
description: 'Update the current team Telegram notification settings.',
path: '/notifications/telegram',
operationId: 'update-current-team-telegram-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Updated Telegram notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_telegram(Request $request): JsonResponse
{
return $this->updateChannel($request, 'telegram');
}
#[OA\Get(
summary: 'Get Pushover notification settings',
description: 'Get the current team Pushover notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
path: '/notifications/pushover',
operationId: 'get-current-team-pushover-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Pushover notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
]
)]
public function pushover(Request $request): JsonResponse
{
return $this->showChannel('pushover');
}
#[OA\Patch(
summary: 'Update Pushover notification settings',
description: 'Update the current team Pushover notification settings.',
path: '/notifications/pushover',
operationId: 'update-current-team-pushover-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Updated Pushover notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_pushover(Request $request): JsonResponse
{
return $this->updateChannel($request, 'pushover');
}
#[OA\Get(
summary: 'Get webhook notification settings',
description: 'Get the current team webhook notification settings. Encrypted secrets are only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner.',
path: '/notifications/webhook',
operationId: 'get-current-team-webhook-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Webhook notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
]
)]
public function webhook(Request $request): JsonResponse
{
return $this->showChannel('webhook');
}
#[OA\Patch(
summary: 'Update webhook notification settings',
description: 'Update the current team webhook notification settings.',
path: '/notifications/webhook',
operationId: 'update-current-team-webhook-notifications',
security: [['bearerAuth' => []]],
tags: ['Notifications'],
responses: [
new OA\Response(response: 200, description: 'Updated webhook notification settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 403, description: 'Forbidden.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update_webhook(Request $request): JsonResponse
{
return $this->updateChannel($request, 'webhook');
}
}
@@ -682,6 +682,155 @@ class ProjectController extends Controller
])->setStatusCode(201);
}
#[OA\Patch(
summary: 'Update Environment',
description: 'Update environment by name or UUID within a project.',
path: '/projects/{uuid}/environments/{environment_name_or_uuid}',
operationId: 'update-environment',
security: [
['bearerAuth' => []],
],
tags: ['Projects'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'environment_name_or_uuid', in: 'path', required: true, description: 'Environment name or UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
description: 'Environment fields to update.',
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'name' => ['type' => 'string', 'description' => 'The name of the environment.'],
'description' => ['type' => 'string', 'description' => 'The description of the environment.'],
],
),
),
),
responses: [
new OA\Response(
response: 200,
description: 'Environment updated.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'uuid' => ['type' => 'string', 'example' => 'env123'],
'name' => ['type' => 'string', 'example' => 'staging'],
'description' => ['type' => 'string', 'example' => 'Staging environment'],
]
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 400,
ref: '#/components/responses/400',
),
new OA\Response(
response: 404,
description: 'Project or environment not found.',
),
new OA\Response(
response: 409,
description: 'Environment with this name already exists.',
),
new OA\Response(
response: 422,
ref: '#/components/responses/422',
),
]
)]
public function update_environment(Request $request)
{
$allowedFields = ['name', 'description'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = Validator::make($request->all(), [
'name' => ValidationPatterns::nameRules(required: false),
'description' => ValidationPatterns::descriptionRules(),
], ValidationPatterns::combinedMessages());
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
if (! $request->uuid) {
return response()->json(['message' => 'Project UUID is required.'], 422);
}
if (! $request->environment_name_or_uuid) {
return response()->json(['message' => 'Environment name or UUID is required.'], 422);
}
$project = Project::whereTeamId($teamId)->whereUuid($request->uuid)->first();
if (! $project) {
return response()->json(['message' => 'Project not found.'], 404);
}
$environment = $project->environments()->whereName($request->environment_name_or_uuid)->first();
if (! $environment) {
$environment = $project->environments()->whereUuid($request->environment_name_or_uuid)->first();
}
if (! $environment) {
return response()->json(['message' => 'Environment not found.'], 404);
}
$this->authorize('update', $environment);
if ($request->filled('name') && $request->name !== $environment->name) {
$existingEnvironment = $project->environments()
->where('name', $request->name)
->where('id', '!=', $environment->id)
->first();
if ($existingEnvironment) {
return response()->json(['message' => 'Environment with this name already exists.'], 409);
}
}
$environment->update($request->only($allowedFields));
auditLog('api.project.environment_updated', [
'team_id' => $teamId,
'project_uuid' => $project->uuid,
'environment_uuid' => $environment->uuid,
'environment_name' => $environment->name,
'changed_fields' => array_values(array_intersect($allowedFields, array_keys($request->all()))),
]);
return response()->json([
'uuid' => $environment->uuid,
'name' => $environment->name,
'description' => $environment->description,
]);
}
#[OA\Delete(
summary: 'Delete Environment',
description: 'Delete environment by name or UUID. Environment must be empty.',
@@ -0,0 +1,566 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\S3Storage;
use App\Rules\SafeWebhookUrl;
use App\Rules\ValidS3BucketName;
use App\Support\ValidationPatterns;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class S3StoragesController extends Controller
{
private function removeSensitiveData(S3Storage $storage)
{
$storage->makeHidden([
'id',
]);
if (request()->attributes->get('can_read_sensitive', false) === true) {
$storage->makeVisible([
'key',
'secret',
]);
}
return serializeApiResponse($storage);
}
/**
* @return array{valid: bool, error: string|null}
*/
private function validateStorageConnection(S3Storage $storage): array
{
try {
$storage->testConnection(shouldSave: true);
return ['valid' => true, 'error' => null];
} catch (\Throwable $e) {
return ['valid' => false, 'error' => $e->getMessage()];
}
}
/**
* @param array<string, mixed> $body
* @param array<int, string> $allowedFields
* @param array<string, mixed> $rules
*/
private function validateBody(array $body, array $allowedFields, array $rules): ?JsonResponse
{
$validator = customApiValidator($body, $rules);
$extraFields = array_diff(array_keys($body), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
return null;
}
#[OA\Get(
summary: 'List S3 Storages',
description: 'List all S3 storages for the authenticated team.',
path: '/s3-storages',
operationId: 'list-s3-storages',
security: [
['bearerAuth' => []],
],
tags: ['S3 Storages'],
responses: [
new OA\Response(
response: 200,
description: 'Get all S3 storages.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'array',
items: new OA\Items(
type: 'object',
properties: [
'uuid' => ['type' => 'string'],
'name' => ['type' => 'string'],
'description' => ['type' => 'string', 'nullable' => true],
'endpoint' => ['type' => 'string'],
'bucket' => ['type' => 'string'],
'region' => ['type' => 'string'],
'is_usable' => ['type' => 'boolean'],
'team_id' => ['type' => 'integer'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
]
)
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 400,
ref: '#/components/responses/400',
),
]
)]
public function index(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$storages = S3Storage::ownedByCurrentTeamAPI($teamId)
->get()
->map(function ($storage) {
return $this->removeSensitiveData($storage);
});
return response()->json($storages);
}
#[OA\Get(
summary: 'Get S3 Storage',
description: 'Get S3 storage by UUID.',
path: '/s3-storages/{uuid}',
operationId: 'get-s3-storage-by-uuid',
security: [
['bearerAuth' => []],
],
tags: ['S3 Storages'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'S3 Storage UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Get S3 storage by UUID',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'uuid' => ['type' => 'string'],
'name' => ['type' => 'string'],
'description' => ['type' => 'string', 'nullable' => true],
'endpoint' => ['type' => 'string'],
'bucket' => ['type' => 'string'],
'region' => ['type' => 'string'],
'is_usable' => ['type' => 'boolean'],
'team_id' => ['type' => 'integer'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
]
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 404,
ref: '#/components/responses/404',
),
]
)]
public function show(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)
->whereUuid($request->uuid)
->first();
if (is_null($storage)) {
return response()->json(['message' => 'S3 storage not found.'], 404);
}
$this->authorize('view', $storage);
return response()->json($this->removeSensitiveData($storage));
}
#[OA\Post(
summary: 'Create S3 Storage',
description: 'Create a new S3 storage configuration for the authenticated team.',
path: '/s3-storages',
operationId: 'create-s3-storage',
security: [
['bearerAuth' => []],
],
tags: ['S3 Storages'],
requestBody: new OA\RequestBody(
required: true,
description: 'S3 storage details',
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
required: ['name', 'endpoint', 'bucket', 'region', 'key', 'secret'],
properties: [
'name' => ['type' => 'string', 'example' => 'My S3 Storage', 'description' => 'A friendly name for the storage.'],
'description' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional description.'],
'endpoint' => ['type' => 'string', 'example' => 'https://s3.us-east-1.amazonaws.com', 'description' => 'S3-compatible endpoint URL.'],
'bucket' => ['type' => 'string', 'example' => 'my-bucket', 'description' => 'S3 bucket name.'],
'region' => ['type' => 'string', 'example' => 'us-east-1', 'description' => 'S3 region.'],
'key' => ['type' => 'string', 'description' => 'Access key.'],
'secret' => ['type' => 'string', 'description' => 'Secret key.'],
'is_usable' => ['type' => 'boolean', 'description' => 'Whether the storage is marked usable.'],
],
),
),
),
responses: [
new OA\Response(
response: 201,
description: 'S3 storage created.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'uuid' => ['type' => 'string', 'example' => 'og888os', 'description' => 'The UUID of the S3 storage.'],
]
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 400,
ref: '#/components/responses/400',
),
new OA\Response(
response: 422,
ref: '#/components/responses/422',
),
]
)]
public function store(Request $request)
{
$allowedFields = ['name', 'description', 'endpoint', 'bucket', 'region', 'key', 'secret', 'is_usable'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$this->authorize('create', [S3Storage::class]);
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$body = $request->json()->all();
$validationError = $this->validateBody($body, $allowedFields, [
'name' => ValidationPatterns::nameRules(),
'description' => ValidationPatterns::descriptionRules(),
'endpoint' => ['required', 'string', 'max:255', new SafeWebhookUrl],
'bucket' => ['required', new ValidS3BucketName],
'region' => 'required|string|max:255',
'key' => 'required|string|max:255',
'secret' => 'required|string|max:255',
'is_usable' => 'sometimes|boolean',
]);
if ($validationError instanceof JsonResponse) {
return $validationError;
}
$storage = S3Storage::create([
'team_id' => $teamId,
'name' => $body['name'],
'description' => $body['description'] ?? null,
'endpoint' => $body['endpoint'],
'bucket' => $body['bucket'],
'region' => $body['region'],
'key' => $body['key'],
'secret' => $body['secret'],
'is_usable' => $body['is_usable'] ?? false,
]);
auditLog('api.s3_storage.created', [
'team_id' => $teamId,
's3_storage_uuid' => $storage->uuid,
's3_storage_name' => $storage->name,
]);
return response()->json([
'uuid' => $storage->uuid,
])->setStatusCode(201);
}
#[OA\Patch(
summary: 'Update S3 Storage',
description: 'Update S3 storage by UUID.',
path: '/s3-storages/{uuid}',
operationId: 'update-s3-storage-by-uuid',
security: [
['bearerAuth' => []],
],
tags: ['S3 Storages'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'S3 Storage UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
description: 'S3 storage fields to update.',
content: new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'name' => ['type' => 'string', 'description' => 'A friendly name for the storage.'],
'description' => ['type' => 'string', 'nullable' => true, 'description' => 'Optional description.'],
'endpoint' => ['type' => 'string', 'description' => 'S3-compatible endpoint URL.'],
'bucket' => ['type' => 'string', 'description' => 'S3 bucket name.'],
'region' => ['type' => 'string', 'description' => 'S3 region.'],
'key' => ['type' => 'string', 'description' => 'Access key.'],
'secret' => ['type' => 'string', 'description' => 'Secret key.'],
'is_usable' => ['type' => 'boolean', 'description' => 'Whether the storage is marked usable.'],
],
),
),
),
responses: [
new OA\Response(
response: 200,
description: 'S3 storage updated.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'uuid' => ['type' => 'string'],
]
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 404,
ref: '#/components/responses/404',
),
new OA\Response(
response: 422,
ref: '#/components/responses/422',
),
]
)]
public function update(Request $request)
{
$allowedFields = ['name', 'description', 'endpoint', 'bucket', 'region', 'key', 'secret', 'is_usable'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$body = $request->json()->all();
$validationError = $this->validateBody($body, $allowedFields, [
'name' => ValidationPatterns::nameRules(required: false),
'description' => ValidationPatterns::descriptionRules(),
'endpoint' => ['sometimes', 'string', 'max:255', new SafeWebhookUrl],
'bucket' => ['sometimes', new ValidS3BucketName],
'region' => 'sometimes|string|max:255',
'key' => 'sometimes|string|max:255',
'secret' => 'sometimes|string|max:255',
'is_usable' => 'sometimes|boolean',
]);
if ($validationError instanceof JsonResponse) {
return $validationError;
}
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)->whereUuid($request->route('uuid'))->first();
if (! $storage) {
return response()->json(['message' => 'S3 storage not found.'], 404);
}
$this->authorize('update', $storage);
$storage->update(array_intersect_key($body, array_flip($allowedFields)));
auditLog('api.s3_storage.updated', [
'team_id' => $teamId,
's3_storage_uuid' => $storage->uuid,
's3_storage_name' => $storage->name,
'changed_fields' => array_values(array_intersect($allowedFields, array_keys($body))),
]);
return response()->json([
'uuid' => $storage->uuid,
]);
}
#[OA\Delete(
summary: 'Delete S3 Storage',
description: 'Delete S3 storage by UUID.',
path: '/s3-storages/{uuid}',
operationId: 'delete-s3-storage-by-uuid',
security: [
['bearerAuth' => []],
],
tags: ['S3 Storages'],
parameters: [
new OA\Parameter(
name: 'uuid',
in: 'path',
description: 'UUID of the S3 storage.',
required: true,
schema: new OA\Schema(
type: 'string',
)
),
],
responses: [
new OA\Response(
response: 200,
description: 'S3 storage deleted.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'message' => ['type' => 'string', 'example' => 'S3 storage deleted.'],
]
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 404,
ref: '#/components/responses/404',
),
]
)]
public function destroy(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
if (! $request->uuid) {
return response()->json(['message' => 'UUID is required.'], 422);
}
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)->whereUuid($request->uuid)->first();
if (! $storage) {
return response()->json(['message' => 'S3 storage not found.'], 404);
}
$this->authorize('delete', $storage);
$storageUuid = $storage->uuid;
$storageName = $storage->name;
$storage->delete();
auditLog('api.s3_storage.deleted', [
'team_id' => $teamId,
's3_storage_uuid' => $storageUuid,
's3_storage_name' => $storageName,
]);
return response()->json(['message' => 'S3 storage deleted.']);
}
#[OA\Post(
summary: 'Validate S3 Storage',
description: 'Validate an S3 storage connection using ListObjectsV2.',
path: '/s3-storages/{uuid}/validate',
operationId: 'validate-s3-storage-by-uuid',
security: [
['bearerAuth' => []],
],
tags: ['S3 Storages'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'S3 Storage UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'S3 storage validation result.',
content: [
new OA\MediaType(
mediaType: 'application/json',
schema: new OA\Schema(
type: 'object',
properties: [
'valid' => ['type' => 'boolean', 'example' => true],
'message' => ['type' => 'string', 'example' => 'S3 storage connection is valid.'],
]
)
),
]),
new OA\Response(
response: 401,
ref: '#/components/responses/401',
),
new OA\Response(
response: 404,
ref: '#/components/responses/404',
),
]
)]
public function validateStorage(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$storage = S3Storage::ownedByCurrentTeamAPI($teamId)->whereUuid($request->uuid)->first();
if (! $storage) {
return response()->json(['message' => 'S3 storage not found.'], 404);
}
$this->authorize('validateConnection', $storage);
$validation = $this->validateStorageConnection($storage);
auditLog('api.s3_storage.validated', [
'team_id' => $teamId,
's3_storage_uuid' => $storage->uuid,
's3_storage_name' => $storage->name,
'valid' => $validation['valid'],
]);
return response()->json([
'valid' => $validation['valid'],
'message' => $validation['valid'] ? 'S3 storage connection is valid.' : $validation['error'],
]);
}
}
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Jobs\ScheduledTaskJob;
use App\Models\Application;
use App\Models\ScheduledTask;
use App\Models\Service;
@@ -224,6 +225,28 @@ class ScheduledTasksController extends Controller
return response()->json($executions);
}
private function executeTask(Request $request, Application|Service $resource): JsonResponse
{
$this->authorize('update', $resource);
$task = $resource->scheduled_tasks()->where('uuid', $request->task_uuid)->first();
if (! $task) {
return response()->json(['message' => 'Scheduled task not found.'], 404);
}
ScheduledTaskJob::dispatch($task);
auditLog('api.scheduled_task.executed', [
'team_id' => getTeamIdFromToken(),
'task_uuid' => $task->uuid,
'task_name' => $task->name,
'resource_type' => $resource instanceof Application ? 'application' : 'service',
'resource_uuid' => $resource->uuid,
]);
return response()->json(['message' => 'Scheduled task execution queued.']);
}
#[OA\Get(
summary: 'List Tasks',
description: 'List all scheduled tasks for an application.',
@@ -949,4 +972,68 @@ class ScheduledTasksController extends Controller
return $this->getExecutions($request, $service);
}
#[OA\Post(
summary: 'Execute Task',
description: 'Queue immediate execution of a scheduled task for an application.',
path: '/applications/{uuid}/scheduled-tasks/{task_uuid}/execute',
operationId: 'execute-scheduled-task-by-application-uuid',
security: [['bearerAuth' => []]],
tags: ['Scheduled Tasks'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the application.', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'task_uuid', in: 'path', required: true, description: 'UUID of the scheduled task.', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Scheduled task execution queued.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function execute_scheduled_task_by_application_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$application = $this->resolveApplication($request, $teamId);
if (! $application) {
return response()->json(['message' => 'Application not found.'], 404);
}
return $this->executeTask($request, $application);
}
#[OA\Post(
summary: 'Execute Task',
description: 'Queue immediate execution of a scheduled task for a service.',
path: '/services/{uuid}/scheduled-tasks/{task_uuid}/execute',
operationId: 'execute-scheduled-task-by-service-uuid',
security: [['bearerAuth' => []]],
tags: ['Scheduled Tasks'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the service.', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'task_uuid', in: 'path', required: true, description: 'UUID of the scheduled task.', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Scheduled task execution queued.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function execute_scheduled_task_by_service_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$service = $this->resolveService($request, $teamId);
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
return $this->executeTask($request, $service);
}
}
@@ -0,0 +1,269 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Server;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class ServerCloudflareTunnelController extends Controller
{
private const ALLOWED_FIELDS = [
'is_cloudflare_tunnel',
];
private function findServerForTeam(int $teamId, string $uuid): ?Server
{
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
}
private function transform(Server $server): array
{
return [
'is_cloudflare_tunnel' => (bool) $server->settings->is_cloudflare_tunnel,
'ip' => $server->ip,
'ip_previous' => $server->ip_previous,
];
}
#[OA\Get(
summary: 'Get Cloudflare Tunnel settings',
description: 'Get Cloudflare Tunnel settings for a server owned by the authenticated team.',
path: '/servers/{uuid}/cloudflare-tunnel',
operationId: 'get-server-cloudflare-tunnel',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Cloudflare Tunnel settings.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'is_cloudflare_tunnel', type: 'boolean'),
new OA\Property(property: 'ip', type: 'string'),
new OA\Property(property: 'ip_previous', type: 'string', nullable: true),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function show(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
return response()->json($this->transform($server));
}
#[OA\Patch(
summary: 'Update Cloudflare Tunnel settings',
description: 'Update stored Cloudflare Tunnel settings for a server. Does not run remote cloudflared configuration; use enable/disable for the manual UI actions.',
path: '/servers/{uuid}/cloudflare-tunnel',
operationId: 'update-server-cloudflare-tunnel',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'is_cloudflare_tunnel', type: 'boolean'),
],
type: 'object',
),
),
responses: [
new OA\Response(response: 200, description: 'Updated Cloudflare Tunnel settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function update(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
if ($server->isLocalhost()) {
return response()->json(['message' => 'Cloudflare Tunnel cannot be configured on the localhost server.'], 422);
}
$validator = customApiValidator($request->all(), [
'is_cloudflare_tunnel' => 'required|boolean',
]);
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$enabled = $request->boolean('is_cloudflare_tunnel');
$server->settings->is_cloudflare_tunnel = $enabled;
$server->settings->save();
if (! $enabled && $server->ip_previous) {
$server->update(['ip' => $server->ip_previous]);
}
auditLog('api.server.cloudflare_tunnel.updated', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
'is_cloudflare_tunnel' => $enabled,
]);
return response()->json($this->transform($server->refresh()));
}
#[OA\Post(
summary: 'Enable Cloudflare Tunnel (manual)',
description: 'Manually mark Cloudflare Tunnel as enabled for a server (matches UI manual enable). Does not deploy cloudflared remotely.',
path: '/servers/{uuid}/cloudflare-tunnel/enable',
operationId: 'enable-server-cloudflare-tunnel',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Cloudflare Tunnel enabled.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function enable(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
if ($server->isLocalhost()) {
return response()->json(['message' => 'Cloudflare Tunnel cannot be configured on the localhost server.'], 422);
}
$server->settings->is_cloudflare_tunnel = true;
$server->settings->save();
auditLog('api.server.cloudflare_tunnel.enabled', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
]);
return response()->json([
'message' => 'Cloudflare Tunnel enabled.',
...$this->transform($server->refresh()),
]);
}
#[OA\Post(
summary: 'Disable Cloudflare Tunnel',
description: 'Mark Cloudflare Tunnel as disabled and restore ip_previous when available. Does not remove the remote cloudflared container.',
path: '/servers/{uuid}/cloudflare-tunnel/disable',
operationId: 'disable-server-cloudflare-tunnel',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Cloudflare Tunnel disabled.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function disable(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
if ($server->isLocalhost()) {
return response()->json(['message' => 'Cloudflare Tunnel cannot be configured on the localhost server.'], 422);
}
$server->settings->is_cloudflare_tunnel = false;
$server->settings->save();
$message = 'Cloudflare Tunnel disabled.';
if ($server->ip_previous) {
$server->update(['ip' => $server->ip_previous]);
$message .= ' Server IP restored to its previous IP address.';
} else {
$message .= ' Action required: Update the server IP address to its real IP address if needed.';
}
auditLog('api.server.cloudflare_tunnel.disabled', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
]);
return response()->json([
'message' => $message,
...$this->transform($server->refresh()),
]);
}
}
@@ -0,0 +1,356 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Jobs\DockerCleanupJob;
use App\Models\Server;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class ServerDockerCleanupController extends Controller
{
private const ALLOWED_FIELDS = [
'docker_cleanup_frequency',
'docker_cleanup_threshold',
'force_docker_cleanup',
'delete_unused_volumes',
'delete_unused_networks',
'disable_application_image_retention',
];
private function findServerForTeam(int $teamId, string $uuid): ?Server
{
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
}
private function transform(Server $server): array
{
$settings = $server->settings;
return [
'docker_cleanup_frequency' => $settings->docker_cleanup_frequency,
'docker_cleanup_threshold' => (int) $settings->docker_cleanup_threshold,
'force_docker_cleanup' => (bool) $settings->force_docker_cleanup,
'delete_unused_volumes' => (bool) $settings->delete_unused_volumes,
'delete_unused_networks' => (bool) $settings->delete_unused_networks,
'disable_application_image_retention' => (bool) $settings->disable_application_image_retention,
];
}
#[OA\Get(
summary: 'Get Docker cleanup settings',
description: 'Get Docker cleanup settings for a server owned by the authenticated team.',
path: '/servers/{uuid}/docker-cleanup',
operationId: 'get-server-docker-cleanup',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Docker cleanup settings.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'docker_cleanup_frequency', type: 'string'),
new OA\Property(property: 'docker_cleanup_threshold', type: 'integer'),
new OA\Property(property: 'force_docker_cleanup', type: 'boolean'),
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
new OA\Property(property: 'disable_application_image_retention', type: 'boolean'),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function show(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
return response()->json($this->transform($server));
}
#[OA\Patch(
summary: 'Update Docker cleanup settings',
description: 'Update Docker cleanup settings for a server owned by the authenticated team.',
path: '/servers/{uuid}/docker-cleanup',
operationId: 'update-server-docker-cleanup',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'docker_cleanup_frequency', type: 'string', description: 'Cron / human frequency expression.'),
new OA\Property(property: 'docker_cleanup_threshold', type: 'integer', minimum: 1, maximum: 99),
new OA\Property(property: 'force_docker_cleanup', type: 'boolean'),
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
new OA\Property(property: 'disable_application_image_retention', type: 'boolean'),
],
type: 'object',
),
),
responses: [
new OA\Response(
response: 200,
description: 'Updated Docker cleanup settings.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'docker_cleanup_frequency', type: 'string'),
new OA\Property(property: 'docker_cleanup_threshold', type: 'integer'),
new OA\Property(property: 'force_docker_cleanup', type: 'boolean'),
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
new OA\Property(property: 'disable_application_image_retention', type: 'boolean'),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function update(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$validator = customApiValidator($request->all(), [
'docker_cleanup_frequency' => 'string',
'docker_cleanup_threshold' => 'integer|min:1|max:99',
'force_docker_cleanup' => 'boolean',
'delete_unused_volumes' => 'boolean',
'delete_unused_networks' => 'boolean',
'disable_application_image_retention' => 'boolean',
]);
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
if ($request->has('docker_cleanup_frequency') && ! validate_cron_expression($request->docker_cleanup_frequency)) {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['docker_cleanup_frequency' => ['Invalid Cron / Human expression for Docker Cleanup Frequency.']],
], 422);
}
$settings = $server->settings;
foreach (self::ALLOWED_FIELDS as $field) {
if ($request->has($field)) {
$settings->{$field} = $request->input($field);
}
}
$settings->save();
auditLog('api.server.docker_cleanup.updated', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
'changed_fields' => array_values(array_intersect(self::ALLOWED_FIELDS, array_keys($request->all()))),
]);
return response()->json($this->transform($server->refresh()));
}
#[OA\Post(
summary: 'Run Docker cleanup',
description: 'Dispatch a manual Docker cleanup job for a server owned by the authenticated team.',
path: '/servers/{uuid}/docker-cleanup/run',
operationId: 'run-server-docker-cleanup',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: false,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'delete_unused_volumes', type: 'boolean'),
new OA\Property(property: 'delete_unused_networks', type: 'boolean'),
],
type: 'object',
),
),
responses: [
new OA\Response(
response: 200,
description: 'Docker cleanup job dispatched.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'message', type: 'string', example: 'Manual cleanup job started.'),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function run(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$validator = customApiValidator($request->all(), [
'delete_unused_volumes' => 'boolean',
'delete_unused_networks' => 'boolean',
]);
$extraFields = array_diff(array_keys($request->all()), ['delete_unused_volumes', 'delete_unused_networks']);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$deleteUnusedVolumes = $request->has('delete_unused_volumes')
? $request->boolean('delete_unused_volumes')
: (bool) $server->settings->delete_unused_volumes;
$deleteUnusedNetworks = $request->has('delete_unused_networks')
? $request->boolean('delete_unused_networks')
: (bool) $server->settings->delete_unused_networks;
DockerCleanupJob::dispatch($server, true, $deleteUnusedVolumes, $deleteUnusedNetworks);
auditLog('api.server.docker_cleanup.run', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
'delete_unused_volumes' => $deleteUnusedVolumes,
'delete_unused_networks' => $deleteUnusedNetworks,
]);
return response()->json([
'message' => 'Manual cleanup job started. Depending on the amount of data, this might take a while.',
]);
}
#[OA\Get(
summary: 'List Docker cleanup executions',
description: 'List recent Docker cleanup execution logs for a server owned by the authenticated team.',
path: '/servers/{uuid}/docker-cleanup/executions',
operationId: 'list-server-docker-cleanup-executions',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Recent Docker cleanup executions.',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(
properties: [
new OA\Property(property: 'uuid', type: 'string'),
new OA\Property(property: 'status', type: 'string'),
new OA\Property(property: 'message', type: 'string', nullable: true),
new OA\Property(property: 'finished_at', type: 'string', nullable: true),
new OA\Property(property: 'created_at', type: 'string'),
new OA\Property(property: 'updated_at', type: 'string'),
],
type: 'object',
),
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function executions(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
$executions = $server->dockerCleanupExecutions()
->orderBy('created_at', 'desc')
->take(20)
->get()
->map(fn ($execution) => [
'uuid' => $execution->uuid,
'status' => $execution->status,
'message' => $execution->message,
'finished_at' => $execution->finished_at,
'created_at' => $execution->created_at,
'updated_at' => $execution->updated_at,
])
->values();
return response()->json($executions);
}
}
@@ -0,0 +1,248 @@
<?php
namespace App\Http\Controllers\Api;
use App\Actions\Server\StartLogDrain;
use App\Actions\Server\StopLogDrain;
use App\Http\Controllers\Controller;
use App\Models\Server;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class ServerLogDrainsController extends Controller
{
private const ALLOWED_FIELDS = [
'is_logdrain_newrelic_enabled',
'logdrain_newrelic_license_key',
'logdrain_newrelic_base_uri',
'is_logdrain_axiom_enabled',
'logdrain_axiom_dataset_name',
'logdrain_axiom_api_key',
'is_logdrain_custom_enabled',
'logdrain_custom_config',
'logdrain_custom_config_parser',
];
private function findServerForTeam(int $teamId, string $uuid): ?Server
{
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
}
private function canReadSensitive(): bool
{
return request()->attributes->get('can_read_sensitive', false) === true;
}
private function transform(Server $server): array
{
$settings = $server->settings;
$payload = [
'is_logdrain_newrelic_enabled' => (bool) $settings->is_logdrain_newrelic_enabled,
'logdrain_newrelic_base_uri' => $settings->logdrain_newrelic_base_uri,
'is_logdrain_axiom_enabled' => (bool) $settings->is_logdrain_axiom_enabled,
'logdrain_axiom_dataset_name' => $settings->logdrain_axiom_dataset_name,
'is_logdrain_custom_enabled' => (bool) $settings->is_logdrain_custom_enabled,
];
if ($this->canReadSensitive()) {
$payload['logdrain_newrelic_license_key'] = $settings->logdrain_newrelic_license_key;
$payload['logdrain_axiom_api_key'] = $settings->logdrain_axiom_api_key;
$payload['logdrain_custom_config'] = $settings->logdrain_custom_config;
$payload['logdrain_custom_config_parser'] = $settings->logdrain_custom_config_parser;
}
return $payload;
}
#[OA\Get(
summary: 'Get log drain settings',
description: 'Get log drain settings for a server owned by the authenticated team. Sensitive fields require the read:sensitive or root token ability.',
path: '/servers/{uuid}/log-drains',
operationId: 'get-server-log-drains',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Log drain settings.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'is_logdrain_newrelic_enabled', type: 'boolean'),
new OA\Property(property: 'logdrain_newrelic_license_key', type: 'string', description: 'Only present with read:sensitive.'),
new OA\Property(property: 'logdrain_newrelic_base_uri', type: 'string', nullable: true),
new OA\Property(property: 'is_logdrain_axiom_enabled', type: 'boolean'),
new OA\Property(property: 'logdrain_axiom_dataset_name', type: 'string', nullable: true),
new OA\Property(property: 'logdrain_axiom_api_key', type: 'string', description: 'Only present with read:sensitive.'),
new OA\Property(property: 'is_logdrain_custom_enabled', type: 'boolean'),
new OA\Property(property: 'logdrain_custom_config', type: 'string', description: 'Only present with read:sensitive.'),
new OA\Property(property: 'logdrain_custom_config_parser', type: 'string', description: 'Only present with read:sensitive.'),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function show(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
return response()->json($this->transform($server));
}
#[OA\Patch(
summary: 'Update log drain settings',
description: 'Update New Relic, Axiom, or custom log drain settings for a server owned by the authenticated team.',
path: '/servers/{uuid}/log-drains',
operationId: 'update-server-log-drains',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'is_logdrain_newrelic_enabled', type: 'boolean'),
new OA\Property(property: 'logdrain_newrelic_license_key', type: 'string'),
new OA\Property(property: 'logdrain_newrelic_base_uri', type: 'string'),
new OA\Property(property: 'is_logdrain_axiom_enabled', type: 'boolean'),
new OA\Property(property: 'logdrain_axiom_dataset_name', type: 'string'),
new OA\Property(property: 'logdrain_axiom_api_key', type: 'string'),
new OA\Property(property: 'is_logdrain_custom_enabled', type: 'boolean'),
new OA\Property(property: 'logdrain_custom_config', type: 'string'),
new OA\Property(property: 'logdrain_custom_config_parser', type: 'string'),
],
type: 'object',
),
),
responses: [
new OA\Response(response: 200, description: 'Updated log drain settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function update(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$validator = customApiValidator($request->all(), [
'is_logdrain_newrelic_enabled' => 'boolean',
'logdrain_newrelic_license_key' => ['nullable', 'string', 'regex:/^[a-zA-Z0-9_\-\.]+$/'],
'logdrain_newrelic_base_uri' => 'nullable|url',
'is_logdrain_axiom_enabled' => 'boolean',
'logdrain_axiom_dataset_name' => ['nullable', 'string', 'regex:/^[a-zA-Z0-9_\-\.]+$/'],
'logdrain_axiom_api_key' => ['nullable', 'string', 'regex:/^[a-zA-Z0-9_\-\.]+$/'],
'is_logdrain_custom_enabled' => 'boolean',
'logdrain_custom_config' => 'nullable|string',
'logdrain_custom_config_parser' => 'nullable|string',
]);
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$settings = $server->settings;
foreach (self::ALLOWED_FIELDS as $field) {
if ($request->has($field)) {
$settings->{$field} = $request->input($field);
}
}
// Conditional required fields when enabling a drain type (matches Livewire).
if ($settings->is_logdrain_newrelic_enabled) {
$errors = [];
if (blank($settings->logdrain_newrelic_license_key)) {
$errors['logdrain_newrelic_license_key'] = ['The New Relic license key is required when New Relic log drain is enabled.'];
}
if (blank($settings->logdrain_newrelic_base_uri)) {
$errors['logdrain_newrelic_base_uri'] = ['The New Relic base URI is required when New Relic log drain is enabled.'];
}
if ($errors !== []) {
return response()->json(['message' => 'Validation failed.', 'errors' => $errors], 422);
}
}
if ($settings->is_logdrain_axiom_enabled) {
$errors = [];
if (blank($settings->logdrain_axiom_dataset_name)) {
$errors['logdrain_axiom_dataset_name'] = ['The Axiom dataset name is required when Axiom log drain is enabled.'];
}
if (blank($settings->logdrain_axiom_api_key)) {
$errors['logdrain_axiom_api_key'] = ['The Axiom API key is required when Axiom log drain is enabled.'];
}
if ($errors !== []) {
return response()->json(['message' => 'Validation failed.', 'errors' => $errors], 422);
}
}
if ($settings->is_logdrain_custom_enabled && blank($settings->logdrain_custom_config)) {
return response()->json([
'message' => 'Validation failed.',
'errors' => [
'logdrain_custom_config' => ['The custom log drain config is required when custom log drain is enabled.'],
],
], 422);
}
$settings->save();
$server->refresh();
// Match Livewire instantSave: start or stop the drain service after settings change.
if ($server->isLogDrainEnabled()) {
StartLogDrain::dispatch($server);
} else {
StopLogDrain::dispatch($server);
}
auditLog('api.server.log_drains.updated', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
'changed_fields' => array_values(array_intersect(self::ALLOWED_FIELDS, array_keys($request->all()))),
]);
return response()->json($this->transform($server));
}
}
@@ -0,0 +1,422 @@
<?php
namespace App\Http\Controllers\Api;
use App\Actions\Proxy\SaveProxyConfiguration;
use App\Enums\ProxyTypes;
use App\Http\Controllers\Controller;
use App\Jobs\RestartProxyJob;
use App\Models\Server;
use App\Rules\SafeExternalUrl;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class ServerProxyController extends Controller
{
private function teamIdOrAbort(): int|JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
return $teamId;
}
private function findServerForTeam(int $teamId, string $uuid): ?Server
{
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
}
private function canReadSensitive(): bool
{
return request()->attributes->get('can_read_sensitive', false) === true;
}
/**
* @return array{
* proxy_type: string|null,
* status: string|null,
* redirect_enabled: bool,
* redirect_url: string|null,
* generate_exact_labels: bool,
* configuration?: string|null
* }
*/
private function payload(Server $server, bool $includeConfiguration = true): array
{
$payload = [
'proxy_type' => $server->proxyType(),
'status' => data_get($server->proxy, 'status'),
'redirect_enabled' => (bool) data_get($server->proxy, 'redirect_enabled', true),
'redirect_url' => data_get($server->proxy, 'redirect_url'),
'generate_exact_labels' => (bool) ($server->settings->generate_exact_labels ?? false),
];
// Proxy compose can contain secrets; only expose with read:sensitive (and admin) like other APIs.
if ($includeConfiguration && $this->canReadSensitive()) {
// Prefer DB-stored config only — never SSH or regenerate for GET.
$configuration = $server->proxy->get('last_saved_proxy_configuration');
$payload['configuration'] = filled($configuration) ? $configuration : null;
}
return $payload;
}
#[OA\Get(
summary: 'Get server proxy',
description: 'Get proxy settings for a server owned by the authenticated team. The raw proxy configuration is only returned when the token has `read:sensitive` (or `root`) and the user is a team admin/owner, and only when already stored in the database (no remote fetch).',
path: '/servers/{uuid}/proxy',
operationId: 'get-server-proxy',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Server proxy settings.',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(property: 'proxy_type', type: 'string', nullable: true, example: 'TRAEFIK'),
new OA\Property(property: 'status', type: 'string', nullable: true, example: 'running'),
new OA\Property(property: 'redirect_enabled', type: 'boolean', example: true),
new OA\Property(property: 'redirect_url', type: 'string', nullable: true, example: 'https://example.com'),
new OA\Property(property: 'generate_exact_labels', type: 'boolean', example: false),
new OA\Property(property: 'configuration', type: 'string', nullable: true, description: 'Docker Compose proxy configuration when stored in the database. Only present with read:sensitive.'),
]
)
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function show(Request $request, string $uuid): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$server = $this->findServerForTeam($teamId, $uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
return response()->json($this->payload($server));
}
#[OA\Patch(
summary: 'Update server proxy',
description: 'Update proxy redirect settings, exact labels generation, and optionally the proxy type for a team-owned server.',
path: '/servers/{uuid}/proxy',
operationId: 'update-server-proxy',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(property: 'redirect_enabled', type: 'boolean'),
new OA\Property(property: 'redirect_url', type: 'string', nullable: true, description: 'Public http(s) redirect URL, or null to clear.'),
new OA\Property(property: 'generate_exact_labels', type: 'boolean'),
new OA\Property(property: 'proxy_type', type: 'string', enum: ['traefik', 'caddy', 'nginx', 'none'], description: 'Proxy type (case-insensitive).'),
]
)
),
responses: [
new OA\Response(
response: 200,
description: 'Proxy settings updated.',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(property: 'proxy_type', type: 'string', nullable: true),
new OA\Property(property: 'status', type: 'string', nullable: true),
new OA\Property(property: 'redirect_enabled', type: 'boolean'),
new OA\Property(property: 'redirect_url', type: 'string', nullable: true),
new OA\Property(property: 'generate_exact_labels', type: 'boolean'),
new OA\Property(property: 'configuration', type: 'string', nullable: true),
]
)
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function update(Request $request, string $uuid): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$allowedFields = ['redirect_enabled', 'redirect_url', 'generate_exact_labels', 'proxy_type'];
$validator = customApiValidator($request->all(), [
'redirect_enabled' => 'boolean',
'redirect_url' => ['nullable', 'string', new SafeExternalUrl],
'generate_exact_labels' => 'boolean',
'proxy_type' => 'string|nullable',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$server = $this->findServerForTeam($teamId, $uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
if ($request->has('proxy_type') && filled($request->proxy_type)) {
$validProxyTypes = collect(ProxyTypes::cases())->map(fn (ProxyTypes $type) => str($type->value)->lower());
if (! $validProxyTypes->contains(str($request->proxy_type)->lower())) {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['proxy_type' => ['Invalid proxy type.']],
], 422);
}
}
$changedFields = array_values(array_intersect($allowedFields, array_keys($request->all())));
$redirectChanged = false;
if ($request->has('redirect_enabled')) {
$server->proxy->redirect_enabled = $request->boolean('redirect_enabled');
$redirectChanged = true;
}
if ($request->exists('redirect_url')) {
$server->proxy->redirect_url = $request->input('redirect_url') ?: null;
$redirectChanged = true;
}
if ($redirectChanged) {
$server->save();
}
if ($request->has('generate_exact_labels')) {
$server->settings->generate_exact_labels = $request->boolean('generate_exact_labels');
$server->settings->save();
}
if ($request->has('proxy_type') && filled($request->proxy_type)) {
$server->changeProxy($request->proxy_type, async: true);
$server->refresh();
}
// Apply redirect file on the server only when reachable (DB settings always saved above).
if ($redirectChanged && $server->isFunctional()) {
$server->setupDefaultRedirect();
}
auditLog('api.server.proxy.updated', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
'changed_fields' => $changedFields,
]);
return response()->json($this->payload($server->fresh()));
}
#[OA\Put(
summary: 'Save server proxy configuration',
description: 'Save the raw proxy Docker Compose configuration for a team-owned server. Multi-line configuration must be base64 encoded (same pattern as other compose payloads).',
path: '/servers/{uuid}/proxy/configuration',
operationId: 'save-server-proxy-configuration',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['configuration'],
type: 'object',
properties: [
new OA\Property(
property: 'configuration',
type: 'string',
description: 'Proxy docker-compose YAML. Prefer base64 encoding for multi-line content.'
),
]
)
),
responses: [
new OA\Response(
response: 200,
description: 'Proxy configuration saved.',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(property: 'message', type: 'string', example: 'Proxy configuration saved.'),
new OA\Property(property: 'proxy_type', type: 'string', nullable: true),
new OA\Property(property: 'status', type: 'string', nullable: true),
new OA\Property(property: 'redirect_enabled', type: 'boolean'),
new OA\Property(property: 'redirect_url', type: 'string', nullable: true),
new OA\Property(property: 'generate_exact_labels', type: 'boolean'),
new OA\Property(property: 'configuration', type: 'string', nullable: true),
]
)
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function saveConfiguration(Request $request, string $uuid): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$allowedFields = ['configuration'];
$validator = customApiValidator($request->all(), [
'configuration' => 'required|string',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$server = $this->findServerForTeam($teamId, $uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$configuration = $request->input('configuration');
if (isBase64Encoded($configuration)) {
$decoded = base64_decode($configuration, true);
if ($decoded === false || mb_detect_encoding($decoded, 'UTF-8', true) === false) {
return response()->json([
'message' => 'Validation failed.',
'errors' => [
'configuration' => ['The configuration should be valid base64-encoded UTF-8 text.'],
],
], 422);
}
$configuration = $decoded;
}
if (! filled(trim($configuration))) {
return response()->json([
'message' => 'Validation failed.',
'errors' => [
'configuration' => ['The configuration field is required.'],
],
], 422);
}
SaveProxyConfiguration::run($server, $configuration);
auditLog('api.server.proxy.configuration_saved', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
]);
$payload = $this->payload($server->fresh());
$payload['message'] = 'Proxy configuration saved.';
return response()->json($payload);
}
#[OA\Post(
summary: 'Restart server proxy',
description: 'Queue a proxy restart for a team-owned server.',
path: '/servers/{uuid}/proxy/restart',
operationId: 'restart-server-proxy',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Proxy restart queued.',
content: new OA\JsonContent(
type: 'object',
properties: [
new OA\Property(property: 'message', type: 'string', example: 'Proxy restart queued.'),
]
)
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function restart(Request $request, string $uuid): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$server = $this->findServerForTeam($teamId, $uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('manageProxy', $server);
RestartProxyJob::dispatch($server);
auditLog('api.server.proxy.restarted', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
]);
return response()->json(['message' => 'Proxy restart queued.']);
}
}
@@ -0,0 +1,226 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Server;
use App\Models\ServerSetting;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class ServerSentinelController extends Controller
{
private const ALLOWED_FIELDS = [
'is_sentinel_enabled',
'is_metrics_enabled',
'is_sentinel_debug_enabled',
'sentinel_token',
'sentinel_metrics_refresh_rate_seconds',
'sentinel_metrics_history_days',
'sentinel_push_interval_seconds',
'sentinel_custom_url',
];
private function findServerForTeam(int $teamId, string $uuid): ?Server
{
return Server::whereTeamId($teamId)->whereUuid($uuid)->first();
}
private function canReadSensitive(): bool
{
return request()->attributes->get('can_read_sensitive', false) === true;
}
private function transform(Server $server): array
{
$settings = $server->settings;
$payload = [
'is_sentinel_enabled' => (bool) $settings->is_sentinel_enabled,
'is_metrics_enabled' => (bool) $settings->is_metrics_enabled,
'is_sentinel_debug_enabled' => (bool) $settings->is_sentinel_debug_enabled,
'sentinel_metrics_refresh_rate_seconds' => (int) $settings->sentinel_metrics_refresh_rate_seconds,
'sentinel_metrics_history_days' => (int) $settings->sentinel_metrics_history_days,
'sentinel_push_interval_seconds' => (int) $settings->sentinel_push_interval_seconds,
'sentinel_updated_at' => $server->sentinel_updated_at,
];
if ($this->canReadSensitive()) {
$payload['sentinel_token'] = $settings->sentinel_token;
$payload['sentinel_custom_url'] = $settings->sentinel_custom_url;
}
return $payload;
}
#[OA\Get(
summary: 'Get Sentinel settings',
description: 'Get Sentinel settings for a server owned by the authenticated team. sentinel_token and sentinel_custom_url require the read:sensitive or root token ability.',
path: '/servers/{uuid}/sentinel',
operationId: 'get-server-sentinel',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Sentinel settings.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'is_sentinel_enabled', type: 'boolean'),
new OA\Property(property: 'is_metrics_enabled', type: 'boolean'),
new OA\Property(property: 'is_sentinel_debug_enabled', type: 'boolean'),
new OA\Property(property: 'sentinel_token', type: 'string', description: 'Only present with read:sensitive.'),
new OA\Property(property: 'sentinel_metrics_refresh_rate_seconds', type: 'integer'),
new OA\Property(property: 'sentinel_metrics_history_days', type: 'integer'),
new OA\Property(property: 'sentinel_push_interval_seconds', type: 'integer'),
new OA\Property(property: 'sentinel_custom_url', type: 'string', description: 'Only present with read:sensitive.'),
new OA\Property(property: 'sentinel_updated_at', type: 'string', nullable: true),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function show(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
return response()->json($this->transform($server));
}
#[OA\Patch(
summary: 'Update Sentinel settings',
description: 'Update Sentinel settings for a server owned by the authenticated team. Changing token/metrics timing fields may restart Sentinel.',
path: '/servers/{uuid}/sentinel',
operationId: 'update-server-sentinel',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'is_sentinel_enabled', type: 'boolean'),
new OA\Property(property: 'is_metrics_enabled', type: 'boolean'),
new OA\Property(property: 'is_sentinel_debug_enabled', type: 'boolean'),
new OA\Property(property: 'sentinel_token', type: 'string'),
new OA\Property(property: 'sentinel_metrics_refresh_rate_seconds', type: 'integer', minimum: 1),
new OA\Property(property: 'sentinel_metrics_history_days', type: 'integer', minimum: 1),
new OA\Property(property: 'sentinel_push_interval_seconds', type: 'integer', minimum: 10),
new OA\Property(property: 'sentinel_custom_url', type: 'string', nullable: true),
],
type: 'object',
),
),
responses: [
new OA\Response(response: 200, description: 'Updated Sentinel settings.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function update(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$server = $this->findServerForTeam($teamId, $request->uuid);
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$validator = customApiValidator($request->all(), [
'is_sentinel_enabled' => 'boolean',
'is_metrics_enabled' => 'boolean',
'is_sentinel_debug_enabled' => 'boolean',
'sentinel_token' => ['string', 'max:500', 'regex:/\A[a-zA-Z0-9._\-+=\/]+\z/'],
'sentinel_metrics_refresh_rate_seconds' => 'integer|min:1',
'sentinel_metrics_history_days' => 'integer|min:1',
'sentinel_push_interval_seconds' => 'integer|min:10',
'sentinel_custom_url' => 'nullable|url',
]);
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
if ($request->has('sentinel_token') && ! ServerSetting::isValidSentinelToken($request->input('sentinel_token'))) {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['sentinel_token' => ['Invalid sentinel token characters.']],
], 422);
}
$settings = $server->settings;
$enablingSentinel = $request->has('is_sentinel_enabled')
&& $request->boolean('is_sentinel_enabled')
&& ! $settings->is_sentinel_enabled;
if ($enablingSentinel && $server->isBuildServer()) {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['is_sentinel_enabled' => ['Sentinel cannot be enabled on build servers.']],
], 422);
}
foreach (self::ALLOWED_FIELDS as $field) {
if ($request->has($field)) {
$settings->{$field} = $request->input($field);
}
}
// Disabling Sentinel also clears related toggles (matches Livewire toggleSentinel).
if ($request->has('is_sentinel_enabled') && ! $request->boolean('is_sentinel_enabled')) {
$settings->is_metrics_enabled = false;
$settings->is_sentinel_debug_enabled = false;
}
$settings->save();
auditLog('api.server.sentinel.updated', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'server_name' => $server->name,
'changed_fields' => array_values(array_intersect(self::ALLOWED_FIELDS, array_keys($request->all()))),
]);
return response()->json($this->transform($server->refresh()));
}
}
@@ -0,0 +1,510 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Server;
use App\Services\ServerTransfer\ServerTransferBundle;
use App\Services\ServerTransfer\ServerTransferClaimer;
use App\Services\ServerTransfer\ServerTransferExporter;
use App\Services\ServerTransfer\ServerTransferImporter;
use App\Services\ServerTransfer\ServerTransferMigrator;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use OpenApi\Attributes as OA;
use Throwable;
class ServerTransferController extends Controller
{
public function __construct(
private ServerTransferExporter $exporter,
private ServerTransferImporter $importer,
private ServerTransferClaimer $claimer,
private ServerTransferMigrator $migrator,
) {
abort_unless(isDev(), 404);
}
#[OA\Post(
summary: 'Migrate server to another Coolify instance',
description: 'One-shot handoff: export this server, import+claim on the target instance (using the provided token), then disable automations here. Requires read:sensitive and write.',
path: '/servers/{uuid}/migrate',
operationId: 'migrate-server-between-instances',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['target_url', 'target_token'],
properties: [
new OA\Property(property: 'target_url', type: 'string', example: 'https://coolify-b.example.com'),
new OA\Property(property: 'target_token', type: 'string', description: 'API token on the target instance (root or write)'),
new OA\Property(property: 'write_remote', type: 'boolean', default: false),
new OA\Property(property: 'rebind_sentinel', type: 'boolean', default: true),
new OA\Property(property: 'preserve_uuids', type: 'boolean', default: true),
new OA\Property(property: 'adopt_mode', type: 'boolean', default: true),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Migrated'),
new OA\Response(response: 403, description: 'Missing sensitive permission'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, description: 'Validation or remote import failed'),
]
)]
public function migrate(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
if (! $this->canReadSensitive($request)) {
return response()->json([
'message' => 'Migrating a server requires a token with read:sensitive (or root) ability and an admin/owner team role.',
], 403);
}
$server = Server::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'target_url' => 'required|string|url',
'target_token' => 'required|string',
'write_remote' => 'boolean|nullable',
'rebind_sentinel' => 'boolean|nullable',
'preserve_uuids' => 'boolean|nullable',
'adopt_mode' => 'boolean|nullable',
]);
$allowedFields = ['target_url', 'target_token', 'write_remote', 'rebind_sentinel', 'preserve_uuids', 'adopt_mode'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || $extraFields !== []) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
try {
$result = $this->migrator->migrate(
server: $server,
targetUrl: $request->string('target_url')->toString(),
targetToken: $request->string('target_token')->toString(),
writeRemote: $request->boolean('write_remote', false),
rebindSentinel: $request->boolean('rebind_sentinel', true),
preserveUuids: $request->boolean('preserve_uuids', true),
adoptMode: $request->boolean('adopt_mode', true),
);
} catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
auditLog('api.server.migrate', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'export_id' => $result['export_id'],
'target_url' => $result['target_url'],
]);
return response()->json($result);
}
#[OA\Get(
summary: 'Export server transfer bundle',
description: 'Export a server and all resources hosted on it as a versioned transfer bundle for moving between Coolify instances. Requires read:sensitive.',
path: '/servers/{uuid}/export',
operationId: 'export-server-transfer-bundle',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'encrypt', in: 'query', required: false, description: 'If true and passphrase is provided, return an encrypted envelope.', schema: new OA\Schema(type: 'boolean')),
new OA\Parameter(name: 'passphrase', in: 'query', required: false, description: 'Passphrase used when encrypt=true.', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Transfer bundle'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 403, description: 'Missing sensitive permission'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function export(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
if (! $this->canReadSensitive($request)) {
return response()->json([
'message' => 'Exporting a server requires a token with read:sensitive (or root) ability and an admin/owner team role.',
], 403);
}
$server = Server::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
try {
$bundle = $this->exporter->export($server, includeSensitive: true);
} catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
auditLog('api.server.export', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'export_id' => data_get($bundle, 'export_id'),
]);
if ($request->boolean('encrypt') && $request->filled('passphrase')) {
return response()->json(
ServerTransferBundle::encryptWithPassphrase($bundle, $request->string('passphrase')->toString())
);
}
return response()->json($bundle);
}
#[OA\Post(
summary: 'Import server transfer bundle',
description: 'Import a server transfer bundle into this Coolify instance (adopt mode by default).',
path: '/servers/import',
operationId: 'import-server-transfer-bundle',
security: [['bearerAuth' => []]],
tags: ['Servers'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'bundle', type: 'object', description: 'Plain or encrypted transfer bundle'),
new OA\Property(property: 'passphrase', type: 'string', nullable: true),
new OA\Property(property: 'dry_run', type: 'boolean', default: false),
new OA\Property(property: 'preserve_uuids', type: 'boolean', default: true),
new OA\Property(property: 'adopt_mode', type: 'boolean', default: true, description: 'Import without forcing redeploy; keep statuses for adoption'),
new OA\Property(property: 'claim', type: 'boolean', default: true, description: 'Automatically claim the host for this instance after import'),
new OA\Property(property: 'write_remote', type: 'boolean', default: false, description: 'When claiming, write ownership file on the host via SSH'),
new OA\Property(property: 'rebind_sentinel', type: 'boolean', default: true, description: 'When claiming, rebind Sentinel to this instance'),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Dry-run result'),
new OA\Response(response: 201, description: 'Imported'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 422, description: 'Validation failed'),
]
)]
public function import(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$this->authorize('create', Server::class);
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'bundle' => 'required|array',
'passphrase' => 'string|nullable',
'dry_run' => 'boolean|nullable',
'preserve_uuids' => 'boolean|nullable',
'adopt_mode' => 'boolean|nullable',
'claim' => 'boolean|nullable',
'write_remote' => 'boolean|nullable',
'rebind_sentinel' => 'boolean|nullable',
]);
$allowedFields = ['bundle', 'passphrase', 'dry_run', 'preserve_uuids', 'adopt_mode', 'claim', 'write_remote', 'rebind_sentinel'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || $extraFields !== []) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$bundle = $request->input('bundle', []);
if (data_get($bundle, 'encrypted')) {
if (! $request->filled('passphrase')) {
return response()->json(['message' => 'Passphrase is required for encrypted bundles.'], 422);
}
try {
$bundle = ServerTransferBundle::decryptWithPassphrase($bundle, $request->string('passphrase')->toString());
} catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
}
try {
$result = $this->importer->import(
bundle: $bundle,
teamId: $teamId,
dryRun: $request->boolean('dry_run', false),
preserveUuids: $request->boolean('preserve_uuids', true),
adoptMode: $request->boolean('adopt_mode', true),
claim: $request->boolean('claim', true),
writeRemote: $request->boolean('write_remote', false),
rebindSentinel: $request->boolean('rebind_sentinel', true),
);
} catch (Throwable $e) {
$status = $e instanceof ValidationException ? 422 : 422;
$payload = ['message' => $e->getMessage()];
if ($e instanceof ValidationException) {
$payload['errors'] = $e->errors();
}
return response()->json($payload, $status);
}
auditLog('api.server.import', [
'team_id' => $teamId,
'server_uuid' => $result['server_uuid'],
'export_id' => $result['export_id'],
'dry_run' => $result['dry_run'],
]);
return response()->json($result, $result['dry_run'] ? 200 : 201);
}
#[OA\Post(
summary: 'Claim imported server',
description: 'Claim a managed host for this instance: write ownership file and rebind Sentinel.',
path: '/servers/{uuid}/claim',
operationId: 'claim-server',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'write_remote', type: 'boolean', default: true),
new OA\Property(property: 'rebind_sentinel', type: 'boolean', default: true),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Claim result'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function claim(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = Server::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$validator = customApiValidator($request->all(), [
'write_remote' => 'boolean|nullable',
'rebind_sentinel' => 'boolean|nullable',
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Validation failed.',
'errors' => $validator->errors(),
], 422);
}
try {
$result = $this->claimer->claim(
$server,
writeRemote: $request->boolean('write_remote', true),
rebindSentinel: $request->boolean('rebind_sentinel', true),
);
} catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
auditLog('api.server.claim', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'claim_written' => $result['claim_written'],
]);
return response()->json($result);
}
#[OA\Post(
summary: 'Mark server transferred',
description: 'Source-instance step: disable automations after a successful export/import handoff.',
path: '/servers/{uuid}/transfer/complete',
operationId: 'complete-server-transfer',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'export_id', type: 'string', nullable: true),
new OA\Property(property: 'target_instance_url', type: 'string', nullable: true),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Marked transferred'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function complete(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$server = Server::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('update', $server);
$validator = customApiValidator($request->all(), [
'export_id' => 'string|nullable',
'target_instance_url' => 'string|nullable',
]);
if ($validator->fails()) {
return response()->json([
'message' => 'Validation failed.',
'errors' => $validator->errors(),
], 422);
}
try {
$result = $this->claimer->markTransferred(
$server,
exportId: $request->input('export_id'),
targetInstanceUrl: $request->input('target_instance_url'),
);
} catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
auditLog('api.server.transfer_complete', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'export_id' => $request->input('export_id'),
]);
return response()->json($result);
}
#[OA\Post(
summary: 'Write transfer bundle to server mailbox',
description: 'Write an export bundle to /data/coolify/exports on the managed host for air-gapped import.',
path: '/servers/{uuid}/export/mailbox',
operationId: 'export-server-transfer-mailbox',
security: [['bearerAuth' => []]],
tags: ['Servers'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'passphrase', type: 'string', nullable: true),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Mailbox write result'),
new OA\Response(response: 403, description: 'Missing sensitive permission'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function writeMailbox(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
if (! $this->canReadSensitive($request)) {
return response()->json([
'message' => 'Writing a transfer mailbox requires read:sensitive (or root) ability and an admin/owner team role.',
], 403);
}
$server = Server::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
$this->authorize('view', $server);
try {
$bundle = $this->exporter->export($server, includeSensitive: true);
$result = $this->claimer->writeMailbox(
$server,
$bundle,
$request->filled('passphrase') ? $request->string('passphrase')->toString() : null,
);
} catch (Throwable $e) {
return response()->json(['message' => $e->getMessage()], 422);
}
auditLog('api.server.export_mailbox', [
'team_id' => $teamId,
'server_uuid' => $server->uuid,
'export_id' => data_get($bundle, 'export_id'),
'path' => $result['path'],
]);
return response()->json([
'export_id' => data_get($bundle, 'export_id'),
'path' => $result['path'],
'written' => $result['written'],
'message' => $result['written']
? 'Transfer bundle written to server mailbox.'
: 'Failed to write mailbox on remote host.',
], $result['written'] ? 200 : 422);
}
private function canReadSensitive(Request $request): bool
{
return (bool) $request->attributes->get('can_read_sensitive', false);
}
}
+15 -2
View File
@@ -663,7 +663,7 @@ class ServersController extends Controller
)]
public function update_server(Request $request)
{
$allowedFields = ['name', 'description', 'ip', 'port', 'user', 'private_key_uuid', 'is_build_server', 'instant_validate', 'proxy_type', 'concurrent_builds', 'dynamic_timeout', 'deployment_queue_limit', 'server_disk_usage_notification_threshold', 'server_disk_usage_check_frequency', 'connection_timeout'];
$allowedFields = ['name', 'description', 'ip', 'port', 'user', 'private_key_uuid', 'is_build_server', 'instant_validate', 'proxy_type', 'concurrent_builds', 'dynamic_timeout', 'deployment_queue_limit', 'server_disk_usage_notification_threshold', 'server_disk_usage_check_frequency', 'connection_timeout', 'is_terminal_enabled'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
@@ -690,6 +690,7 @@ class ServersController extends Controller
'server_disk_usage_notification_threshold' => 'integer|min:1|max:100',
'server_disk_usage_check_frequency' => 'string',
'connection_timeout' => 'integer|min:1|max:300',
'is_terminal_enabled' => 'boolean|nullable',
], [
...ValidationPatterns::serverUsernameMessages(),
]);
@@ -751,6 +752,12 @@ class ServersController extends Controller
]);
}
if ($request->has('is_terminal_enabled')) {
$server->settings()->update([
'is_terminal_enabled' => $request->boolean('is_terminal_enabled'),
]);
}
$advancedSettings = $request->only(['concurrent_builds', 'dynamic_timeout', 'deployment_queue_limit', 'server_disk_usage_notification_threshold', 'server_disk_usage_check_frequency', 'connection_timeout']);
if (! empty($advancedSettings)) {
$server->settings()->update(array_filter($advancedSettings, fn ($value) => ! is_null($value)));
@@ -851,7 +858,7 @@ class ServersController extends Controller
if ($server->definedResources()->count() > 0 && ! $force) {
return response()->json(['message' => 'Server has resources. Use ?force=true to delete all resources and the server, or delete resources manually first.'], 400);
}
if ($server->isLocalhost()) {
if ($server->is_coolify_host) {
return response()->json(['message' => 'Local server cannot be deleted.'], 400);
}
@@ -963,6 +970,12 @@ class ServersController extends Controller
}
$this->authorize('update', $server);
if (! $server->canBeValidated()) {
return response()->json([
'message' => 'This server was transferred to another Coolify instance and cannot be revalidated here.',
], 422);
}
$validator = customApiValidator($request->all(), [
'install' => 'boolean',
]);
@@ -242,6 +242,13 @@ class ServiceApplicationsController extends Controller
nullable: true,
description: 'Comma-separated list of URLs (e.g. "http://app.example.com:8080,https://app2.example.com"). Stored as fqdn.'
),
'noindex_domains' => new OA\Property(
property: 'noindex_domains',
type: 'array',
items: new OA\Items(type: 'string'),
description: 'The subset of the service application domains served with an X-Robots-Tag: noindex, nofollow response header, keeping them out of search engines. Entries that are not among the domains are ignored.',
nullable: true,
),
'human_name' => new OA\Property(property: 'human_name', type: 'string', nullable: true),
'description' => new OA\Property(property: 'description', type: 'string', nullable: true),
'image' => new OA\Property(property: 'image', type: 'string', nullable: true),
@@ -313,6 +320,7 @@ class ServiceApplicationsController extends Controller
$allowedFields = [
'url',
'noindex_domains',
'human_name',
'description',
'image',
@@ -324,6 +332,8 @@ class ServiceApplicationsController extends Controller
$validationRules = [
'url' => 'nullable|string',
'noindex_domains' => 'sometimes|array|nullable',
'noindex_domains.*' => 'string',
'human_name' => 'nullable|string|max:255',
'description' => 'nullable|string',
'image' => 'nullable|string',
@@ -7,17 +7,21 @@ use App\Actions\Service\StartService;
use App\Actions\Service\StopService;
use App\Http\Controllers\Controller;
use App\Jobs\DeleteResourceJob;
use App\Jobs\VolumeCloneJob;
use App\Models\EnvironmentVariable;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use App\Support\ValidationPatterns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Validator;
use OpenApi\Attributes as OA;
use Symfony\Component\Yaml\Yaml;
@@ -1970,6 +1974,54 @@ class ServicesController extends Controller
return moveResourceToEnvironment($request, $service, 'Service', $teamId);
}
#[OA\Post(
summary: 'Migrate to Server',
description: 'Migrate a service to another destination/server owned by the authenticated team. Stops the service, optionally transfers persistent volume data when both servers are managed by Coolify, and updates database records. Redeploy after migration completes.',
path: '/services/{uuid}/migrate',
operationId: 'migrate-service-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Services'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the service.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string', description: 'UUID of the target destination.'),
new OA\Property(property: 'migrate_volumes', type: 'boolean', default: true, description: 'Whether to transfer persistent volume data when migrating across servers.'),
]
)
),
responses: [
new OA\Response(response: 200, description: 'Service migration started or completed.'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function migrate_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['message' => 'UUID is required.'], 400);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
$this->authorize('update', $service);
return migrateResourceToDestination($request, $service, 'Service', $teamId);
}
#[OA\Post(
summary: 'Start',
description: 'Start service.',
@@ -3075,4 +3127,241 @@ class ServicesController extends Controller
{
return $this->deleteTag($request);
}
#[OA\Post(
summary: 'Clone',
description: 'Clone a service to a destination owned by the authenticated team.',
path: '/services/{uuid}/clone',
operationId: 'clone-service-by-uuid',
security: [['bearerAuth' => []]],
tags: ['Services'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'UUID of the service.', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['destination_uuid'],
properties: [
new OA\Property(property: 'destination_uuid', type: 'string'),
new OA\Property(property: 'name', type: 'string', nullable: true),
new OA\Property(property: 'clone_volumes', type: 'boolean', default: false),
]
)
),
responses: [
new OA\Response(response: 201, description: 'Service cloned.'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function clone_by_uuid(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'destination_uuid' => 'required|string',
'name' => 'string|max:255|nullable',
'clone_volumes' => 'boolean',
]);
$allowedFields = ['destination_uuid', 'name', 'clone_volumes'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->route('uuid'))->first();
if (! $service) {
return response()->json(['message' => 'Service not found.'], 404);
}
$this->authorize('update', $service);
$destination = StandaloneDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first()
?? SwarmDocker::ownedByCurrentTeamAPI($teamId)->where('uuid', $request->destination_uuid)->first();
if (! $destination || ! $destination->server?->canHostResources()) {
return response()->json(['message' => 'Destination not found.'], 404);
}
$uuid = new_public_id();
$name = $request->filled('name')
? $request->string('name')->toString()
: $service->name.'-clone-'.$uuid;
$cloneVolumeData = $request->boolean('clone_volumes', false);
$newService = $service->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => $uuid,
'name' => $name,
'destination_id' => $destination->id,
'destination_type' => $destination->getMorphClass(),
'server_id' => $destination->server_id,
]);
$newService->save();
foreach ($service->tags as $tag) {
$newService->tags()->attach($tag->id);
}
foreach ($service->scheduled_tasks()->get() as $task) {
$task->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => new_public_id(),
'service_id' => $newService->id,
'team_id' => $teamId,
])->save();
}
foreach ($service->environment_variables()->get() as $environmentVariable) {
$environmentVariable->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'resourceable_id' => $newService->id,
'resourceable_type' => $newService->getMorphClass(),
])->save();
}
// Create applications/databases (and their volumes) for the clone first.
// Child rows are not copied by Service::replicate().
$newService->parse();
$newService->refresh();
$sourceApplicationsByName = $service->applications()->get()->keyBy('name');
$sourceDatabasesByName = $service->databases()->get()->keyBy('name');
$pendingVolumeClones = [];
$sourceServer = $service->destination?->server;
$targetServer = $newService->destination?->server;
foreach ($newService->applications()->get() as $application) {
$application->fill(['status' => 'exited'])->save();
$sourceApplication = $sourceApplicationsByName->get($application->name);
if (! $sourceApplication) {
continue;
}
if ($cloneVolumeData) {
$targetVolumesByMount = $application->persistentStorages()->get()->keyBy('mount_path');
foreach ($sourceApplication->persistentStorages()->get() as $sourceVolume) {
$targetVolume = $targetVolumesByMount->get($sourceVolume->mount_path);
if (! $targetVolume) {
continue;
}
$pendingVolumeClones[] = [
'source' => $sourceVolume->name,
'target' => $targetVolume->name,
'model' => $targetVolume,
];
}
}
}
foreach ($newService->databases()->get() as $database) {
$database->fill(['status' => 'exited'])->save();
$sourceDatabase = $sourceDatabasesByName->get($database->name);
if (! $sourceDatabase) {
continue;
}
if ($cloneVolumeData) {
$targetVolumesByMount = $database->persistentStorages()->get()->keyBy('mount_path');
foreach ($sourceDatabase->persistentStorages()->get() as $sourceVolume) {
$targetVolume = $targetVolumesByMount->get($sourceVolume->mount_path);
if (! $targetVolume) {
continue;
}
$pendingVolumeClones[] = [
'source' => $sourceVolume->name,
'target' => $targetVolume->name,
'model' => $targetVolume,
];
}
}
foreach ($sourceDatabase->scheduledBackups()->get() as $backup) {
$backup->replicate([
'id',
'created_at',
'updated_at',
])->fill([
'uuid' => new_public_id(),
'database_id' => $database->id,
'database_type' => $database->getMorphClass(),
'team_id' => $teamId,
])->save();
}
}
if ($cloneVolumeData && $pendingVolumeClones !== [] && $sourceServer && $targetServer) {
try {
$chain = [
function () use ($service) {
StopService::run($service);
},
];
foreach ($pendingVolumeClones as $clone) {
$chain[] = new VolumeCloneJob(
$clone['source'],
$clone['target'],
$sourceServer,
$targetServer,
$clone['model'],
);
}
$chain[] = function () use ($service) {
StartService::run($service);
};
Bus::chain($chain)->onQueue('high')->dispatch();
} catch (\Exception $e) {
\Log::error('Failed to queue service volume clone for '.$service->uuid.': '.$e->getMessage());
}
}
auditLog('api.service.cloned', [
'team_id' => $teamId,
'source_uuid' => $service->uuid,
'service_uuid' => $newService->uuid,
'service_name' => $newService->name,
'destination_uuid' => $destination->uuid,
'clone_volumes' => $cloneVolumeData,
]);
return response()->json([
'uuid' => $newService->uuid,
'message' => 'Service cloned.',
], 201);
}
}
@@ -0,0 +1,907 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
use App\Models\SharedEnvironmentVariable;
use App\Support\ValidationPatterns;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use OpenApi\Attributes as OA;
class SharedEnvironmentVariablesController extends Controller
{
private const ALLOWED_FIELDS = ['key', 'value', 'is_literal', 'is_multiline', 'is_shown_once', 'comment'];
private function removeSensitiveData(SharedEnvironmentVariable $env): mixed
{
$env->makeHidden([
'team_id',
'project_id',
'environment_id',
'server_id',
'version',
]);
if (request()->attributes->get('can_read_sensitive', false) === true) {
$env->makeVisible(['value']);
}
if ($env->is_shown_once ?? false) {
$env->makeHidden(['value']);
}
return serializeApiResponse($env);
}
private function teamIdOrAbort(): int|JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
return $teamId;
}
private function validateEnvPayload(Request $request, bool $requireKey = true): JsonResponse|true
{
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
if ($request->has('key')) {
$request->merge(['key' => ValidationPatterns::normalizeEnvironmentVariableKey((string) $request->key)]);
}
$validator = customApiValidator($request->all(), [
'key' => ValidationPatterns::environmentVariableKeyRules(required: $requireKey),
'value' => 'string|nullable',
'is_literal' => 'boolean',
'is_multiline' => 'boolean',
'is_shown_once' => 'boolean',
'comment' => 'string|nullable|max:256',
]);
$extraFields = array_diff(array_keys($request->all()), self::ALLOWED_FIELDS);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
if (! $requireKey && $request->all() === []) {
return response()->json(['message' => 'At least one field must be provided.'], 422);
}
return true;
}
private function findEnvInScope(int $teamId, int|string $envId, string $type, array $scope = []): ?SharedEnvironmentVariable
{
$query = SharedEnvironmentVariable::ownedByCurrentTeamAPI($teamId)
->where('type', $type)
->where('id', $envId);
if (array_key_exists('project_id', $scope)) {
$query->where('project_id', $scope['project_id']);
}
if (array_key_exists('environment_id', $scope)) {
$query->where('environment_id', $scope['environment_id']);
}
if (array_key_exists('server_id', $scope)) {
$query->where('server_id', $scope['server_id']);
}
return $query->first();
}
private function keyExistsInScope(int $teamId, string $key, string $type, array $scope = [], ?int $exceptId = null): bool
{
$query = SharedEnvironmentVariable::ownedByCurrentTeamAPI($teamId)
->where('type', $type)
->where('key', $key);
if (array_key_exists('project_id', $scope)) {
$query->where('project_id', $scope['project_id']);
} else {
$query->whereNull('project_id');
}
if (array_key_exists('environment_id', $scope)) {
$query->where('environment_id', $scope['environment_id']);
} else {
$query->whereNull('environment_id');
}
if (array_key_exists('server_id', $scope)) {
$query->where('server_id', $scope['server_id']);
} else {
$query->whereNull('server_id');
}
if ($exceptId !== null) {
$query->where('id', '!=', $exceptId);
}
return $query->exists();
}
private function listEnvs(int $teamId, string $type, array $scope = []): JsonResponse
{
$query = SharedEnvironmentVariable::ownedByCurrentTeamAPI($teamId)
->where('type', $type)
->orderBy('id');
if (array_key_exists('project_id', $scope)) {
$query->where('project_id', $scope['project_id']);
}
if (array_key_exists('environment_id', $scope)) {
$query->where('environment_id', $scope['environment_id']);
}
if (array_key_exists('server_id', $scope)) {
$query->where('server_id', $scope['server_id']);
}
$envs = $query->get()->map(fn (SharedEnvironmentVariable $env) => $this->removeSensitiveData($env));
return response()->json($envs);
}
private function createEnv(Request $request, int $teamId, string $type, array $attributes = []): JsonResponse
{
$validated = $this->validateEnvPayload($request, requireKey: true);
if ($validated instanceof JsonResponse) {
return $validated;
}
$this->authorize('create', SharedEnvironmentVariable::class);
$scope = array_filter([
'project_id' => $attributes['project_id'] ?? null,
'environment_id' => $attributes['environment_id'] ?? null,
'server_id' => $attributes['server_id'] ?? null,
], fn ($value) => ! is_null($value));
if ($this->keyExistsInScope($teamId, $request->key, $type, $scope)) {
return response()->json([
'message' => 'Environment variable already exists. Use PATCH request to update it.',
], 409);
}
$env = SharedEnvironmentVariable::create([
'key' => $request->key,
'value' => $request->value,
'is_literal' => $request->boolean('is_literal'),
'is_multiline' => $request->boolean('is_multiline'),
'is_shown_once' => $request->boolean('is_shown_once'),
'comment' => $request->comment,
'type' => $type,
'team_id' => $teamId,
'project_id' => $attributes['project_id'] ?? null,
'environment_id' => $attributes['environment_id'] ?? null,
'server_id' => $attributes['server_id'] ?? null,
]);
auditLog('api.shared_env.created', [
'team_id' => $teamId,
'env_id' => $env->id,
'env_key' => $env->key,
'type' => $type,
]);
return response()->json([
'id' => $env->id,
], 201);
}
private function updateEnv(Request $request, int $teamId, int|string $envId, string $type, array $scope = []): JsonResponse
{
$env = $this->findEnvInScope($teamId, $envId, $type, $scope);
if (! $env) {
return response()->json(['message' => 'Environment variable not found.'], 404);
}
$this->authorize('update', $env);
$validated = $this->validateEnvPayload($request, requireKey: false);
if ($validated instanceof JsonResponse) {
return $validated;
}
if ($request->has('key') && $request->key !== $env->key) {
if ($this->keyExistsInScope($teamId, $request->key, $type, $scope, exceptId: $env->id)) {
return response()->json([
'message' => 'Environment variable already exists with this key.',
], 409);
}
$env->key = $request->key;
}
if ($request->has('value')) {
$env->value = $request->value;
}
if ($request->has('is_literal')) {
$env->is_literal = $request->boolean('is_literal');
}
if ($request->has('is_multiline')) {
$env->is_multiline = $request->boolean('is_multiline');
}
if ($request->has('is_shown_once')) {
$env->is_shown_once = $request->boolean('is_shown_once');
}
if ($request->has('comment')) {
$env->comment = $request->comment;
}
$env->save();
auditLog('api.shared_env.updated', [
'team_id' => $teamId,
'env_id' => $env->id,
'env_key' => $env->key,
'type' => $type,
]);
return response()->json($this->removeSensitiveData($env->fresh()));
}
private function deleteEnv(int $teamId, int|string $envId, string $type, array $scope = []): JsonResponse
{
$env = $this->findEnvInScope($teamId, $envId, $type, $scope);
if (! $env) {
return response()->json(['message' => 'Environment variable not found.'], 404);
}
$this->authorize('delete', $env);
$envKey = $env->key;
$envIdValue = $env->id;
$env->delete();
auditLog('api.shared_env.deleted', [
'team_id' => $teamId,
'env_id' => $envIdValue,
'env_key' => $envKey,
'type' => $type,
]);
return response()->json([
'message' => 'Environment variable deleted.',
]);
}
private function resolveProject(int $teamId, string $uuid): Project|JsonResponse
{
$project = Project::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $project) {
return response()->json(['message' => 'Project not found.'], 404);
}
return $project;
}
private function resolveServer(int $teamId, string $uuid): Server|JsonResponse
{
$server = Server::whereTeamId($teamId)->whereUuid($uuid)->first();
if (! $server) {
return response()->json(['message' => 'Server not found.'], 404);
}
return $server;
}
private function resolveEnvironment(Project $project, string $environmentNameOrUuid): Environment|JsonResponse
{
$environment = $project->environments()->whereName($environmentNameOrUuid)->first();
if (! $environment) {
$environment = $project->environments()->whereUuid($environmentNameOrUuid)->first();
}
if (! $environment) {
return response()->json(['message' => 'Environment not found.'], 404);
}
return $environment;
}
// ── Team ──────────────────────────────────────────────────────────
#[OA\Get(
summary: 'List Team Shared Envs',
description: 'List shared environment variables for the current team (type=team).',
path: '/team/envs',
operationId: 'list-team-shared-envs',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
responses: [
new OA\Response(response: 200, description: 'Team shared environment variables.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
],
)]
public function team_envs(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$this->authorize('viewAny', SharedEnvironmentVariable::class);
return $this->listEnvs($teamId, 'team');
}
#[OA\Post(
summary: 'Create Team Shared Env',
description: 'Create a shared environment variable for the current team (type=team).',
path: '/team/envs',
operationId: 'create-team-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['key'],
properties: [
new OA\Property(property: 'key', type: 'string'),
new OA\Property(property: 'value', type: 'string', nullable: true),
new OA\Property(property: 'is_literal', type: 'boolean'),
new OA\Property(property: 'is_multiline', type: 'boolean'),
new OA\Property(property: 'is_shown_once', type: 'boolean'),
new OA\Property(property: 'comment', type: 'string', nullable: true),
],
),
),
responses: [
new OA\Response(response: 201, description: 'Environment variable created.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 409, description: 'Environment variable already exists.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function team_create_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
return $this->createEnv($request, $teamId, 'team');
}
#[OA\Patch(
summary: 'Update Team Shared Env',
description: 'Update a team shared environment variable by id.',
path: '/team/envs/{env_id}',
operationId: 'update-team-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable updated.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function team_update_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
return $this->updateEnv($request, $teamId, $request->route('env_id'), 'team');
}
#[OA\Delete(
summary: 'Delete Team Shared Env',
description: 'Delete a team shared environment variable by id.',
path: '/team/envs/{env_id}',
operationId: 'delete-team-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable deleted.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function team_delete_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
return $this->deleteEnv($teamId, $request->route('env_id'), 'team');
}
// ── Project ───────────────────────────────────────────────────────
#[OA\Get(
summary: 'List Project Shared Envs',
description: 'List shared environment variables for a project (type=project).',
path: '/projects/{uuid}/envs',
operationId: 'list-project-shared-envs',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Project shared environment variables.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function project_envs(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$this->authorize('view', $project);
return $this->listEnvs($teamId, 'project', ['project_id' => $project->id]);
}
#[OA\Post(
summary: 'Create Project Shared Env',
description: 'Create a shared environment variable for a project (type=project).',
path: '/projects/{uuid}/envs',
operationId: 'create-project-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 201, description: 'Environment variable created.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 409, description: 'Environment variable already exists.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function project_create_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$this->authorize('view', $project);
return $this->createEnv($request, $teamId, 'project', ['project_id' => $project->id]);
}
#[OA\Patch(
summary: 'Update Project Shared Env',
description: 'Update a project shared environment variable by id.',
path: '/projects/{uuid}/envs/{env_id}',
operationId: 'update-project-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable updated.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function project_update_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$this->authorize('view', $project);
return $this->updateEnv(
$request,
$teamId,
$request->route('env_id'),
'project',
['project_id' => $project->id],
);
}
#[OA\Delete(
summary: 'Delete Project Shared Env',
description: 'Delete a project shared environment variable by id.',
path: '/projects/{uuid}/envs/{env_id}',
operationId: 'delete-project-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable deleted.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function project_delete_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$this->authorize('view', $project);
return $this->deleteEnv(
$teamId,
$request->route('env_id'),
'project',
['project_id' => $project->id],
);
}
// ── Environment ───────────────────────────────────────────────────
#[OA\Get(
summary: 'List Environment Shared Envs',
description: 'List shared environment variables for a project environment (type=environment).',
path: '/projects/{uuid}/environments/{environment_name_or_uuid}/envs',
operationId: 'list-environment-shared-envs',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'environment_name_or_uuid', in: 'path', required: true, description: 'Environment name or UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Environment shared environment variables.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function environment_envs(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$environment = $this->resolveEnvironment($project, $request->route('environment_name_or_uuid'));
if ($environment instanceof JsonResponse) {
return $environment;
}
$this->authorize('view', $project);
return $this->listEnvs($teamId, 'environment', ['environment_id' => $environment->id]);
}
#[OA\Post(
summary: 'Create Environment Shared Env',
description: 'Create a shared environment variable for a project environment (type=environment).',
path: '/projects/{uuid}/environments/{environment_name_or_uuid}/envs',
operationId: 'create-environment-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'environment_name_or_uuid', in: 'path', required: true, description: 'Environment name or UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 201, description: 'Environment variable created.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 409, description: 'Environment variable already exists.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function environment_create_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$environment = $this->resolveEnvironment($project, $request->route('environment_name_or_uuid'));
if ($environment instanceof JsonResponse) {
return $environment;
}
$this->authorize('view', $project);
return $this->createEnv($request, $teamId, 'environment', ['environment_id' => $environment->id]);
}
#[OA\Patch(
summary: 'Update Environment Shared Env',
description: 'Update an environment shared environment variable by id.',
path: '/projects/{uuid}/environments/{environment_name_or_uuid}/envs/{env_id}',
operationId: 'update-environment-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'environment_name_or_uuid', in: 'path', required: true, description: 'Environment name or UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable updated.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function environment_update_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$environment = $this->resolveEnvironment($project, $request->route('environment_name_or_uuid'));
if ($environment instanceof JsonResponse) {
return $environment;
}
$this->authorize('view', $project);
return $this->updateEnv(
$request,
$teamId,
$request->route('env_id'),
'environment',
['environment_id' => $environment->id],
);
}
#[OA\Delete(
summary: 'Delete Environment Shared Env',
description: 'Delete an environment shared environment variable by id.',
path: '/projects/{uuid}/environments/{environment_name_or_uuid}/envs/{env_id}',
operationId: 'delete-environment-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Project UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'environment_name_or_uuid', in: 'path', required: true, description: 'Environment name or UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable deleted.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function environment_delete_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$project = $this->resolveProject($teamId, $request->route('uuid'));
if ($project instanceof JsonResponse) {
return $project;
}
$environment = $this->resolveEnvironment($project, $request->route('environment_name_or_uuid'));
if ($environment instanceof JsonResponse) {
return $environment;
}
$this->authorize('view', $project);
return $this->deleteEnv(
$teamId,
$request->route('env_id'),
'environment',
['environment_id' => $environment->id],
);
}
// ── Server ────────────────────────────────────────────────────────
#[OA\Get(
summary: 'List Server Shared Envs',
description: 'List shared environment variables for a server (type=server).',
path: '/servers/{uuid}/envs',
operationId: 'list-server-shared-envs',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Server shared environment variables.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function server_envs(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$server = $this->resolveServer($teamId, $request->route('uuid'));
if ($server instanceof JsonResponse) {
return $server;
}
$this->authorize('view', $server);
return $this->listEnvs($teamId, 'server', ['server_id' => $server->id]);
}
#[OA\Post(
summary: 'Create Server Shared Env',
description: 'Create a shared environment variable for a server (type=server).',
path: '/servers/{uuid}/envs',
operationId: 'create-server-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 201, description: 'Environment variable created.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 409, description: 'Environment variable already exists.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function server_create_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$server = $this->resolveServer($teamId, $request->route('uuid'));
if ($server instanceof JsonResponse) {
return $server;
}
$this->authorize('view', $server);
return $this->createEnv($request, $teamId, 'server', ['server_id' => $server->id]);
}
#[OA\Patch(
summary: 'Update Server Shared Env',
description: 'Update a server shared environment variable by id.',
path: '/servers/{uuid}/envs/{env_id}',
operationId: 'update-server-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable updated.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
],
)]
public function server_update_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$server = $this->resolveServer($teamId, $request->route('uuid'));
if ($server instanceof JsonResponse) {
return $server;
}
$this->authorize('view', $server);
return $this->updateEnv(
$request,
$teamId,
$request->route('env_id'),
'server',
['server_id' => $server->id],
);
}
#[OA\Delete(
summary: 'Delete Server Shared Env',
description: 'Delete a server shared environment variable by id.',
path: '/servers/{uuid}/envs/{env_id}',
operationId: 'delete-server-shared-env',
security: [['bearerAuth' => []]],
tags: ['Shared Environment Variables'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Server UUID', schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'env_id', in: 'path', required: true, description: 'Shared env id (integer).', schema: new OA\Schema(type: 'integer')),
],
responses: [
new OA\Response(response: 200, description: 'Environment variable deleted.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
],
)]
public function server_delete_env(Request $request): JsonResponse
{
$teamId = $this->teamIdOrAbort();
if (! is_int($teamId)) {
return $teamId;
}
$server = $this->resolveServer($teamId, $request->route('uuid'));
if ($server instanceof JsonResponse) {
return $server;
}
$this->authorize('view', $server);
return $this->deleteEnv(
$teamId,
$request->route('env_id'),
'server',
['server_id' => $server->id],
);
}
}
+258
View File
@@ -4,8 +4,10 @@ namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Tag;
use Illuminate\Database\QueryException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use OpenApi\Attributes as OA;
class TagsController extends Controller
@@ -20,6 +22,57 @@ class TagsController extends Controller
];
}
private function normalizeTagName(string $name): string
{
return strtolower(trim(strip_tags($name)));
}
private function validateTagWriteRequest(Request $request, array $allowedFields = ['name']): array|JsonResponse
{
$return = validateIncomingRequest($request);
if ($return instanceof JsonResponse) {
return $return;
}
$validator = Validator::make($request->all(), [
'name' => 'required|string|min:2|max:255',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$name = $this->normalizeTagName((string) $request->input('name'));
if (mb_strlen($name) < 2) {
return response()->json([
'message' => 'Validation failed.',
'errors' => ['name' => ['The tag name must be at least 2 characters after sanitization.']],
], 422);
}
return ['name' => $name];
}
private function isUniqueConstraintViolation(QueryException $exception): bool
{
$sqlState = $exception->errorInfo[0] ?? null;
$driverCode = (string) ($exception->errorInfo[1] ?? $exception->getCode());
return in_array($sqlState, ['23000', '23505'], true)
|| in_array($driverCode, ['19', '1062', '2067'], true);
}
#[OA\Get(
summary: 'List',
description: 'List all tags for the current team.',
@@ -58,4 +111,209 @@ class TagsController extends Controller
return response()->json($tags->map(self::serializeTag(...)));
}
#[OA\Post(
summary: 'Create',
description: 'Create a tag for the current team.',
path: '/tags',
operationId: 'create-tag',
security: [
['bearerAuth' => []],
],
tags: ['Tags'],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['name'],
properties: [
new OA\Property(property: 'name', type: 'string', minLength: 2, maxLength: 255),
],
type: 'object',
),
),
responses: [
new OA\Response(
response: 201,
description: 'Tag created.',
content: new OA\JsonContent(ref: '#/components/schemas/Tag'),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 409, description: 'Tag with this name already exists.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function create(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$this->authorize('create', Tag::class);
$validated = $this->validateTagWriteRequest($request);
if ($validated instanceof JsonResponse) {
return $validated;
}
if (Tag::where('team_id', $teamId)->where('name', $validated['name'])->exists()) {
return response()->json(['message' => 'Tag with this name already exists.'], 409);
}
try {
$tag = Tag::create([
'name' => $validated['name'],
'team_id' => $teamId,
]);
} catch (QueryException $exception) {
if ($this->isUniqueConstraintViolation($exception)) {
return response()->json(['message' => 'Tag with this name already exists.'], 409);
}
throw $exception;
}
auditLog('api.tag.created', [
'team_id' => $teamId,
'tag_uuid' => $tag->uuid,
'tag_name' => $tag->name,
]);
return response()->json(self::serializeTag($tag), 201);
}
#[OA\Patch(
summary: 'Update',
description: 'Update a tag name for the current team.',
path: '/tags/{uuid}',
operationId: 'update-tag-by-uuid',
security: [
['bearerAuth' => []],
],
tags: ['Tags'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Tag UUID', schema: new OA\Schema(type: 'string')),
],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['name'],
properties: [
new OA\Property(property: 'name', type: 'string', minLength: 2, maxLength: 255),
],
type: 'object',
),
),
responses: [
new OA\Response(
response: 200,
description: 'Tag updated.',
content: new OA\JsonContent(ref: '#/components/schemas/Tag'),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 400, ref: '#/components/responses/400'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
new OA\Response(response: 409, description: 'Tag with this name already exists.'),
new OA\Response(response: 422, ref: '#/components/responses/422'),
]
)]
public function update(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$validated = $this->validateTagWriteRequest($request);
if ($validated instanceof JsonResponse) {
return $validated;
}
$tag = Tag::where('team_id', $teamId)->where('uuid', $uuid)->first();
if (! $tag) {
return response()->json(['message' => 'Tag not found.'], 404);
}
$this->authorize('update', $tag);
if ($validated['name'] !== $tag->name
&& Tag::where('team_id', $teamId)->where('name', $validated['name'])->where('id', '!=', $tag->id)->exists()) {
return response()->json(['message' => 'Tag with this name already exists.'], 409);
}
try {
$tag->update(['name' => $validated['name']]);
} catch (QueryException $exception) {
if ($this->isUniqueConstraintViolation($exception)) {
return response()->json(['message' => 'Tag with this name already exists.'], 409);
}
throw $exception;
}
auditLog('api.tag.updated', [
'team_id' => $teamId,
'tag_uuid' => $tag->uuid,
'tag_name' => $tag->name,
'changed_fields' => ['name'],
]);
return response()->json(self::serializeTag($tag->refresh()));
}
#[OA\Delete(
summary: 'Delete',
description: 'Delete a tag for the current team. Detaches the tag from all resources via cascade.',
path: '/tags/{uuid}',
operationId: 'delete-tag-by-uuid',
security: [
['bearerAuth' => []],
],
tags: ['Tags'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, description: 'Tag UUID', schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(
response: 200,
description: 'Tag deleted.',
content: new OA\JsonContent(
properties: [
new OA\Property(property: 'message', type: 'string', example: 'Tag deleted.'),
],
type: 'object',
),
),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function delete(Request $request, string $uuid): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$tag = Tag::where('team_id', $teamId)->where('uuid', $uuid)->first();
if (! $tag) {
return response()->json(['message' => 'Tag not found.'], 404);
}
$this->authorize('delete', $tag);
$tagUuid = $tag->uuid;
$tagName = $tag->name;
// taggables rows cascade-delete via FK on tag_id
$tag->delete();
auditLog('api.tag.deleted', [
'team_id' => $teamId,
'tag_uuid' => $tagUuid,
'tag_name' => $tagName,
]);
return response()->json(['message' => 'Tag deleted.']);
}
}
+8 -8
View File
@@ -184,9 +184,9 @@ class TeamController extends Controller
#[OA\Get(
summary: 'Authenticated Team',
description: 'Get currently authenticated team.',
path: '/teams/current',
operationId: 'get-current-team',
description: 'Get the team bound to the API token.',
path: '/team',
operationId: 'get-token-team',
security: [
['bearerAuth' => []],
],
@@ -194,7 +194,7 @@ class TeamController extends Controller
responses: [
new OA\Response(
response: 200,
description: 'Current Team.',
description: 'Team bound to the API token.',
content: new OA\JsonContent(ref: '#/components/schemas/Team')),
new OA\Response(
response: 401,
@@ -224,9 +224,9 @@ class TeamController extends Controller
#[OA\Get(
summary: 'Authenticated Team Members',
description: 'Get currently authenticated team members.',
path: '/teams/current/members',
operationId: 'get-current-team-members',
description: 'Get members of the team bound to the API token.',
path: '/team/members',
operationId: 'get-token-team-members',
security: [
['bearerAuth' => []],
],
@@ -234,7 +234,7 @@ class TeamController extends Controller
responses: [
new OA\Response(
response: 200,
description: 'Currently authenticated team members.',
description: 'Members of the team bound to the API token.',
content: [
new OA\MediaType(
mediaType: 'application/json',
@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Api;
use App\Actions\Shared\DeleteScheduledVolumeBackup;
use App\Http\Controllers\Controller;
use App\Jobs\VolumeBackupJob;
use App\Models\Application;
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
@@ -442,4 +443,103 @@ class VolumeBackupsController extends Controller
'timeout' => $backup->timeout,
];
}
#[OA\Post(
summary: 'Run application storage backup',
description: 'Queue an immediate volume backup for an application storage that has a schedule.',
path: '/applications/{uuid}/storages/{storage_uuid}/backups/run',
operationId: 'run-application-storage-backup',
security: [['bearerAuth' => []]],
tags: ['Applications'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'storage_uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Storage backup queued.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
#[OA\Post(
summary: 'Run database storage backup',
description: 'Queue an immediate volume backup for a database storage that has a schedule.',
path: '/databases/{uuid}/storages/{storage_uuid}/backups/run',
operationId: 'run-database-storage-backup',
security: [['bearerAuth' => []]],
tags: ['Databases'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'storage_uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Storage backup queued.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
#[OA\Post(
summary: 'Run service storage backup',
description: 'Queue an immediate volume backup for a service storage that has a schedule.',
path: '/services/{uuid}/storages/{storage_uuid}/backups/run',
operationId: 'run-service-storage-backup',
security: [['bearerAuth' => []]],
tags: ['Services'],
parameters: [
new OA\Parameter(name: 'uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
new OA\Parameter(name: 'storage_uuid', in: 'path', required: true, schema: new OA\Schema(type: 'string')),
],
responses: [
new OA\Response(response: 200, description: 'Storage backup queued.'),
new OA\Response(response: 401, ref: '#/components/responses/401'),
new OA\Response(response: 404, ref: '#/components/responses/404'),
]
)]
public function run(Request $request): JsonResponse
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$resourceType = $request->route('resource_type');
$resource = $this->findResource($resourceType, $request->route('uuid'), $teamId);
if (! $resource) {
return response()->json([
'message' => match ($resourceType) {
'application' => 'Application not found.',
'database' => 'Database not found.',
'service' => 'Service not found.',
default => 'Resource not found.',
},
], 404);
}
$this->authorize('update', $resource);
$storage = $this->findStorage($resource, $request->route('storage_uuid'));
if (! $storage) {
return response()->json(['message' => 'Storage not found.'], 404);
}
$backup = $storage->scheduledBackups()->first();
if (! $backup) {
return response()->json(['message' => 'Storage backup schedule not found.'], 404);
}
VolumeBackupJob::dispatch($backup);
auditLog('api.volume_backup.run', [
'team_id' => $teamId,
'resource_type' => $resourceType,
'resource_uuid' => $resource->uuid,
'storage_uuid' => $storage->uuid,
'backup_uuid' => $backup->uuid,
]);
return response()->json([
'message' => 'Storage backup queued.',
'uuid' => $backup->uuid,
]);
}
}
@@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers;
use App\Services\AvatarStorageService;
use Illuminate\Http\Response;
class ProfileAvatarController extends Controller
{
public function __invoke(AvatarStorageService $avatarStorage): Response
{
$contents = $avatarStorage->contents(auth()->user());
abort_if($contents === null, 404);
return response($contents, 200, [
'Content-Type' => 'image/jpeg',
'Cache-Control' => 'private, max-age=300',
]);
}
}
@@ -0,0 +1,636 @@
<?php
namespace App\Http\Controllers\V5;
use App\Actions\V5\Application\DestroyNginxApplication;
use App\Actions\V5\Proxy\StartCaddyIngress;
use App\Enums\V5\ApplicationStatus;
use App\Enums\V5\IngressStatus;
use App\Enums\V5\ServerStatus;
use App\Exceptions\V5\UnsupportedCooldVerb;
use App\Http\Controllers\Controller;
use App\Http\Controllers\V5\Concerns\HandlesIngressSyncErrors;
use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;
use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;
use App\Http\Controllers\V5\Concerns\SerializesCanvasResources;
use App\Jobs\V5DeployApplicationJob;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Team;
use App\Models\V5\Application as V5Application;
use App\Models\V5\ApplicationDomain as V5ApplicationDomain;
use App\Models\V5\ResourceConnection;
use App\Models\V5\Server as V5Server;
use App\Rules\ValidHostname;
use App\Services\Flux\FluxClient;
use App\Support\V5\CanvasResourceSerializer;
use App\Support\V5\ConnectionFirewallSync;
use App\Support\V5\StatusObservation;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
class ApplicationController extends Controller
{
use HandlesIngressSyncErrors;
use ResolvesCurrentTeam;
use ResolvesProjectSelection;
use SerializesCanvasResources;
private const DEFAULT_NGINX_IMAGE = 'docker.io/library/nginx:alpine';
public function __construct(private readonly ConnectionFirewallSync $firewallSync) {}
public function store(Request $request): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('create', [V5Application::class, $currentTeam]);
$projects = $this->projects($currentTeam);
[$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);
if ($selectedProject === null || $selectedEnvironment === null) {
return response()->json([
'message' => 'Select a project and environment before deploying nginx.',
], 422);
}
$project = $this->projectQuery($currentTeam)
->where('uuid', $selectedProject['uuid'])
->first();
if (! $project instanceof Project) {
abort(403);
}
$environment = $this->selectedEnvironment($project, $selectedEnvironment['uuid']);
if (! $environment instanceof Environment) {
abort(403);
}
$validated = $request->validate([
'server_uuid' => ['nullable', 'string', 'max:255'],
'image' => ['nullable', 'string', 'max:255', 'regex:/^[a-zA-Z0-9][a-zA-Z0-9._\/:@-]*$/'],
]);
$image = trim($validated['image'] ?? '') ?: self::DEFAULT_NGINX_IMAGE;
$server = V5Server::query()
->where('team_id', $currentTeam->id)
->when(
isset($validated['server_uuid']),
fn (Builder $query) => $query->where('uuid', $validated['server_uuid']),
fn (Builder $query) => $query
->orderByRaw('last_bootstrapped_at is null')
->orderBy('name')
)
->first();
if (! $server instanceof V5Server) {
return response()->json([
'message' => 'Add a v5 server before deploying nginx.',
], 422);
}
if ($server->status !== ServerStatus::Installed->value || $server->last_bootstrapped_at === null) {
return response()->json([
'message' => "Bootstrap server {$server->name} before deploying to it.",
], 422);
}
$canvasPosition = $this->nextApplicationCanvasPosition($currentTeam, $project, $environment);
$application = V5Application::query()->create([
'team_id' => $currentTeam->id,
'project_id' => $project->id,
'environment_id' => $environment->id,
'server_id' => $server->id,
'created_by_user_id' => $request->user()->id,
'name' => 'nginx-test',
'image' => $image,
'container_name' => 'coolify-v5-nginx-'.strtolower((string) Str::ulid()),
'status' => ApplicationStatus::Creating->value,
'status_message' => 'Starting nginx container.',
'mesh_namespace' => 'default',
'canvas_x' => $canvasPosition['canvas_x'],
'canvas_y' => $canvasPosition['canvas_y'],
]);
V5DeployApplicationJob::dispatch($application->id);
return response()->json([
'application' => $this->serializeApplication($application),
], 202);
}
public function refresh(Request $request, FluxClient $fluxClient): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$projects = $this->projects($currentTeam);
[$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);
if ($selectedProject === null || $selectedEnvironment === null) {
return response()->json([
'message' => 'Select a project and environment before refreshing applications.',
], 422);
}
$applications = $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)
->with('server')
->get();
$errors = [];
$applications
->groupBy('server_id')
->each(function (Collection $serverApplications) use ($fluxClient, &$errors): void {
/** @var V5Application|null $firstApplication */
$firstApplication = $serverApplications->first();
$server = $firstApplication?->server;
$hostId = $server?->fluxHostId();
if (! $server instanceof V5Server || ! is_string($hostId) || $hostId === '') {
$errors[] = 'A server is missing its Flux host id.';
return;
}
// The moment we query coold is the observation time for the rows
// this refresh writes, so a fresher webhook always wins the
// status_observed_at watermark and is never clobbered.
$observedAt = CarbonImmutable::now();
try {
$containers = collect($fluxClient->listContainers($hostId));
} catch (\Throwable $e) {
$errors[] = $e->getMessage();
return;
}
$serverApplications->each(function (V5Application $application) use ($containers, $observedAt): void {
$container = $containers->first(function (array $container) use ($application): bool {
return ($application->runtime_container_id !== null && ($container['id'] ?? null) === $application->runtime_container_id)
|| ($container['name'] ?? null) === $application->container_name;
});
if (! is_array($container)) {
// A creating application without a container id simply has
// not materialized yet; the deploy job will settle it.
if ($application->status === ApplicationStatus::Creating->value && $application->runtime_container_id === null) {
return;
}
if (StatusObservation::isStale($observedAt, $application->status_observed_at, 'application status', ['application_id' => $application->id])) {
return;
}
$application->update([
'status' => ApplicationStatus::Exited->value,
'status_message' => 'Container not found on server.',
'status_observed_at' => $observedAt,
]);
return;
}
if (StatusObservation::isStale($observedAt, $application->status_observed_at, 'application status', ['application_id' => $application->id])) {
return;
}
$rawState = is_string($container['state'] ?? null) && $container['state'] !== '' ? $container['state'] : null;
$application->update([
'status' => StatusObservation::normalize($rawState, ApplicationStatus::class) ?? ApplicationStatus::Unknown->value,
'status_message' => 'Container state refreshed from coold.',
'status_observed_at' => $observedAt,
'runtime_container_id' => is_string($container['id'] ?? null) ? $container['id'] : $application->runtime_container_id,
]);
});
});
V5Server::query()
->where('team_id', $currentTeam->id)
->orderBy('name')
->get()
->filter(fn (V5Server $server) => $server->isIngress())
->each(function (V5Server $server) use ($fluxClient, &$errors): void {
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
$errors[] = "Caddy ingress server {$server->name} is missing its Flux host id.";
return;
}
try {
$containers = collect($fluxClient->listContainers($hostId));
} catch (\Throwable $e) {
$errors[] = $e->getMessage();
return;
}
$container = $containers->first(fn (array $container) => ($container['name'] ?? null) === 'coolify-v5-caddy');
$rawState = is_array($container) && is_string($container['state'] ?? null) && $container['state'] !== '' ? $container['state'] : null;
$state = $rawState !== null
? (StatusObservation::normalize($rawState, IngressStatus::class) ?? IngressStatus::Unknown->value)
: IngressStatus::Exited->value;
$server->update([
'ingress_type' => 'caddy',
'ingress_status' => $state,
'last_status_check' => 'flux',
'last_status_output' => 'Caddy ingress state refreshed from coold.',
'last_status_checked_at' => now(),
]);
});
return response()->json([
'applications' => $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)
->with('server')
->orderBy('created_at')
->get()
->map(fn (V5Application $application) => $this->serializeApplication($application))
->all(),
'caddyIngresses' => $this->caddyIngresses($currentTeam),
'errors' => $errors,
]);
}
public function logs(Request $request, V5Application $application): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('view', [$application, $currentTeam]);
$application->loadMissing('server');
$server = $application->server;
$hostId = $server?->fluxHostId();
$containerId = $application->runtime_container_id;
$logs = null;
$logsError = null;
// A container id only appears once the deploy actually created one; a
// deploy that failed before that (e.g. host not connected) has none, so
// there is nothing to fetch and the frontend just shows the status.
if (is_string($containerId) && $containerId !== '' && $server instanceof V5Server && $server->status !== ServerStatus::Unreachable->value && is_string($hostId) && $hostId !== '') {
try {
$logs = app(FluxClient::class)->containerLogs($hostId, $containerId);
} catch (UnsupportedCooldVerb $exception) {
$logsError = "This node's coold does not support container logs.";
} catch (\RuntimeException $exception) {
Log::warning('V5 application container logs request failed', [
'application_id' => $application->id,
'message' => $exception->getMessage(),
]);
$logsError = 'Could not fetch container logs through Flux. Check the Flux and coold status, then try again.';
}
}
return response()->json([
'status' => $application->status,
'statusMessage' => $application->status_message,
'containerId' => $containerId,
'logs' => $logs,
'logsError' => $logsError,
]);
}
public function updatePosition(Request $request, V5Application $application): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('update', [$application, $currentTeam]);
$validated = $request->validate([
'canvas_x' => ['required', 'integer', 'min:-100000', 'max:100000'],
'canvas_y' => ['required', 'integer', 'min:-100000', 'max:100000'],
]);
$application->update([
'canvas_x' => $validated['canvas_x'],
'canvas_y' => $validated['canvas_y'],
]);
return response()->json([
'application' => $this->serializeApplication($application->refresh()->load('server')),
]);
}
public function updateIngress(Request $request, V5Application $application): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('updateIngress', [$application, $currentTeam]);
$validated = $request->validate([
'ingress_enabled' => ['required', 'boolean'],
'internal_port' => ['nullable', 'integer', 'min:1', 'max:65535'],
'domains' => [Rule::requiredIf(fn () => $request->boolean('ingress_enabled')), 'array', 'min:1'],
'domains.*' => ['required', 'string', 'max:255', 'distinct:ignore_case', new ValidHostname],
]);
$application->loadMissing('server');
if ($validated['ingress_enabled'] && ! $application->server?->isIngress()) {
return response()->json([
'message' => 'Enable ingress on the server before enabling app ingress.',
], 422);
}
if ($validated['ingress_enabled'] && array_key_exists('domains', $validated)) {
$conflict = $this->conflictingApplicationDomain($application, $validated['domains']);
if ($conflict instanceof V5ApplicationDomain) {
return response()->json([
'message' => "The domain {$conflict->domain} is already used by application \"{$conflict->application?->name}\" on this server.",
], 422);
}
}
$originalAttributes = $application->only(['ingress_enabled', 'internal_port']);
$originalDomains = $application->domains()->pluck('domain')->all();
DB::transaction(function () use ($application, $validated): void {
$application->update([
'ingress_enabled' => $validated['ingress_enabled'],
'internal_port' => $validated['internal_port'] ?? null,
]);
if (array_key_exists('domains', $validated)) {
$application->domains()->delete();
collect($validated['domains'])
->map(fn (string $domain) => trim($domain))
->filter()
->unique()
->each(fn (string $domain) => V5ApplicationDomain::query()->create([
'application_id' => $application->id,
'domain' => $domain,
]));
}
});
$application->refresh()->load(['server', 'domains']);
if ($application->server?->isIngress() && $application->server->status === ServerStatus::Installed->value) {
try {
StartCaddyIngress::run($application->server);
} catch (\RuntimeException $exception) {
$this->restoreApplicationIngress($application, $originalAttributes, $originalDomains);
return $this->ingressSyncErrorResponse($exception);
}
}
return response()->json([
'application' => $this->serializeApplication($application),
]);
}
public function updateCaddyIngressPosition(Request $request, V5Server $server): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('updateCanvasPosition', [$server, $currentTeam]);
$validated = $request->validate([
'canvas_x' => ['required', 'integer', 'min:-100000', 'max:100000'],
'canvas_y' => ['required', 'integer', 'min:-100000', 'max:100000'],
]);
$server->update([
'canvas_x' => $validated['canvas_x'],
'canvas_y' => $validated['canvas_y'],
]);
return response()->json([
'caddyIngress' => $this->serializeCaddyIngress($server->refresh()),
]);
}
public function destroy(Request $request, V5Application $application, FluxClient $fluxClient): Response|JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('delete', [$application, $currentTeam]);
$application->loadMissing(['server', 'domains']);
$server = $application->server;
$connections = $this->applicationResourceConnections($application);
if ($request->boolean('delete_locally')) {
$this->deleteApplicationLocally($application, $connections);
return response()->noContent();
}
$oldFirewallRules = $connections
->flatMap(function (ResourceConnection $connection): Collection {
// Deletion must never be blocked by an endpoint that already lost
// its server; those rules can no longer be revoked anyway.
try {
return $this->firewallSync->rulesFor($connection->load('rules'));
} catch (\RuntimeException $exception) {
report($exception);
return collect();
}
});
$originalIngressAttributes = null;
$originalIngressDomains = [];
$ingressConfigurationChanged = false;
try {
$this->firewallSync->sync($fluxClient, $oldFirewallRules, collect());
} catch (\RuntimeException $exception) {
report($exception);
return response()->json([
'message' => 'Could not sync firewall rules through Flux.',
'detail' => $exception->getMessage(),
], 502);
}
if ($server instanceof V5Server && $server->isIngress() && $server->status === ServerStatus::Installed->value && $application->ingress_enabled) {
$originalIngressAttributes = $application->only(['ingress_enabled', 'internal_port']);
$originalIngressDomains = $application->domains()->pluck('domain')->all();
DB::transaction(function () use ($application): void {
$application->update([
'ingress_enabled' => false,
'internal_port' => null,
]);
$application->domains()->delete();
});
try {
StartCaddyIngress::run($server);
$ingressConfigurationChanged = true;
} catch (\RuntimeException $exception) {
$this->restoreApplicationIngress($application, $originalIngressAttributes, $originalIngressDomains);
return $this->ingressSyncErrorResponse($exception);
}
}
$error = DestroyNginxApplication::run($application);
if ($error !== null) {
if ($originalIngressAttributes !== null) {
$this->restoreApplicationIngress($application, $originalIngressAttributes, $originalIngressDomains);
if ($ingressConfigurationChanged && $server instanceof V5Server) {
try {
StartCaddyIngress::run($server);
} catch (\RuntimeException $exception) {
report($exception);
}
}
}
try {
$this->firewallSync->sync($fluxClient, collect(), $oldFirewallRules);
} catch (\RuntimeException $exception) {
report($exception);
}
return response()->json([
'message' => $error,
'can_delete_locally' => true,
], 422);
}
$this->deleteApplicationLocally($application, $connections);
return response()->noContent();
}
/**
* @param Collection<int, ResourceConnection> $connections
*/
private function deleteApplicationLocally(V5Application $application, Collection $connections): void
{
DB::transaction(function () use ($application, $connections): void {
$connections->each(function (ResourceConnection $connection): void {
$connection->rules()->delete();
$connection->delete();
});
$application->delete();
});
}
/**
* @return Collection<int, ResourceConnection>
*/
private function applicationResourceConnections(V5Application $application): Collection
{
return ResourceConnection::query()
->where('team_id', $application->team_id)
->where(function (Builder $query) use ($application): void {
$query
->where(function (Builder $query) use ($application): void {
$query
->where('resource_one_type', $application->getMorphClass())
->where('resource_one_id', $application->id);
})
->orWhere(function (Builder $query) use ($application): void {
$query
->where('resource_two_type', $application->getMorphClass())
->where('resource_two_id', $application->id);
});
})
->with('rules')
->get();
}
/**
* @return array{canvas_x: int, canvas_y: int}
*/
private function nextApplicationCanvasPosition(Team $currentTeam, Project $project, Environment $environment): array
{
$existingApplications = V5Application::query()
->where('team_id', $currentTeam->id)
->where('project_id', $project->id)
->where('environment_id', $environment->id)
->get(['canvas_x', 'canvas_y']);
$horizontalStep = CanvasResourceSerializer::CARD_WIDTH + CanvasResourceSerializer::CARD_GAP;
$verticalStep = CanvasResourceSerializer::CARD_HEIGHT + CanvasResourceSerializer::CARD_GAP;
for ($row = 0; $row < 100; $row++) {
for ($column = 0; $column < 100; $column++) {
$candidate = [
'canvas_x' => $column * $horizontalStep,
'canvas_y' => $row * $verticalStep,
];
if (! $this->canvasPositionCollides($candidate, $existingApplications)) {
return $candidate;
}
}
}
return [
'canvas_x' => $existingApplications->max('canvas_x') + $horizontalStep,
'canvas_y' => 0,
];
}
/**
* @param array{canvas_x: int, canvas_y: int} $candidate
* @param Collection<int, V5Application> $existingApplications
*/
private function canvasPositionCollides(array $candidate, Collection $existingApplications): bool
{
return $existingApplications->contains(function (V5Application $application) use ($candidate) {
return abs($candidate['canvas_x'] - $application->canvas_x) < CanvasResourceSerializer::CARD_WIDTH + CanvasResourceSerializer::CARD_GAP
&& abs($candidate['canvas_y'] - $application->canvas_y) < CanvasResourceSerializer::CARD_HEIGHT + CanvasResourceSerializer::CARD_GAP;
});
}
/**
* @param array<int, string> $domains
*/
private function conflictingApplicationDomain(V5Application $application, array $domains): ?V5ApplicationDomain
{
$normalizedDomains = collect($domains)
->map(fn (string $domain) => Str::lower(trim($domain)))
->filter()
->values();
if ($normalizedDomains->isEmpty()) {
return null;
}
return V5ApplicationDomain::query()
->whereIn(DB::raw('LOWER(domain)'), $normalizedDomains->all())
->whereHas('application', fn (Builder $query) => $query
->where('server_id', $application->server_id)
->whereKeyNot($application->id)
->where('ingress_enabled', true))
->with('application:id,name')
->first();
}
/**
* @param array<string, mixed> $attributes
* @param array<int, string> $domains
*/
private function restoreApplicationIngress(V5Application $application, array $attributes, array $domains): void
{
DB::transaction(function () use ($application, $attributes, $domains): void {
$application->update($attributes);
$application->domains()->delete();
foreach ($domains as $domain) {
V5ApplicationDomain::query()->create([
'application_id' => $application->id,
'domain' => $domain,
]);
}
});
}
}
@@ -0,0 +1,207 @@
<?php
namespace App\Http\Controllers\V5;
use App\Http\Controllers\Controller;
use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;
use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;
use App\Http\Controllers\V5\Concerns\ValidatesBuilderConfiguration;
use App\Models\PrivateKey;
use App\Models\Team;
use App\Models\V5\Cluster as V5Cluster;
use App\Services\Flux\FluxHealth;
use App\Support\V5\ClusterSerializer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Inertia\Inertia;
use Inertia\Response;
class ClusterController extends Controller
{
use ResolvesCurrentTeam;
use ResolvesProjectSelection;
use ValidatesBuilderConfiguration;
public function index(Request $request, FluxHealth $fluxHealth): Response
{
$currentTeam = $request->attributes->get('v5.currentTeam');
$projects = $this->projects($currentTeam);
[$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);
return Inertia::render('Clusters', [
'currentTeam' => $this->serializeCurrentTeam($currentTeam),
'flux' => $fluxHealth->check(),
'clusters' => $this->clusters($currentTeam),
'privateKeys' => $this->privateKeys($currentTeam),
'projects' => $projects,
'selectedProjectUuid' => $selectedProject['uuid'] ?? null,
'selectedEnvironmentUuid' => $selectedEnvironment['uuid'] ?? null,
]);
}
public function show(Request $request, V5Cluster $cluster): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('view', [$cluster, $currentTeam]);
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
]);
}
public function store(Request $request): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('create', [V5Cluster::class, $currentTeam]);
$validated = $request->validate([
'name' => [
'required',
'string',
'max:255',
Rule::unique('v5_clusters', 'name')->where('team_id', $currentTeam->id),
],
'description' => ['nullable', 'string', 'max:1000'],
'wireguard_interface' => ['sometimes', 'string', 'max:32', 'regex:/^[a-zA-Z0-9_.-]+$/'],
'wireguard_management_pool' => ['sometimes', 'string', 'max:64', $this->ipv4CidrRule()],
'wireguard_listen_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],
'container_network_pool' => ['sometimes', 'string', 'max:64', $this->ipv4CidrRule()],
'container_network_prefix' => ['sometimes', 'integer', 'min:1', 'max:32'],
'namespaces' => ['sometimes', 'array', 'min:1'],
'namespaces.*' => ['string', 'distinct', 'regex:/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/'],
'default_deny_containers' => ['sometimes', 'boolean'],
'coold_version' => ['sometimes', 'string', 'max:64'],
'corrosion_version' => ['sometimes', 'string', 'max:64'],
'corrosion_gossip_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],
'corrosion_api_port' => ['sometimes', 'integer', 'min:1', 'max:65535'],
'builder_enabled' => ['sometimes', 'boolean'],
'builder_capacity' => $this->builderCapacityRules(
$this->requestedBuilderEnabled($request, true)
),
'builder_cpu_quota' => ['sometimes', 'string', 'max:32'],
'builder_memory_max' => ['sometimes', 'string', 'max:32'],
'builder_timeout_secs' => ['sometimes', 'integer', 'min:1', 'max:86400'],
]);
$cluster = V5Cluster::query()->create([
...$this->defaultClusterConfiguration(),
...collect($validated)->except(['name', 'description'])->all(),
'team_id' => $currentTeam->id,
'created_by_user_id' => $request->user()->id,
'name' => $validated['name'],
'description' => $validated['description'] ?? null,
]);
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
], 201);
}
public function destroy(Request $request, V5Cluster $cluster): \Illuminate\Http\Response|JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('delete', [$cluster, $currentTeam]);
if ($cluster->servers()->exists()) {
return response()->json([
'message' => 'Only empty clusters can be deleted.',
], 422);
}
$cluster->delete();
return response()->noContent();
}
/**
* @return array<int, array<string, mixed>>
*/
private function clusters(mixed $currentTeam): array
{
if (! $currentTeam instanceof Team) {
return [];
}
$serializer = app(ClusterSerializer::class);
return V5Cluster::query()
->where('team_id', $currentTeam->id)
->with(['servers' => fn ($query) => $query
->with('privateKey')
->orderBy('name')])
->withCount('servers')
->orderBy('name')
->get()
->map(fn (V5Cluster $cluster) => $serializer->serialize($cluster))
->all();
}
/**
* @return array<int, array{id: string, name: string}>
*/
private function privateKeys(mixed $currentTeam): array
{
if (! $currentTeam instanceof Team) {
return [];
}
return PrivateKey::query()
->where('team_id', $currentTeam->id)
->where('is_git_related', false)
->orderBy('name')
->get(['id', 'uuid', 'name'])
->map(fn (PrivateKey $privateKey) => [
'id' => $privateKey->uuid,
'name' => $privateKey->name,
])
->all();
}
/**
* @return array<string, mixed>
*/
private function defaultClusterConfiguration(): array
{
return [
'wireguard_interface' => V5Cluster::DEFAULT_WIREGUARD_INTERFACE,
'wireguard_management_pool' => V5Cluster::DEFAULT_WIREGUARD_MANAGEMENT_POOL,
'wireguard_listen_port' => V5Cluster::DEFAULT_WIREGUARD_LISTEN_PORT,
'container_network_pool' => V5Cluster::DEFAULT_CONTAINER_NETWORK_POOL,
'container_network_prefix' => V5Cluster::DEFAULT_CONTAINER_NETWORK_PREFIX,
'namespaces' => V5Cluster::DEFAULT_NAMESPACES,
'default_deny_containers' => true,
'coold_version' => V5Cluster::DEFAULT_COOLD_VERSION,
'corrosion_version' => V5Cluster::DEFAULT_CORROSION_VERSION,
'corrosion_gossip_port' => V5Cluster::DEFAULT_CORROSION_GOSSIP_PORT,
'corrosion_api_port' => V5Cluster::DEFAULT_CORROSION_API_PORT,
'builder_enabled' => true,
'builder_capacity' => V5Cluster::DEFAULT_BUILDER_CAPACITY,
'builder_cpu_quota' => V5Cluster::DEFAULT_BUILDER_CPU_QUOTA,
'builder_memory_max' => V5Cluster::DEFAULT_BUILDER_MEMORY_MAX,
'builder_timeout_secs' => V5Cluster::DEFAULT_BUILDER_TIMEOUT_SECS,
];
}
private function ipv4CidrRule(): \Closure
{
return function (string $attribute, mixed $value, \Closure $fail): void {
if (! is_string($value) || ! str_contains($value, '/')) {
$fail('The :attribute must be a valid IPv4 CIDR range.');
return;
}
[$ip, $prefix] = explode('/', $value, 2);
if (
filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
|| ! ctype_digit($prefix)
|| (int) $prefix < 0
|| (int) $prefix > 32
) {
$fail('The :attribute must be a valid IPv4 CIDR range.');
}
};
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\V5\Concerns;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Str;
trait HandlesIngressSyncErrors
{
protected function ingressSyncErrorResponse(\RuntimeException $exception): JsonResponse
{
return response()->json([
'message' => $this->friendlyIngressSyncError($exception->getMessage()),
'detail' => $exception->getMessage(),
], 502);
}
protected function friendlyIngressSyncError(string $message): string
{
$normalized = Str::lower($message);
if (str_contains($normalized, 'invalid http response') || str_contains($normalized, 'could not talk to flux')) {
return 'Could not reach Flux. Check that Flux is running in the Coolify container and try again.';
}
if (str_contains($normalized, 'dispatch timeout') || str_contains($normalized, 'timed out')) {
return 'coold did not respond in time. Check that the server agent is running and connected to Flux.';
}
if (str_contains($normalized, 'validate caddyfile')) {
return 'Caddy rejected the generated ingress configuration. Check the domains and internal port, then try again.';
}
if (str_contains($normalized, 'start caddy ingress') || str_contains($normalized, 'reload caddy ingress')) {
return 'Could not start Caddy ingress on the server. Check that Podman is running and port 80 is available.';
}
return 'Could not update ingress. Check Flux and coold logs, then try again.';
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Controllers\V5\Concerns;
use App\Models\Team;
use Illuminate\Http\Request;
trait ResolvesCurrentTeam
{
/**
* Resolve the current team set by the EnsureCurrentTeam middleware, or
* abort with a 404 so resources outside the team stay invisible.
*/
protected function currentTeamOrFail(Request $request): Team
{
$currentTeam = $request->attributes->get('v5.currentTeam');
abort_unless($currentTeam instanceof Team, 404);
return $currentTeam;
}
}
@@ -0,0 +1,122 @@
<?php
namespace App\Http\Controllers\V5\Concerns;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Team;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
trait ResolvesProjectSelection
{
protected const SELECTED_PROJECT_SESSION_KEY = 'v5.selectedProjectUuid';
protected const SELECTED_ENVIRONMENT_SESSION_KEY = 'v5.selectedEnvironmentUuid';
/**
* @return array{id: int}|null
*/
protected function serializeCurrentTeam(mixed $currentTeam): ?array
{
if (! $currentTeam instanceof Team) {
return null;
}
return [
'id' => $currentTeam->id,
];
}
/**
* @param array<int, array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}> $projects
* @return array{0: array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}|null, 1: array{uuid: string, name: string}|null}
*/
protected function selectedProjectAndEnvironment(Request $request, array $projects): array
{
$selectedProjectUuid = $request->query('project', $request->session()->get(self::SELECTED_PROJECT_SESSION_KEY));
$selectedEnvironmentUuid = $request->query('environment', $request->session()->get(self::SELECTED_ENVIRONMENT_SESSION_KEY));
$selectedProject = null;
foreach ($projects as $project) {
if ($project['uuid'] === $selectedProjectUuid) {
$selectedProject = $project;
break;
}
}
$selectedProject ??= $projects[0] ?? null;
$selectedEnvironment = null;
foreach ($selectedProject['environments'] ?? [] as $environment) {
if ($environment['uuid'] === $selectedEnvironmentUuid) {
$selectedEnvironment = $environment;
break;
}
}
$selectedEnvironment ??= $selectedProject['environments'][0] ?? null;
if ($request->query->has('project') || $request->query->has('environment')) {
$request->session()->put([
self::SELECTED_PROJECT_SESSION_KEY => $selectedProject['uuid'] ?? null,
self::SELECTED_ENVIRONMENT_SESSION_KEY => $selectedEnvironment['uuid'] ?? null,
]);
}
return [$selectedProject, $selectedEnvironment];
}
protected function selectedEnvironment(Project $project, ?string $environmentUuid): ?Environment
{
if ($environmentUuid === null) {
return $project->environments->first();
}
$environment = $project->environments->firstWhere('uuid', $environmentUuid);
if (! $environment instanceof Environment) {
abort(422, 'The selected environment is not available for the selected project.');
}
return $environment;
}
/**
* @return array<int, array{uuid: string, name: string, environments: array<int, array{uuid: string, name: string}>}>
*/
protected function projects(mixed $currentTeam): array
{
if (! $currentTeam instanceof Team) {
return [];
}
return $this->projectQuery($currentTeam)
->get()
->map(fn (Project $project) => [
'uuid' => $project->uuid,
'name' => $project->name,
'environments' => $project->environments
->map(fn ($environment) => [
'uuid' => $environment->uuid,
'name' => $environment->name,
])
->all(),
])
->all();
}
protected function projectQuery(Team $currentTeam): Builder
{
return Project::query()
->select(['id', 'uuid', 'name', 'team_id'])
->where('team_id', $currentTeam->id)
->with(['environments' => fn ($query) => $query
->select(['id', 'uuid', 'name', 'project_id'])
->orderByRaw("CASE WHEN LOWER(name) = 'production' THEN 0 ELSE 1 END")
->orderByRaw('LOWER(name)')])
->orderByRaw('LOWER(name)');
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers\V5\Concerns;
use App\Models\Team;
use App\Models\V5\Application as V5Application;
use App\Models\V5\Server as V5Server;
use App\Support\V5\CanvasResourceSerializer;
use Illuminate\Database\Eloquent\Builder;
trait SerializesCanvasResources
{
/**
* @return array<string, mixed>
*/
protected function serializeApplication(V5Application $application): array
{
return app(CanvasResourceSerializer::class)->serializeApplication($application);
}
/**
* @return array<string, mixed>
*/
protected function serializeCaddyIngress(V5Server $server, int $index = 0): array
{
return app(CanvasResourceSerializer::class)->serializeCaddyIngress($server, $index);
}
/**
* @return array<int, array<string, mixed>>
*/
protected function caddyIngresses(mixed $currentTeam): array
{
if (! $currentTeam instanceof Team) {
return [];
}
return V5Server::query()
->where('team_id', $currentTeam->id)
->orderBy('name')
->get()
->filter(fn (V5Server $server) => $server->isIngress())
->values()
->map(fn (V5Server $server, int $index) => $this->serializeCaddyIngress($server, $index))
->all();
}
/**
* @param array{uuid: string} $selectedProject
* @param array{uuid: string} $selectedEnvironment
* @return Builder<V5Application>
*/
protected function applicationQuery(Team $currentTeam, array $selectedProject, array $selectedEnvironment): Builder
{
return V5Application::query()
->where('team_id', $currentTeam->id)
->whereHas('project', fn (Builder $query) => $query
->where('team_id', $currentTeam->id)
->where('uuid', $selectedProject['uuid']))
->whereHas('environment', fn (Builder $query) => $query
->where('uuid', $selectedEnvironment['uuid']));
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Http\Controllers\V5\Concerns;
use Illuminate\Http\Request;
trait ValidatesBuilderConfiguration
{
/**
* @return array<int, string>
*/
protected function builderCapacityRules(bool $builderEnabled, bool $required = false): array
{
return [
$required ? 'required' : 'sometimes',
'integer',
$builderEnabled ? 'min:1' : 'min:0',
'max:1000',
];
}
protected function requestedBuilderEnabled(Request $request, bool $default): bool
{
if (! $request->has('builder_enabled')) {
return $default;
}
return $request->boolean('builder_enabled');
}
}
@@ -0,0 +1,171 @@
<?php
namespace App\Http\Controllers\V5;
use App\Events\V5RealtimeTestEvent;
use App\Http\Controllers\Controller;
use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;
use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;
use App\Http\Controllers\V5\Concerns\SerializesCanvasResources;
use App\Models\Project;
use App\Models\Team;
use App\Models\V5\Application as V5Application;
use App\Models\V5\ResourceConnection;
use App\Models\V5\Server as V5Server;
use App\Services\Flux\FluxHealth;
use App\Support\V5\ResourceConnectionSerializer;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class DashboardController extends Controller
{
use ResolvesCurrentTeam;
use ResolvesProjectSelection;
use SerializesCanvasResources;
public function __construct(private readonly ResourceConnectionSerializer $connectionSerializer) {}
public function __invoke(Request $request, FluxHealth $fluxHealth): Response
{
$currentTeam = $request->attributes->get('v5.currentTeam');
$projects = $this->projects($currentTeam);
[$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);
$applications = $this->applications($currentTeam, $selectedProject, $selectedEnvironment);
$requestedApplicationUuid = $request->query('application');
$selectedApplicationUuid = collect($applications)->contains(
fn (array $application): bool => $application['id'] === $requestedApplicationUuid
) ? $requestedApplicationUuid : null;
return Inertia::render('Dashboard', [
'currentTeam' => $this->serializeCurrentTeam($currentTeam),
'flux' => $fluxHealth->check(),
'applications' => $applications,
'caddyIngresses' => $this->caddyIngresses($currentTeam),
'resourceConnections' => $this->resourceConnections($currentTeam, $selectedProject, $selectedEnvironment),
'nginxServers' => $this->nginxServers($currentTeam),
'projects' => $projects,
'selectedProjectUuid' => $selectedProject['uuid'] ?? null,
'selectedEnvironmentUuid' => $selectedEnvironment['uuid'] ?? null,
'selectedApplicationUuid' => $selectedApplicationUuid,
]);
}
public function realtimeTest(Request $request): Response
{
$currentTeam = $this->currentTeamOrFail($request);
return Inertia::render('RealtimeTest', [
'currentTeam' => [
'id' => $currentTeam->id,
],
]);
}
public function broadcastRealtimeTest(Request $request): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$validated = $request->validate([
'message' => ['nullable', 'string', 'max:255'],
]);
V5RealtimeTestEvent::dispatch(
$currentTeam->id,
$validated['message'] ?? 'Manual v5 realtime test'
);
return response()->json([
'message' => 'Realtime test event broadcasted.',
], 202);
}
public function updateSelection(Request $request): \Illuminate\Http\Response
{
$currentTeam = $this->currentTeamOrFail($request);
$validated = $request->validate([
'project_uuid' => ['required', 'string'],
'environment_uuid' => ['nullable', 'string'],
]);
$project = $this->projectQuery($currentTeam)
->where('uuid', $validated['project_uuid'])
->first();
if (! $project instanceof Project) {
abort(403);
}
$environment = $this->selectedEnvironment($project, $validated['environment_uuid'] ?? null);
$request->session()->put([
self::SELECTED_PROJECT_SESSION_KEY => $project->uuid,
self::SELECTED_ENVIRONMENT_SESSION_KEY => $environment?->uuid,
]);
return response()->noContent();
}
/**
* @return array<int, array<string, mixed>>
*/
private function applications(mixed $currentTeam, ?array $selectedProject, ?array $selectedEnvironment): array
{
if (! $currentTeam instanceof Team || $selectedProject === null || $selectedEnvironment === null) {
return [];
}
return $this->applicationQuery($currentTeam, $selectedProject, $selectedEnvironment)
->with('server')
->orderBy('created_at')
->get()
->map(fn (V5Application $application) => $this->serializeApplication($application))
->all();
}
/**
* @return array<int, array<string, mixed>>
*/
private function resourceConnections(mixed $currentTeam, ?array $selectedProject, ?array $selectedEnvironment): array
{
if (! $currentTeam instanceof Team || $selectedProject === null || $selectedEnvironment === null) {
return [];
}
return ResourceConnection::query()
->where('team_id', $currentTeam->id)
->whereHas('project', fn (Builder $query) => $query
->where('team_id', $currentTeam->id)
->where('uuid', $selectedProject['uuid']))
->whereHas('environment', fn (Builder $query) => $query
->where('uuid', $selectedEnvironment['uuid']))
->with('rules')
->orderBy('id')
->get()
->map(fn (ResourceConnection $connection) => $this->connectionSerializer->serialize($connection))
->all();
}
private function nginxServers(mixed $currentTeam): array
{
if (! $currentTeam instanceof Team) {
return [];
}
return V5Server::query()
->where('team_id', $currentTeam->id)
->orderByRaw('last_bootstrapped_at is null')
->orderBy('name')
->get(['id', 'uuid', 'name', 'host', 'status'])
->map(fn (V5Server $server) => [
'id' => $server->uuid,
'name' => $server->name,
'host' => $server->host,
'status' => $server->status,
])
->all();
}
}
@@ -0,0 +1,331 @@
<?php
namespace App\Http\Controllers\V5;
use App\Http\Controllers\Controller;
use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;
use App\Http\Controllers\V5\Concerns\ResolvesProjectSelection;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Team;
use App\Models\V5\Application as V5Application;
use App\Models\V5\ResourceConnection;
use App\Services\Flux\FluxClient;
use App\Support\V5\ConnectionFirewallSync;
use App\Support\V5\ResourceConnectionSerializer;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\Rule;
class ResourceConnectionController extends Controller
{
use ResolvesCurrentTeam;
use ResolvesProjectSelection;
public function __construct(
private readonly ConnectionFirewallSync $firewallSync,
private readonly ResourceConnectionSerializer $connectionSerializer,
) {}
public function store(Request $request): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('create', [ResourceConnection::class, $currentTeam]);
$projects = $this->projects($currentTeam);
[$selectedProject, $selectedEnvironment] = $this->selectedProjectAndEnvironment($request, $projects);
if ($selectedProject === null || $selectedEnvironment === null) {
return response()->json([
'message' => 'Select a project and environment before connecting resources.',
], 422);
}
$project = $this->projectQuery($currentTeam)
->where('uuid', $selectedProject['uuid'])
->first();
if (! $project instanceof Project) {
abort(403);
}
$environment = $this->selectedEnvironment($project, $selectedEnvironment['uuid']);
if (! $environment instanceof Environment) {
abort(403);
}
$validated = $request->validate([
'resource_one' => ['required', 'array'],
'resource_one.type' => ['required', 'string', Rule::in(['application'])],
'resource_one.uuid' => ['required', 'string', 'max:255'],
'resource_two' => ['required', 'array'],
'resource_two.type' => ['required', 'string', Rule::in(['application'])],
'resource_two.uuid' => ['required', 'string', 'max:255'],
]);
$resourceOne = $this->resolveConnectableResource($currentTeam, $project, $environment, $validated['resource_one']);
$resourceTwo = $this->resolveConnectableResource($currentTeam, $project, $environment, $validated['resource_two']);
if ($this->resourceIdentity($resourceOne) === $this->resourceIdentity($resourceTwo)) {
return response()->json([
'message' => 'A resource cannot connect to itself.',
], 422);
}
$connection = ResourceConnection::query()->firstOrCreate(
[
'team_id' => $currentTeam->id,
'resource_pair_key' => $this->resourcePairKey($resourceOne, $resourceTwo),
],
[
'project_id' => $project->id,
'environment_id' => $environment->id,
'resource_one_type' => $resourceOne->getMorphClass(),
'resource_one_id' => $resourceOne->getKey(),
'resource_two_type' => $resourceTwo->getMorphClass(),
'resource_two_id' => $resourceTwo->getKey(),
'created_by_user_id' => $request->user()->id,
],
);
return response()->json([
'connection' => $this->connectionSerializer->serialize($connection->load('rules')),
], $connection->wasRecentlyCreated ? 201 : 200);
}
/**
* Update the connection's rules, then converge the node firewalls.
*
* Ordering & failure semantics:
* 1. Snapshot the current DB rules and their firewall representation; abort
* with 502 before mutating anything when the snapshot cannot be built.
* 2. Commit the requested rules in a DB transaction the DB always holds
* the desired state.
* 3. Converge the node firewalls through Flux. Nodes whose coold lacks the
* firewall verbs (UnsupportedCooldVerb) are tolerated: the committed
* rules are kept and the request succeeds.
* 4. On a real Flux failure the previous rules are restored in a second DB
* transaction, the node firewalls are rolled back to the restored rules
* best-effort (warning-logged when that also fails deterministic rule
* ids keep a later re-sync idempotent), and the original error surfaces
* to the caller as a 502 {message, detail} response.
*/
public function update(Request $request, ResourceConnection $connection, FluxClient $fluxClient): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('update', [$connection, $currentTeam]);
$validated = $request->validate([
'ports_by_direction' => ['present', 'array'],
'ports_by_direction.*' => ['array'],
'ports_by_direction.*.*' => ['integer', 'min:1', 'max:65535', 'distinct'],
]);
$connection->load('rules');
$oldRulePayloads = $connection->rules
->map(fn ($rule): array => [
'source_resource_type' => $rule->source_resource_type,
'source_resource_id' => $rule->source_resource_id,
'target_resource_type' => $rule->target_resource_type,
'target_resource_id' => $rule->target_resource_id,
'protocol' => $rule->protocol,
'port' => $rule->port,
])
->all();
try {
$oldFirewallRules = $this->firewallSync->rulesFor($connection);
} catch (\RuntimeException $exception) {
report($exception);
Log::warning('V5 resource connection firewall snapshot failed', [
'connection_id' => $connection->id,
'message' => $exception->getMessage(),
]);
return response()->json([
'message' => 'Could not sync firewall rules through Flux.',
'detail' => 'The connection was left unchanged. Check the server diagnostics and try again.',
], 502);
}
DB::transaction(function () use ($connection, $validated): void {
$connection->rules()->delete();
$resourcesByUuid = $this->connectionSerializer->applicationsByUuid($connection);
foreach ($validated['ports_by_direction'] as $direction => $ports) {
[$sourceResourceUuid, $targetResourceUuid] = array_pad(explode('->', (string) $direction, 2), 2, null);
$sourceResource = is_string($sourceResourceUuid) ? $resourcesByUuid->get($sourceResourceUuid) : null;
$targetResource = is_string($targetResourceUuid) ? $resourcesByUuid->get($targetResourceUuid) : null;
if (! $sourceResource instanceof V5Application || ! $targetResource instanceof V5Application) {
continue;
}
foreach (array_unique($ports) as $port) {
$connection->rules()->create([
'source_resource_type' => $this->resourceTypeForConnectionUuid($connection, $sourceResource->uuid),
'source_resource_id' => $sourceResource->id,
'target_resource_type' => $this->resourceTypeForConnectionUuid($connection, $targetResource->uuid),
'target_resource_id' => $targetResource->id,
'protocol' => 'tcp',
'port' => (int) $port,
]);
}
}
});
$connection->refresh()->load('rules');
$newFirewallRules = null;
try {
$newFirewallRules = $this->firewallSync->rulesFor($connection);
$this->firewallSync->sync($fluxClient, $oldFirewallRules, $newFirewallRules);
} catch (\RuntimeException $exception) {
$this->restoreConnectionRules($connection, $oldRulePayloads);
$this->rollBackFirewallRules($fluxClient, $connection, $newFirewallRules, $oldFirewallRules);
report($exception);
Log::warning('V5 resource connection firewall sync failed', [
'connection_id' => $connection->id,
'message' => $exception->getMessage(),
]);
return response()->json([
'message' => 'Could not sync firewall rules through Flux.',
'detail' => 'The previous rules were restored. Check the server diagnostics and try again.',
], 502);
}
return response()->json([
'connection' => $this->connectionSerializer->serialize($connection),
]);
}
/**
* Delete the connection using revoke-first ordering.
*
* The node firewall rules are revoked before any DB rows are removed. When
* a revoke fails with a real error the delete is aborted with a 502
* {message, detail} response so the DB never loses track of rules that may
* still be open on a reachable node; UnsupportedCooldVerb and
* already-missing rules are tolerated. When the firewall snapshot cannot
* be built (an endpoint lost its server host id) the node cannot be
* addressed at all, so the failure is reported and the delete proceeds.
* Deterministic rule ids make a retried delete revoke the same node-side
* rules idempotently.
*/
public function destroy(Request $request, ResourceConnection $connection, FluxClient $fluxClient): Response|JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('delete', [$connection, $currentTeam]);
try {
$oldFirewallRules = $this->firewallSync->rulesFor($connection->load('rules'));
} catch (\RuntimeException $exception) {
report($exception);
$oldFirewallRules = collect();
}
try {
$this->firewallSync->sync($fluxClient, $oldFirewallRules, collect());
} catch (\RuntimeException $exception) {
report($exception);
Log::warning('V5 resource connection firewall revoke failed', [
'connection_id' => $connection->id,
'message' => $exception->getMessage(),
]);
return response()->json([
'message' => 'Could not sync firewall rules through Flux.',
'detail' => 'The connection was not deleted. Check the server diagnostics and try again.',
], 502);
}
$connection->delete();
return response()->noContent();
}
/**
* @param array{type: string, uuid: string} $resource
*/
private function resolveConnectableResource(Team $team, Project $project, Environment $environment, array $resource): Model
{
return match ($resource['type']) {
'application' => V5Application::query()
->where('team_id', $team->id)
->where('project_id', $project->id)
->where('environment_id', $environment->id)
->where('uuid', $resource['uuid'])
->firstOrFail(),
};
}
private function resourcePairKey(Model $resourceOne, Model $resourceTwo): string
{
return collect([
$this->resourceIdentity($resourceOne),
$this->resourceIdentity($resourceTwo),
])->sort()->implode('|');
}
private function resourceIdentity(Model $resource): string
{
return $resource->getMorphClass().':'.$resource->getKey();
}
private function resourceTypeForConnectionUuid(ResourceConnection $connection, string $resourceUuid): string
{
$resourcesByUuid = $this->connectionSerializer->applicationsByUuid($connection);
$resource = $resourcesByUuid->get($resourceUuid);
return $resource instanceof V5Application && (int) $connection->resource_one_id === $resource->id
? $connection->resource_one_type
: $connection->resource_two_type;
}
/**
* @param array<int, array<string, mixed>> $rulePayloads
*/
private function restoreConnectionRules(ResourceConnection $connection, array $rulePayloads): void
{
DB::transaction(function () use ($connection, $rulePayloads): void {
$connection->rules()->delete();
foreach ($rulePayloads as $rulePayload) {
$connection->rules()->create($rulePayload);
}
});
}
/**
* Best-effort roll back of a partially converged node firewall to the
* restored rules after a failed forward sync. Skipped when the forward
* sync never started (the node was not touched). Failures are only logged
* because the DB already holds the restored, authoritative rules and the
* deterministic rule ids keep a later re-sync idempotent.
*
* @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}>|null $attemptedFirewallRules
* @param Collection<int, array{id: string, hostId: string, rule: array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}}> $restoredFirewallRules
*/
private function rollBackFirewallRules(FluxClient $fluxClient, ResourceConnection $connection, ?Collection $attemptedFirewallRules, Collection $restoredFirewallRules): void
{
if (! $attemptedFirewallRules instanceof Collection) {
return;
}
try {
$this->firewallSync->sync($fluxClient, $attemptedFirewallRules, $restoredFirewallRules);
} catch (\RuntimeException $exception) {
Log::warning('V5 resource connection firewall rollback failed; node firewall may diverge from the restored rules until the next sync', [
'connection_id' => $connection->id,
'message' => $exception->getMessage(),
]);
}
}
}
@@ -0,0 +1,901 @@
<?php
namespace App\Http\Controllers\V5;
use App\Actions\V5\Proxy\StartCaddyIngress;
use App\Actions\V5\Proxy\StopCaddyIngress;
use App\Actions\V5\Server\RemoveBootstrapMarker;
use App\Enums\V5\ServerStatus;
use App\Events\V5ClusterUpdated;
use App\Http\Controllers\Controller;
use App\Http\Controllers\V5\Concerns\HandlesIngressSyncErrors;
use App\Http\Controllers\V5\Concerns\ResolvesCurrentTeam;
use App\Http\Controllers\V5\Concerns\ValidatesBuilderConfiguration;
use App\Jobs\V5BootstrapServerJob;
use App\Models\PrivateKey;
use App\Models\V5\Application as V5Application;
use App\Models\V5\Cluster as V5Cluster;
use App\Models\V5\Server as V5Server;
use App\Rules\ValidServerIp;
use App\Services\Flux\AgentTokenIssuer;
use App\Services\Flux\FluxClient;
use App\Support\V5\ClusterSerializer;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Validation\Rule;
class ServerController extends Controller
{
use HandlesIngressSyncErrors;
use ResolvesCurrentTeam;
use ValidatesBuilderConfiguration;
public function store(Request $request, V5Cluster $cluster): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('create', [V5Server::class, $currentTeam, $cluster]);
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'host' => [
'required',
'string',
'max:255',
$this->noControlCharactersRule(),
new ValidServerIp,
Rule::unique('v5_servers', 'host')
->where('team_id', $currentTeam->id)
->where('ssh_port', (int) $request->input('ssh_port', 22)),
],
'ssh_user' => ['required', 'string', 'max:255', 'regex:/^[A-Za-z0-9._-]+$/', $this->noControlCharactersRule()],
'ssh_port' => ['required', 'integer', 'min:1', 'max:65535'],
'private_key_uuid' => [
'required',
'string',
Rule::exists('private_keys', 'uuid')->where('team_id', $currentTeam->id),
],
'node_address' => [
'nullable',
'string',
'max:255',
$this->noControlCharactersRule(),
new ValidServerIp,
Rule::unique('v5_servers', 'node_address')->where('team_id', $currentTeam->id),
],
'builder_enabled' => ['sometimes', 'boolean'],
'builder_capacity' => $this->builderCapacityRules(
$this->requestedBuilderEnabled($request, $cluster->builder_enabled)
),
'builder_cpu_quota' => ['sometimes', 'string', 'max:32'],
'wireguard_listen_port_override' => ['nullable', 'integer', 'min:1', 'max:65535'],
'wireguard_endpoint_override' => [
'nullable',
'string',
'max:255',
$this->noControlCharactersRule(),
$this->hostPortRule(),
Rule::unique('v5_servers', 'wireguard_endpoint_override')->where('cluster_id', $cluster->id),
],
'ingress_enabled' => ['sometimes', 'boolean'],
'ingress_type' => [
Rule::requiredIf(fn () => $request->boolean('ingress_enabled')),
'nullable',
'string',
Rule::in(['caddy']),
],
]);
$capacity = $this->clusterServerCapacity($cluster);
if ($capacity !== null && $cluster->servers()->count() >= $capacity) {
return response()->json([
'message' => "This cluster's network pools are full ({$capacity} server(s) max). Grow the pools or remove a server first.",
], 422);
}
$builderEnabled = (bool) ($validated['builder_enabled'] ?? $cluster->builder_enabled);
$ingressEnabled = (bool) ($validated['ingress_enabled'] ?? false);
$ingressType = $ingressEnabled ? $validated['ingress_type'] : null;
$builderCapacity = (int) ($validated['builder_capacity'] ?? $cluster->builder_capacity);
$builderCpuQuota = $validated['builder_cpu_quota'] ?? $cluster->builder_cpu_quota;
$devWireguardOverrides = $this->devLimaWireguardOverrides($validated['host'], (int) $validated['ssh_port']);
$privateKey = PrivateKey::query()
->where('team_id', $currentTeam->id)
->where('uuid', $validated['private_key_uuid'])
->firstOrFail();
V5Server::query()->create([
'team_id' => $currentTeam->id,
'cluster_id' => $cluster->id,
'created_by_user_id' => $request->user()->id,
'name' => $validated['name'],
'host' => $validated['host'],
'ssh_user' => $validated['ssh_user'],
'ssh_port' => $validated['ssh_port'],
'private_key_id' => $privateKey->id,
'status' => ServerStatus::Added->value,
'ingress_type' => $ingressType,
'is_ingress' => $ingressEnabled,
'builder_enabled' => $builderEnabled,
'builder_capacity' => $builderCapacity,
'builder_cpu_quota' => $builderCpuQuota,
'node_address' => $validated['node_address'] ?? $validated['host'],
'wireguard_listen_port_override' => $validated['wireguard_listen_port_override'] ?? $devWireguardOverrides['listen_port'],
'wireguard_endpoint_override' => $validated['wireguard_endpoint_override'] ?? $devWireguardOverrides['endpoint'],
]);
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
], 201);
}
public function update(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('update', [$server, $currentTeam, $cluster]);
$validated = $request->validate([
'builder_enabled' => ['required', 'boolean'],
'builder_capacity' => $this->builderCapacityRules(
$request->boolean('builder_enabled'),
required: true
),
'builder_cpu_quota' => ['required', 'string', 'max:32'],
'ingress_enabled' => ['sometimes', 'boolean'],
'ingress_type' => [
Rule::requiredIf(fn () => $request->boolean('ingress_enabled')),
'nullable',
'string',
Rule::in(['caddy']),
],
]);
$wasIngress = $server->isIngress();
$builderEnabled = (bool) $validated['builder_enabled'];
$ingressEnabled = (bool) ($validated['ingress_enabled'] ?? $wasIngress);
$ingressType = $ingressEnabled ? ($validated['ingress_type'] ?? $server->ingress_type ?? 'caddy') : null;
$originalServerAttributes = $server->only([
'is_ingress',
'ingress_type',
'ingress_status',
'builder_enabled',
'builder_capacity',
'builder_cpu_quota',
]);
// Stop the ingress before persisting the change: StopCaddyIngress needs
// the server's current ingress state, and a failed stop must leave the
// capability untouched.
if ($wasIngress && ! $ingressEnabled && $server->status === ServerStatus::Installed->value) {
try {
StopCaddyIngress::run($server);
} catch (\RuntimeException $exception) {
return $this->ingressSyncErrorResponse($exception);
}
}
$server->update([
'is_ingress' => $ingressEnabled,
'ingress_type' => $ingressType,
'builder_enabled' => $builderEnabled,
'builder_capacity' => (int) $validated['builder_capacity'],
'builder_cpu_quota' => $validated['builder_cpu_quota'],
]);
$server->refresh();
if (! $wasIngress && $ingressEnabled && $server->status === ServerStatus::Installed->value) {
try {
StartCaddyIngress::run($server);
} catch (\RuntimeException $exception) {
$server->update($originalServerAttributes);
return $this->ingressSyncErrorResponse($exception);
}
}
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
]);
}
public function check(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('check', [$server, $currentTeam, $cluster]);
if (! $server->privateKey instanceof PrivateKey) {
return response()->json([
'status' => 'failed',
'output' => 'No private key is attached to this server.',
'checkedAt' => now()->toJSON(),
]);
}
$keyDirectory = storage_path('app/ssh/keys');
if (! is_dir($keyDirectory)) {
mkdir($keyDirectory, 0700, true);
}
$keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');
if ($keyLocation === false) {
return response()->json([
'status' => 'failed',
'output' => 'Could not create a temporary SSH key file.',
'checkedAt' => now()->toJSON(),
]);
}
file_put_contents($keyLocation, $server->privateKey->private_key);
chmod($keyLocation, 0600);
$target = "{$server->ssh_user}@{$server->host}";
$command = [
'ssh',
'-o',
'BatchMode=yes',
'-o',
'LogLevel=ERROR',
'-o',
'StrictHostKeyChecking=no',
'-o',
'UserKnownHostsFile=/dev/null',
'-o',
'ConnectTimeout=10',
'-o',
'IdentitiesOnly=yes',
'-i',
$keyLocation,
'-p',
(string) $server->ssh_port,
$target,
"printf 'SSH connection OK\n'; hostname; uname -srm; command -v docker || true; command -v podman || true",
];
try {
$result = Process::timeout(15)->run($command);
$output = trim($result->output()."\n".$result->errorOutput());
$status = $result->successful() ? 'reachable' : 'failed';
} catch (\Throwable $e) {
$output = $e->getMessage();
$status = 'failed';
} finally {
@unlink($keyLocation);
}
return response()->json([
'status' => $status,
'output' => str($output !== '' ? $output : 'No output returned.')->limit(10000)->toString(),
'checkedAt' => now()->toJSON(),
]);
}
public function restartCoold(Request $request, V5Cluster $cluster, V5Server $server, AgentTokenIssuer $agentTokenIssuer, FluxClient $fluxClient): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('restartCoold', [$server, $currentTeam, $cluster]);
$server->loadMissing('privateKey');
if (! $server->privateKey instanceof PrivateKey) {
return response()->json([
'message' => 'No private key is attached to this server.',
], 422);
}
try {
$token = $agentTokenIssuer->issueForServer($server);
$output = $this->restartCooldOverSsh($server, $token);
} catch (\Throwable $e) {
Log::warning('V5 coold restart over SSH failed', [
'server_id' => $server->id,
'message' => $e->getMessage(),
]);
return response()->json([
'message' => str($e->getMessage() !== '' ? $e->getMessage() : 'Could not restart coold over SSH.')->limit(10000)->toString(),
], 502);
}
$connected = false;
try {
usleep(500_000);
$fluxClient->cooldLogs($server->fluxHostId(), 1);
$connected = true;
$server->forceFill([
'status' => ServerStatus::Installed->value,
'last_status_check' => 'flux',
'last_status_output' => 'coold restarted over SSH and reconnected to Flux.',
])->save();
} catch (\Throwable $e) {
Log::info('V5 coold restart succeeded but Flux reconnect is not confirmed yet', [
'server_id' => $server->id,
'message' => $e->getMessage(),
]);
}
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
'output' => $output,
'connected' => $connected,
'restartedAt' => now()->toJSON(),
]);
}
private function restartCooldOverSsh(V5Server $server, string $token): string
{
$encodedToken = base64_encode($token);
$script = implode(PHP_EOL, [
'set -e',
"SUDO=''",
'if [ "$(id -u)" != "0" ]; then SUDO="sudo -n"; fi',
'$SUDO mkdir -p /etc/coolify',
'printf %s '.escapeshellarg($encodedToken).' | base64 -d | $SUDO tee /etc/coolify/host-jwt >/dev/null',
'$SUDO chmod 600 /etc/coolify/host-jwt',
'$SUDO systemctl reset-failed coold.service || true',
'$SUDO systemctl restart coold.service',
'$SUDO systemctl is-active coold.service',
'$SUDO systemctl status coold.service --no-pager -l | sed -n "1,18p"',
]);
return $this->runServerSshCommand($server, $script, 'SSH coold restart command failed.', 45);
}
public function cooldLogs(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('viewDiagnostics', [$server, $currentTeam, $cluster]);
$validated = $request->validate([
'tail' => ['sometimes', 'integer', 'min:1', 'max:1000'],
]);
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
return response()->json([
'message' => 'This server is missing its Flux host id.',
], 422);
}
try {
$output = $fluxClient->cooldLogs($hostId, (int) ($validated['tail'] ?? 200));
} catch (\Throwable $e) {
Log::warning('V5 coold logs request failed', [
'server_id' => $server->id,
'message' => $e->getMessage(),
]);
if ($server->privateKey instanceof PrivateKey) {
try {
return response()->json([
'output' => $this->cooldLogsOverSsh($server, (int) ($validated['tail'] ?? 200)),
'source' => 'ssh',
'fetchedAt' => now()->toJSON(),
]);
} catch (\Throwable $sshException) {
Log::warning('V5 coold logs SSH fallback failed', [
'server_id' => $server->id,
'message' => $sshException->getMessage(),
]);
}
}
return response()->json([
'message' => 'Could not fetch coold logs through Flux. Check the Flux and coold status, then try again.',
], 502);
}
return response()->json([
'output' => $output,
'source' => 'flux',
'fetchedAt' => now()->toJSON(),
]);
}
private function cooldLogsOverSsh(V5Server $server, int $tail): string
{
return $this->runServerSshCommand(
$server,
'sudo -n journalctl -u coold -n '.max(1, min($tail, 1000)).' --no-pager -q || journalctl -u coold -n '.max(1, min($tail, 1000)).' --no-pager -q',
'SSH coold log command failed.',
);
}
private function runServerSshCommand(V5Server $server, string $remoteCommand, string $failureMessage, int $timeout = 15): string
{
$keyDirectory = storage_path('app/ssh/keys');
if (! is_dir($keyDirectory)) {
mkdir($keyDirectory, 0700, true);
}
$keyLocation = tempnam($keyDirectory, 'v5_ssh_key_');
if ($keyLocation === false) {
throw new \RuntimeException('Could not create a temporary SSH key file.');
}
file_put_contents($keyLocation, $server->privateKey->private_key);
chmod($keyLocation, 0600);
try {
$result = Process::timeout($timeout)->run([
'ssh',
'-o',
'BatchMode=yes',
'-o',
'LogLevel=ERROR',
'-o',
'StrictHostKeyChecking=no',
'-o',
'UserKnownHostsFile=/dev/null',
'-o',
'ConnectTimeout=10',
'-o',
'IdentitiesOnly=yes',
'-i',
$keyLocation,
'-p',
(string) $server->ssh_port,
"{$server->ssh_user}@{$server->host}",
$remoteCommand,
]);
$output = trim($result->output()."\n".$result->errorOutput());
if (! $result->successful()) {
throw new \RuntimeException($output !== '' ? $output : $failureMessage);
}
return str($output)->limit(10000)->toString();
} finally {
@unlink($keyLocation);
}
}
public function corrosionTables(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('viewDiagnostics', [$server, $currentTeam, $cluster]);
$validated = $request->validate([
'limit' => ['sometimes', 'integer', 'min:1', 'max:1000'],
]);
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
return response()->json([
'message' => 'This server is missing its Flux host id.',
], 422);
}
try {
$output = $fluxClient->corrosionTables($hostId, (int) ($validated['limit'] ?? 200));
} catch (\Throwable $e) {
Log::warning('V5 corrosion tables request failed', [
'server_id' => $server->id,
'message' => $e->getMessage(),
]);
if ($server->privateKey instanceof PrivateKey) {
try {
return response()->json([
'output' => $this->corrosionTablesOverSsh($server, $cluster, (int) ($validated['limit'] ?? 200)),
'source' => 'ssh',
'fetchedAt' => now()->toJSON(),
]);
} catch (\Throwable $sshException) {
Log::warning('V5 corrosion tables SSH fallback failed', [
'server_id' => $server->id,
'message' => $sshException->getMessage(),
]);
}
}
return response()->json([
'message' => 'Could not fetch corrosion tables through Flux. Check the Flux and coold status, then try again.',
], 502);
}
return response()->json([
'output' => $output,
'source' => 'flux',
'fetchedAt' => now()->toJSON(),
]);
}
private function corrosionTablesOverSsh(V5Server $server, V5Cluster $cluster, int $limit): string
{
$limit = max(1, min($limit, 1000));
$script = <<<'PYTHON'
python3 - <<'PY'
import json
import urllib.request
limit = __LIMIT__
url = "http://127.0.0.1:__PORT__/v1/queries"
def query(sql):
request = urllib.request.Request(
url,
data=json.dumps([sql, []]).encode(),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=10) as response:
return json.loads(response.read().decode())
def quote_identifier(value):
return '"' + value.replace('"', '""') + '"'
tables = []
for row in query("SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"):
name = row[0] if row else None
if not isinstance(name, str):
continue
identifier = quote_identifier(name)
columns = [column[1] for column in query(f"PRAGMA table_info({identifier})") if len(column) > 1]
rows = query(f"SELECT * FROM {identifier} LIMIT {limit}")
tables.append({"name": name, "columns": columns, "rows": rows})
print(json.dumps({"limit": limit, "tables": tables}, separators=(",", ":")))
PY
PYTHON;
return $this->runServerSshCommand($server, str_replace(
['__LIMIT__', '__PORT__'],
[(string) $limit, (string) $cluster->corrosion_api_port],
$script,
), 'SSH corrosion table command failed.');
}
public function firewallRules(Request $request, V5Cluster $cluster, V5Server $server, FluxClient $fluxClient): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('viewDiagnostics', [$server, $currentTeam, $cluster]);
$validated = $request->validate([
'namespace' => ['sometimes', 'string', 'max:63'],
]);
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
return response()->json([
'message' => 'This server is missing its Flux host id.',
], 422);
}
try {
$rules = $fluxClient->listFirewallRules($hostId, (string) ($validated['namespace'] ?? ''));
} catch (\Throwable $e) {
Log::warning('V5 firewall rules request failed', [
'server_id' => $server->id,
'message' => $e->getMessage(),
]);
if ($server->privateKey instanceof PrivateKey) {
try {
return response()->json([
'rules' => $this->firewallRulesOverSsh($server, (string) ($validated['namespace'] ?? '')),
'source' => 'ssh',
'fetchedAt' => now()->toJSON(),
]);
} catch (\Throwable $sshException) {
Log::warning('V5 firewall rules SSH fallback failed', [
'server_id' => $server->id,
'message' => $sshException->getMessage(),
]);
}
}
return response()->json([
'message' => 'Could not fetch firewall rules through Flux. Check the Flux and coold status, then try again.',
], 502);
}
return response()->json([
'rules' => $rules,
'source' => 'flux',
'fetchedAt' => now()->toJSON(),
]);
}
/**
* @return array<int, array{id: string, namespace: string, src: string, dst: string, proto: string, port: int}>
*/
private function firewallRulesOverSsh(V5Server $server, string $namespace): array
{
$script = str_replace('__NAMESPACE__', json_encode($namespace, JSON_THROW_ON_ERROR), <<<'PYTHON'
python3 - <<'PY'
import json
from pathlib import Path
namespace = __NAMESPACE__
path = Path("/etc/coolify/firewall-rules.tsv")
rules = []
if path.exists():
for line in path.read_text().splitlines():
parts = line.split("\t")
if len(parts) == 6:
rule_id, rule_namespace, src, dst, proto, port = parts
elif len(parts) == 5:
rule_id = ""
rule_namespace, src, dst, proto, port = parts
else:
continue
if namespace and rule_namespace != namespace:
continue
try:
port = int(port)
except ValueError:
continue
rules.append({
"id": rule_id,
"namespace": rule_namespace,
"src": src,
"dst": dst,
"proto": proto,
"port": port,
})
print(json.dumps(rules, separators=(",", ":")))
PY
PYTHON);
$output = $this->runServerSshCommand($server, $script, 'SSH firewall rules command failed.');
$rules = json_decode($output, true, 512, JSON_THROW_ON_ERROR);
return is_array($rules) ? $rules : [];
}
public function bootstrap(Request $request, V5Cluster $cluster, V5Server $server): JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('bootstrap', [$server, $currentTeam, $cluster]);
// Fail fast: the bootstrap job hard-fails on Flux enrollment (after
// the WireGuard mesh is already built) when no Flux URL is configured.
if (trim((string) config('coold.flux_url', '')) === '') {
return response()->json([
'message' => 'COOLIFY_COOLD_FLUX_URL is not configured, so bootstrapped servers cannot be enrolled into Flux. Set it and retry the bootstrap.',
], 422);
}
if ($server->last_bootstrapped_at !== null) {
return response()->json([
'message' => 'This server is already bootstrapped.',
], 409);
}
$installedServers = $cluster->servers()
->with('privateKey')
->whereNotNull('last_bootstrapped_at')
->orderBy('name')
->get();
$server->load('privateKey');
$servers = $installedServers->toBase()
->push($server)
->unique('id')
->values();
if ($servers->contains(fn (V5Server $server) => ! $server->privateKey instanceof PrivateKey)) {
return response()->json([
'message' => 'The new server and every already-bootstrapped server in this cluster must have a private key before extending the cluster.',
], 422);
}
$claim = DB::transaction(function () use ($cluster, $server, $installedServers): array {
$clusterServers = $cluster->servers()->lockForUpdate()->get();
$activeServer = $clusterServers->first(fn (V5Server $candidate): bool => $this->hasActiveBootstrapClaim($candidate));
if ($activeServer instanceof V5Server) {
return ['claimed' => false, 'active_server_id' => $activeServer->id];
}
// Sweep provably dead claims (lost job or killed worker) so retries
// are possible and the UI reflects reality.
$clusterServers
->filter(fn (V5Server $candidate): bool => in_array($candidate->last_bootstrap_status, ['queued', 'running'], true))
->each(fn (V5Server $candidate) => $candidate->update([
'last_bootstrap_status' => 'failed',
'last_bootstrap_output' => 'The previous bootstrap attempt timed out or its worker died. Retry the bootstrap.',
]));
$server->update([
'last_bootstrap_action' => $installedServers->isEmpty() ? 'bootstrap' : 'extend',
'last_bootstrap_status' => 'queued',
'last_bootstrap_output' => "Queued Coolify bootstrap for {$server->name}.",
'last_bootstrap_ran_at' => now(),
]);
return ['claimed' => true, 'active_server_id' => null];
});
if (! $claim['claimed']) {
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
'message' => $claim['active_server_id'] === $server->id
? 'Bootstrap is already queued or running for this server.'
: 'Another server bootstrap is already queued or running for this cluster.',
], 409);
}
V5ClusterUpdated::dispatch($currentTeam->id, $cluster->id);
V5BootstrapServerJob::dispatch($cluster->id, $server->id);
return response()->json([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
'message' => 'Bootstrap queued.',
], 202);
}
public function destroy(Request $request, V5Cluster $cluster, V5Server $server): Response|JsonResponse
{
$currentTeam = $this->currentTeamOrFail($request);
$this->authorize('delete', [$server, $currentTeam, $cluster]);
if (V5Application::query()->where('server_id', $server->id)->exists()) {
return response()->json([
'message' => 'Delete or move applications from this server before deleting it.',
], 422);
}
$warning = null;
if ($server->last_bootstrapped_at !== null) {
if ($server->isIngress() && $server->status === ServerStatus::Installed->value) {
try {
StopCaddyIngress::run($server);
} catch (\Throwable $exception) {
report($exception);
$warning = 'Could not stop the Caddy ingress on the server before deleting it.';
}
}
if (! RemoveBootstrapMarker::run($server)) {
$warning = 'Could not clean up the server over SSH. Remove /etc/coolify/v5-node.json manually before re-adding this server.';
}
}
$server->delete();
return response()->json(array_filter([
'cluster' => app(ClusterSerializer::class)->serializeFresh($cluster),
'warning' => $warning,
]));
}
/**
* A queued claim is active while the job could still pick it up; a running
* claim is active until the job timeout (plus margin) has passed. Anything
* older is provably dead because the job runs with $tries = 1.
*/
private function hasActiveBootstrapClaim(V5Server $server): bool
{
$ranAt = $server->last_bootstrap_ran_at;
return match ($server->last_bootstrap_status) {
'queued' => $ranAt !== null && $ranAt->gt(now()->subMinutes(15)),
'running' => $ranAt !== null && $ranAt->gt(now()->subSeconds(V5BootstrapServerJob::TIMEOUT_SECONDS + 300)),
default => false,
};
}
/**
* @return array{listen_port: int|null, endpoint: string|null}
*/
private function devLimaWireguardOverrides(string $host, int $sshPort): array
{
if (! app()->environment(['local', 'development', 'testing']) || $host !== 'host.docker.internal') {
return ['listen_port' => null, 'endpoint' => null];
}
if ($sshPort < 60001 || $sshPort > 60009) {
return ['listen_port' => null, 'endpoint' => null];
}
$wireguardPort = $sshPort - 8180;
return [
'listen_port' => $wireguardPort,
'endpoint' => "host.lima.internal:{$wireguardPort}",
];
}
private function clusterServerCapacity(V5Cluster $cluster): ?int
{
$namespaceCount = max(1, count($cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES));
[, $poolPrefix] = array_pad(explode('/', (string) $cluster->container_network_pool, 2), 2, null);
$containerPrefix = (int) $cluster->container_network_prefix;
if (! is_string($poolPrefix) || ! ctype_digit($poolPrefix) || $containerPrefix < (int) $poolPrefix || $containerPrefix > 32) {
return null;
}
$containerCapacity = intdiv(2 ** ($containerPrefix - (int) $poolPrefix), $namespaceCount);
[, $managementPrefix] = array_pad(explode('/', (string) $cluster->wireguard_management_pool, 2), 2, null);
$managementCapacity = is_string($managementPrefix) && ctype_digit($managementPrefix) && (int) $managementPrefix <= 30
? (2 ** (32 - (int) $managementPrefix)) - 2
: null;
return $managementCapacity === null ? $containerCapacity : min($containerCapacity, $managementCapacity);
}
private function noControlCharactersRule(): \Closure
{
return function (string $attribute, mixed $value, \Closure $fail): void {
if (! is_string($value)) {
return;
}
if (preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {
$fail('The :attribute contains invalid control characters.');
}
};
}
private function hostPortRule(): \Closure
{
return function (string $attribute, mixed $value, \Closure $fail): void {
if ($value === null || $value === '') {
return;
}
if (! is_string($value)) {
$fail('The :attribute must be in host:port format.');
return;
}
$value = trim($value);
if (preg_match('/^\[(?<host>.+)]:(?<port>\d+)$/', $value, $matches) === 1) {
$host = trim((string) $matches['host']);
$port = trim((string) $matches['port']);
} else {
$separatorPosition = strrpos($value, ':');
if ($separatorPosition === false) {
$fail('The :attribute must be in host:port format.');
return;
}
$host = trim(substr($value, 0, $separatorPosition));
$port = trim(substr($value, $separatorPosition + 1));
if (str_contains($host, ':')) {
$fail('The :attribute must use [ipv6]:port format for IPv6 addresses.');
return;
}
}
if ($host === '' || $port === '' || ! ctype_digit($port) || (int) $port < 1 || (int) $port > 65535) {
$fail('The :attribute must be in host:port format.');
return;
}
$failed = false;
(new ValidServerIp)->validate($attribute, $host, function () use (&$failed): void {
$failed = true;
});
if ($failed) {
$fail('The :attribute must be in host:port format.');
}
};
}
}
+305 -2
View File
@@ -6,10 +6,14 @@ use App\Actions\Application\CleanupPreviewDeployment;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Webhook\Concerns\DetectsSkipDeployCommits;
use App\Http\Controllers\Webhook\Concerns\MatchesManualWebhookApplications;
use App\Livewire\Source\Gitlab\Change as GitlabSource;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\GitlabApp;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
class Gitlab extends Controller
@@ -17,6 +21,307 @@ class Gitlab extends Controller
use DetectsSkipDeployCommits;
use MatchesManualWebhookApplications;
public function redirect(Request $request)
{
try {
$code = $request->query('code');
$state = $request->query('state');
if (! $code || ! $state) {
return redirect()->route('source.all')->with('error', 'Invalid GitLab OAuth callback. Missing code or state.');
}
// Validate the one-time, team-bound state (not a guessable source UUID) to stop forged callbacks from overwriting a source's tokens.
$payload = Cache::pull(GitlabSource::oauthStateCacheKey($state));
$team_id = $request->user()?->currentTeam()?->id;
if (! is_array($payload) || is_null($team_id) || (int) data_get($payload, 'team_id') !== (int) $team_id) {
return redirect()->route('source.all')->with('error', 'Invalid or expired GitLab OAuth state. Please start the authorization again.');
}
$gitlabApp = GitlabApp::whereKey(data_get($payload, 'gitlab_app_id'))->firstOrFail();
// Only users who may administer the source can complete OAuth and store tokens.
if (! $request->user()->can('update', $gitlabApp)) {
return redirect()->route('source.all')->with('error', 'You are not authorized to connect this GitLab App.');
}
$baseUrl = rtrim($gitlabApp->html_url, '/');
$response = Http::asForm()->post("{$baseUrl}/oauth/token", [
'client_id' => $gitlabApp->client_id,
'client_secret' => $gitlabApp->client_secret,
'code' => $code,
'grant_type' => 'authorization_code',
'redirect_uri' => $gitlabApp->redirect_uri,
]);
if (! $response->successful()) {
$error = data_get($response->json(), 'error_description', 'Token exchange failed');
return redirect()->route('source.gitlab.show', ['gitlab_app_uuid' => $gitlabApp->uuid])
->with('error', "GitLab OAuth failed: {$error}");
}
$data = $response->json();
$gitlabApp->update([
'access_token' => $data['access_token'],
'refresh_token' => $data['refresh_token'],
'expires_at' => time() + ($data['expires_in'] ?? 7200),
]);
return redirect()->route('source.gitlab.show', ['gitlab_app_uuid' => $gitlabApp->uuid]);
} catch (Exception $e) {
return redirect()->route('source.all')->with('error', $e->getMessage());
}
}
public function normal(Request $request)
{
try {
$return_payloads = collect([]);
$payload = $request->collect();
$x_gitlab_token = $request->header('X-Gitlab-Token');
$object_kind = data_get($payload, 'object_kind');
$project_id = data_get($payload, 'project.id');
$allowed_events = ['push', 'merge_request'];
if (! in_array($object_kind, $allowed_events)) {
return response([
'status' => 'failed',
'message' => 'Event not allowed. Only push and merge_request events are allowed.',
]);
}
if (empty($x_gitlab_token)) {
auditLogWebhookFailure('gitlab', 'webhook_token_missing', [
'event' => $object_kind,
]);
return response([
'status' => 'failed',
'message' => 'Missing X-Gitlab-Token header.',
], 401);
}
$gitlab_app = GitlabApp::findByWebhookToken($x_gitlab_token);
if (! $gitlab_app) {
auditLogWebhookFailure('gitlab', 'invalid_token', [
'event' => $object_kind,
]);
return response([
'status' => 'failed',
'message' => 'Invalid webhook token.',
], 401);
}
$applications = Application::where('source_id', $gitlab_app->id)
->where('source_type', GitlabApp::class)
->where('repository_project_id', $project_id);
if ($object_kind === 'push') {
$branch = data_get($payload, 'ref');
if (Str::isMatch('/refs\/heads\/*/', $branch)) {
$branch = Str::after($branch, 'refs/heads/');
}
if (! $branch) {
return response([
'status' => 'failed',
'message' => 'No branch found in the request.',
]);
}
$applications = $applications->where('git_branch', $branch)->get();
$added_files = data_get($payload, 'commits.*.added');
$removed_files = data_get($payload, 'commits.*.removed');
$modified_files = data_get($payload, 'commits.*.modified');
$changed_files = collect($added_files)->concat($removed_files)->concat($modified_files)->unique()->flatten();
$skip_deploy_commits = self::shouldSkipDeploy(data_get($payload, 'commits.*.message', []));
foreach ($applications as $application) {
if (! $application->destination->server->isFunctional()) {
$return_payloads->push([
'application' => $application->name,
'status' => 'failed',
'message' => 'Server is not functional',
]);
continue;
}
if (! $application->isDeployable()) {
$return_payloads->push([
'application' => $application->name,
'status' => 'failed',
'message' => 'Deployments disabled',
]);
continue;
}
$is_watch_path_triggered = $application->isWatchPathsTriggered($changed_files);
if (! $is_watch_path_triggered && ! blank($application->watch_paths)) {
$return_payloads->push([
'application' => $application->name,
'status' => 'failed',
'message' => 'Changed files do not match watch paths.',
]);
continue;
}
if ($skip_deploy_commits) {
$return_payloads->push([
'application' => $application->name,
'status' => 'skipped',
'message' => 'All commits contain [skip cd] or [skip ci].',
]);
continue;
}
$deployment_uuid = new Cuid2;
$result = queue_application_deployment(
application: $application,
deployment_uuid: $deployment_uuid,
commit: data_get($payload, 'after', 'HEAD'),
force_rebuild: false,
is_webhook: true,
);
if ($result['status'] === 'queue_full') {
return response($result['message'], 429)->header('Retry-After', 60);
}
auditLog('webhook.deployment.queued', [
'provider' => 'gitlab',
'mode' => 'app',
'application_uuid' => $application->uuid,
'application_name' => $application->name,
'deployment_uuid' => $deployment_uuid->toString(),
'commit' => data_get($payload, 'after'),
]);
$return_payloads->push([
'application' => $application->name,
'status' => $result['status'] ?? 'success',
'message' => $result['message'] ?? 'Deployment queued.',
]);
}
}
if ($object_kind === 'merge_request') {
$action = data_get($payload, 'object_attributes.action');
$branch = data_get($payload, 'object_attributes.source_branch');
$base_branch = data_get($payload, 'object_attributes.target_branch');
$pull_request_id = data_get($payload, 'object_attributes.iid');
$pull_request_html_url = data_get($payload, 'object_attributes.url');
$pull_request_title = data_get($payload, 'object_attributes.title');
$latest_commit_message = data_get($payload, 'object_attributes.last_commit.message');
$skip_deploy_pr = self::shouldSkipDeployAny([$pull_request_title, $latest_commit_message]);
$applications = $applications->where('git_branch', $base_branch)->get();
foreach ($applications as $application) {
if (! $application->destination->server->isFunctional()) {
$return_payloads->push([
'application' => $application->name,
'status' => 'failed',
'message' => 'Server is not functional',
]);
continue;
}
if (in_array($action, ['open', 'opened', 'synchronize', 'reopened', 'reopen', 'update'])) {
if (! $application->isPRDeployable()) {
$return_payloads->push([
'application' => $application->name,
'status' => 'failed',
'message' => 'Preview deployments disabled',
]);
continue;
}
if ($skip_deploy_pr) {
$return_payloads->push([
'application' => $application->name,
'status' => 'skipped',
'message' => 'PR title or latest commit contains [skip cd] or [skip ci].',
]);
continue;
}
$deployment_uuid = new Cuid2;
$found = ApplicationPreview::where('application_id', $application->id)
->where('pull_request_id', $pull_request_id)
->first();
if (! $found) {
if ($application->build_pack === 'dockercompose') {
$pr_app = ApplicationPreview::create([
'git_type' => 'gitlab',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
'pull_request_html_url' => $pull_request_html_url,
'docker_compose_domains' => $application->docker_compose_domains,
]);
$pr_app->generate_preview_fqdn_compose();
} else {
$pr_app = ApplicationPreview::create([
'git_type' => 'gitlab',
'application_id' => $application->id,
'pull_request_id' => $pull_request_id,
'pull_request_html_url' => $pull_request_html_url,
]);
$pr_app->generate_preview_fqdn();
}
}
$result = queue_application_deployment(
application: $application,
pull_request_id: $pull_request_id,
deployment_uuid: $deployment_uuid,
commit: data_get($payload, 'object_attributes.last_commit.id', 'HEAD'),
force_rebuild: false,
is_webhook: true,
git_type: 'gitlab',
);
if ($result['status'] === 'queue_full') {
return response($result['message'], 429)->header('Retry-After', 60);
}
$return_payloads->push([
'application' => $application->name,
'status' => $result['status'] ?? 'success',
'message' => $result['message'] ?? 'Preview Deployment queued',
]);
} elseif (in_array($action, ['closed', 'close', 'merge'])) {
$found = ApplicationPreview::where('application_id', $application->id)
->where('pull_request_id', $pull_request_id)
->first();
if ($found) {
CleanupPreviewDeployment::run($application, $pull_request_id, $found);
$return_payloads->push([
'application' => $application->name,
'status' => 'success',
'message' => 'Preview deployment closed.',
]);
}
}
}
}
return response($return_payloads);
} catch (Exception $e) {
return handleError($e);
}
}
public function manual(Request $request)
{
try {
@@ -291,8 +596,6 @@ class Gitlab extends Controller
} elseif ($action === 'closed' || $action === 'close' || $action === 'merge') {
$found = ApplicationPreview::where('application_id', $application->id)->where('pull_request_id', $pull_request_id)->first();
if ($found) {
// Use comprehensive cleanup that cancels active deployments,
// kills helper containers, and removes all PR containers
CleanupPreviewDeployment::run($application, $pull_request_id, $found);
$return_payloads->push([
+22
View File
@@ -2,6 +2,7 @@
namespace App\Http;
use App\Http\Middleware\AddServerTimingHeaders;
use App\Http\Middleware\ApiAbility;
use App\Http\Middleware\ApiSensitiveData;
use App\Http\Middleware\Authenticate;
@@ -19,6 +20,8 @@ use App\Http\Middleware\RedirectIfAuthenticated;
use App\Http\Middleware\TrimStrings;
use App\Http\Middleware\TrustHosts;
use App\Http\Middleware\TrustProxies;
use App\Http\Middleware\V5\EnsureCurrentTeam as V5EnsureCurrentTeam;
use App\Http\Middleware\V5\HandleInertiaRequests as V5HandleInertiaRequests;
use App\Http\Middleware\ValidateSignature;
use App\Http\Middleware\VerifyCsrfToken;
use Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
@@ -49,6 +52,8 @@ class Kernel extends HttpKernel
* @var array<int, class-string|string>
*/
protected $middleware = [
// Outermost so Server-Timing includes the full middleware + app cost.
AddServerTimingHeaders::class,
TrustHosts::class,
TrustProxies::class,
HandleCors::class,
@@ -77,6 +82,23 @@ class Kernel extends HttpKernel
],
'v5.web' => [
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ShareErrorsFromSession::class,
VerifyCsrfToken::class,
SubstituteBindings::class,
V5HandleInertiaRequests::class,
],
'v5.authenticated' => [
'auth',
'verified',
'throttle:v5',
V5EnsureCurrentTeam::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
ThrottleRequests::class.':api',
@@ -0,0 +1,152 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Event;
use Symfony\Component\HttpFoundation\Response;
/**
* Adds W3C Server-Timing headers in local/dev so Chrome DevTools can show
* app + database cost per response (Network Timing Server Timing).
*
* Also injects a small on-screen HUD into full HTML documents so metrics are
* visible without opening DevTools. Livewire/fetch responses only get headers;
* the HUD updates from Server-Timing on those requests via a fetch patch.
*
* Client-side metrics (paint, LCP, layout, JS/CSS download) cannot be measured
* here use the Performance panel. Compare app dur vs wall-clock TTFB to see
* network/proxy overhead outside PHP.
*/
class AddServerTimingHeaders
{
public function handle(Request $request, Closure $next): Response
{
if (! $this->shouldAddHeaders()) {
return $next($request);
}
$startedAt = hrtime(true);
$queryCount = 0;
$queryTimeMs = 0.0;
$slowestQueryMs = 0.0;
$active = true;
Event::listen(QueryExecuted::class, function (QueryExecuted $query) use (&$queryCount, &$queryTimeMs, &$slowestQueryMs, &$active): void {
if (! $active) {
return;
}
$queryCount++;
$queryTimeMs += $query->time;
if ($query->time > $slowestQueryMs) {
$slowestQueryMs = $query->time;
}
});
$response = $next($request);
$active = false;
return $this->withServerTiming($response, $request, $startedAt, $queryCount, $queryTimeMs, $slowestQueryMs);
}
protected function shouldAddHeaders(): bool
{
return (bool) config('app.server_timing', false);
}
protected function withServerTiming(
Response $response,
Request $request,
int $startedAt,
int $queryCount,
float $queryTimeMs,
float $slowestQueryMs,
): Response {
$totalMs = (hrtime(true) - $startedAt) / 1_000_000;
$memoryMb = round(memory_get_peak_usage(true) / 1024 / 1024, 2);
$content = $response->getContent();
$htmlBytes = is_string($content) ? strlen($content) : 0;
$metrics = [
'app' => round($totalMs, 2),
'db' => round($queryTimeMs, 2),
'php' => round(max(0, $totalMs - $queryTimeMs), 2),
'dbslow' => round($slowestQueryMs, 2),
'queries' => $queryCount,
'html' => $htmlBytes,
'mem' => $memoryMb,
];
// Non-time metrics use dur so Chrome DevTools lists the value in Server Timing.
// queries = count, html = response body bytes (not milliseconds).
$headerMetrics = [
sprintf('app;desc="Total";dur=%.2f', $metrics['app']),
sprintf('db;desc="Database (%d queries)";dur=%.2f', $queryCount, $metrics['db']),
sprintf('php;desc="PHP (excl. DB)";dur=%.2f', $metrics['php']),
sprintf('dbslow;desc="Slowest query";dur=%.2f', $metrics['dbslow']),
sprintf('queries;desc="Query count";dur=%d', $queryCount),
sprintf('html;desc="Response bytes";dur=%d', $htmlBytes),
sprintf('mem;desc="Peak memory (MB)";dur=%.2f', $memoryMb),
];
$response->headers->set('Server-Timing', implode(', ', $headerMetrics));
// Convenience mirrors for curl / non-DevTools clients.
$response->headers->set('X-Debug-Memory-MB', (string) $memoryMb);
$response->headers->set('X-Debug-Query-Count', (string) $queryCount);
$response->headers->set('X-Debug-Html-Bytes', (string) $htmlBytes);
return $this->injectHud($response, $request, $metrics);
}
/**
* Inject a floating HUD into full HTML documents only (not Livewire partials/JSON).
*/
protected function injectHud(Response $response, Request $request, array $metrics): Response
{
$content = $response->getContent();
if (! is_string($content) || $content === '') {
return $response;
}
if (! $this->isFullHtmlDocument($response, $content)) {
return $response;
}
// Avoid double-inject (e.g. nested error pages).
if (str_contains($content, 'id="server-timing-hud"') || str_contains($content, "id='server-timing-hud'")) {
return $response;
}
$hud = view('components.server-timing-hud', [
'metrics' => $metrics,
'path' => '/'.ltrim($request->path(), '/'),
])->render();
$replaced = preg_replace('/<\/body>/i', $hud.'</body>', $content, 1, $count);
if ($count === 0 || ! is_string($replaced)) {
return $response;
}
$response->setContent($replaced);
$response->headers->remove('Content-Length');
// Keep html metric as pre-HUD page size (more useful for profiling the app).
return $response;
}
protected function isFullHtmlDocument(Response $response, string $content): bool
{
$contentType = (string) $response->headers->get('Content-Type', '');
if ($contentType !== '' && ! str_contains(strtolower($contentType), 'text/html')) {
return false;
}
// Full documents only — skip Livewire component HTML fragments.
return str_contains(strtolower($content), '</body>')
&& (str_contains(strtolower($content), '<html') || str_contains(strtolower($content), '<!doctype'));
}
}
@@ -27,8 +27,27 @@ class EnsureTokenBelongsToCurrentTeamMember
}
$role = $team->pivot?->role;
if (($token->can('root') || $token->can('write') || $token->can('write:sensitive'))
&& ! in_array($role, ['admin', 'owner'], true)) {
// Match ApiAbility::MEMBER_DISALLOWED_ABILITIES — members are read-only.
$elevated = $token->can('root')
|| $token->can('write')
|| $token->can('write:sensitive')
|| $token->can('deploy')
|| $token->can('read:sensitive');
if ($elevated && ! in_array($role, ['admin', 'owner'], true)) {
// MCP clients expect JSON-RPC envelopes (often only parsed on HTTP 200).
// Keep REST API clients on plain 403 JSON.
if ($request->is('mcp') || $request->is('mcp/*')) {
return response()->json([
'jsonrpc' => '2.0',
'id' => $request->input('id'),
'error' => [
'code' => -32003,
'message' => 'Missing required team role.',
],
]);
}
return response()->json(['message' => 'Missing required team role.'], 403);
}
@@ -0,0 +1,58 @@
<?php
namespace App\Http\Middleware\V5;
use App\Models\Team;
use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureCurrentTeam
{
public function handle(Request $request, Closure $next): Response
{
/** @var User|null $user */
$user = $request->user();
if (! $user) {
return $next($request);
}
$currentTeam = $this->resolveCurrentTeam($user);
if (! $currentTeam) {
abort(403, 'No team available for this user.');
}
// The v4 UI stores a full Team model under the same session key and
// reads arbitrary columns off it, so only rewrite the session when the
// resolved team actually changed — and always store the full model.
if (data_get(session('currentTeam'), 'id') !== $currentTeam->id) {
session(['currentTeam' => $currentTeam]);
}
$request->attributes->set('v5.currentTeam', $currentTeam);
return $next($request);
}
private function resolveCurrentTeam(User $user): ?Team
{
$sessionTeamId = data_get(session('currentTeam'), 'id');
if ($sessionTeamId) {
$sessionTeam = $user->teams()
->whereKey($sessionTeamId)
->first();
if ($sessionTeam) {
return $sessionTeam;
}
}
return $user->teams()
->orderBy('teams.id')
->first();
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware\V5;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
protected $rootView = 'v5.app';
public function share(Request $request): array
{
return [
...parent::share($request),
'auth' => [
'user' => $request->user() ? [
'id' => $request->user()->id,
'name' => $request->user()->name,
'email' => $request->user()->email,
] : null,
],
'currentTeam' => $request->attributes->get('v5.currentTeam') ? [
'id' => $request->attributes->get('v5.currentTeam')->id,
] : null,
];
}
}
+24 -17
View File
@@ -1343,19 +1343,21 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
if ($this->pull_request_id === 0) {
// Generate SERVICE_ variables first for dockercompose
if ($this->build_pack === 'dockercompose') {
$domains = collect(json_decode($this->application->docker_compose_domains)) ?? collect([]);
$domains = collect(json_decode($this->application->docker_compose_domains ?: '[]', true) ?: []);
// Generate SERVICE_FQDN & SERVICE_URL for dockercompose
// Env keys always use underscore-normalized names so hyphen/dot storage keys stay valid.
foreach ($domains as $forServiceName => $domain) {
$parsedDomain = data_get($domain, 'domain');
$parsedDomain = composeDomainEntryString($domain);
if (filled($parsedDomain)) {
$parsedDomain = str($parsedDomain)->explode(',')->first();
$coolifyUrl = Url::fromString($parsedDomain);
$coolifyScheme = $coolifyUrl->getScheme();
$coolifyFqdn = $coolifyUrl->getHost();
$coolifyUrl = $coolifyUrl->withScheme($coolifyScheme)->withHost($coolifyFqdn)->withPort(null);
$envs->push('SERVICE_URL_'.str($forServiceName)->upper().'='.$coolifyUrl->__toString());
$envs->push('SERVICE_FQDN_'.str($forServiceName)->upper().'='.$coolifyFqdn);
$serviceEnvKey = str(normalizeComposeServiceName((string) $forServiceName))->upper();
$envs->push('SERVICE_URL_'.$serviceEnvKey.'='.$coolifyUrl->__toString());
$envs->push('SERVICE_FQDN_'.$serviceEnvKey.'='.$coolifyFqdn);
}
}
@@ -1413,19 +1415,20 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
} else {
// Generate SERVICE_ variables first for dockercompose preview
if ($this->build_pack === 'dockercompose') {
$domains = collect(json_decode(data_get($this->preview, 'docker_compose_domains'))) ?? collect([]);
$domains = collect(json_decode(data_get($this->preview, 'docker_compose_domains') ?: '[]', true) ?: []);
// Generate SERVICE_FQDN & SERVICE_URL for dockercompose
foreach ($domains as $forServiceName => $domain) {
$parsedDomain = data_get($domain, 'domain');
$parsedDomain = composeDomainEntryString($domain);
if (filled($parsedDomain)) {
$parsedDomain = str($parsedDomain)->explode(',')->first();
$coolifyUrl = Url::fromString($parsedDomain);
$coolifyScheme = $coolifyUrl->getScheme();
$coolifyFqdn = $coolifyUrl->getHost();
$coolifyUrl = $coolifyUrl->withScheme($coolifyScheme)->withHost($coolifyFqdn)->withPort(null);
$envs->push('SERVICE_URL_'.str($forServiceName)->replace('-', '_')->replace('.', '_')->upper().'='.$coolifyUrl->__toString());
$envs->push('SERVICE_FQDN_'.str($forServiceName)->replace('-', '_')->replace('.', '_')->upper().'='.$coolifyFqdn);
$serviceEnvKey = str(normalizeComposeServiceName((string) $forServiceName))->upper();
$envs->push('SERVICE_URL_'.$serviceEnvKey.'='.$coolifyUrl->__toString());
$envs->push('SERVICE_FQDN_'.$serviceEnvKey.'='.$coolifyFqdn);
}
}
@@ -1664,17 +1667,18 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
}
// Generate SERVICE_FQDN & SERVICE_URL for non-PR deployments
$domains = collect(json_decode($this->application->docker_compose_domains)) ?? collect([]);
$domains = collect(json_decode($this->application->docker_compose_domains ?: '[]', true) ?: []);
foreach ($domains as $forServiceName => $domain) {
$parsedDomain = data_get($domain, 'domain');
$parsedDomain = composeDomainEntryString($domain);
if (filled($parsedDomain)) {
$parsedDomain = str($parsedDomain)->explode(',')->first();
$coolifyUrl = Url::fromString($parsedDomain);
$coolifyScheme = $coolifyUrl->getScheme();
$coolifyFqdn = $coolifyUrl->getHost();
$coolifyUrl = $coolifyUrl->withScheme($coolifyScheme)->withHost($coolifyFqdn)->withPort(null);
$envs_dict['SERVICE_URL_'.str($forServiceName)->replace('-', '_')->replace('.', '_')->upper()] = escapeBashEnvValue($coolifyUrl->__toString());
$envs_dict['SERVICE_FQDN_'.str($forServiceName)->replace('-', '_')->replace('.', '_')->upper()] = escapeBashEnvValue($coolifyFqdn);
$serviceEnvKey = str(normalizeComposeServiceName((string) $forServiceName))->upper();
$envs_dict['SERVICE_URL_'.$serviceEnvKey] = escapeBashEnvValue($coolifyUrl->__toString());
$envs_dict['SERVICE_FQDN_'.$serviceEnvKey] = escapeBashEnvValue($coolifyFqdn);
}
}
} else {
@@ -1686,17 +1690,18 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
}
// Generate SERVICE_FQDN & SERVICE_URL for preview deployments with PR-specific domains
$domains = collect(json_decode(data_get($this->preview, 'docker_compose_domains'))) ?? collect([]);
$domains = collect(json_decode(data_get($this->preview, 'docker_compose_domains') ?: '[]', true) ?: []);
foreach ($domains as $forServiceName => $domain) {
$parsedDomain = data_get($domain, 'domain');
$parsedDomain = composeDomainEntryString($domain);
if (filled($parsedDomain)) {
$parsedDomain = str($parsedDomain)->explode(',')->first();
$coolifyUrl = Url::fromString($parsedDomain);
$coolifyScheme = $coolifyUrl->getScheme();
$coolifyFqdn = $coolifyUrl->getHost();
$coolifyUrl = $coolifyUrl->withScheme($coolifyScheme)->withHost($coolifyFqdn)->withPort(null);
$envs_dict['SERVICE_URL_'.str($forServiceName)->replace('-', '_')->replace('.', '_')->upper()] = escapeBashEnvValue($coolifyUrl->__toString());
$envs_dict['SERVICE_FQDN_'.str($forServiceName)->replace('-', '_')->replace('.', '_')->upper()] = escapeBashEnvValue($coolifyFqdn);
$serviceEnvKey = str(normalizeComposeServiceName((string) $forServiceName))->upper();
$envs_dict['SERVICE_URL_'.$serviceEnvKey] = escapeBashEnvValue($coolifyUrl->__toString());
$envs_dict['SERVICE_FQDN_'.$serviceEnvKey] = escapeBashEnvValue($coolifyFqdn);
}
}
}
@@ -2155,7 +2160,9 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
$this->dockerConfigFileExists = instant_remote_process(["test -f {$this->serverUserHomeDir}/.docker/config.json && echo 'OK' || echo 'NOK'"], $this->server);
$env_flags = $this->generate_docker_env_flags_for_secrets();
$buildxMetadataVolume = "-v {$this->serverUserHomeDir}/.docker/buildx:/root/.docker/buildx";
$buildxMetadataVolume = isDev() && $this->server->isLocalhost()
? '-v coolify-buildx:/root/.docker/buildx'
: "-v {$this->serverUserHomeDir}/.docker/buildx:/root/.docker/buildx";
if ($this->use_build_server) {
if ($this->dockerConfigFileExists === 'NOK') {
throw new DeploymentException('Docker config file (~/.docker/config.json) not found on the build server. Please run "docker login" to login to the docker registry on the server.');
+1 -1
View File
@@ -778,7 +778,7 @@ class DatabaseBackupJob implements ShouldBeEncrypted, ShouldQueue
$escapedSecret = escapeshellarg($secret);
$escapedBackupLocation = escapeshellarg($this->backup_location);
$escapedS3Destination = escapeshellarg("temporary/{$bucket}{$this->backup_dir}/");
$resolveOptions = collect(SafeWebhookUrl::minioClientResolveOptions($endpoint))
$resolveOptions = collect(SafeWebhookUrl::minioClientResolveOptions($endpoint, $this->s3->trustedInternalHosts()))
->map(fn (string $resolveOption): string => '--resolve '.escapeshellarg($resolveOption))
->implode(' ');
$resolveOptions = $resolveOptions === '' ? '' : ' '.$resolveOptions;
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Jobs;
use App\Actions\Shared\MigrateResourceToDestination;
use App\Models\Application;
use App\Models\Service;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDocker;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\SwarmDocker;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
/**
* Final step of a server migration: update destination pointers after volume data is transferred.
*/
class FinalizeResourceMigrationJob implements ShouldBeEncrypted, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public Application|Service|StandalonePostgresql|StandaloneRedis|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $resource,
public StandaloneDocker|SwarmDocker $destination,
) {
$this->onQueue('high');
}
public function handle(): void
{
MigrateResourceToDestination::make()->applyDestination(
$this->resource->fresh(),
$this->destination
);
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Jobs;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
/**
* Copy a bind-mount host path from one Coolify-managed server to another.
*/
class HostPathCloneJob implements ShouldBeEncrypted, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $cloneDir = '/data/coolify/clone';
public int $timeout = 3600;
public function __construct(
protected string $sourcePath,
protected string $targetPath,
protected Server $sourceServer,
protected Server $targetServer
) {
$this->onQueue('high');
}
public function handle(): void
{
if ($this->sourceServer->id === $this->targetServer->id && $this->sourcePath === $this->targetPath) {
return;
}
if ($this->sourceServer->id === $this->targetServer->id) {
$this->cloneLocalPath();
return;
}
$this->cloneRemotePath();
}
protected function cloneLocalPath(): void
{
$src = escapeshellarg($this->sourcePath);
$tgt = escapeshellarg($this->targetPath);
$tgtParent = escapeshellarg(dirname($this->targetPath));
instant_remote_process([
"mkdir -p {$tgtParent}",
"mkdir -p {$tgt}",
"docker run --rm -v {$src}:/source:ro -v {$tgt}:/target alpine sh -c 'cp -a /source/. /target/'",
], $this->sourceServer);
}
protected function cloneRemotePath(): void
{
$archiveName = 'hostpath-data.tar.gz';
$token = Str::uuid()->toString();
$sourceCloneDir = "{$this->cloneDir}/hostpath-{$token}";
$targetCloneDir = "{$this->cloneDir}/hostpath-{$token}";
$srcDir = escapeshellarg($sourceCloneDir);
$tgtDir = escapeshellarg($targetCloneDir);
$srcPath = escapeshellarg($this->sourcePath);
$tgtPath = escapeshellarg($this->targetPath);
$tgtParent = escapeshellarg(dirname($this->targetPath));
$localTempDir = storage_path('app/tmp/hostpath-clones/'.$token);
$localArchive = $localTempDir.'/'.$archiveName;
try {
File::ensureDirectoryExists($localTempDir, 0755);
instant_remote_process([
"mkdir -p {$srcDir}",
"chmod 777 {$srcDir}",
"test -e {$srcPath}",
"docker run --rm -v {$srcPath}:/source:ro -v {$srcDir}:/clone alpine sh -c 'cd /source && tar czf /clone/{$archiveName} .'",
], $this->sourceServer);
instant_remote_process([
"mkdir -p {$tgtDir}",
"chmod 777 {$tgtDir}",
], $this->targetServer);
instant_scp_from_server(
"{$sourceCloneDir}/{$archiveName}",
$localArchive,
$this->sourceServer
);
instant_scp(
$localArchive,
"{$targetCloneDir}/{$archiveName}",
$this->targetServer
);
instant_remote_process([
"mkdir -p {$tgtParent}",
"mkdir -p {$tgtPath}",
"docker run --rm -v {$tgtPath}:/target -v {$tgtDir}:/clone alpine sh -c 'cd /target && tar xzf /clone/{$archiveName}'",
], $this->targetServer);
} catch (\Exception $e) {
\Log::error("Failed to clone host path {$this->sourcePath} to {$this->targetPath}: ".$e->getMessage());
throw $e;
} finally {
try {
File::deleteDirectory($localTempDir);
} catch (\Exception $e) {
\Log::warning('Failed to clean up local host-path clone directory: '.$e->getMessage());
}
try {
instant_remote_process(["rm -rf {$srcDir}"], $this->sourceServer, false);
} catch (\Exception $e) {
\Log::warning('Failed to clean up source host-path clone directory: '.$e->getMessage());
}
try {
instant_remote_process(["rm -rf {$tgtDir}"], $this->targetServer, false);
} catch (\Exception $e) {
\Log::warning('Failed to clean up target host-path clone directory: '.$e->getMessage());
}
}
}
}
+839
View File
@@ -0,0 +1,839 @@
<?php
namespace App\Jobs;
use App\Actions\V5\Proxy\StartCaddyIngress;
use App\Enums\V5\ServerStatus;
use App\Events\V5ClusterUpdated;
use App\Models\PrivateKey;
use App\Models\V5\Cluster as V5Cluster;
use App\Models\V5\Server as V5Server;
use App\Services\Flux\AgentTokenIssuer;
use App\Services\Flux\FluxClient;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeEncrypted;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
class V5BootstrapServerJob implements ShouldBeEncrypted, ShouldBeUnique, ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private const BOOTSTRAP_MARKER_PATH = '/etc/coolify/v5-node.json';
public const TIMEOUT_SECONDS = 7200;
public int $tries = 1;
public int $timeout = self::TIMEOUT_SECONDS;
/**
* Second idempotency layer on top of the controller's DB bootstrap claim,
* aligned with its running-claim window (TIMEOUT_SECONDS plus margin).
*/
public int $uniqueFor = self::TIMEOUT_SECONDS + 300;
public function __construct(public int $clusterId, public int $serverId) {}
public function uniqueId(): string
{
return (string) $this->serverId;
}
public function handle(): void
{
$cluster = V5Cluster::query()->findOrFail($this->clusterId);
$server = V5Server::query()->with('privateKey')->findOrFail($this->serverId);
if ($server->cluster_id !== $cluster->id || $server->last_bootstrapped_at !== null) {
return;
}
$installedServers = $cluster->servers()
->with('privateKey')
->whereNotNull('last_bootstrapped_at')
->orderBy('name')
->get();
$action = $installedServers->isEmpty() ? 'bootstrap' : 'extend';
$servers = $installedServers->toBase()
->push($server)
->unique('id')
->values();
$started = V5Server::query()
->whereKey($server->id)
->where('last_bootstrap_status', 'queued')
->update([
'last_bootstrap_action' => $action,
'last_bootstrap_status' => 'running',
'last_bootstrap_output' => "Starting Coolify CLI {$action} for {$server->name}...",
'last_bootstrap_ran_at' => now(),
]);
if ($started === 0) {
return;
}
$server->refresh();
if ($servers->contains(fn (V5Server $server) => ! $server->privateKey instanceof PrivateKey)) {
$this->markFailed($server, $action, 'The new server and every already-bootstrapped server in this cluster must have a private key before extending the cluster.');
return;
}
$this->broadcastClusterUpdated($server);
$keyDirectory = storage_path('app/ssh/keys');
if (! is_dir($keyDirectory)) {
mkdir($keyDirectory, 0700, true);
}
$tempDirectory = $keyDirectory.'/v5_bootstrap_'.str()->random(16);
if (! mkdir($tempDirectory, 0700, true) && ! is_dir($tempDirectory)) {
$this->markFailed($server, $action, 'Could not create a temporary SSH configuration directory.');
return;
}
try {
$sshConfigLocation = $this->writeBootstrapSshConfig($servers, $tempDirectory);
$existingBootstrap = $this->detectExistingBootstrap($server, $sshConfigLocation);
if (($existingBootstrap['cluster_id'] ?? null) !== null) {
$markerClusterUuid = $existingBootstrap['cluster_uuid'] ?? null;
if (
(string) $existingBootstrap['cluster_id'] !== (string) $cluster->id
|| (is_string($markerClusterUuid) && $markerClusterUuid !== $cluster->uuid)
) {
$this->markFailed($server, $action, 'This server is already bootstrapped for another cluster. Reset the host bootstrap state before joining this cluster.');
return;
}
$this->adoptExistingBootstrap($cluster, $server, $existingBootstrap, $sshConfigLocation);
return;
}
$result = Process::timeout(7200)
->run($this->bootstrapCommand($cluster, $servers, $server, $sshConfigLocation, $action));
$output = trim($result->output()."\n".$result->errorOutput());
$successful = $result->successful();
$server->update([
'last_bootstrap_action' => $action,
'last_bootstrap_status' => $successful ? 'succeeded' : 'failed',
'last_bootstrap_output' => str($output !== '' ? $output : 'No output returned.')->limit(20000)->toString(),
'last_bootstrap_ran_at' => now(),
]);
$this->broadcastClusterUpdated($server);
if (! $successful) {
return;
}
$this->persistBootstrapAssignments($cluster, $server, $result->output(), $sshConfigLocation);
$server->refresh();
// Resolve the coold version once so the on-host marker and the
// database row always agree.
$cooldVersion = $this->bootstrappedCooldVersion($cluster, $result->output());
$this->writeBootstrapMarker($cluster, $server, $sshConfigLocation, $cooldVersion);
$this->enrollCooldIntoFlux($server, $sshConfigLocation);
$this->waitForFluxHostConnection($server);
$server->update([
'status' => ServerStatus::Installed->value,
'has_coold' => true,
'coold_version' => $cooldVersion,
'last_bootstrapped_at' => now(),
]);
$this->broadcastClusterUpdated($server);
if ($server->isIngress()) {
StartCaddyIngress::run($server->fresh('privateKey'));
}
} catch (\Throwable $e) {
$this->markFailed($server, $action, $e->getMessage());
} finally {
$this->deleteDirectory($tempDirectory);
}
}
public function failed(?\Throwable $exception): void
{
$server = V5Server::query()->find($this->serverId);
if (! $server instanceof V5Server) {
return;
}
$this->markFailed($server, $server->last_bootstrap_action ?? 'bootstrap', $exception?->getMessage() ?? 'Bootstrap job failed.');
Log::warning('V5 server bootstrap job failed', [
'server_id' => $this->serverId,
'cluster_id' => $this->clusterId,
'exception' => $exception?->getMessage(),
]);
}
private function markFailed(V5Server $server, string $action, string $output): void
{
$server->update([
'last_bootstrap_action' => $action,
'last_bootstrap_status' => 'failed',
'last_bootstrap_output' => str($output)->limit(20000)->toString(),
'last_bootstrap_ran_at' => now(),
]);
$this->broadcastClusterUpdated($server);
}
private function broadcastClusterUpdated(V5Server $server): void
{
V5ClusterUpdated::dispatch($server->team_id, $server->cluster_id);
}
private function bootstrapCommand(V5Cluster $cluster, Collection $servers, V5Server $newServer, string $sshConfigLocation, string $action): array
{
$command = [
$this->coolifyCliBin(),
'init',
$action,
'--format',
'json',
'--nodes',
$servers->map(fn (V5Server $server) => $this->bootstrapNode($server))->implode(','),
'--ssh-config',
$sshConfigLocation,
'--ssh-user',
$newServer->ssh_user,
'--namespaces',
implode(',', $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES),
'--container-pool',
$cluster->container_network_pool,
'--container-prefix',
(string) $cluster->container_network_prefix,
'--wg-mgmt-pool',
$cluster->wireguard_management_pool,
'--wg-interface',
$cluster->wireguard_interface,
'--wg-listen-port',
(string) $cluster->wireguard_listen_port,
'--coold-version',
$cluster->coold_version,
'--corrosion-version',
$cluster->corrosion_version,
'--corrosion-gossip-port',
(string) $cluster->corrosion_gossip_port,
'--corrosion-api-port',
(string) $cluster->corrosion_api_port,
];
if ($action === 'extend') {
array_push($command, '--new-nodes', $this->bootstrapNode($newServer));
}
$listenOverrides = $this->wireguardListenPortOverrides($servers);
if ($listenOverrides !== '') {
array_push($command, '--wg-listen-port-overrides', $listenOverrides);
}
$endpointOverrides = $this->wireguardEndpointOverrides($servers);
if ($endpointOverrides !== '') {
array_push($command, '--wg-endpoint-overrides', $endpointOverrides);
}
if (! $cluster->default_deny_containers) {
$command[] = '--skip-default-deny';
}
$command[] = '--yes';
return $command;
}
private function coolifyCliBin(): string
{
$configuredBinary = (string) config('coold.coolify_cli_bin', '/usr/local/bin/coolify');
$devBinary = base_path('.dev/bin/coolify');
if ($configuredBinary === '/usr/local/bin/coolify' && $this->isRunnableDevelopmentCliBinary($devBinary)) {
return $devBinary;
}
return $configuredBinary;
}
private function isRunnableDevelopmentCliBinary(string $binary): bool
{
if (! is_file($binary)) {
return false;
}
$header = file_get_contents($binary, false, null, 0, 4);
if ($header === false) {
return false;
}
if (str_starts_with($header, '#!')) {
return true;
}
if ($header === "\x7FELF") {
return true;
}
return false;
}
private function bootstrapNode(V5Server $server): string
{
return 'v5-server-'.($server->uuid ?: $server->id);
}
/**
* @return array<string, mixed>
*/
private function detectExistingBootstrap(V5Server $server, string $sshConfigLocation): array
{
$result = Process::timeout(15)->run([
'ssh',
'-F',
$sshConfigLocation,
$this->bootstrapNode($server),
'if [ -f '.escapeshellarg(self::BOOTSTRAP_MARKER_PATH).' ]; then cat '.escapeshellarg(self::BOOTSTRAP_MARKER_PATH).'; fi',
]);
if (! $result->successful()) {
return [];
}
$output = trim($result->output());
if ($output === '') {
return [];
}
try {
$decoded = json_decode($output, true, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return [];
}
return is_array($decoded) ? $decoded : [];
}
/**
* @param array<string, mixed> $marker
*/
private function adoptExistingBootstrap(V5Cluster $cluster, V5Server $server, array $marker, string $sshConfigLocation): void
{
$bootstrapNode = $this->bootstrapNode($server);
$serverUuid = is_string($marker['server_uuid'] ?? null) ? $marker['server_uuid'] : null;
$updates = [
'wireguard_management_ip' => is_string($marker['wireguard_management_ip'] ?? null) ? $marker['wireguard_management_ip'] : $server->wireguard_management_ip,
'wireguard_public_key' => is_string($marker['wireguard_public_key'] ?? null) ? $marker['wireguard_public_key'] : $server->wireguard_public_key,
'coold_version' => is_string($marker['coold_version'] ?? null) && trim($marker['coold_version']) !== '' ? trim($marker['coold_version']) : $cluster->coold_version,
'container_subnets' => is_array($marker['container_subnets'] ?? null) ? $marker['container_subnets'] : $server->container_subnets,
'has_coold' => true,
'status' => ServerStatus::Installed->value,
'last_bootstrap_status' => 'succeeded',
'last_bootstrap_output' => 'Adopted existing Coolify bootstrap state for this cluster.',
'last_bootstrap_ran_at' => now(),
'last_bootstrapped_at' => now(),
];
if ($serverUuid !== null && ! V5Server::query()->where('uuid', $serverUuid)->whereKeyNot($server->id)->exists()) {
$updates['uuid'] = $serverUuid;
}
$server->update($updates);
$this->broadcastClusterUpdated($server);
$this->enrollCooldIntoFlux($server->fresh(), $sshConfigLocation, $bootstrapNode);
$this->waitForFluxHostConnection($server->fresh());
if ($server->isIngress()) {
StartCaddyIngress::run($server->fresh('privateKey'));
}
}
private function persistBootstrapAssignments(V5Cluster $cluster, V5Server $server, string $output, string $sshConfigLocation): void
{
$verifiedNode = $this->verifiedBootstrapNode($output, $server);
$wireguardManagementIp = is_array($verifiedNode) && is_string($verifiedNode['wireguard_ip'] ?? null)
? $verifiedNode['wireguard_ip']
: null;
$warnings = [];
if (! is_string($wireguardManagementIp) || $wireguardManagementIp === '') {
$wireguardManagementIp = $this->readWireguardManagementIp($cluster, $server, $sshConfigLocation, $warnings);
}
$wireguardPublicKey = $this->readWireguardPublicKey($cluster, $server, $sshConfigLocation, $warnings);
$containerSubnets = $this->readContainerSubnets($cluster, $server, $sshConfigLocation, $warnings);
$updates = [];
if ($wireguardManagementIp !== null && $wireguardManagementIp !== '') {
$updates['wireguard_management_ip'] = $wireguardManagementIp;
if (! is_string($server->node_address) || $server->node_address === '' || $server->node_address === $server->host) {
$updates['node_address'] = $wireguardManagementIp;
}
} else {
$warnings[] = 'Warning: could not determine the WireGuard management IP from the CLI output.';
}
if ($wireguardPublicKey !== null && $wireguardPublicKey !== '') {
$updates['wireguard_public_key'] = $wireguardPublicKey;
}
if ($containerSubnets !== []) {
$updates['container_subnets'] = $containerSubnets;
}
if ($warnings !== []) {
$updates['last_bootstrap_output'] = str(trim($server->last_bootstrap_output."\n".implode("\n", $warnings)))
->limit(20000)
->toString();
}
if ($updates !== []) {
$server->update($updates);
}
}
/**
* @param array<int, string> $warnings
*/
private function readWireguardManagementIp(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, array &$warnings): ?string
{
$interface = escapeshellarg($cluster->wireguard_interface);
$script = implode("\n", [
"SUDO=''",
'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',
"\$SUDO ip -4 -o addr show dev {$interface} | awk '{print \$4}' | cut -d/ -f1 | head -n1",
]);
$result = Process::timeout(15)->run([
'ssh',
'-F',
$sshConfigLocation,
$this->bootstrapNode($server),
$script,
]);
$ipAddress = trim($result->output());
if (! $result->successful() || filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
$warnings[] = 'Warning: could not read the WireGuard management IP from the server.';
return null;
}
return $ipAddress;
}
/**
* @return array<string, mixed>|null
*/
private function verifiedBootstrapNode(string $output, V5Server $server): ?array
{
$decoded = $this->decodedBootstrapOutput($output);
if (! is_array($decoded)) {
return null;
}
$verifiedNodes = data_get($decoded, 'verified');
if (! is_array($verifiedNodes)) {
return null;
}
$bootstrapNode = $this->bootstrapNode($server);
foreach ($verifiedNodes as $verifiedNode) {
if (! is_array($verifiedNode)) {
continue;
}
$host = $verifiedNode['host'] ?? $verifiedNode['node'] ?? $verifiedNode['name'] ?? null;
if ($host === $bootstrapNode || $host === $server->uuid || $host === $server->name || $host === $server->host) {
return $verifiedNode;
}
}
return null;
}
/**
* @return array<string, mixed>|null
*/
private function decodedBootstrapOutput(string $output): ?array
{
$output = trim($output);
if ($output === '' || ! str_starts_with($output, '{')) {
return null;
}
try {
$decoded = json_decode($output, true, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return null;
}
return is_array($decoded) ? $decoded : null;
}
/**
* The CLI init JSON output does not currently report the installed coold
* version, so fall back to the version the cluster asked the CLI to
* install (`--coold-version`). If a future CLI adds a `coold_version` key
* to its JSON output, prefer that.
*/
private function bootstrappedCooldVersion(V5Cluster $cluster, string $output): ?string
{
$reported = data_get($this->decodedBootstrapOutput($output), 'coold_version');
if (is_string($reported) && trim($reported) !== '') {
return trim($reported);
}
return $cluster->coold_version;
}
/**
* @param array<int, string> $warnings
*/
private function readWireguardPublicKey(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, array &$warnings): ?string
{
$interface = escapeshellarg($cluster->wireguard_interface);
$script = implode("\n", [
"SUDO=''",
'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',
"\$SUDO wg show {$interface} public-key",
]);
$result = Process::timeout(15)->run([
'ssh',
'-F',
$sshConfigLocation,
$this->bootstrapNode($server),
$script,
]);
$publicKey = trim($result->output());
if (! $result->successful() || $publicKey === '') {
$warnings[] = 'Warning: could not read the WireGuard public key from the server.';
return null;
}
return $publicKey;
}
/**
* The container subnets are allocated by the coolify CLI on the host; the podman
* networks it creates are the source of truth, so read them back instead of
* re-deriving the allocation locally.
*
* @param array<int, string> $warnings
* @return array<string, string>
*/
private function readContainerSubnets(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, array &$warnings): array
{
$namespaces = $cluster->namespaces ?? V5Cluster::DEFAULT_NAMESPACES;
if ($namespaces === []) {
return [];
}
$namespaceArguments = collect($namespaces)
->map(fn (string $namespace): string => escapeshellarg($namespace))
->implode(' ');
$script = implode("\n", [
"SUDO=''",
'if [ "$(id -u)" != "0" ]; then SUDO=\'sudo\'; fi',
"for ns in {$namespaceArguments}; do",
' printf \'%s=\' "$ns"',
' $SUDO podman network inspect "coolify-${ns}-mesh" --format \'{{range .Subnets}}{{.Subnet}}{{end}}\' 2>/dev/null || true',
' printf \'\n\'',
'done',
]);
$result = Process::timeout(30)->run([
'ssh',
'-F',
$sshConfigLocation,
$this->bootstrapNode($server),
$script,
]);
if (! $result->successful()) {
$warnings[] = 'Warning: could not read the container subnets from the server.';
return [];
}
$subnets = [];
foreach (preg_split('/\r?\n/', trim($result->output())) ?: [] as $line) {
[$namespace, $subnet] = array_pad(explode('=', trim($line), 2), 2, null);
if (! is_string($namespace) || ! in_array($namespace, $namespaces, true) || ! $this->isIpv4Cidr($subnet)) {
continue;
}
$subnets[$namespace] = $subnet;
}
if (count($subnets) !== count($namespaces)) {
$warnings[] = 'Warning: could not read every container subnet from the server; the stored subnets may be incomplete.';
}
return $subnets;
}
private function isIpv4Cidr(?string $value): bool
{
if (! is_string($value) || ! str_contains($value, '/')) {
return false;
}
[$ip, $prefix] = explode('/', $value, 2);
return filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false
&& ctype_digit($prefix)
&& (int) $prefix <= 32;
}
private function enrollCooldIntoFlux(V5Server $server, string $sshConfigLocation, ?string $bootstrapNode = null): void
{
$fluxUrl = trim((string) config('coold.flux_url', ''));
if ($fluxUrl === '') {
throw new \RuntimeException('COOLIFY_COOLD_FLUX_URL is not configured, so the server cannot be enrolled into Flux. Set it and retry the bootstrap.');
}
$jwtPath = trim((string) config('coold.flux_host_jwt_path', '/etc/coolify/host-jwt'));
if ($jwtPath === '') {
$jwtPath = '/etc/coolify/host-jwt';
}
$fluxUrl = str_replace(["\r", "\n"], '', $fluxUrl);
$jwtPath = str_replace(["\r", "\n"], '', $jwtPath);
$hostId = $server->fluxHostId();
$token = app(AgentTokenIssuer::class)->issueForServer($server);
$tokenArgument = $this->shellArg($token);
$hostId = str_replace(["\r", "\n"], '', $hostId);
$jwtPathArgument = $this->shellPathArg($jwtPath);
$dropInDirectory = '/etc/systemd/system/coold.service.d';
$dropInPath = "{$dropInDirectory}/10-flux.conf";
$script = <<<SH
set -e
SUDO=''
if [ "\$(id -u)" != "0" ]; then SUDO='sudo'; fi
\$SUDO mkdir -p /etc/coolify {$dropInDirectory}
printf %s {$tokenArgument} | \$SUDO tee {$jwtPathArgument} >/dev/null
\$SUDO chmod 600 {$jwtPathArgument}
cat <<'COOLIFY_FLUX_ENV' | \$SUDO tee {$dropInPath} >/dev/null
[Service]
Environment=COOLIFY_COOLD_FLUX_URL={$fluxUrl}
Environment=COOLIFY_COOLD_HOST_ID={$hostId}
Environment=COOLIFY_COOLD_HOST_JWT_PATH={$jwtPath}
COOLIFY_FLUX_ENV
\$SUDO systemctl daemon-reload
\$SUDO systemctl restart coold.service
SH;
$result = Process::timeout(60)->run([
'ssh',
'-F',
$sshConfigLocation,
$bootstrapNode ?? $this->bootstrapNode($server),
$script,
]);
if (! $result->successful()) {
$output = trim($result->output()."\n".$result->errorOutput());
throw new \RuntimeException(
($output !== '' ? $output : 'Could not enroll coold into Flux.')
."\nThe WireGuard mesh was created successfully; retrying this bootstrap is safe and will resume from Flux enrollment."
);
}
}
private function waitForFluxHostConnection(V5Server $server): void
{
$timeoutSeconds = (int) config('flux.bootstrap_host_connection_timeout_seconds', 30);
if ($timeoutSeconds <= 0) {
return;
}
$hostId = $server->fluxHostId();
if (! is_string($hostId) || $hostId === '') {
throw new \RuntimeException('Server is missing its Flux host id after bootstrap.');
}
$deadline = time() + $timeoutSeconds;
$lastError = null;
do {
try {
app(FluxClient::class)->cooldLogs($hostId, 1);
return;
} catch (\Throwable $exception) {
$lastError = $exception->getMessage();
sleep(1);
}
} while (time() < $deadline);
throw new \RuntimeException(
'The server was bootstrapped, but coold did not connect to Flux in time. '
.'Wait a moment and retry the bootstrap before deploying applications.'
.($lastError !== null ? " Last Flux error: {$lastError}" : '')
);
}
private function shellArg(string $value): string
{
return escapeshellarg($value);
}
private function shellPathArg(string $value): string
{
if (preg_match('/^[A-Za-z0-9_\/:.,@%+=-]+$/', $value) === 1) {
return $value;
}
return $this->shellArg($value);
}
private function writeBootstrapMarker(V5Cluster $cluster, V5Server $server, string $sshConfigLocation, ?string $cooldVersion = null): void
{
$payload = base64_encode(json_encode([
'cluster_id' => $cluster->id,
'cluster_uuid' => $cluster->uuid,
'server_uuid' => $server->uuid,
'wireguard_management_ip' => $server->wireguard_management_ip,
'wireguard_public_key' => $server->wireguard_public_key,
'coold_version' => $cooldVersion ?? $server->coold_version ?? $cluster->coold_version,
'container_subnets' => $server->container_subnets ?? [],
], JSON_THROW_ON_ERROR));
$result = Process::timeout(15)->run([
'ssh',
'-F',
$sshConfigLocation,
$this->bootstrapNode($server),
"payload='{$payload}'; if [ \"$(id -u)\" = \"0\" ]; then mkdir -p /etc/coolify && printf %s \"$payload\" | base64 -d > ".escapeshellarg(self::BOOTSTRAP_MARKER_PATH)."; else sudo mkdir -p /etc/coolify && printf %s \"$payload\" | base64 -d | sudo tee ".escapeshellarg(self::BOOTSTRAP_MARKER_PATH).' >/dev/null; fi',
]);
if (! $result->successful()) {
$output = trim($result->output()."\n".$result->errorOutput());
throw new \RuntimeException('Could not write the bootstrap marker to the server: '.($output !== '' ? $output : 'the SSH command failed.'));
}
}
/**
* @param Collection<int, V5Server> $servers
*/
private function writeBootstrapSshConfig(Collection $servers, string $tempDirectory): string
{
$config = '';
$servers->each(function (V5Server $server) use (&$config, $tempDirectory): void {
$keyLocation = "{$tempDirectory}/server-{$server->id}.key";
file_put_contents($keyLocation, $server->privateKey->private_key);
chmod($keyLocation, 0600);
$config .= implode("\n", [
'Host '.$this->bootstrapNode($server),
' HostName '.$server->host,
' Port '.$server->ssh_port,
' User '.$server->ssh_user,
' IdentityFile '.$keyLocation,
' IdentitiesOnly yes',
' LogLevel ERROR',
' StrictHostKeyChecking no',
' UserKnownHostsFile /dev/null',
' BatchMode yes',
'',
]);
});
$sshConfigLocation = "{$tempDirectory}/ssh.config";
file_put_contents($sshConfigLocation, $config);
chmod($sshConfigLocation, 0600);
return $sshConfigLocation;
}
private function deleteDirectory(string $directory): void
{
if (! is_dir($directory)) {
return;
}
foreach (scandir($directory) ?: [] as $file) {
if ($file === '.' || $file === '..') {
continue;
}
$path = "{$directory}/{$file}";
if (is_dir($path)) {
$this->deleteDirectory($path);
continue;
}
@unlink($path);
}
@rmdir($directory);
}
/**
* @param Collection<int, V5Server> $servers
*/
private function wireguardListenPortOverrides(Collection $servers): string
{
return $servers
->filter(fn (V5Server $server) => $server->wireguard_listen_port_override !== null)
->map(fn (V5Server $server) => $this->bootstrapNode($server).'='.$server->wireguard_listen_port_override)
->implode(',');
}
/**
* @param Collection<int, V5Server> $servers
*/
private function wireguardEndpointOverrides(Collection $servers): string
{
return $servers
->filter(fn (V5Server $server) => $server->wireguard_endpoint_override !== null)
->map(fn (V5Server $server) => $this->bootstrapNode($server).'='.$server->wireguard_endpoint_override)
->implode(',');
}
}

Some files were not shown because too many files have changed in this diff Show More