From 05a0fc5fc92fea89989ff054c708857ece05471b Mon Sep 17 00:00:00 2001 From: Yash Kumar Date: Wed, 4 Nov 2026 19:01:20 +0530 Subject: [PATCH 01/84] fix(schedules): restore jobs before accepting requests --- apps/schedules/src/index.ts | 13 ++++++++++--- apps/schedules/src/utils.ts | 1 + 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/apps/schedules/src/index.ts b/apps/schedules/src/index.ts index 28eacbe1cad..eedcb90fdc0 100644 --- a/apps/schedules/src/index.ts +++ b/apps/schedules/src/index.ts @@ -15,9 +15,6 @@ import { firstWorker, secondWorker, thirdWorker } from "./workers.js"; const app = new Hono(); -cleanQueue(); -initializeJobs(); - app.use(async (c, next) => { if (c.req.path === "/health") { return next(); @@ -113,5 +110,15 @@ process.on("unhandledRejection", (reason, _promise) => { const port = Number.parseInt(process.env.PORT || "3000"); +// Restore jobs before accepting requests, so cleanQueue() can't wipe jobs +// registered through the API during startup. +try { + await cleanQueue(); + await initializeJobs(); +} catch (error) { + logger.error(error, "Failed to initialize jobs"); + process.exit(1); +} + logger.info("Starting Schedules Server ✅", port); serve({ fetch: app.fetch, port }); diff --git a/apps/schedules/src/utils.ts b/apps/schedules/src/utils.ts index 85de85f9a98..b841e518b4a 100644 --- a/apps/schedules/src/utils.ts +++ b/apps/schedules/src/utils.ts @@ -216,6 +216,7 @@ export const initializeJobs = async () => { scheduleId: schedule.scheduleId, type: "schedule", cronSchedule: schedule.cronExpression, + timezone: schedule.timezone, }); } catch (error) { logger.error(error, `Failed to schedule ${schedule.scheduleId}`); From 7c8806ad652ecd5f5443e90079d67bec55d98bef Mon Sep 17 00:00:00 2001 From: Yash Kumar Date: Thu, 5 Nov 2026 03:45:05 +0530 Subject: [PATCH 02/84] fix(terminal): close SSH sessions when the terminal WebSocket closes --- .../wss/terminal-ssh-lifecycle.test.ts | 148 ++++++++++++++++++ .../docker/terminal/docker-terminal.tsx | 4 +- .../settings/web-server/terminal.tsx | 2 +- .../server/wss/docker-container-terminal.ts | 10 +- apps/dokploy/server/wss/terminal.ts | 15 +- 5 files changed, 164 insertions(+), 15 deletions(-) create mode 100644 apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts diff --git a/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts b/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts new file mode 100644 index 00000000000..f0030e109a5 --- /dev/null +++ b/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts @@ -0,0 +1,148 @@ +import { EventEmitter } from "node:events"; +import http from "node:http"; +import type { AddressInfo } from "node:net"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import WebSocket from "ws"; + +const clients = vi.hoisted(() => [] as FakeClient[]); +const lookupDelay = vi.hoisted(() => ({ ms: 0 })); + +interface FakeClient extends EventEmitter { + connect: ReturnType; + destroy: ReturnType; + end: ReturnType; + shell: ReturnType; + exec: ReturnType; +} + +vi.mock("ssh2", async () => { + const { EventEmitter } = await import("node:events"); + class Client extends EventEmitter { + connect = vi.fn(() => this); + destroy = vi.fn(() => this); + end = vi.fn(() => this); + shell = vi.fn(); + exec = vi.fn(); + constructor() { + super(); + clients.push(this as unknown as FakeClient); + } + } + return { Client }; +}); +vi.mock("node-pty", () => ({ spawn: vi.fn() })); +vi.mock("public-ip", () => ({ publicIpv4: vi.fn(), publicIpv6: vi.fn() })); +vi.mock("@dokploy/server", () => ({ + IS_CLOUD: false, + execAsync: vi.fn(async () => ({ stdout: "", stderr: "" })), + paths: vi.fn(() => ({ SSH_PATH: "/tmp" })), + validateRequest: vi.fn(async () => ({ + user: { id: "user-1" }, + session: { activeOrganizationId: "org-1" }, + })), + findServerById: vi.fn(async () => { + await new Promise((r) => setTimeout(r, lookupDelay.ms)); + return { + organizationId: "org-1", + ipAddress: "10.0.0.1", + port: 22, + username: "root", + sshKeyId: "key-1", + sshKey: { privateKey: "key" }, + }; + }), +})); +vi.mock("@/server/wss/authorize", () => ({ + canAccessTerminalOverWss: vi.fn(async () => true), + canAccessDockerOverWss: vi.fn(async () => true), +})); +vi.mock("@/server/wss/container-ownership", () => ({ + containerBelongsToService: vi.fn(async () => true), +})); + +import { setupDockerContainerTerminalWebSocketServer } from "@/server/wss/docker-container-terminal"; +import { setupTerminalWebSocketServer } from "@/server/wss/terminal"; + +const terminals = { + server: { + path: "/terminal?serverId=srv-1", + openChannel: (c: FakeClient) => c.shell, + }, + container: { + path: "/docker-container-terminal?containerId=abc123&serverId=srv-1", + openChannel: (c: FakeClient) => c.exec, + }, +} as const; + +let server: http.Server; +let base: string; + +beforeEach(async () => { + clients.length = 0; + lookupDelay.ms = 0; + server = http.createServer(); + setupTerminalWebSocketServer(server); + setupDockerContainerTerminalWebSocketServer(server); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + base = `ws://127.0.0.1:${(server.address() as AddressInfo).port}`; +}); + +afterEach(async () => { + await new Promise((r) => server.close(r)); +}); + +const connect = async (path: string) => { + const ws = new WebSocket(`${base}${path}`); + ws.on("error", () => {}); + await new Promise((r) => ws.once("open", r)); + return ws; +}; + +const fakeStream = () => + Object.assign(new EventEmitter(), { + stderr: new EventEmitter(), + write: vi.fn(), + setWindow: vi.fn(), + end: vi.fn(), + }); + +describe.each(Object.entries(terminals))("%s terminal over SSH", (_, t) => { + it("destroys a pending connection when the browser closes mid-handshake", async () => { + const ws = await connect(t.path); + await vi.waitFor(() => expect(clients[0]?.connect).toHaveBeenCalled()); + + ws.close(); + + await vi.waitFor(() => expect(clients[0]?.destroy).toHaveBeenCalled()); + expect(t.openChannel(clients[0] as FakeClient)).not.toHaveBeenCalled(); + }); + + it("never connects when the browser leaves during the server lookup", async () => { + lookupDelay.ms = 200; + const ws = await connect(t.path); + ws.close(); + + await new Promise((r) => setTimeout(r, 400)); + expect(clients).toHaveLength(0); + }); + + it("destroys the connection when the browser closes an open shell", async () => { + const ws = await connect(t.path); + await vi.waitFor(() => expect(clients[0]?.connect).toHaveBeenCalled()); + const client = clients[0] as FakeClient; + + client.emit("ready"); + const openChannel = t.openChannel(client); + expect(openChannel).toHaveBeenCalledOnce(); + const callback = openChannel.mock.calls[0]?.at(-1); + callback(undefined, fakeStream()); + + ws.close(); + + await vi.waitFor(() => + expect( + client.destroy.mock.calls.length + client.end.mock.calls.length, + ).toBeGreaterThan(0), + ); + }); +}); diff --git a/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx b/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx index 2d79b85cc96..f57c7511cfc 100644 --- a/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx +++ b/apps/dokploy/components/dashboard/docker/terminal/docker-terminal.tsx @@ -93,9 +93,7 @@ export const DockerTerminal: React.FC = ({ cancelled = true; cancelAnimationFrame(frame); resizeObserver?.disconnect(); - if (ws && ws.readyState === WebSocket.OPEN) { - ws.close(); - } + ws?.close(); term?.dispose(); }; }, [containerId, activeWay, id]); diff --git a/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx b/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx index 4a4189d1188..1a7ec789fc6 100644 --- a/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx +++ b/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx @@ -83,7 +83,7 @@ export const Terminal: React.FC = ({ id, serverId }) => { return () => { resizeObserver.disconnect(); - ws.readyState === WebSocket.OPEN && ws.close(); + ws.close(); }; }, [id, serverId]); diff --git a/apps/dokploy/server/wss/docker-container-terminal.ts b/apps/dokploy/server/wss/docker-container-terminal.ts index 5549808fccc..fdf33c49e41 100644 --- a/apps/dokploy/server/wss/docker-container-terminal.ts +++ b/apps/dokploy/server/wss/docker-container-terminal.ts @@ -94,7 +94,10 @@ export const setupDockerContainerTerminalWebSocketServer = ( if (!server.sshKeyId) throw new Error("No SSH key available for this server"); + if (ws.readyState !== ws.OPEN) return; + const conn = new Client(); + ws.once("close", () => conn.destroy()); let _stdout = ""; let _stderr = ""; conn @@ -121,6 +124,7 @@ export const setupDockerContainerTerminalWebSocketServer = ( .on("close", (code: number, _signal: string) => { ws.send(`\nContainer closed with code: ${code}\n`); conn.end(); + ws.close(); }) .on("data", (data: string) => { _stdout += data.toString(); @@ -153,12 +157,6 @@ export const setupDockerContainerTerminalWebSocketServer = ( ws.send(errorMessage); } }); - - ws.on("close", () => { - stream.end(); - // Ensure SSH connection is closed when WebSocket closes - conn.end(); - }); }); }) .on("error", (err) => { diff --git a/apps/dokploy/server/wss/terminal.ts b/apps/dokploy/server/wss/terminal.ts index ed9495aeb8e..0c35b8ea15e 100644 --- a/apps/dokploy/server/wss/terminal.ts +++ b/apps/dokploy/server/wss/terminal.ts @@ -187,7 +187,10 @@ export const setupTerminalWebSocketServer = ( }; } + if (ws.readyState !== ws.OPEN) return; + const conn = new Client(); + ws.once("close", () => conn.destroy()); let _stdout = ""; let _stderr = ""; @@ -199,12 +202,18 @@ export const setupTerminalWebSocketServer = ( ws.send("\x1bc"); conn.shell({ cols, rows }, (err, stream) => { - if (err) throw err; + if (err) { + ws.send(`SSH shell error: ${err.message}`); + ws.close(); + conn.end(); + return; + } stream .on("close", (code: number, _signal: string) => { ws.send(`\nContainer closed with code: ${code}\n`); conn.end(); + ws.close(); }) .on("data", (data: string) => { _stdout += data.toString(); @@ -237,10 +246,6 @@ export const setupTerminalWebSocketServer = ( ws.send(errorMessage); } }); - - ws.on("close", () => { - stream.end(); - }); }); }) .on("error", (err) => { From 01dbf5dcb7747182bab15ee98be074037bff7011 Mon Sep 17 00:00:00 2001 From: Yash Kumar Date: Thu, 5 Nov 2026 03:58:46 +0530 Subject: [PATCH 03/84] fix(terminal): connect in dev StrictMode, test exit paths, quiet cancelled-login logs --- .../wss/terminal-ssh-lifecycle.test.ts | 45 +++++-- .../settings/web-server/terminal.tsx | 113 +++++++++--------- .../server/wss/docker-container-terminal.ts | 2 +- 3 files changed, 96 insertions(+), 64 deletions(-) diff --git a/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts b/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts index f0030e109a5..95f2788569e 100644 --- a/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts +++ b/apps/dokploy/__test__/wss/terminal-ssh-lifecycle.test.ts @@ -106,6 +106,22 @@ const fakeStream = () => end: vi.fn(), }); +const openShell = async ( + t: (typeof terminals)[keyof typeof terminals], + error?: Error, +) => { + const ws = await connect(t.path); + await vi.waitFor(() => expect(clients[0]?.connect).toHaveBeenCalled()); + const client = clients[0] as FakeClient; + client.emit("ready"); + const stream = fakeStream(); + t.openChannel(client).mock.calls[0]?.at(-1)( + error, + error ? undefined : stream, + ); + return { ws, client, stream }; +}; + describe.each(Object.entries(terminals))("%s terminal over SSH", (_, t) => { it("destroys a pending connection when the browser closes mid-handshake", async () => { const ws = await connect(t.path); @@ -127,15 +143,7 @@ describe.each(Object.entries(terminals))("%s terminal over SSH", (_, t) => { }); it("destroys the connection when the browser closes an open shell", async () => { - const ws = await connect(t.path); - await vi.waitFor(() => expect(clients[0]?.connect).toHaveBeenCalled()); - const client = clients[0] as FakeClient; - - client.emit("ready"); - const openChannel = t.openChannel(client); - expect(openChannel).toHaveBeenCalledOnce(); - const callback = openChannel.mock.calls[0]?.at(-1); - callback(undefined, fakeStream()); + const { ws, client } = await openShell(t); ws.close(); @@ -145,4 +153,23 @@ describe.each(Object.entries(terminals))("%s terminal over SSH", (_, t) => { ).toBeGreaterThan(0), ); }); + + it("closes the socket and the connection when the remote shell exits", async () => { + const { ws, client, stream } = await openShell(t); + + stream.emit("close", 0); + + await vi.waitFor(() => expect(ws.readyState).toBe(WebSocket.CLOSED)); + expect(client.end).toHaveBeenCalled(); + }); + + it("closes the socket and the connection when the shell cannot be opened", async () => { + const { ws, client } = await openShell( + t, + new Error("channel open failure"), + ); + + await vi.waitFor(() => expect(ws.readyState).toBe(WebSocket.CLOSED)); + expect(client.end).toHaveBeenCalled(); + }); }); diff --git a/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx b/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx index 1a7ec789fc6..575637c0100 100644 --- a/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx +++ b/apps/dokploy/components/dashboard/settings/web-server/terminal.tsx @@ -16,74 +16,79 @@ interface Props { export const Terminal: React.FC = ({ id, serverId }) => { const termRef = useRef(null); - const initialized = useRef(false); const { resolvedTheme } = useTheme(); useEffect(() => { - if (initialized.current) { - // Required in strict mode to avoid issues due to double wss connection - return; - } + let cancelled = false; + let term: XTerm | null = null; + let ws: WebSocket | null = null; + let resizeObserver: ResizeObserver | null = null; - initialized.current = true; - const container = document.getElementById(id); - if (container) { - container.innerHTML = ""; - } - const term = new XTerm({ - cursorBlink: true, - lineHeight: 1.4, - convertEol: true, - theme: { - cursor: resolvedTheme === "light" ? "#000000" : "transparent", - background: "rgba(0, 0, 0, 0)", - foreground: "currentColor", - }, - }); + const frame = requestAnimationFrame(() => { + if (cancelled) return; - const addonFit = new FitAddon(); - const clipboardAddon = new ClipboardAddon(); - term.loadAddon(clipboardAddon); - fixMacOsAltKeys(term); + const container = document.getElementById(id); + if (container) { + container.innerHTML = ""; + } + term = new XTerm({ + cursorBlink: true, + lineHeight: 1.4, + convertEol: true, + theme: { + cursor: resolvedTheme === "light" ? "#000000" : "transparent", + background: "rgba(0, 0, 0, 0)", + foreground: "currentColor", + }, + }); - // @ts-expect-error - term.open(termRef.current); - term.loadAddon(addonFit); - addonFit.fit(); + const addonFit = new FitAddon(); + const clipboardAddon = new ClipboardAddon(); + term.loadAddon(clipboardAddon); + fixMacOsAltKeys(term); - const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; + // @ts-expect-error + term.open(termRef.current); + term.loadAddon(addonFit); + addonFit.fit(); - const urlParams = new URLSearchParams(); - urlParams.set("serverId", serverId); - urlParams.set("cols", term.cols.toString()); - urlParams.set("rows", term.rows.toString()); + const protocol = window.location.protocol === "https:" ? "wss:" : "ws:"; - if (serverId === "local") { - const { port, username } = getLocalServerData(); - urlParams.set("port", port.toString()); - urlParams.set("username", username); - } + const urlParams = new URLSearchParams(); + urlParams.set("serverId", serverId); + urlParams.set("cols", term.cols.toString()); + urlParams.set("rows", term.rows.toString()); - const wsUrl = `${protocol}//${window.location.host}/terminal?${urlParams}`; + if (serverId === "local") { + const { port, username } = getLocalServerData(); + urlParams.set("port", port.toString()); + urlParams.set("username", username); + } - const ws = new WebSocket(wsUrl); - const addonAttach = new AttachAddon(ws); - term.loadAddon(addonAttach); + const wsUrl = `${protocol}//${window.location.host}/terminal?${urlParams}`; - const sendResize = (cols: number, rows: number) => { - if (ws.readyState === WebSocket.OPEN) { - ws.send(JSON.stringify({ type: "resize", cols, rows })); - } - }; - term.onResize(({ cols, rows }) => sendResize(cols, rows)); + ws = new WebSocket(wsUrl); + const addonAttach = new AttachAddon(ws); + term.loadAddon(addonAttach); + + const sendResize = (cols: number, rows: number) => { + if (ws && ws.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ type: "resize", cols, rows })); + } + }; + term.onResize(({ cols, rows }) => sendResize(cols, rows)); - const resizeObserver = new ResizeObserver(() => addonFit.fit()); - if (termRef.current) { - resizeObserver.observe(termRef.current); - } + resizeObserver = new ResizeObserver(() => addonFit.fit()); + if (termRef.current) { + resizeObserver.observe(termRef.current); + } + }); return () => { - resizeObserver.disconnect(); - ws.close(); + cancelled = true; + cancelAnimationFrame(frame); + resizeObserver?.disconnect(); + ws?.close(); + term?.dispose(); }; }, [id, serverId]); diff --git a/apps/dokploy/server/wss/docker-container-terminal.ts b/apps/dokploy/server/wss/docker-container-terminal.ts index fdf33c49e41..324ad5a77ac 100644 --- a/apps/dokploy/server/wss/docker-container-terminal.ts +++ b/apps/dokploy/server/wss/docker-container-terminal.ts @@ -160,8 +160,8 @@ export const setupDockerContainerTerminalWebSocketServer = ( }); }) .on("error", (err) => { - console.error("SSH connection error:", err); if (ws.readyState === ws.OPEN) { + console.error("SSH connection error:", err); ws.send(`SSH error: ${err.message}`); ws.close(); } From 4dae09ad55316aa8961a5d9e7a329d2e4ba263fd Mon Sep 17 00:00:00 2001 From: Yash Kumar Date: Thu, 5 Nov 2026 19:14:13 +0530 Subject: [PATCH 04/84] fix(traefik): harden the Traefik update and rollback --- .../traefik/reconnect-services.test.ts | 6 +- .../standalone-traefik-recreate.test.ts | 217 +++++++++++++++++- packages/server/src/services/settings.ts | 2 +- packages/server/src/setup/traefik-setup.ts | 68 ++++-- 4 files changed, 258 insertions(+), 35 deletions(-) diff --git a/apps/dokploy/__test__/traefik/reconnect-services.test.ts b/apps/dokploy/__test__/traefik/reconnect-services.test.ts index a60b0504b12..22608518522 100644 --- a/apps/dokploy/__test__/traefik/reconnect-services.test.ts +++ b/apps/dokploy/__test__/traefik/reconnect-services.test.ts @@ -50,8 +50,8 @@ describe("reconnectServicesToTraefik", () => { expect(mocks.execAsync).toHaveBeenCalledOnce(); expect(mocks.execAsync).toHaveBeenCalledWith( - 'docker network connect first-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n' + - 'docker network connect second-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n', + 'docker network connect first-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n' + + 'docker network connect second-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n', ); expect(mocks.execAsyncRemote).not.toHaveBeenCalled(); }); @@ -64,7 +64,7 @@ describe("reconnectServicesToTraefik", () => { expect(mocks.execAsyncRemote).toHaveBeenCalledOnce(); expect(mocks.execAsyncRemote).toHaveBeenCalledWith( "server-id", - 'docker network connect remote-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n', + 'docker network connect remote-compose $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n', ); expect(mocks.execAsync).not.toHaveBeenCalled(); }); diff --git a/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts b/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts index f6c87cbe043..010639b9ff9 100644 --- a/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts +++ b/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts @@ -29,24 +29,37 @@ const CRASH_LOG = frame( interface FakeOptions { oldRunning?: boolean | null; staleBackup?: boolean; + staleBackupRunning?: boolean; imagePresent?: boolean; pullEvents?: { error?: string }[]; startError?: Error; crashLoop?: boolean; restoreError?: Error; + backupRenameError?: Error; + oldNetworks?: Record; + connectError?: Error; } const fakeDocker = ({ oldRunning = true, staleBackup = false, + staleBackupRunning = false, imagePresent = true, pullEvents = [], startError, crashLoop = false, restoreError, + backupRenameError, + oldNetworks = {}, + connectError, }: FakeOptions = {}) => { const log: string[] = []; const containers: { id: string; name: string; running: boolean }[] = []; + const networks: Record< + string, + Record + > = { old: { ...oldNetworks } }; + const neverStarted = new Set(); if (oldRunning !== null) { containers.push({ id: "old", @@ -58,7 +71,7 @@ const fakeDocker = ({ containers.push({ id: "stale", name: "dokploy-traefik-previous", - running: false, + running: staleBackupRunning, }); } let hasImage = imagePresent; @@ -73,17 +86,38 @@ const fakeDocker = ({ }; const container = (ref: string) => ({ + id: ref, inspect: async () => { const c = find(ref); const startedAt = c.id === "new" && crashLoop ? `crash-${++restarts}` : "steady"; - return { Id: c.id, State: { Running: c.running, StartedAt: startedAt } }; + return { + Id: c.id, + State: { + Running: c.running, + Status: c.running + ? "running" + : neverStarted.has(c.id) + ? "created" + : "exited", + StartedAt: startedAt, + }, + NetworkSettings: { Networks: networks[c.id] ?? {} }, + }; }, rename: async ({ name }: { name: string }) => { const c = find(ref); - if (restoreError && c.id === "old" && name === "dokploy-traefik") { + if (c.running) { + throw new Error( + `could not add service state for endpoint ${name} to cluster on UpdateDNSNames: cannot create entry in table endpoint_table, already exists`, + ); + } + if (restoreError && name === "dokploy-traefik") { throw restoreError; } + if (backupRenameError && name === "dokploy-traefik-previous") { + throw backupRenameError; + } log.push(`rename ${c.id} -> ${name}`); c.name = name; }, @@ -96,6 +130,7 @@ const fakeDocker = ({ const c = find(ref); log.push(`start ${c.id}`); if (startError && c.id === "new") throw startError; + neverStarted.delete(c.id); c.running = true; }, remove: async () => { @@ -127,6 +162,22 @@ const fakeDocker = ({ }, }, getContainer: (ref: string) => container(ref), + getNetwork: (networkId: string) => ({ + connect: async ({ + Container, + EndpointConfig, + }: { + Container: string; + EndpointConfig: { Aliases?: string[] }; + }) => { + if (connectError) throw connectError; + log.push(`connect ${Container} -> ${networkId}`); + networks[Container] = { + ...networks[Container], + [networkId]: { NetworkID: networkId, ...EndpointConfig }, + }; + }, + }), createContainer: async (settings: Record) => { const name = settings.name as string; if (containers.some((c) => c.name === name)) { @@ -136,6 +187,7 @@ const fakeDocker = ({ created += 1; const id = created === 1 ? "new" : `new${created}`; containers.push({ id, name, running: false }); + neverStarted.add(id); log.push(`create ${id}`); return container(id); }, @@ -145,6 +197,7 @@ const fakeDocker = ({ docker, log, containers, + networks, createdWith: () => createdWith, }; }; @@ -185,8 +238,8 @@ describe("initializeStandaloneTraefik", () => { expect(error).toBeNull(); expect(fake.log).toEqual([ - "rename old -> dokploy-traefik-previous", "stop old", + "rename old -> dokploy-traefik-previous", "create new", "start new", "remove old", @@ -237,8 +290,8 @@ describe("initializeStandaloneTraefik", () => { "port is already allocated. The previous Traefik was restored.", ); expect(fake.log).toEqual([ - "rename old -> dokploy-traefik-previous", "stop old", + "rename old -> dokploy-traefik-previous", "create new", "start new", "remove new", @@ -284,9 +337,54 @@ describe("initializeStandaloneTraefik", () => { const error = await recreate(fake); expect(error).toBeNull(); - expect(fake.log.slice(0, 2)).toEqual([ + expect(fake.log.slice(0, 3)).toEqual([ "remove stale", + "stop old", + "rename old -> dokploy-traefik-previous", + ]); + }); + + it("joins the new container to every other network the old one was on, before starting it", async () => { + const fake = fakeDocker({ + oldNetworks: { + "dokploy-network": { NetworkID: "dokploy-network-id" }, + "my-compose": { NetworkID: "my-compose-id" }, + "manual-net": { NetworkID: "manual-net-id", Aliases: ["proxy"] }, + }, + }); + + const error = await recreate(fake); + + expect(error).toBeNull(); + expect(fake.log).toEqual([ + "stop old", "rename old -> dokploy-traefik-previous", + "create new", + "connect new -> my-compose-id", + "connect new -> manual-net-id", + "start new", + "remove old", + ]); + expect(fake.networks.new).toEqual({ + "my-compose-id": { NetworkID: "my-compose-id" }, + "manual-net-id": { NetworkID: "manual-net-id", Aliases: ["proxy"] }, + }); + }); + + it("puts the old container back when the new one cannot join a network", async () => { + const fake = fakeDocker({ + oldNetworks: { "manual-net": { NetworkID: "manual-net-id" } }, + connectError: new Error("network manual-net-id not found"), + }); + + const error = await recreate(fake); + + expect(error?.message).toBe( + "network manual-net-id not found. The previous Traefik was restored.", + ); + expect(fake.log).not.toContain("start new"); + expect(fake.containers).toEqual([ + { id: "old", name: "dokploy-traefik", running: true }, ]); }); @@ -303,6 +401,20 @@ describe("initializeStandaloneTraefik", () => { ); }); + it("starts the old container again when it cannot be moved aside", async () => { + const fake = fakeDocker({ + backupRenameError: new Error("name already in use"), + }); + + const error = await recreate(fake); + + expect(error?.message).toBe("name already in use"); + expect(fake.log).toEqual(["stop old", "start old"]); + expect(fake.containers).toEqual([ + { id: "old", name: "dokploy-traefik", running: true }, + ]); + }); + it("runs overlapping recreates of the same server one after another", async () => { const fake = fakeDocker(); mocks.getRemoteDocker.mockResolvedValue(fake.docker); @@ -318,13 +430,13 @@ describe("initializeStandaloneTraefik", () => { await expect(first).resolves.toBeUndefined(); await expect(second).resolves.toBeUndefined(); expect(fake.log).toEqual([ - "rename old -> dokploy-traefik-previous", "stop old", + "rename old -> dokploy-traefik-previous", "create new", "start new", "remove old", - "rename new -> dokploy-traefik-previous", "stop new", + "rename new -> dokploy-traefik-previous", "create new2", "start new2", "remove new", @@ -408,6 +520,93 @@ describe("restoreInterruptedTraefik", () => { ]); }); + it("starts the backup again even when renaming it back fails", async () => { + const fake = fakeDocker({ + oldRunning: null, + staleBackup: true, + staleBackupRunning: true, + restoreError: new Error("name already in use"), + }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + + await expect(restoreInterruptedTraefik()).rejects.toThrow( + "name already in use", + ); + + expect(fake.containers).toEqual([ + { id: "stale", name: "dokploy-traefik-previous", running: true }, + ]); + }); + + it("stops a running backup before renaming it back", async () => { + const fake = fakeDocker({ + oldRunning: null, + staleBackup: true, + staleBackupRunning: true, + }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual([ + "stop stale", + "rename stale -> dokploy-traefik", + "start stale", + ]); + expect(fake.containers).toEqual([ + { id: "stale", name: "dokploy-traefik", running: true }, + ]); + }); + + it("clears a new container that never started and brings back the backup", async () => { + const fake = fakeDocker({ oldRunning: null, staleBackup: true }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + await fake.docker.createContainer({ name: "dokploy-traefik" }); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual([ + "create new", + "remove new", + "rename stale -> dokploy-traefik", + "start stale", + ]); + expect(fake.containers).toEqual([ + { id: "stale", name: "dokploy-traefik", running: true }, + ]); + }); + + it("leaves a stopped Traefik alone even when a backup exists", async () => { + const fake = fakeDocker({ oldRunning: false, staleBackup: true }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual([]); + }); + + it("waits for a running update instead of restoring its backup mid-way", async () => { + const fake = fakeDocker(); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + + const update = initializeStandaloneTraefik().then( + () => null, + (error: Error) => error, + ); + await vi.advanceTimersByTimeAsync(1000); + expect(fake.containers.map((c) => c.name)).toEqual([ + "dokploy-traefik-previous", + ]); + const restore = restoreInterruptedTraefik(); + await vi.runAllTimersAsync(); + + expect(await update).toBeNull(); + await expect(restore).resolves.toBeUndefined(); + expect(fake.containers).toEqual([ + { id: "new", name: "dokploy-traefik", running: true }, + ]); + }); + it("leaves things alone when Traefik exists", async () => { const fake = fakeDocker({ staleBackup: true }); mocks.getRemoteDocker.mockResolvedValue(fake.docker); @@ -435,8 +634,8 @@ describe("restoreInterruptedTraefik", () => { expect(fake.log).toEqual([ "rename stale -> dokploy-traefik", "start stale", - "rename stale -> dokploy-traefik-previous", "stop stale", + "rename stale -> dokploy-traefik-previous", "create new", "start new", "remove stale", diff --git a/packages/server/src/services/settings.ts b/packages/server/src/services/settings.ts index 8f6e0e1bbd4..496ab5097e9 100644 --- a/packages/server/src/services/settings.ts +++ b/packages/server/src/services/settings.ts @@ -660,7 +660,7 @@ export const reconnectServicesToTraefik = async (serverId?: string) => { let commands = ""; for (const compose of composeResult) { - commands += `docker network connect ${compose.appName} $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1\n`; + commands += `docker network connect ${compose.appName} $(docker ps --filter "name=dokploy-traefik" -q) >/dev/null 2>&1 || true\n`; } if (serverId) { diff --git a/packages/server/src/setup/traefik-setup.ts b/packages/server/src/setup/traefik-setup.ts index 988f8e9145b..4ee57e8093a 100644 --- a/packages/server/src/setup/traefik-setup.ts +++ b/packages/server/src/setup/traefik-setup.ts @@ -37,14 +37,15 @@ export interface TraefikOptions { }[]; } -// Overlapping recreates of one server would remove each other's containers. +// Overlapping recreates and restores of one server would remove each other's containers. const recreateQueue = new Map>(); -export const initializeStandaloneTraefik = (options: TraefikOptions = {}) => { - const key = options.serverId ?? "local"; - const run = (recreateQueue.get(key) ?? Promise.resolve()).then(() => - recreateStandaloneTraefik(options), - ); +export const initializeStandaloneTraefik = (options: TraefikOptions = {}) => + runQueued(options.serverId, () => recreateStandaloneTraefik(options)); + +const runQueued = (serverId: string | undefined, task: () => Promise) => { + const key = serverId ?? "local"; + const run = (recreateQueue.get(key) ?? Promise.resolve()).then(task); // So a hung Docker call can't block later recreates. const settled = Promise.race([run.catch(() => {}), sleep(5 * 60_000)]).then( () => {}, @@ -120,7 +121,7 @@ const recreateStandaloneTraefik = async ({ }; const docker = await getRemoteDocker(serverId); - await restoreInterruptedTraefik(serverId); + await restoreBackupTraefik(serverId); await ensureTraefikImage(serverId); // Kept until the new container stays up, so it can be restored on failure. @@ -134,13 +135,30 @@ const recreateStandaloneTraefik = async ({ .getContainer(PREVIOUS_TRAEFIK_CONTAINER) .remove({ force: true }) .catch(() => {}); - await current.rename({ name: PREVIOUS_TRAEFIK_CONTAINER }); await current.stop().catch(() => {}); + try { + await current.rename({ name: PREVIOUS_TRAEFIK_CONTAINER }); + } catch (error) { + if (currentInfo?.State.Running) { + await current.start(); + } + throw error; + } await sleep(5000); } + const otherNetworks = Object.entries( + currentInfo?.NetworkSettings?.Networks ?? {}, + ).filter(([name]) => name !== "dokploy-network"); + try { const created = await docker.createContainer(settings); + for (const [, endpoint] of otherNetworks) { + await docker.getNetwork(endpoint.NetworkID).connect({ + Container: created.id, + EndpointConfig: { Aliases: endpoint.Aliases }, + }); + } await created.start(); await waitUntilStable(created); } catch (error) { @@ -172,19 +190,12 @@ const recreateStandaloneTraefik = async ({ const PREVIOUS_TRAEFIK_CONTAINER = "dokploy-traefik-previous"; -// An interrupted recreate (e.g. a Dokploy restart) leaves only the stopped backup. -export const restoreInterruptedTraefik = async (serverId?: string) => { +export const restoreInterruptedTraefik = (serverId?: string) => + runQueued(serverId, () => restoreBackupTraefik(serverId)); + +// An interrupted recreate (e.g. a Dokploy restart) leaves the stopped backup, possibly beside a new container that never started. +const restoreBackupTraefik = async (serverId?: string) => { const docker = await getRemoteDocker(serverId); - const exists = await docker - .getContainer("dokploy-traefik") - .inspect() - .then( - () => true, - () => false, - ); - if (exists) { - return; - } const backupInfo = await docker .getContainer(PREVIOUS_TRAEFIK_CONTAINER) .inspect() @@ -192,9 +203,22 @@ export const restoreInterruptedTraefik = async (serverId?: string) => { if (!backupInfo) { return; } + const currentInfo = await docker + .getContainer("dokploy-traefik") + .inspect() + .catch(() => null); + if (currentInfo?.State.Status === "created") { + await docker.getContainer(currentInfo.Id).remove({ force: true }); + } else if (currentInfo) { + return; + } const backup = docker.getContainer(backupInfo.Id); - await backup.rename({ name: "dokploy-traefik" }); - if (!backupInfo.State.Running) { + if (backupInfo.State.Running) { + await backup.stop().catch(() => {}); + } + try { + await backup.rename({ name: "dokploy-traefik" }); + } finally { await backup.start(); } console.log("Restored Traefik left behind by an interrupted recreate"); From 0104c2c6ab34db04508ae24b19c1ca781638b185 Mon Sep 17 00:00:00 2001 From: Yash Kumar Date: Thu, 5 Nov 2026 19:29:09 +0530 Subject: [PATCH 05/84] fix(traefik): recover an update interrupted after Traefik stops --- .../standalone-traefik-recreate.test.ts | 116 +++++++++++++++--- .../utils/docker-cleanup-traefik.test.ts | 3 + packages/server/src/setup/traefik-setup.ts | 100 ++++++++------- packages/server/src/utils/docker/utils.ts | 2 +- 4 files changed, 158 insertions(+), 63 deletions(-) diff --git a/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts b/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts index 010639b9ff9..9c8b8537917 100644 --- a/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts +++ b/apps/dokploy/__test__/traefik/standalone-traefik-recreate.test.ts @@ -107,12 +107,19 @@ const fakeDocker = ({ }, rename: async ({ name }: { name: string }) => { const c = find(ref); + if (containers.some((other) => other !== c && other.name === name)) { + throw new Error(`Conflict: ${name} is already in use`); + } if (c.running) { throw new Error( `could not add service state for endpoint ${name} to cluster on UpdateDNSNames: cannot create entry in table endpoint_table, already exists`, ); } - if (restoreError && name === "dokploy-traefik") { + if ( + restoreError && + name === "dokploy-traefik" && + !c.id.startsWith("new") + ) { throw restoreError; } if (backupRenameError && name === "dokploy-traefik-previous") { @@ -238,9 +245,10 @@ describe("initializeStandaloneTraefik", () => { expect(error).toBeNull(); expect(fake.log).toEqual([ + "create new", "stop old", "rename old -> dokploy-traefik-previous", - "create new", + "rename new -> dokploy-traefik", "start new", "remove old", ]); @@ -248,7 +256,7 @@ describe("initializeStandaloneTraefik", () => { { id: "new", name: "dokploy-traefik", running: true }, ]); expect(fake.createdWith()).toMatchObject({ - name: "dokploy-traefik", + name: "dokploy-traefik-next", Image: `traefik:v${TRAEFIK_VERSION}`, HostConfig: { PortBindings: { "8080/tcp": [{ HostPort: "8080" }] } }, }); @@ -290,9 +298,10 @@ describe("initializeStandaloneTraefik", () => { "port is already allocated. The previous Traefik was restored.", ); expect(fake.log).toEqual([ + "create new", "stop old", "rename old -> dokploy-traefik-previous", - "create new", + "rename new -> dokploy-traefik", "start new", "remove new", "rename old -> dokploy-traefik", @@ -337,7 +346,8 @@ describe("initializeStandaloneTraefik", () => { const error = await recreate(fake); expect(error).toBeNull(); - expect(fake.log.slice(0, 3)).toEqual([ + expect(fake.log.slice(0, 4)).toEqual([ + "create new", "remove stale", "stop old", "rename old -> dokploy-traefik-previous", @@ -357,11 +367,12 @@ describe("initializeStandaloneTraefik", () => { expect(error).toBeNull(); expect(fake.log).toEqual([ - "stop old", - "rename old -> dokploy-traefik-previous", "create new", "connect new -> my-compose-id", "connect new -> manual-net-id", + "stop old", + "rename old -> dokploy-traefik-previous", + "rename new -> dokploy-traefik", "start new", "remove old", ]); @@ -371,7 +382,7 @@ describe("initializeStandaloneTraefik", () => { }); }); - it("puts the old container back when the new one cannot join a network", async () => { + it("keeps the old container running when the new one cannot join a network", async () => { const fake = fakeDocker({ oldNetworks: { "manual-net": { NetworkID: "manual-net-id" } }, connectError: new Error("network manual-net-id not found"), @@ -379,10 +390,8 @@ describe("initializeStandaloneTraefik", () => { const error = await recreate(fake); - expect(error?.message).toBe( - "network manual-net-id not found. The previous Traefik was restored.", - ); - expect(fake.log).not.toContain("start new"); + expect(error?.message).toBe("network manual-net-id not found"); + expect(fake.log).toEqual(["create new", "remove new"]); expect(fake.containers).toEqual([ { id: "old", name: "dokploy-traefik", running: true }, ]); @@ -409,7 +418,12 @@ describe("initializeStandaloneTraefik", () => { const error = await recreate(fake); expect(error?.message).toBe("name already in use"); - expect(fake.log).toEqual(["stop old", "start old"]); + expect(fake.log).toEqual([ + "create new", + "stop old", + "start old", + "remove new", + ]); expect(fake.containers).toEqual([ { id: "old", name: "dokploy-traefik", running: true }, ]); @@ -430,14 +444,16 @@ describe("initializeStandaloneTraefik", () => { await expect(first).resolves.toBeUndefined(); await expect(second).resolves.toBeUndefined(); expect(fake.log).toEqual([ + "create new", "stop old", "rename old -> dokploy-traefik-previous", - "create new", + "rename new -> dokploy-traefik", "start new", "remove old", + "create new2", "stop new", "rename new -> dokploy-traefik-previous", - "create new2", + "rename new2 -> dokploy-traefik", "start new2", "remove new", ]); @@ -477,7 +493,11 @@ describe("initializeStandaloneTraefik", () => { const error = await recreate(fake); expect(error).toBeNull(); - expect(fake.log).toEqual(["create new", "start new"]); + expect(fake.log).toEqual([ + "create new", + "rename new -> dokploy-traefik", + "start new", + ]); }); it("keeps the old behaviour on a fresh setup that fails: logs instead of throwing", async () => { @@ -489,7 +509,12 @@ describe("initializeStandaloneTraefik", () => { const error = await recreate(fake); expect(error).toBeNull(); - expect(fake.log).toEqual(["create new", "start new"]); + expect(fake.log).toEqual([ + "create new", + "rename new -> dokploy-traefik", + "start new", + "remove new", + ]); }); }); @@ -576,6 +601,59 @@ describe("restoreInterruptedTraefik", () => { ]); }); + it("starts Traefik again when Dokploy restarted right after an update stopped it", async () => { + const fake = fakeDocker({ oldRunning: false }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + await fake.docker.createContainer({ name: "dokploy-traefik-next" }); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual(["create new", "start old", "remove new"]); + expect(fake.containers).toEqual([ + { id: "old", name: "dokploy-traefik", running: true }, + ]); + }); + + it("only clears the new container when Dokploy restarted before the update stopped Traefik", async () => { + const fake = fakeDocker(); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + await fake.docker.createContainer({ name: "dokploy-traefik-next" }); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual(["create new", "remove new"]); + expect(fake.containers).toEqual([ + { id: "old", name: "dokploy-traefik", running: true }, + ]); + }); + + it("brings back the backup when Dokploy restarted mid-swap", async () => { + const fake = fakeDocker({ oldRunning: null, staleBackup: true }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + await fake.docker.createContainer({ name: "dokploy-traefik-next" }); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual([ + "create new", + "rename stale -> dokploy-traefik", + "start stale", + "remove new", + ]); + expect(fake.containers).toEqual([ + { id: "stale", name: "dokploy-traefik", running: true }, + ]); + }); + + it("leaves a stopped Traefik alone when no update was interrupted", async () => { + const fake = fakeDocker({ oldRunning: false }); + mocks.getRemoteDocker.mockResolvedValue(fake.docker); + + await restoreInterruptedTraefik(); + + expect(fake.log).toEqual([]); + }); + it("leaves a stopped Traefik alone even when a backup exists", async () => { const fake = fakeDocker({ oldRunning: false, staleBackup: true }); mocks.getRemoteDocker.mockResolvedValue(fake.docker); @@ -596,6 +674,7 @@ describe("restoreInterruptedTraefik", () => { await vi.advanceTimersByTimeAsync(1000); expect(fake.containers.map((c) => c.name)).toEqual([ "dokploy-traefik-previous", + "dokploy-traefik-next", ]); const restore = restoreInterruptedTraefik(); await vi.runAllTimersAsync(); @@ -634,9 +713,10 @@ describe("restoreInterruptedTraefik", () => { expect(fake.log).toEqual([ "rename stale -> dokploy-traefik", "start stale", + "create new", "stop stale", "rename stale -> dokploy-traefik-previous", - "create new", + "rename new -> dokploy-traefik", "start new", "remove stale", ]); diff --git a/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts b/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts index 630d5fb264c..187d28c064b 100644 --- a/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts +++ b/apps/dokploy/__test__/utils/docker-cleanup-traefik.test.ts @@ -81,6 +81,9 @@ describe("docker cleanup keeps a stopped dokploy-traefik", () => { expect( runWithFakeDocker(script!, { "dokploy-traefik-previous": "false" }), ).toEqual([]); + expect( + runWithFakeDocker(script!, { "dokploy-traefik-next": "false" }), + ).toEqual([]); expect(runWithFakeDocker(script!, { "dokploy-traefik": "true" })).toEqual([ prune, ]); diff --git a/packages/server/src/setup/traefik-setup.ts b/packages/server/src/setup/traefik-setup.ts index 4ee57e8093a..6c8ba9d5760 100644 --- a/packages/server/src/setup/traefik-setup.ts +++ b/packages/server/src/setup/traefik-setup.ts @@ -98,7 +98,7 @@ const recreateStandaloneTraefik = async ({ } const settings: ContainerCreateOptions = { - name: containerName, + name: NEXT_TRAEFIK_CONTAINER, Image: imageName, NetworkingConfig: { EndpointsConfig: { @@ -130,46 +130,49 @@ const recreateStandaloneTraefik = async ({ .inspect() .catch(() => null); const current = currentInfo ? docker.getContainer(currentInfo.Id) : null; - if (current) { - await docker - .getContainer(PREVIOUS_TRAEFIK_CONTAINER) - .remove({ force: true }) - .catch(() => {}); - await current.stop().catch(() => {}); - try { - await current.rename({ name: PREVIOUS_TRAEFIK_CONTAINER }); - } catch (error) { - if (currentInfo?.State.Running) { - await current.start(); - } - throw error; - } - await sleep(5000); - } - const otherNetworks = Object.entries( currentInfo?.NetworkSettings?.Networks ?? {}, ).filter(([name]) => name !== "dokploy-network"); + let created: Container | undefined; + let movedAside = false; try { - const created = await docker.createContainer(settings); + // Created first so an interrupted update can be detected. + created = await docker.createContainer(settings); for (const [, endpoint] of otherNetworks) { await docker.getNetwork(endpoint.NetworkID).connect({ Container: created.id, EndpointConfig: { Aliases: endpoint.Aliases }, }); } + if (current) { + await docker + .getContainer(PREVIOUS_TRAEFIK_CONTAINER) + .remove({ force: true }) + .catch(() => {}); + await current.stop().catch(() => {}); + await current.rename({ name: PREVIOUS_TRAEFIK_CONTAINER }); + movedAside = true; + await sleep(5000); + } + await created.rename({ name: containerName }); await created.start(); await waitUntilStable(created); } catch (error) { if (!current) { + await created?.remove({ force: true }).catch(() => {}); console.log("Traefik Not Found: Starting ", error); return; } - await docker - .getContainer(containerName) - .remove({ force: true }) - .catch(() => {}); + if (!movedAside) { + const now = await current.inspect().catch(() => null); + if (currentInfo?.State.Running && !now?.State.Running) { + await current.start(); + } + await created?.remove({ force: true }).catch(() => {}); + throw error; + } + await created?.remove({ force: true }).catch(() => {}); const reason = error instanceof Error ? error.message : String(error); try { await current.rename({ name: containerName }); @@ -188,40 +191,49 @@ const recreateStandaloneTraefik = async ({ console.log("Traefik Started ✅"); }; +const NEXT_TRAEFIK_CONTAINER = "dokploy-traefik-next"; const PREVIOUS_TRAEFIK_CONTAINER = "dokploy-traefik-previous"; export const restoreInterruptedTraefik = (serverId?: string) => runQueued(serverId, () => restoreBackupTraefik(serverId)); -// An interrupted recreate (e.g. a Dokploy restart) leaves the stopped backup, possibly beside a new container that never started. +// Undoes an update interrupted by a Dokploy restart. const restoreBackupTraefik = async (serverId?: string) => { const docker = await getRemoteDocker(serverId); - const backupInfo = await docker - .getContainer(PREVIOUS_TRAEFIK_CONTAINER) - .inspect() - .catch(() => null); - if (!backupInfo) { + const inspect = (name: string) => + docker + .getContainer(name) + .inspect() + .catch(() => null); + const nextInfo = await inspect(NEXT_TRAEFIK_CONTAINER); + const backupInfo = await inspect(PREVIOUS_TRAEFIK_CONTAINER); + if (!nextInfo && !backupInfo) { return; } - const currentInfo = await docker - .getContainer("dokploy-traefik") - .inspect() - .catch(() => null); - if (currentInfo?.State.Status === "created") { + let currentInfo = await inspect("dokploy-traefik"); + if (currentInfo?.State.Status === "created" && backupInfo) { await docker.getContainer(currentInfo.Id).remove({ force: true }); - } else if (currentInfo) { - return; + currentInfo = null; } - const backup = docker.getContainer(backupInfo.Id); - if (backupInfo.State.Running) { - await backup.stop().catch(() => {}); + if (currentInfo) { + if (nextInfo && !currentInfo.State.Running) { + await docker.getContainer(currentInfo.Id).start(); + } + } else if (backupInfo) { + const backup = docker.getContainer(backupInfo.Id); + if (backupInfo.State.Running) { + await backup.stop().catch(() => {}); + } + try { + await backup.rename({ name: "dokploy-traefik" }); + } finally { + await backup.start(); + } + console.log("Restored Traefik left behind by an interrupted recreate"); } - try { - await backup.rename({ name: "dokploy-traefik" }); - } finally { - await backup.start(); + if (nextInfo) { + await docker.getContainer(nextInfo.Id).remove({ force: true }); } - console.log("Restored Traefik left behind by an interrupted recreate"); }; // docker.pull resolves before the download ends and reports errors in the stream. diff --git a/packages/server/src/utils/docker/utils.ts b/packages/server/src/utils/docker/utils.ts index e4a669c8b5a..6efe3dd19bd 100644 --- a/packages/server/src/utils/docker/utils.ts +++ b/packages/server/src/utils/docker/utils.ts @@ -186,7 +186,7 @@ echo "Execution completed." // A stopped Traefik must stay startable; keeping its container also keeps its image from `image prune --all`. const skipIfTraefikStopped = (command: string) => ` -if docker container inspect --format '{{.State.Running}}' dokploy-traefik dokploy-traefik-previous 2>/dev/null | grep -q false; then +if docker container inspect --format '{{.State.Running}}' dokploy-traefik dokploy-traefik-previous dokploy-traefik-next 2>/dev/null | grep -q false; then echo "Skipping '${command}': dokploy-traefik is stopped" else ${command} From 9b0db9aed14668dbeea71b7fe8bdeab547986935 Mon Sep 17 00:00:00 2001 From: Narciso Date: Thu, 5 Nov 2026 15:34:54 -0400 Subject: [PATCH 06/84] fix(access-log): rewrite access.log in place on cleanup mv swapped the inode, leaving containers that bind-mount the file (e.g. CrowdSec template) reading a stale/deleted file. --- packages/server/src/utils/access-log/handler.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/server/src/utils/access-log/handler.ts b/packages/server/src/utils/access-log/handler.ts index 0feae622cff..3b662836b50 100644 --- a/packages/server/src/utils/access-log/handler.ts +++ b/packages/server/src/utils/access-log/handler.ts @@ -29,8 +29,9 @@ export const startLogCleanup = async ( return; } + // In-place rewrite: `mv` changes the inode and breaks file bind mounts. await execAsync( - `tail -n 1000 ${accessLogPath} > ${accessLogPath}.tmp && mv ${accessLogPath}.tmp ${accessLogPath}`, + `tail -n 1000 ${accessLogPath} > ${accessLogPath}.tmp && cat ${accessLogPath}.tmp > ${accessLogPath} && rm ${accessLogPath}.tmp`, ); // Traefik can run as a standalone container ("dokploy-traefik") or a From 190d2c97d25f6b1aa96c4e1208843c7a2e48af38 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Thu, 5 Nov 2026 22:11:11 +0100 Subject: [PATCH 07/84] fix(onboarding): let users continue past plan step after starting a trial Going back to the plan step after starting a trial only offered "Start trial", which failed with "already have an active plan or trial", leaving users stuck. Show the active plan/trial with a Continue button, and hide the trial button once the trial has been used. --- .../dashboard/onboarding/steps/plan-step.tsx | 63 +++++++++++++------ 1 file changed, 45 insertions(+), 18 deletions(-) diff --git a/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx b/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx index c32a0dac28f..819ffa26db9 100644 --- a/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx +++ b/apps/dokploy/components/dashboard/onboarding/steps/plan-step.tsx @@ -61,6 +61,7 @@ export const PlanStep = ({ onNext }: Props) => { `${"trial" | "checkout"}:${Tier}` | null >(null); const { data } = api.stripe.getProducts.useQuery(); + const { data: status } = api.project.onboardingStatus.useQuery(); const { mutateAsync: createCheckoutSession } = api.stripe.createCheckoutSession.useMutation(); const { mutateAsync: startFreeTrial } = @@ -121,6 +122,28 @@ export const PlanStep = ({ onNext }: Props) => {

+ {status?.hasActiveAccess && ( +
+
+

+ {status.isOnTrial + ? `Your ${status.plan ? `${status.plan[0]!.toUpperCase()}${status.plan.slice(1)} ` : ""}trial is active` + : "You already have an active plan"} +

+ {status.isOnTrial && status.trialDaysRemaining !== null && ( +

+ {status.trialDaysRemaining}{" "} + {status.trialDaysRemaining === 1 ? "day" : "days"} remaining +

+ )} +
+ +
+ )} +
{PLANS.map((plan) => { const productId = @@ -161,24 +184,28 @@ export const PlanStep = ({ onNext }: Props) => { ))}
-
- - -
+ {!status?.hasActiveAccess && ( +
+ {!status?.hasUsedTrial && ( + + )} + +
+ )} ); })} From 4b582856b36a0d037ff43ecbed2026d93f22ecc6 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 00:43:05 +0100 Subject: [PATCH 08/84] fix(security): enforce org/role boundaries across routers, webhooks and auth Hardens authorization and input containment found in a source audit. - shared assertServerAccess guard (org + accessedServers; rejects the local control-plane host on Cloud) applied to network, destination, registry, certificate, ai.deploy, docker/volume/image, swarm, cluster and settings - getRemoteDocker fails closed when the target server has no SSH key - bind path inputs to their owner: unzipDrop (zip-slip), patch repo file/dir read, backup object key, and volume restore (+ strict backupFileName) - domain.create authorizes every service id regardless of domainType - git-provider update (github/gitlab/gitea/bitbucket) checks provider ownership - notification update binds the channel sub-record id to the notification - backup web-server restore and service-less backup ops are owner/admin and org-bound - listen-deployment binds the requested logPath to an authorized deployment - github webhook pull_request closed scopes preview removal to the verified provider - gitea/gitlab OAuth callbacks require a session whose org owns the provider - SSRF: metrics endpoints, compose template baseUrl and AI model fetch go through providerFetch - apps/api and apps/schedules fail closed when API_KEY is unset - better-auth: member role/invite only via tRPC (+ admin-role ceiling), API-key sessions fail closed without a membership row, and reset/verification links use the canonical host instead of the request Host header Adds role-based regression tests (owner/admin/member/custom) covering both preserved legitimate access and blocked escalation. --- apps/api/src/index.ts | 24 ++- .../backup-destination-organization.test.ts | 74 ++++++++- .../domain/domain-create-authz.test.ts | 92 ++++++++++++ .../drop-zip-slip-within-basepath.test.ts | 73 +++++++++ .../git-provider/github-update-authz.test.ts | 67 +++++++++ .../patch/read-repo-file-traversal.test.ts | 54 +++++++ .../permissions/assert-server-access.test.ts | 122 +++++++++++++++ .../permissions/member-role-ceiling.test.ts | 141 ++++++++++++++++++ .../__test__/wss/listen-deployment.test.ts | 10 ++ apps/dokploy/pages/api/deploy/github.ts | 7 +- .../pages/api/providers/gitea/authorize.ts | 10 ++ .../pages/api/providers/gitea/callback.ts | 11 +- .../pages/api/providers/gitlab/callback.ts | 11 +- apps/dokploy/server/api/routers/ai.ts | 13 +- apps/dokploy/server/api/routers/backup.ts | 80 +++++++++- apps/dokploy/server/api/routers/bitbucket.ts | 2 + .../dokploy/server/api/routers/certificate.ts | 2 + apps/dokploy/server/api/routers/cluster.ts | 5 + .../dokploy/server/api/routers/destination.ts | 4 +- .../server/api/routers/docker-image.ts | 4 + .../server/api/routers/docker-volume.ts | 9 ++ apps/dokploy/server/api/routers/docker.ts | 19 +++ apps/dokploy/server/api/routers/domain.ts | 23 ++- apps/dokploy/server/api/routers/gitea.ts | 2 + apps/dokploy/server/api/routers/github.ts | 2 + apps/dokploy/server/api/routers/gitlab.ts | 2 + apps/dokploy/server/api/routers/network.ts | 4 + .../server/api/routers/notification.ts | 72 +++++++++ .../server/api/routers/organization.ts | 23 +++ apps/dokploy/server/api/routers/patch.ts | 15 +- apps/dokploy/server/api/routers/registry.ts | 5 +- apps/dokploy/server/api/routers/server.ts | 3 +- apps/dokploy/server/api/routers/settings.ts | 86 ++++++++++- apps/dokploy/server/api/routers/swarm.ts | 6 + apps/dokploy/server/api/routers/user.ts | 3 +- .../server/api/routers/volume-backups.ts | 11 +- apps/dokploy/server/wss/listen-deployment.ts | 50 ++++++- apps/schedules/src/index.ts | 24 ++- packages/server/src/lib/auth.ts | 39 ++++- packages/server/src/services/deployment.ts | 12 ++ packages/server/src/services/patch-repo.ts | 33 +++- .../server/src/services/preview-deployment.ts | 11 ++ packages/server/src/services/server.ts | 17 +++ packages/server/src/templates/github.ts | 9 +- packages/server/src/utils/builders/drop.ts | 7 +- .../server/src/utils/servers/remote-docker.ts | 6 +- .../src/utils/volume-backups/restore.ts | 2 +- 47 files changed, 1239 insertions(+), 62 deletions(-) create mode 100644 apps/dokploy/__test__/domain/domain-create-authz.test.ts create mode 100644 apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts create mode 100644 apps/dokploy/__test__/git-provider/github-update-authz.test.ts create mode 100644 apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts create mode 100644 apps/dokploy/__test__/permissions/assert-server-access.test.ts create mode 100644 apps/dokploy/__test__/permissions/member-role-ceiling.test.ts diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 0bb6e1401e6..6a1c69fed63 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -1,3 +1,4 @@ +import { timingSafeEqual } from "node:crypto"; import { serve } from "@hono/node-server"; import { Hono } from "hono"; import "dotenv/config"; @@ -82,6 +83,27 @@ export const deploymentFunction = inngest.createFunction( }, ); +if (!process.env.API_KEY) { + console.error( + "API_KEY is not set; all authenticated routes will be rejected", + ); +} + +const isValidApiKey = (header: string | undefined): boolean => { + const apiKey = process.env.API_KEY; + if (!apiKey || !header) { + return false; + } + + const headerBuffer = Buffer.from(header); + const apiKeyBuffer = Buffer.from(apiKey); + if (headerBuffer.length !== apiKeyBuffer.length) { + return false; + } + + return timingSafeEqual(headerBuffer, apiKeyBuffer); +}; + app.use(async (c, next) => { if (c.req.path === "/health" || c.req.path === "/api/inngest") { return next(); @@ -89,7 +111,7 @@ app.use(async (c, next) => { const authHeader = c.req.header("X-API-Key"); - if (process.env.API_KEY !== authHeader) { + if (!isValidApiKey(authHeader)) { return c.json({ message: "Invalid API Key" }, 403); } diff --git a/apps/dokploy/__test__/backups/backup-destination-organization.test.ts b/apps/dokploy/__test__/backups/backup-destination-organization.test.ts index 3e0b1b80e91..00ba9bf70fd 100644 --- a/apps/dokploy/__test__/backups/backup-destination-organization.test.ts +++ b/apps/dokploy/__test__/backups/backup-destination-organization.test.ts @@ -73,6 +73,12 @@ const caller = backupRouter.createCaller({ user: { id: "user-1", email: "user@example.com", role: "owner" }, } as Parameters[0]); +const callerAs = (role: string) => + backupRouter.createCaller({ + session: { activeOrganizationId: "org-a" }, + user: { id: "user-1", email: "user@example.com", role }, + } as Parameters[0]); + const ownDestination = { destinationId: "dest-a", organizationId: "org-a" }; const foreignDestination = { destinationId: "dest-b", organizationId: "org-b" }; @@ -122,7 +128,10 @@ describe("backup endpoints scope destinations to the active organization", () => databaseType: "postgres", backupType: "database", }); - mocks.findPostgresById.mockResolvedValue({ postgresId: "pg-1" }); + mocks.findPostgresById.mockResolvedValue({ + postgresId: "pg-1", + appName: "app", + }); }); it("rejects creating a backup on a destination from another organization", async () => { @@ -181,16 +190,65 @@ describe("backup endpoints scope destinations to the active organization", () => expect(mocks.restorePostgresBackup).toHaveBeenCalledTimes(1); }); - it("leaves service-less web-server schedules unscoped (maintainer decision)", async () => { + it("rejects a service-less web-server schedule on a foreign destination", async () => { mocks.findDestinationRow.mockResolvedValue(foreignDestination); - await caller.create({ - ...createInput, - postgresId: undefined, - databaseType: "web-server", - destinationId: "dest-b", + await expect( + caller.create({ + ...createInput, + postgresId: undefined, + databaseType: "web-server", + destinationId: "dest-b", + }), + ).rejects.toMatchObject({ + message: "You don't have access to this destination.", }); - expect(mocks.createBackup).toHaveBeenCalledTimes(1); + expect(mocks.createBackup).not.toHaveBeenCalled(); + }); +}); + +describe("restore access by role", () => { + beforeEach(() => { + vi.clearAllMocks(); + mocks.findPostgresById.mockResolvedValue({ + postgresId: "pg-1", + appName: "app", + }); + }); + + const webServerRestore = { + databaseId: "", + databaseType: "web-server" as const, + backupType: "database" as const, + databaseName: "panel", + backupFile: "panel.zip", + destinationId: "dest-a", + }; + + for (const role of ["owner", "admin"]) { + it(`${role} can run a web-server restore`, async () => { + mocks.findDestinationRow.mockResolvedValue(ownDestination); + const stream = await callerAs(role).restoreBackupWithLogs(webServerRestore); + await drain(stream); + expect(mocks.restoreWebServerBackup).toHaveBeenCalledTimes(1); + }); + } + + it("a member cannot run a web-server restore (panel wipe)", async () => { + mocks.findDestinationRow.mockResolvedValue(ownDestination); + const stream = await callerAs("member").restoreBackupWithLogs(webServerRestore); + await expect(drain(stream)).rejects.toMatchObject({ code: "UNAUTHORIZED" }); + expect(mocks.restoreWebServerBackup).not.toHaveBeenCalled(); + }); + + it("a member with service access can still restore its own database", async () => { + mocks.findDestinationRow.mockResolvedValue(ownDestination); + const stream = await callerAs("member").restoreBackupWithLogs({ + ...restoreInput, + destinationId: "dest-a", + }); + await drain(stream); + expect(mocks.restorePostgresBackup).toHaveBeenCalledTimes(1); }); }); diff --git a/apps/dokploy/__test__/domain/domain-create-authz.test.ts b/apps/dokploy/__test__/domain/domain-create-authz.test.ts new file mode 100644 index 00000000000..1274252394c --- /dev/null +++ b/apps/dokploy/__test__/domain/domain-create-authz.test.ts @@ -0,0 +1,92 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + createDomain: vi.fn(), + findPreviewDeploymentById: vi.fn(), + checkServiceAccess: vi.fn(), +})); + +vi.mock("@dokploy/server", () => ({ + createDomain: mocks.createDomain, + findPreviewDeploymentById: mocks.findPreviewDeploymentById, +})); +vi.mock("@dokploy/server/services/permission", () => ({ + checkServicePermissionAndAccess: mocks.checkServiceAccess, + checkPermission: vi.fn(async () => undefined), +})); +vi.mock("@/server/api/utils/audit", () => ({ audit: vi.fn(async () => undefined) })); + +const { domainRouter } = await import("@/server/api/routers/domain"); + +const callerAs = (role: string) => + domainRouter.createCaller({ + user: { id: "u1", role }, + session: { activeOrganizationId: "org-a" }, + } as never); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.createDomain.mockResolvedValue({ domainId: "d1", host: "x.example.com" }); + mocks.findPreviewDeploymentById.mockResolvedValue({ applicationId: "app-1" }); +}); + +describe("domain.create — authorized users still create domains", () => { + for (const role of ["owner", "admin", "member"]) { + it(`${role} with access creates an application domain`, async () => { + mocks.checkServiceAccess.mockResolvedValue(undefined); + await callerAs(role).create({ + host: "x.example.com", + applicationId: "app-1", + domainType: "application", + customCertResolver: "", + } as never); + expect(mocks.checkServiceAccess).toHaveBeenCalledWith( + expect.anything(), + "app-1", + { domain: ["create"] }, + ); + expect(mocks.createDomain).toHaveBeenCalledTimes(1); + }); + } + + it("still authorizes and creates when domainType is omitted", async () => { + mocks.checkServiceAccess.mockResolvedValue(undefined); + await callerAs("member").create({ + host: "x.example.com", + applicationId: "app-1", + customCertResolver: "", + } as never); + expect(mocks.checkServiceAccess).toHaveBeenCalledWith( + expect.anything(), + "app-1", + { domain: ["create"] }, + ); + expect(mocks.createDomain).toHaveBeenCalledTimes(1); + }); +}); + +describe("domain.create — unauthorized is blocked", () => { + it("rejects when the caller lacks access to the service (even with omitted domainType)", async () => { + mocks.checkServiceAccess.mockRejectedValue( + Object.assign(new Error("UNAUTHORIZED"), { code: "UNAUTHORIZED" }), + ); + await expect( + callerAs("member").create({ + host: "x.example.com", + applicationId: "victim-app", + customCertResolver: "", + } as never), + ).rejects.toBeTruthy(); + expect(mocks.createDomain).not.toHaveBeenCalled(); + }); + + it("rejects when no service id is provided", async () => { + await expect( + callerAs("owner").create({ + host: "x.example.com", + customCertResolver: "", + } as never), + ).rejects.toBeTruthy(); + expect(mocks.createDomain).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts b/apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts new file mode 100644 index 00000000000..80402e6ea49 --- /dev/null +++ b/apps/dokploy/__test__/drop/drop-zip-slip-within-basepath.test.ts @@ -0,0 +1,73 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { unzipDrop } from "@dokploy/server"; +import AdmZip from "adm-zip"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; + +// Production layout: BASE_PATH is the PARENT of APPLICATIONS_PATH +// (/etc/dokploy vs /etc/dokploy/applications). The existing GHSA-66v7 test +// collapses them to the same dir, so it only catches escapes that leave +// BASE_PATH entirely. This reproduces the in-BASE_PATH escape instead. +const TMP = path.join(os.tmpdir(), `dokploy-zipslip-${process.pid}`); +const BASE_PATH = path.join(TMP, "base"); +const APPLICATIONS_PATH = path.join(BASE_PATH, "applications"); + +vi.mock("@dokploy/server/constants", async (importOriginal) => { + const actual = (await importOriginal()) as any; + return { + ...actual, + paths: () => ({ ...actual.paths(), BASE_PATH, APPLICATIONS_PATH }), + }; +}); + +if (typeof window === "undefined") { + const undici = require("undici"); + globalThis.File = undici.File as any; + globalThis.FileList = undici.FileList as any; +} + +const app = { appName: "attacker", serverId: null, buildServerId: null } as any; + +describe("zip-slip within BASE_PATH (cross-service write)", () => { + beforeAll(async () => { + await fs.rm(TMP, { recursive: true, force: true }); + await fs.mkdir(path.join(APPLICATIONS_PATH, "attacker", "code"), { + recursive: true, + }); + }); + afterAll(async () => { + await fs.rm(TMP, { recursive: true, force: true }); + }); + + it("rejects an entry that escapes the app dir but stays under BASE_PATH", async () => { + const traversalEntry = "../../victim/code/pwned.txt"; + const placeholder = "x".repeat(traversalEntry.length); + const zip = new AdmZip(); + zip.addFile("package.json", Buffer.from('{"name":"a","version":"1.0.0"}')); + zip.addFile(placeholder, Buffer.from("PWNED")); + let buf = Buffer.from(zip.toBuffer()); + buf = Buffer.from( + buf.toString("binary").split(placeholder).join(traversalEntry), + "binary", + ); + const file = new File([buf as unknown as ArrayBuffer], "exploit.zip"); + + await expect(unzipDrop(file, app)).rejects.toThrow( + /resolved path escapes output directory/, + ); + + const victimFile = path.join( + APPLICATIONS_PATH, + "victim", + "code", + "pwned.txt", + ); + const written = await fs + .readFile(victimFile, "utf8") + .then((c) => c) + .catch(() => null); + + expect(written).toBeNull(); + }); +}); diff --git a/apps/dokploy/__test__/git-provider/github-update-authz.test.ts b/apps/dokploy/__test__/git-provider/github-update-authz.test.ts new file mode 100644 index 00000000000..ed8a153d8e6 --- /dev/null +++ b/apps/dokploy/__test__/git-provider/github-update-authz.test.ts @@ -0,0 +1,67 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + findGithubById: vi.fn(), + assertGitProviderAccess: vi.fn(), + updateGitProvider: vi.fn(), + updateGithub: vi.fn(), +})); + +vi.mock("@dokploy/server", () => ({ + findGithubById: mocks.findGithubById, + assertGitProviderAccess: mocks.assertGitProviderAccess, + updateGitProvider: mocks.updateGitProvider, + updateGithub: mocks.updateGithub, + canViewGitProviderSecrets: vi.fn(async () => true), + getAccessibleGitProviderIds: vi.fn(async () => new Set()), +})); +vi.mock("@dokploy/server/services/permission", () => ({ + checkPermission: vi.fn(async () => undefined), +})); +vi.mock("@/server/api/utils/audit", () => ({ audit: vi.fn(async () => undefined) })); + +const { githubRouter } = await import("@/server/api/routers/github"); + +const callerAs = (role: string) => + githubRouter.createCaller({ + user: { id: "u1", role }, + session: { activeOrganizationId: "org-a" }, + } as never); + +const input = { + githubId: "gh-1", + gitProviderId: "gp-1", + name: "my-provider", + githubAppName: "app", +}; + +beforeEach(() => { + vi.clearAllMocks(); + mocks.findGithubById.mockResolvedValue({ + githubId: "gh-1", + gitProvider: { gitProviderId: "gp-1", organizationId: "org-a" }, + }); +}); + +describe("github.update — owner/admin update their own provider", () => { + for (const role of ["owner", "admin"]) { + it(`${role} can update a provider in their org`, async () => { + mocks.assertGitProviderAccess.mockResolvedValue(undefined); + await callerAs(role).update(input as never); + expect(mocks.assertGitProviderAccess).toHaveBeenCalledTimes(1); + expect(mocks.updateGitProvider).toHaveBeenCalledTimes(1); + expect(mocks.updateGithub).toHaveBeenCalledTimes(1); + }); + } +}); + +describe("github.update — cross-org takeover is blocked", () => { + it("rejects and does not mutate when the provider is not in the caller's org", async () => { + mocks.assertGitProviderAccess.mockRejectedValue( + Object.assign(new Error("not found"), { code: "NOT_FOUND" }), + ); + await expect(callerAs("owner").update(input as never)).rejects.toBeTruthy(); + expect(mocks.updateGitProvider).not.toHaveBeenCalled(); + expect(mocks.updateGithub).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts b/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts new file mode 100644 index 00000000000..026cb5e22bd --- /dev/null +++ b/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts @@ -0,0 +1,54 @@ +import { join } from "node:path"; +import { paths } from "@dokploy/server/constants"; +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const execMocks = vi.hoisted(() => ({ + execAsync: vi.fn((_command: string) => + Promise.resolve({ stdout: "ROOT:x:0:0", stderr: "" }), + ), + execAsyncRemote: vi.fn((_serverId: string, _command: string) => + Promise.resolve({ stdout: "", stderr: "" }), + ), +})); +vi.mock("@dokploy/server/utils/process/execAsync", () => execMocks); + +vi.mock("@dokploy/server/services/application", () => ({ + findApplicationById: vi.fn(() => + Promise.resolve({ appName: "app1", serverId: null, buildServerId: null }), + ), +})); +vi.mock("@dokploy/server/services/compose", () => ({ + findComposeById: vi.fn(() => + Promise.resolve({ appName: "c1", serverId: null }), + ), +})); + +const { readPatchRepoFile } = await import( + "@dokploy/server/services/patch-repo" +); + +beforeEach(() => vi.clearAllMocks()); + +describe("patch.readRepoFile path traversal", () => { + it("rejects a filePath that escapes the patch-repos directory with ../", async () => { + await expect( + readPatchRepoFile( + "a", + "application", + "../../../../../../../../../../etc/passwd", + ), + ).rejects.toMatchObject({ code: "BAD_REQUEST" }); + + // No shell command is built when the path is rejected. + expect(execMocks.execAsync).not.toHaveBeenCalled(); + }); + + it("still reads a normal file inside the repo", async () => { + const out = await readPatchRepoFile("a", "application", "Dockerfile"); + expect(execMocks.execAsync).toHaveBeenCalledTimes(1); + const command = execMocks.execAsync.mock.calls[0][0] as string; + const { PATCH_REPOS_PATH } = paths(false); + expect(command).toContain(join(PATCH_REPOS_PATH, "application", "app1")); + expect(out).toBe("ROOT:x:0:0"); + }); +}); diff --git a/apps/dokploy/__test__/permissions/assert-server-access.test.ts b/apps/dokploy/__test__/permissions/assert-server-access.test.ts new file mode 100644 index 00000000000..ec0ac52d495 --- /dev/null +++ b/apps/dokploy/__test__/permissions/assert-server-access.test.ts @@ -0,0 +1,122 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mockDb = vi.hoisted(() => ({ + query: { + server: { findMany: vi.fn() }, + member: { findFirst: vi.fn() }, + }, +})); +vi.mock("@dokploy/server/db", () => ({ db: mockDb })); + +const mockHasValidLicense = vi.hoisted(() => vi.fn()); +vi.mock("@dokploy/server/services/proprietary/license-key", () => ({ + hasValidLicense: mockHasValidLicense, +})); + +vi.mock("@dokploy/server/constants", async (importOriginal) => ({ + ...(await importOriginal()), + IS_CLOUD: false, +})); + +const { assertServerAccess } = await import("@dokploy/server/services/server"); + +const session = { userId: "user-1", activeOrganizationId: "org-a" }; + +// org-a owns srv-a and srv-c; srv-b belongs to another org. +const orgServers = [{ serverId: "srv-a" }, { serverId: "srv-c" }]; + +const setMember = ( + role: string, + accessedServers: string[], + licensed: boolean, +) => { + mockDb.query.member.findFirst.mockResolvedValue({ role, accessedServers }); + mockHasValidLicense.mockResolvedValue(licensed); +}; + +beforeEach(() => { + vi.clearAllMocks(); + mockDb.query.server.findMany.mockResolvedValue(orgServers); +}); + +const allow = (p: Promise) => expect(p).resolves.toBeUndefined(); +const deny = (p: Promise) => + expect(p).rejects.toMatchObject({ code: "UNAUTHORIZED" }); + +describe("assertServerAccess — legitimate access is preserved per role", () => { + it("owner reaches any server in the org (ignores accessedServers)", async () => { + setMember("owner", [], true); + await allow(assertServerAccess(session, "srv-a")); + await allow(assertServerAccess(session, "srv-c")); + }); + + it("admin reaches any server in the org", async () => { + setMember("admin", [], true); + await allow(assertServerAccess(session, "srv-a")); + await allow(assertServerAccess(session, "srv-c")); + }); + + it("member in an UNLICENSED org reaches any server in the org", async () => { + setMember("member", [], false); + await allow(assertServerAccess(session, "srv-a")); + await allow(assertServerAccess(session, "srv-c")); + }); + + it("licensed member reaches a server in its accessedServers", async () => { + setMember("member", ["srv-a"], true); + await allow(assertServerAccess(session, "srv-a")); + }); + + it("custom role reaches a server in its accessedServers", async () => { + setMember("deployer", ["srv-c"], true); + await allow(assertServerAccess(session, "srv-c")); + }); + + it("any role may act on the local host (no serverId) on self-hosted", async () => { + setMember("member", [], true); + await allow(assertServerAccess(session, null)); + }); +}); + +describe("assertServerAccess — unauthorized access is blocked", () => { + it("rejects a server of another organization for everyone", async () => { + for (const role of ["owner", "admin", "member"]) { + setMember(role, ["srv-a"], true); + await deny(assertServerAccess(session, "srv-b")); + } + }); + + it("rejects a server the licensed member was not granted", async () => { + setMember("member", ["srv-a"], true); + await deny(assertServerAccess(session, "srv-c")); + }); + + it("rejects a custom role for a server outside its grant", async () => { + setMember("deployer", ["srv-a"], true); + await deny(assertServerAccess(session, "srv-c")); + }); +}); + +describe("assertServerAccess on Cloud", () => { + it("rejects the local control-plane host (no serverId) when IS_CLOUD", async () => { + vi.resetModules(); + vi.doMock("@dokploy/server/constants", async (importOriginal) => ({ + ...(await importOriginal()), + IS_CLOUD: true, + })); + vi.doMock("@dokploy/server/db", () => ({ db: mockDb })); + vi.doMock("@dokploy/server/services/proprietary/license-key", () => ({ + hasValidLicense: mockHasValidLicense, + })); + const { assertServerAccess: cloudAssert } = await import( + "@dokploy/server/services/server" + ); + setMember("owner", [], true); + await expect(cloudAssert(session, null)).rejects.toMatchObject({ + code: "UNAUTHORIZED", + }); + // A real owned server is still reachable on Cloud. + await expect(cloudAssert(session, "srv-a")).resolves.toBeUndefined(); + vi.doUnmock("@dokploy/server/constants"); + }); +}); diff --git a/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts b/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts new file mode 100644 index 00000000000..e9bcdad8784 --- /dev/null +++ b/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts @@ -0,0 +1,141 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + memberFindFirst: vi.fn(), + userFindFirst: vi.fn(), + invitationFindFirst: vi.fn(), + orgRoleFindFirst: vi.fn(), + updateSet: vi.fn(), +})); + +vi.mock("@dokploy/server/db", () => ({ + db: { + query: { + member: { findFirst: mocks.memberFindFirst }, + user: { findFirst: mocks.userFindFirst }, + invitation: { findFirst: mocks.invitationFindFirst }, + organizationRole: { findFirst: mocks.orgRoleFindFirst }, + }, + update: vi.fn(() => ({ + set: (...args: unknown[]) => { + mocks.updateSet(...args); + return { where: () => Promise.resolve() }; + }, + })), + }, +})); + +vi.mock("@dokploy/server/index", () => ({ IS_CLOUD: false })); + +vi.mock("@dokploy/server/services/permission", () => ({ + checkPermission: vi.fn(async () => undefined), +})); + +vi.mock("@/server/api/utils/audit", () => ({ audit: vi.fn(async () => undefined) })); +vi.mock("@/server/api/utils/plan-limits", () => ({ + assertMemberLimit: vi.fn(async () => undefined), +})); + +const { organizationRouter } = await import("@/server/api/routers/organization"); + +const callerAs = (role: string, userId = "caller-1") => + organizationRouter.createCaller({ + user: { id: userId, role }, + session: { activeOrganizationId: "org-a" }, + } as never); + +const targetMember = (role: string) => ({ + id: "member-2", + role, + organizationId: "org-a", + userId: "victim-1", + user: { email: "victim@example.com" }, +}); + +beforeEach(() => { + vi.clearAllMocks(); + mocks.orgRoleFindFirst.mockResolvedValue({ role: "deployer" }); + mocks.userFindFirst.mockResolvedValue(undefined); + mocks.invitationFindFirst.mockResolvedValue(undefined); +}); + +describe("updateMemberRole — privileged roles keep working", () => { + it("owner can promote a member to admin", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("member")); + await expect( + callerAs("owner").updateMemberRole({ memberId: "member-2", role: "admin" }), + ).resolves.toBe(true); + expect(mocks.updateSet).toHaveBeenCalledWith({ role: "admin" }); + }); + + it("admin can promote a member to admin", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("member")); + await expect( + callerAs("admin").updateMemberRole({ memberId: "member-2", role: "admin" }), + ).resolves.toBe(true); + }); + + it("admin can assign a custom role to a member", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("member")); + await expect( + callerAs("admin").updateMemberRole({ + memberId: "member-2", + role: "deployer", + }), + ).resolves.toBe(true); + }); + + it("a custom role with member:update can still assign a non-admin custom role", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("member")); + await expect( + callerAs("user-manager").updateMemberRole({ + memberId: "member-2", + role: "deployer", + }), + ).resolves.toBe(true); + }); +}); + +describe("updateMemberRole — privilege escalation is blocked", () => { + it("a custom role cannot promote a member to admin", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("member")); + await expect( + callerAs("user-manager").updateMemberRole({ + memberId: "member-2", + role: "admin", + }), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + expect(mocks.updateSet).not.toHaveBeenCalled(); + }); + + it("a custom role cannot demote an existing admin", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("admin")); + await expect( + callerAs("user-manager").updateMemberRole({ + memberId: "member-2", + role: "member", + }), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); + + it("an admin cannot change another admin's role (pre-existing rule)", async () => { + mocks.memberFindFirst.mockResolvedValue(targetMember("admin")); + await expect( + callerAs("admin").updateMemberRole({ + memberId: "member-2", + role: "member", + }), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); +}); + +describe("inviteMember — admin ceiling", () => { + it("a custom role cannot invite an admin", async () => { + await expect( + callerAs("user-manager").inviteMember({ + email: "new@example.com", + role: "admin", + }), + ).rejects.toMatchObject({ code: "FORBIDDEN" }); + }); +}); diff --git a/apps/dokploy/__test__/wss/listen-deployment.test.ts b/apps/dokploy/__test__/wss/listen-deployment.test.ts index 947006da2a5..1cc279a8c69 100644 --- a/apps/dokploy/__test__/wss/listen-deployment.test.ts +++ b/apps/dokploy/__test__/wss/listen-deployment.test.ts @@ -51,10 +51,16 @@ vi.mock("ssh2", () => ({ const mockValidateRequest = vi.hoisted(() => vi.fn()); const mockFindServerById = vi.hoisted(() => vi.fn()); +const mockFindDeploymentByLogPath = vi.hoisted(() => vi.fn()); +const mockCheckServiceAccess = vi.hoisted(() => vi.fn()); vi.mock("@dokploy/server", () => ({ IS_CLOUD: false, validateRequest: mockValidateRequest, findServerById: mockFindServerById, + findDeploymentByLogPath: mockFindDeploymentByLogPath, +})); +vi.mock("@dokploy/server/services/permission", () => ({ + checkServicePermissionAndAccess: mockCheckServiceAccess, })); vi.mock("@dokploy/server/wss/utils", () => ({ readValidDirectory: () => true, @@ -85,6 +91,10 @@ beforeEach(async () => { sshClients.length = 0; nextChild.ignoreSigterm = false; vi.clearAllMocks(); + // Authorized-by-default: the requested logPath maps to a deployment of an + // accessible service. Individual tests override as needed. + mockFindDeploymentByLogPath.mockResolvedValue({ applicationId: "app-1" }); + mockCheckServiceAccess.mockResolvedValue(undefined); server = http.createServer(); setupDeploymentLogsWebSocketServer(server); await new Promise((r) => server.listen(0, "127.0.0.1", r)); diff --git a/apps/dokploy/pages/api/deploy/github.ts b/apps/dokploy/pages/api/deploy/github.ts index 756361d0893..86a36a4b238 100644 --- a/apps/dokploy/pages/api/deploy/github.ts +++ b/apps/dokploy/pages/api/deploy/github.ts @@ -4,7 +4,7 @@ import { createSecurityBlockedComment, findGithubById, findPreviewDeploymentByApplicationId, - findPreviewDeploymentsByPullRequestId, + findPreviewDeploymentsByPullRequestIdForGithub, IS_CLOUD, removePreviewDeployment, shouldDeploy, @@ -351,7 +351,10 @@ export default async function handler( if (action === "closed") { const previewDeploymentResult = - await findPreviewDeploymentsByPullRequestId(prId); + await findPreviewDeploymentsByPullRequestIdForGithub( + prId, + githubResult.githubId, + ); if (previewDeploymentResult.length > 0) { for (const previewDeployment of previewDeploymentResult) { diff --git a/apps/dokploy/pages/api/providers/gitea/authorize.ts b/apps/dokploy/pages/api/providers/gitea/authorize.ts index 8ab0e70f9a9..f70c0ea694f 100644 --- a/apps/dokploy/pages/api/providers/gitea/authorize.ts +++ b/apps/dokploy/pages/api/providers/gitea/authorize.ts @@ -1,3 +1,4 @@ +import { validateRequest } from "@dokploy/server"; import type { NextApiRequest, NextApiResponse } from "next"; import { findGitea, redirectWithError } from "./helper"; @@ -16,11 +17,20 @@ export default async function handler( return res.status(400).json({ error: "Invalid Gitea provider ID" }); } + const { user, session } = await validateRequest(req); + if (!user || !session?.activeOrganizationId) { + return res.status(401).json({ error: "Unauthorized" }); + } + const gitea = await findGitea(giteaId as string); if (!gitea || !gitea.clientId || !gitea.redirectUri) { return redirectWithError(res, "Incomplete OAuth configuration"); } + if (gitea.gitProvider.organizationId !== session.activeOrganizationId) { + return redirectWithError(res, "Incomplete OAuth configuration"); + } + // Generate the Gitea authorization URL const authorizationUrl = new URL(`${gitea.giteaUrl}/login/oauth/authorize`); authorizationUrl.searchParams.append("client_id", gitea.clientId as string); diff --git a/apps/dokploy/pages/api/providers/gitea/callback.ts b/apps/dokploy/pages/api/providers/gitea/callback.ts index 9e7e66a5604..79ce28a0d62 100644 --- a/apps/dokploy/pages/api/providers/gitea/callback.ts +++ b/apps/dokploy/pages/api/providers/gitea/callback.ts @@ -1,4 +1,4 @@ -import { updateGitea } from "@dokploy/server"; +import { updateGitea, validateRequest } from "@dokploy/server"; import type { NextApiRequest, NextApiResponse } from "next"; import { findGitea, type Gitea, redirectWithError } from "./helper"; @@ -51,12 +51,21 @@ export default async function handler( ); } + const { user, session } = await validateRequest(req); + if (!user || !session?.activeOrganizationId) { + return redirectWithError(res, "Unauthorized"); + } + const giteaId = parseState(state as string); if (!giteaId) return redirectWithError(res, "Invalid state format"); const gitea = await findGitea(giteaId); if (!gitea) return redirectWithError(res, "Failed to find Gitea provider"); + if (gitea.gitProvider.organizationId !== session.activeOrganizationId) { + return redirectWithError(res, "Failed to find Gitea provider"); + } + // Fetch the access token from Gitea const result = await fetchAccessToken(gitea, code as string); diff --git a/apps/dokploy/pages/api/providers/gitlab/callback.ts b/apps/dokploy/pages/api/providers/gitlab/callback.ts index a43e8889034..3b12cff7981 100644 --- a/apps/dokploy/pages/api/providers/gitlab/callback.ts +++ b/apps/dokploy/pages/api/providers/gitlab/callback.ts @@ -1,4 +1,4 @@ -import { findGitlabById, updateGitlab } from "@dokploy/server"; +import { findGitlabById, updateGitlab, validateRequest } from "@dokploy/server"; import type { NextApiRequest, NextApiResponse } from "next"; export default async function handler( @@ -11,7 +11,16 @@ export default async function handler( return res.status(400).json({ error: "Missing or invalid code" }); } + const { user, session } = await validateRequest(req); + if (!user || !session?.activeOrganizationId) { + return res.status(401).json({ error: "Unauthorized" }); + } + const gitlab = await findGitlabById(gitlabId as string); + + if (gitlab.gitProvider.organizationId !== session.activeOrganizationId) { + return res.status(404).json({ error: "Gitlab provider not found" }); + } // Use internal URL for token exchange when GitLab is on same instance as Dokploy const baseUrl = gitlab.gitlabInternalUrl || gitlab.gitlabUrl; const gitlabUrl = new URL(baseUrl); diff --git a/apps/dokploy/server/api/routers/ai.ts b/apps/dokploy/server/api/routers/ai.ts index f2fe711a956..0b6e0fbb72b 100644 --- a/apps/dokploy/server/api/routers/ai.ts +++ b/apps/dokploy/server/api/routers/ai.ts @@ -6,6 +6,7 @@ import { deploySuggestionSchema, } from "@dokploy/server/db/schema/ai"; import { + assertServerAccess, createDomain, createMount, findEnvironmentById, @@ -23,6 +24,7 @@ import { suggestVariants, } from "@dokploy/server/services/ai"; import { createComposeByTemplate } from "@dokploy/server/services/compose"; +import { providerFetch } from "@dokploy/server/services/logs-and-metrics/provider-fetch"; import { addNewService, checkServiceAccess, @@ -87,10 +89,12 @@ export const aiRouter = createTRPCRouter({ let response = null; switch (providerName) { case "ollama": - response = await fetch(`${input.apiUrl}/api/tags`, { headers }); + response = await providerFetch(`${input.apiUrl}/api/tags`, { + headers, + }); break; case "gemini": - response = await fetch( + response = await providerFetch( `${input.apiUrl}/models?key=${encodeURIComponent(apiKey)}`, { headers: {} }, ); @@ -159,7 +163,9 @@ export const aiRouter = createTRPCRouter({ code: "BAD_REQUEST", message: "API key must contain at least 1 character(s)", }); - response = await fetch(`${input.apiUrl}/models`, { headers }); + response = await providerFetch(`${input.apiUrl}/models`, { + headers, + }); } if (!response.ok) { @@ -411,6 +417,7 @@ ${input.logs}`, deploy: withPermission("ai", "read") .input(deploySuggestionSchema) .mutation(async ({ ctx, input }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); const environment = await findEnvironmentById(input.environmentId); const project = await findProjectById(environment.projectId); await checkServiceAccess(ctx, environment.projectId, "create"); diff --git a/apps/dokploy/server/api/routers/backup.ts b/apps/dokploy/server/api/routers/backup.ts index fd6f283f930..5df2fbf1783 100644 --- a/apps/dokploy/server/api/routers/backup.ts +++ b/apps/dokploy/server/api/routers/backup.ts @@ -93,6 +93,17 @@ export const backupRouter = createTRPCRouter({ input.destinationId, ctx.session.activeOrganizationId, ); + } else { + if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can manage web-server backups", + }); + } + await findDestinationByIdForOrganization( + input.destinationId, + ctx.session.activeOrganizationId, + ); } if (IS_CLOUD) { @@ -184,6 +195,11 @@ export const backupRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, serviceId, { backup: ["read"], }); + } else if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can read web-server backups", + }); } return backup; @@ -208,6 +224,17 @@ export const backupRouter = createTRPCRouter({ input.destinationId, ctx.session.activeOrganizationId, ); + } else { + if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can manage web-server backups", + }); + } + await findDestinationByIdForOrganization( + input.destinationId, + ctx.session.activeOrganizationId, + ); } await updateBackupById(input.backupId, input); @@ -265,6 +292,11 @@ export const backupRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, serviceId, { backup: ["delete"], }); + } else if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can manage web-server backups", + }); } const value = await removeBackupById(input.backupId); @@ -461,6 +493,12 @@ export const backupRouter = createTRPCRouter({ manualBackupWebServer: withPermission("backup", "create") .input(apiFindOneBackup) .mutation(async ({ input, ctx }) => { + if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can run a web-server backup", + }); + } const backup = await findBackupById(input.backupId); await runWebServerBackup(backup); await keepLatestNBackups(backup); @@ -597,42 +635,70 @@ export const backupRouter = createTRPCRouter({ }) .input(apiRestoreBackup) .subscription(async function* ({ input, ctx, signal }) { - if (input.databaseId) { + if (input.databaseType === "web-server") { + if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can restore a web-server backup", + }); + } + } else { + if (!input.databaseId) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "A target service is required", + }); + } await checkServicePermissionAndAccess(ctx, input.databaseId, { backup: ["restore"], }); } - const destination = input.databaseId - ? await findDestinationByIdForOrganization( - input.destinationId, - ctx.session.activeOrganizationId, - ) - : await findDestinationById(input.destinationId); + const destination = await findDestinationByIdForOrganization( + input.destinationId, + ctx.session.activeOrganizationId, + ); const queue: string[] = []; let done = false; const onLog = (log: string) => queue.push(log); + const assertBackupFileInService = (appName: string) => { + if ( + input.backupFile !== appName && + !input.backupFile.startsWith(`${appName}/`) + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Backup file does not belong to this service", + }); + } + }; const runRestore = async () => { if (input.backupType === "database") { if (input.databaseType === "postgres") { const postgres = await findPostgresById(input.databaseId); + assertBackupFileInService(postgres.appName); await restorePostgresBackup(postgres, destination, input, onLog); } else if (input.databaseType === "mysql") { const mysql = await findMySqlById(input.databaseId); + assertBackupFileInService(mysql.appName); await restoreMySqlBackup(mysql, destination, input, onLog); } else if (input.databaseType === "mariadb") { const mariadb = await findMariadbById(input.databaseId); + assertBackupFileInService(mariadb.appName); await restoreMariadbBackup(mariadb, destination, input, onLog); } else if (input.databaseType === "mongo") { const mongo = await findMongoById(input.databaseId); + assertBackupFileInService(mongo.appName); await restoreMongoBackup(mongo, destination, input, onLog); } else if (input.databaseType === "libsql") { const libsql = await findLibsqlById(input.databaseId); + assertBackupFileInService(libsql.appName); await restoreLibsqlBackup(libsql, destination, input, onLog); } else if (input.databaseType === "web-server") { await restoreWebServerBackup(destination, input.backupFile, onLog); } } else if (input.backupType === "compose") { const compose = await findComposeById(input.databaseId); + assertBackupFileInService(compose.appName); await restoreComposeBackup(compose, destination, input, onLog); } }; diff --git a/apps/dokploy/server/api/routers/bitbucket.ts b/apps/dokploy/server/api/routers/bitbucket.ts index ce79df1e008..8ecc468d320 100644 --- a/apps/dokploy/server/api/routers/bitbucket.ts +++ b/apps/dokploy/server/api/routers/bitbucket.ts @@ -126,6 +126,8 @@ export const bitbucketRouter = createTRPCRouter({ update: withPermission("gitProviders", "create") .input(apiUpdateBitbucket) .mutation(async ({ input, ctx }) => { + const existing = await findBitbucketById(input.bitbucketId); + await assertGitProviderAccess(ctx.session, existing.gitProvider); const result = await updateBitbucket(input.bitbucketId, { ...input, organizationId: ctx.session.activeOrganizationId, diff --git a/apps/dokploy/server/api/routers/certificate.ts b/apps/dokploy/server/api/routers/certificate.ts index b0692ebad7e..568d5411466 100644 --- a/apps/dokploy/server/api/routers/certificate.ts +++ b/apps/dokploy/server/api/routers/certificate.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, createCertificate, findCertificateById, IS_CLOUD, @@ -21,6 +22,7 @@ export const certificateRouter = createTRPCRouter({ create: withPermission("certificate", "create") .input(apiCreateCertificate) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (IS_CLOUD && !input.serverId) { throw new TRPCError({ code: "UNAUTHORIZED", diff --git a/apps/dokploy/server/api/routers/cluster.ts b/apps/dokploy/server/api/routers/cluster.ts index f121c62ea83..68799613974 100644 --- a/apps/dokploy/server/api/routers/cluster.ts +++ b/apps/dokploy/server/api/routers/cluster.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, type DockerNode, execAsync, execAsyncRemote, @@ -20,6 +21,7 @@ export const clusterRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const targetServer = await findServerById(input.serverId); if (targetServer.organizationId !== ctx.session.activeOrganizationId) { @@ -42,6 +44,7 @@ export const clusterRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const targetServer = await findServerById(input.serverId); if (targetServer.organizationId !== ctx.session.activeOrganizationId) { @@ -85,6 +88,7 @@ export const clusterRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const targetServer = await findServerById(input.serverId); if (targetServer.organizationId !== ctx.session.activeOrganizationId) { @@ -119,6 +123,7 @@ export const clusterRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const targetServer = await findServerById(input.serverId); if (targetServer.organizationId !== ctx.session.activeOrganizationId) { diff --git a/apps/dokploy/server/api/routers/destination.ts b/apps/dokploy/server/api/routers/destination.ts index 3d2ad60574f..94cad266fcb 100644 --- a/apps/dokploy/server/api/routers/destination.ts +++ b/apps/dokploy/server/api/routers/destination.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, createDestination, execAsync, execAsyncRemote, @@ -47,7 +48,8 @@ export const destinationRouter = createTRPCRouter({ }), testConnection: withPermission("destination", "create") .input(apiCreateDestination) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); const { secretAccessKey, bucket, diff --git a/apps/dokploy/server/api/routers/docker-image.ts b/apps/dokploy/server/api/routers/docker-image.ts index dd825cabb8f..e9c81469f14 100644 --- a/apps/dokploy/server/api/routers/docker-image.ts +++ b/apps/dokploy/server/api/routers/docker-image.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, findServerById, getImageConfig, getImages, @@ -17,6 +18,7 @@ export const dockerImageRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -34,6 +36,7 @@ export const dockerImageRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -54,6 +57,7 @@ export const dockerImageRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { diff --git a/apps/dokploy/server/api/routers/docker-volume.ts b/apps/dokploy/server/api/routers/docker-volume.ts index 643dff5d411..19f09f8a32d 100644 --- a/apps/dokploy/server/api/routers/docker-volume.ts +++ b/apps/dokploy/server/api/routers/docker-volume.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, deleteVolumeFile, findServerById, getVolumeConfig, @@ -33,6 +34,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -49,6 +51,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -70,6 +73,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -95,6 +99,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -117,6 +122,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -152,6 +158,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -178,6 +185,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -198,6 +206,7 @@ export const dockerVolumeRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { diff --git a/apps/dokploy/server/api/routers/docker.ts b/apps/dokploy/server/api/routers/docker.ts index 010b7723f38..1f407d1f053 100644 --- a/apps/dokploy/server/api/routers/docker.ts +++ b/apps/dokploy/server/api/routers/docker.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, containerKill, containerRemove, containerRestart, @@ -45,6 +46,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -63,6 +65,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); await checkPermission(ctx, { docker: ["read"], server: ["read"] }); if (input.serverId) { const server = await findServerById(input.serverId); @@ -88,6 +91,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -114,6 +118,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -140,6 +145,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -166,6 +172,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -192,6 +199,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -218,6 +226,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -236,6 +245,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -258,6 +268,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -279,6 +290,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -296,6 +308,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -308,6 +321,7 @@ export const dockerRouter = createTRPCRouter({ uploadFileToContainer: withPermission("docker", "read") .input(uploadFileToContainerSchema) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -350,6 +364,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -375,6 +390,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -401,6 +417,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -436,6 +453,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -459,6 +477,7 @@ export const dockerRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { diff --git a/apps/dokploy/server/api/routers/domain.ts b/apps/dokploy/server/api/routers/domain.ts index 10c0b8a8c76..a51bbf6c53b 100644 --- a/apps/dokploy/server/api/routers/domain.ts +++ b/apps/dokploy/server/api/routers/domain.ts @@ -37,15 +37,34 @@ export const domainRouter = createTRPCRouter({ .input(apiCreateDomain) .mutation(async ({ input, ctx }) => { try { - if (input.domainType === "compose" && input.composeId) { + if ( + !input.applicationId && + !input.composeId && + !input.previewDeploymentId + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "A target service is required", + }); + } + if (input.composeId) { await checkServicePermissionAndAccess(ctx, input.composeId, { domain: ["create"], }); - } else if (input.domainType === "application" && input.applicationId) { + } + if (input.applicationId) { await checkServicePermissionAndAccess(ctx, input.applicationId, { domain: ["create"], }); } + if (input.previewDeploymentId) { + const preview = await findPreviewDeploymentById( + input.previewDeploymentId, + ); + await checkServicePermissionAndAccess(ctx, preview.applicationId, { + domain: ["create"], + }); + } const domain = await createDomain(input); await audit(ctx, { action: "create", diff --git a/apps/dokploy/server/api/routers/gitea.ts b/apps/dokploy/server/api/routers/gitea.ts index 63cfc4e798a..0849d341f36 100644 --- a/apps/dokploy/server/api/routers/gitea.ts +++ b/apps/dokploy/server/api/routers/gitea.ts @@ -187,6 +187,8 @@ export const giteaRouter = createTRPCRouter({ update: withPermission("gitProviders", "create") .input(apiUpdateGitea) .mutation(async ({ input, ctx }) => { + const existing = await findGiteaById(input.giteaId); + await assertGitProviderAccess(ctx.session, existing.gitProvider); if (input.name) { await updateGitProvider(input.gitProviderId, { name: input.name, diff --git a/apps/dokploy/server/api/routers/github.ts b/apps/dokploy/server/api/routers/github.ts index dd765dee880..2671f0c0f73 100644 --- a/apps/dokploy/server/api/routers/github.ts +++ b/apps/dokploy/server/api/routers/github.ts @@ -106,6 +106,8 @@ export const githubRouter = createTRPCRouter({ update: withPermission("gitProviders", "create") .input(apiUpdateGithub) .mutation(async ({ input, ctx }) => { + const existing = await findGithubById(input.githubId); + await assertGitProviderAccess(ctx.session, existing.gitProvider); await updateGitProvider(input.gitProviderId, { name: input.name, organizationId: ctx.session.activeOrganizationId, diff --git a/apps/dokploy/server/api/routers/gitlab.ts b/apps/dokploy/server/api/routers/gitlab.ts index 133610763b1..7679238a8a6 100644 --- a/apps/dokploy/server/api/routers/gitlab.ts +++ b/apps/dokploy/server/api/routers/gitlab.ts @@ -136,6 +136,8 @@ export const gitlabRouter = createTRPCRouter({ update: withPermission("gitProviders", "create") .input(apiUpdateGitlab) .mutation(async ({ input, ctx }) => { + const existing = await findGitlabById(input.gitlabId); + await assertGitProviderAccess(ctx.session, existing.gitProvider); if (input.name) { await updateGitProvider(input.gitProviderId, { name: input.name, diff --git a/apps/dokploy/server/api/routers/network.ts b/apps/dokploy/server/api/routers/network.ts index cee7ec9a101..b0ed0a1b6e0 100644 --- a/apps/dokploy/server/api/routers/network.ts +++ b/apps/dokploy/server/api/routers/network.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, createNetwork, findNetworkById, findNetworksToSync, @@ -52,6 +53,7 @@ export const networkRouter = createTRPCRouter({ create: protectedProcedure .input(apiCreateNetwork) .mutation(async ({ ctx, input }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); const created = await createNetwork( input, ctx.session.activeOrganizationId, @@ -67,6 +69,7 @@ export const networkRouter = createTRPCRouter({ networksToSync: protectedProcedure .input(z.object({ serverId: z.string().optional() })) .query(async ({ ctx, input }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); return findNetworksToSync( ctx.session.activeOrganizationId, input.serverId ?? null, @@ -81,6 +84,7 @@ export const networkRouter = createTRPCRouter({ }), ) .mutation(async ({ ctx, input }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); const result = await importDockerNetworks( ctx.session.activeOrganizationId, input.serverId ?? null, diff --git a/apps/dokploy/server/api/routers/notification.ts b/apps/dokploy/server/api/routers/notification.ts index ae1c35d12b0..47b5b786a8a 100644 --- a/apps/dokploy/server/api/routers/notification.ts +++ b/apps/dokploy/server/api/routers/notification.ts @@ -124,6 +124,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.slackId !== input.slackId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateSlackNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -189,6 +195,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.telegramId !== input.telegramId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateTelegramNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -255,6 +267,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.discordId !== input.discordId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateDiscordNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -326,6 +344,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.emailId !== input.emailId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateEmailNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -392,6 +416,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.resendId !== input.resendId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateResendNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -582,6 +612,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.gotifyId !== input.gotifyId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateGotifyNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -647,6 +683,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.ntfyId !== input.ntfyId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateNtfyNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -720,6 +762,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.mattermostId !== input.mattermostId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateMattermostNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -782,6 +830,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.customId !== input.customId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateCustomNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -847,6 +901,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.larkId !== input.larkId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateLarkNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -913,6 +973,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.teamsId !== input.teamsId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updateTeamsNotification({ ...input, organizationId: ctx.session.activeOrganizationId, @@ -980,6 +1046,12 @@ export const notificationRouter = createTRPCRouter({ message: "You are not authorized to update this notification", }); } + if (notification.pushoverId !== input.pushoverId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to update this notification", + }); + } const result = await updatePushoverNotification({ ...input, organizationId: ctx.session.activeOrganizationId, diff --git a/apps/dokploy/server/api/routers/organization.ts b/apps/dokploy/server/api/routers/organization.ts index 6a7740238ac..17d168c070a 100644 --- a/apps/dokploy/server/api/routers/organization.ts +++ b/apps/dokploy/server/api/routers/organization.ts @@ -356,6 +356,17 @@ export const organizationRouter = createTRPCRouter({ }); } + if ( + input.role === "admin" && + ctx.user.role !== "owner" && + ctx.user.role !== "admin" + ) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Only owners and admins can invite a user as admin", + }); + } + // If assigning a custom role, verify it exists if (!["owner", "admin", "member"].includes(input.role)) { const customRole = await db.query.organizationRole.findFirst({ @@ -506,6 +517,18 @@ export const organizationRouter = createTRPCRouter({ }); } + const callerIsPrivileged = + ctx.user.role === "owner" || ctx.user.role === "admin"; + if ( + !callerIsPrivileged && + (input.role === "admin" || target.role === "admin") + ) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Only owners and admins can assign or change the admin role", + }); + } + // If assigning a custom role (not admin/member), verify it exists if (input.role !== "admin" && input.role !== "member") { const customRole = await db.query.organizationRole.findFirst({ diff --git a/apps/dokploy/server/api/routers/patch.ts b/apps/dokploy/server/api/routers/patch.ts index 333dd1856a2..8a6f2f23e50 100644 --- a/apps/dokploy/server/api/routers/patch.ts +++ b/apps/dokploy/server/api/routers/patch.ts @@ -8,6 +8,7 @@ import { findPatchByFilePath, findPatchById, findPatchesByEntityId, + getPatchRepoPath, markPatchForDeletion, readPatchRepoDirectory, readPatchRepoFile, @@ -190,15 +191,11 @@ export const patchRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.id, { service: ["read"], }); - let serverId: string | null = null; - if (input.type === "application") { - const app = await findApplicationById(input.id); - serverId = app.serverId; - } else { - const compose = await findComposeById(input.id); - serverId = compose.serverId; - } - return await readPatchRepoDirectory(input.repoPath, serverId); + const { repoPath, serverId } = await getPatchRepoPath( + input.id, + input.type, + ); + return await readPatchRepoDirectory(repoPath, serverId); }), readRepoFile: protectedProcedure diff --git a/apps/dokploy/server/api/routers/registry.ts b/apps/dokploy/server/api/routers/registry.ts index ce6e2b4b846..e26ce756175 100644 --- a/apps/dokploy/server/api/routers/registry.ts +++ b/apps/dokploy/server/api/routers/registry.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, createRegistry, dockerLogin, findRegistryById, @@ -101,7 +102,8 @@ export const registryRouter = createTRPCRouter({ }), testRegistry: withPermission("registry", "read") .input(apiTestRegistry) - .mutation(async ({ input }) => { + .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); try { if (IS_CLOUD && !input.serverId) { throw new TRPCError({ @@ -132,6 +134,7 @@ export const registryRouter = createTRPCRouter({ testRegistryById: withPermission("registry", "read") .input(apiTestRegistryById) .mutation(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); try { const registryData = await db.query.registry.findFirst({ where: eq(registry.registryId, input.registryId ?? ""), diff --git a/apps/dokploy/server/api/routers/server.ts b/apps/dokploy/server/api/routers/server.ts index 2684aef31c1..3d49bc89fcb 100644 --- a/apps/dokploy/server/api/routers/server.ts +++ b/apps/dokploy/server/api/routers/server.ts @@ -22,6 +22,7 @@ import { updateServerById, } from "@dokploy/server"; import { db } from "@dokploy/server/db"; +import { providerFetch } from "@dokploy/server/services/logs-and-metrics/provider-fetch"; import { findMemberByUserId, hasPermission, @@ -621,7 +622,7 @@ export const serverRouter = createTRPCRouter({ try { const url = new URL(input.url); url.searchParams.append("limit", input.dataPoints); - const response = await fetch(url.toString(), { + const response = await providerFetch(url.toString(), { headers: { Authorization: `Bearer ${input.token}`, }, diff --git a/apps/dokploy/server/api/routers/settings.ts b/apps/dokploy/server/api/routers/settings.ts index e4cfe9cf694..baab76d4ddf 100644 --- a/apps/dokploy/server/api/routers/settings.ts +++ b/apps/dokploy/server/api/routers/settings.ts @@ -171,6 +171,10 @@ export const settingsRouter = createTRPCRouter({ reloadTraefik: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); // Run in background so the request returns immediately; avoids proxy timeouts. void reloadDockerResource("dokploy-traefik", input?.serverId).catch( (err) => { @@ -187,6 +191,10 @@ export const settingsRouter = createTRPCRouter({ toggleDashboard: adminProcedure .input(apiEnableDashboard) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); const ports = await readPorts("dokploy-traefik", input.serverId); const env = await readEnvironmentVariables( "dokploy-traefik", @@ -235,6 +243,10 @@ export const settingsRouter = createTRPCRouter({ cleanUnusedImages: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await cleanupImages(input?.serverId); await audit(ctx, { action: "delete", @@ -246,6 +258,10 @@ export const settingsRouter = createTRPCRouter({ cleanUnusedVolumes: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await cleanupVolumes(input?.serverId); await audit(ctx, { action: "delete", @@ -257,6 +273,10 @@ export const settingsRouter = createTRPCRouter({ cleanStoppedContainers: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await cleanupContainers(input?.serverId); await audit(ctx, { action: "delete", @@ -268,6 +288,10 @@ export const settingsRouter = createTRPCRouter({ cleanDockerBuilder: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await cleanupBuilders(input?.serverId); await audit(ctx, { action: "delete", @@ -278,6 +302,10 @@ export const settingsRouter = createTRPCRouter({ cleanDockerPrune: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await cleanupSystem(input?.serverId); await cleanupBuilders(input?.serverId); await audit(ctx, { @@ -290,6 +318,10 @@ export const settingsRouter = createTRPCRouter({ cleanAll: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); // Execute cleanup in background and return immediately to avoid gateway timeouts const result = await cleanupAllBackground(input?.serverId); await audit(ctx, { @@ -659,6 +691,10 @@ export const settingsRouter = createTRPCRouter({ readDirectories: protectedProcedure .input(apiServerSchema) .query(async ({ ctx, input }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); try { await checkPermission(ctx, { traefikFiles: ["read"] }); if (input?.serverId) { @@ -678,6 +714,10 @@ export const settingsRouter = createTRPCRouter({ updateTraefikFile: protectedProcedure .input(apiModifyTraefikConfig) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await checkPermission(ctx, { traefikFiles: ["write"] }); if (input.serverId) { const server = await findServerById(input.serverId); @@ -702,6 +742,10 @@ export const settingsRouter = createTRPCRouter({ readTraefikFile: protectedProcedure .input(apiReadTraefikConfig) .query(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); await checkPermission(ctx, { traefikFiles: ["read"] }); if (input.serverId) { @@ -829,7 +873,11 @@ export const settingsRouter = createTRPCRouter({ ), readTraefikEnv: adminProcedure .input(apiServerSchema) - .query(async ({ input }) => { + .query(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); const envVars = await readEnvironmentVariables( "dokploy-traefik", input?.serverId, @@ -840,6 +888,10 @@ export const settingsRouter = createTRPCRouter({ writeTraefikEnv: adminProcedure .input(z.object({ env: z.string(), serverId: z.string().optional() })) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); const envs = prepareEnvironmentVariables(input.env); const ports = await readPorts("dokploy-traefik", input?.serverId); @@ -905,12 +957,16 @@ export const settingsRouter = createTRPCRouter({ }), haveTraefikDashboardPortEnabled: adminProcedure .input(apiServerSchema) - .query(async ({ input }) => { + .query(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); const ports = await readPorts("dokploy-traefik", input?.serverId); return ports.some((port) => port.targetPort === 8080); }), - readStatsLogs: protectedProcedure + readStatsLogs: adminProcedure .meta({ openapi: { path: "/read-stats-logs", @@ -984,7 +1040,7 @@ export const settingsRouter = createTRPCRouter({ return !!parsedConfig?.accessLog?.filePath; }), - toggleRequests: protectedProcedure + toggleRequests: adminProcedure .input( z.object({ enable: z.boolean(), @@ -1074,6 +1130,10 @@ export const settingsRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); if (IS_CLOUD && !input.serverId) { throw new Error("Select a server to enable the GPU Setup"); } @@ -1097,7 +1157,11 @@ export const settingsRouter = createTRPCRouter({ serverId: z.string().optional(), }), ) - .query(async ({ input }) => { + .query(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); if (IS_CLOUD && !input.serverId) { return { driverInstalled: false, @@ -1139,6 +1203,10 @@ export const settingsRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); try { if (IS_CLOUD && !input.serverId) { throw new TRPCError({ @@ -1195,7 +1263,11 @@ export const settingsRouter = createTRPCRouter({ }), getTraefikPorts: adminProcedure .input(apiServerSchema) - .query(async ({ input }) => { + .query(async ({ input, ctx }) => { + await assertTraefikAccess( + input?.serverId, + ctx.session.activeOrganizationId, + ); const ports = await readPorts("dokploy-traefik", input?.serverId); return ports; }), @@ -1308,7 +1380,7 @@ export const settingsRouter = createTRPCRouter({ }); return true; }), - updateLogCleanup: protectedProcedure + updateLogCleanup: adminProcedure .input( z.object({ cronExpression: z.string().nullable(), diff --git a/apps/dokploy/server/api/routers/swarm.ts b/apps/dokploy/server/api/routers/swarm.ts index 771c52adf36..a96a92e47f7 100644 --- a/apps/dokploy/server/api/routers/swarm.ts +++ b/apps/dokploy/server/api/routers/swarm.ts @@ -1,4 +1,5 @@ import { + assertServerAccess, findServerById, getAllContainerStats, getApplicationInfo, @@ -19,6 +20,7 @@ export const swarmRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -33,6 +35,7 @@ export const swarmRouter = createTRPCRouter({ getNodeInfo: withPermission("docker", "read") .input(z.object({ nodeId: z.string(), serverId: z.string().optional() })) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -51,6 +54,7 @@ export const swarmRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -82,6 +86,7 @@ export const swarmRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { @@ -100,6 +105,7 @@ export const swarmRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertServerAccess(ctx.session, input.serverId ?? null); if (input.serverId) { const server = await findServerById(input.serverId); if (server.organizationId !== ctx.session?.activeOrganizationId) { diff --git a/apps/dokploy/server/api/routers/user.ts b/apps/dokploy/server/api/routers/user.ts index 8ca9cc0f0f8..3ce4a576451 100644 --- a/apps/dokploy/server/api/routers/user.ts +++ b/apps/dokploy/server/api/routers/user.ts @@ -33,6 +33,7 @@ import { session, user, } from "@dokploy/server/db/schema"; +import { providerFetch } from "@dokploy/server/services/logs-and-metrics/provider-fetch"; import { hasPermission, resolvePermissions, @@ -683,7 +684,7 @@ export const userRouter = createTRPCRouter({ const url = new URL(`${input.url}/metrics/containers`); url.searchParams.append("limit", input.dataPoints); url.searchParams.append("appName", input.appName); - const response = await fetch(url.toString(), { + const response = await providerFetch(url.toString(), { headers: { Authorization: `Bearer ${input.token}`, }, diff --git a/apps/dokploy/server/api/routers/volume-backups.ts b/apps/dokploy/server/api/routers/volume-backups.ts index 29c586f50f3..13a153641a7 100644 --- a/apps/dokploy/server/api/routers/volume-backups.ts +++ b/apps/dokploy/server/api/routers/volume-backups.ts @@ -296,7 +296,13 @@ export const volumeBackupsRouter = createTRPCRouter({ }) .input( z.object({ - backupFileName: z.string().min(1), + backupFileName: z + .string() + .min(1) + .regex( + /^[A-Za-z0-9._/-]+$/, + "Invalid backup file name: only letters, numbers, '.', '_', '-' and '/' are allowed", + ), destinationId: z.string().min(1), volumeName: z .string() @@ -308,6 +314,9 @@ export const volumeBackupsRouter = createTRPCRouter({ }), ) .subscription(async ({ input, ctx }) => { + await checkServicePermissionAndAccess(ctx, input.id, { + volumeBackup: ["restore"], + }); const destination = await findDestinationById(input.destinationId); if (destination.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ diff --git a/apps/dokploy/server/wss/listen-deployment.ts b/apps/dokploy/server/wss/listen-deployment.ts index 96a06c7f340..e3d4262cadf 100644 --- a/apps/dokploy/server/wss/listen-deployment.ts +++ b/apps/dokploy/server/wss/listen-deployment.ts @@ -1,6 +1,12 @@ import { spawn } from "node:child_process"; import type http from "node:http"; -import { findServerById, IS_CLOUD, validateRequest } from "@dokploy/server"; +import { + findDeploymentByLogPath, + findServerById, + IS_CLOUD, + validateRequest, +} from "@dokploy/server"; +import { checkServicePermissionAndAccess } from "@dokploy/server/services/permission"; import { encodeBase64 } from "@dokploy/server/utils/docker/utils"; import { readValidDirectory } from "@dokploy/server/wss/utils"; import { Client } from "ssh2"; @@ -56,6 +62,46 @@ export const setupDeploymentLogsWebSocketServer = ( return; } + try { + const deployment = await findDeploymentByLogPath(logPath); + if (!deployment) { + ws.close(4003, "Not authorized"); + return; + } + const ctxLike = { + user: { id: user.id }, + session: { activeOrganizationId: session.activeOrganizationId }, + } as Parameters[0]; + + const serviceId = + deployment.applicationId ?? + deployment.composeId ?? + deployment.previewDeployment?.applicationId ?? + null; + + if (serviceId) { + await checkServicePermissionAndAccess(ctxLike, serviceId, { + deployment: ["read"], + }); + } else { + const org = + deployment.server?.organizationId ?? + deployment.schedule?.organizationId ?? + null; + if (!org || org !== session.activeOrganizationId) { + ws.close(4003, "Not authorized"); + return; + } + } + } catch { + ws.close(4003, "Not authorized"); + return; + } + + if (ws.readyState !== ws.OPEN) { + return; + } + let tailProcess: ReturnType | null = null; let sshClient: Client | null = null; @@ -192,7 +238,7 @@ export const setupDeploymentLogsWebSocketServer = ( sshClient.end(); } if (ws.readyState === ws.OPEN) { - // @ts-ignore + // @ts-expect-error const errorMessage = error?.message as unknown as string; ws.send(errorMessage || "An error occurred"); ws.close(); diff --git a/apps/schedules/src/index.ts b/apps/schedules/src/index.ts index 28eacbe1cad..ca73e66c697 100644 --- a/apps/schedules/src/index.ts +++ b/apps/schedules/src/index.ts @@ -1,3 +1,4 @@ +import { timingSafeEqual } from "node:crypto"; import { serve } from "@hono/node-server"; import { Hono } from "hono"; import "dotenv/config"; @@ -18,13 +19,34 @@ const app = new Hono(); cleanQueue(); initializeJobs(); +if (!process.env.API_KEY) { + console.error( + "API_KEY is not set; all authenticated routes will be rejected", + ); +} + +const isValidApiKey = (header: string | undefined): boolean => { + const apiKey = process.env.API_KEY; + if (!apiKey || !header) { + return false; + } + + const headerBuffer = Buffer.from(header); + const apiKeyBuffer = Buffer.from(apiKey); + if (headerBuffer.length !== apiKeyBuffer.length) { + return false; + } + + return timingSafeEqual(headerBuffer, apiKeyBuffer); +}; + app.use(async (c, next) => { if (c.req.path === "/health") { return next(); } const authHeader = c.req.header("X-API-Key"); - if (process.env.API_KEY !== authHeader) { + if (!isValidApiKey(authHeader)) { return c.json({ message: "Invalid API Key" }, 403); } diff --git a/packages/server/src/lib/auth.ts b/packages/server/src/lib/auth.ts index 07894ee7179..5fcf0b72b73 100644 --- a/packages/server/src/lib/auth.ts +++ b/packages/server/src/lib/auth.ts @@ -68,6 +68,29 @@ const resolveTrustedOrigins = async () => { } }; +const rewriteToCanonicalOrigin = async (url: string): Promise => { + try { + const configured = process.env.BETTER_AUTH_URL; + let origin: string | null = configured ?? null; + if (!origin) { + const settings = await getWebServerSettings(); + origin = settings?.host + ? `https://${settings.host}` + : settings?.serverIp + ? `http://${settings.serverIp}:3000` + : null; + } + if (!origin) return url; + const target = new URL(url); + const canonical = new URL(origin); + target.protocol = canonical.protocol; + target.host = canonical.host; + return target.toString(); + } catch { + return url; + } +}; + const createBetterAuth = () => betterAuth({ database: drizzleAdapter(db, { @@ -79,6 +102,8 @@ const createBetterAuth = () => "/organization/create", "/organization/update", "/organization/delete", + "/organization/update-member-role", + "/organization/invite-member", // GHSA-j8v8-g9cx-5qf4: SCIM providers are managed via tRPC, org-scoped only. "/scim/generate-token", "/scim/list-provider-connections", @@ -185,7 +210,7 @@ const createBetterAuth = () => await sendVerificationEmail({ userName: user.name || "User", email: user.email, - verificationUrl: url, + verificationUrl: await rewriteToCanonicalOrigin(url), }); } }, @@ -204,11 +229,12 @@ const createBetterAuth = () => }, }, sendResetPassword: async ({ user, url }) => { + const safeUrl = await rewriteToCanonicalOrigin(url); await sendEmail({ email: user.email, subject: "Reset your password", text: ` -

Click the link to reset your password: Reset Password

+

Click the link to reset your password: Reset Password

`, }); }, @@ -548,8 +574,6 @@ const createBetterAuth = () => ], }); -// Una sola instancia de better-auth por proceso aunque el módulo esté -// duplicado en varios bundles. const globalForAuth = globalThis as unknown as { betterAuthInstance?: ReturnType; }; @@ -630,6 +654,13 @@ export const validateRequest = async (request: IncomingMessage) => { }, }); + if (!member) { + return { + session: null, + user: null, + }; + } + // When accessing from DB, use actual column names const userFromDb = apiKeyRecord.user as typeof apiKeyRecord.user & { firstName: string; diff --git a/packages/server/src/services/deployment.ts b/packages/server/src/services/deployment.ts index 05d8383640b..1035a139db3 100644 --- a/packages/server/src/services/deployment.ts +++ b/packages/server/src/services/deployment.ts @@ -1106,3 +1106,15 @@ export const clearOldDeployments = async ( await execAsync(command); } }; + +export const findDeploymentByLogPath = async (logPath: string) => { + return db.query.deployments.findFirst({ + where: (fields, { eq }) => eq(fields.logPath, logPath), + columns: { applicationId: true, composeId: true }, + with: { + server: { columns: { organizationId: true } }, + schedule: { columns: { organizationId: true } }, + previewDeployment: { columns: { applicationId: true } }, + }, + }); +}; diff --git a/packages/server/src/services/patch-repo.ts b/packages/server/src/services/patch-repo.ts index f946d1dcd95..d9c73c69761 100644 --- a/packages/server/src/services/patch-repo.ts +++ b/packages/server/src/services/patch-repo.ts @@ -1,4 +1,4 @@ -import { join } from "node:path"; +import { join, resolve, sep } from "node:path"; import { paths } from "@dokploy/server/constants"; import { TRPCError } from "@trpc/server"; import { quote } from "shell-quote"; @@ -78,6 +78,25 @@ interface DirectoryEntry { children?: DirectoryEntry[]; } +export const getPatchRepoPath = async ( + id: string, + type: "application" | "compose", +): Promise<{ repoPath: string; serverId: string | null }> => { + let serverId: string | null = null; + let appName: string; + if (type === "application") { + const application = await findApplicationById(id); + serverId = application.buildServerId || application.serverId; + appName = application.appName; + } else { + const compose = await findComposeById(id); + serverId = compose.serverId; + appName = compose.appName; + } + const { PATCH_REPOS_PATH } = paths(!!serverId); + return { repoPath: join(PATCH_REPOS_PATH, type, appName), serverId }; +}; + /** * Read directory tree of the patch repo */ @@ -169,6 +188,18 @@ export const readPatchRepoFile = async ( const repoPath = join(PATCH_REPOS_PATH, type, application.appName); const fullPath = join(repoPath, filePath); + const resolvedRepo = resolve(repoPath); + const resolvedFull = resolve(fullPath); + if ( + resolvedFull !== resolvedRepo && + !resolvedFull.startsWith(resolvedRepo + sep) + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Invalid file path", + }); + } + const command = `cat ${quote([fullPath])}`; if (serverId) { diff --git a/packages/server/src/services/preview-deployment.ts b/packages/server/src/services/preview-deployment.ts index 6ada57d07ed..020243ee4c2 100644 --- a/packages/server/src/services/preview-deployment.ts +++ b/packages/server/src/services/preview-deployment.ts @@ -241,6 +241,17 @@ export const findPreviewDeploymentsByPullRequestId = async ( return previewDeploymentResult; }; +export const findPreviewDeploymentsByPullRequestIdForGithub = async ( + pullRequestId: string, + githubId: string, +) => { + const rows = await db.query.previewDeployments.findMany({ + where: eq(previewDeployments.pullRequestId, pullRequestId), + with: { application: true }, + }); + return rows.filter((row) => row.application?.githubId === githubId); +}; + export const findPreviewDeploymentByApplicationId = async ( applicationId: string, pullRequestId: string, diff --git a/packages/server/src/services/server.ts b/packages/server/src/services/server.ts index a065d0bf46a..bc6185bff2b 100644 --- a/packages/server/src/services/server.ts +++ b/packages/server/src/services/server.ts @@ -1,3 +1,4 @@ +import { IS_CLOUD } from "@dokploy/server/constants"; import { db } from "@dokploy/server/db"; import { type apiCreateServer, @@ -307,3 +308,19 @@ export const getAccessibleServerIds = async (session: { return new Set(memberRecord?.accessedServers ?? []); }; + +export const assertServerAccess = async ( + session: { userId: string; activeOrganizationId: string }, + serverId?: string | null, +) => { + if (!serverId) { + if (IS_CLOUD) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + return; + } + const accessible = await getAccessibleServerIds(session); + if (!accessible.has(serverId)) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } +}; diff --git a/packages/server/src/templates/github.ts b/packages/server/src/templates/github.ts index f3bdca2ba63..7495dbbe56d 100644 --- a/packages/server/src/templates/github.ts +++ b/packages/server/src/templates/github.ts @@ -1,3 +1,4 @@ +import { providerFetch } from "@dokploy/server/services/logs-and-metrics/provider-fetch"; import { parse } from "toml"; /** @@ -56,7 +57,7 @@ interface TemplateMetadata { export async function fetchTemplatesList( baseUrl = "https://templates.dokploy.com", ): Promise { - const response = await fetch(`${baseUrl}/meta.json`, { + const response = await providerFetch(`${baseUrl}/meta.json`, { signal: AbortSignal.timeout(10000), }); if (!response.ok) { @@ -92,7 +93,7 @@ export async function fetchTemplateLogo( const template = templates.find((t) => t.id === templateId); if (!template?.logo) return null; - const response = await fetch( + const response = await providerFetch( `${baseUrl}/blueprints/${templateId}/${template.logo}`, { signal: AbortSignal.timeout(10000) }, ); @@ -126,10 +127,10 @@ export async function fetchTemplateFiles( ): Promise<{ config: CompleteTemplate; dockerCompose: string }> { const timeout = AbortSignal.timeout(10000); const [templateYmlResponse, dockerComposeResponse] = await Promise.all([ - fetch(`${baseUrl}/blueprints/${templateId}/template.toml`, { + providerFetch(`${baseUrl}/blueprints/${templateId}/template.toml`, { signal: timeout, }), - fetch(`${baseUrl}/blueprints/${templateId}/docker-compose.yml`, { + providerFetch(`${baseUrl}/blueprints/${templateId}/docker-compose.yml`, { signal: timeout, }), ]); diff --git a/packages/server/src/utils/builders/drop.ts b/packages/server/src/utils/builders/drop.ts index b2a454970f4..394930a58f0 100644 --- a/packages/server/src/utils/builders/drop.ts +++ b/packages/server/src/utils/builders/drop.ts @@ -66,7 +66,12 @@ export const unzipDrop = async (zipFile: File, application: Application) => { if (!filePath) continue; const fullPath = path.join(outputPath, filePath).replace(/\\/g, "/"); - if (!readValidDirectory(fullPath, application.serverId)) { + const resolvedOutput = path.resolve(outputPath); + const resolvedFull = path.resolve(fullPath); + const withinOutput = + resolvedFull === resolvedOutput || + resolvedFull.startsWith(resolvedOutput + path.sep); + if (!withinOutput || !readValidDirectory(fullPath, targetServerId)) { throw new Error( `Path traversal detected: resolved path escapes output directory: ${filePath}`, ); diff --git a/packages/server/src/utils/servers/remote-docker.ts b/packages/server/src/utils/servers/remote-docker.ts index 237373ed098..f71a5b215f9 100644 --- a/packages/server/src/utils/servers/remote-docker.ts +++ b/packages/server/src/utils/servers/remote-docker.ts @@ -6,13 +6,15 @@ import { sshKeepalive } from "../process/execAsync"; export const getRemoteDocker = async (serverId?: string | null) => { if (!serverId) return docker; const server = await findServerById(serverId); - if (!server.sshKeyId) return docker; + if (!server.sshKeyId) { + throw new Error("No SSH key available for this server"); + } const dockerode = new Dockerode({ host: server.ipAddress, port: server.port, username: server.username, protocol: "ssh", - // @ts-ignore + // @ts-expect-error sshOptions: { privateKey: server.sshKey?.privateKey, ...sshKeepalive, diff --git a/packages/server/src/utils/volume-backups/restore.ts b/packages/server/src/utils/volume-backups/restore.ts index 812f6cefd43..6f7162ff3c8 100644 --- a/packages/server/src/utils/volume-backups/restore.ts +++ b/packages/server/src/utils/volume-backups/restore.ts @@ -30,7 +30,7 @@ export const restoreVolume = async ( const baseRestoreCommand = ` set -e echo "Volume name: ${volumeName}" - echo "Backup file name: ${backupFileName}" + echo ${quote([`Backup file name: ${backupFileName}`])} echo "Volume backup path: ${volumeBackupPath}" echo "Downloading backup from S3..." mkdir -p ${volumeBackupPath} From 934de3db4a770c6ebb450b88cbae1125596d110a Mon Sep 17 00:00:00 2001 From: Mauricio Siu <47042324+Siumauricio@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:36:33 +0100 Subject: [PATCH 09/84] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4021b6c33e3..4e78a277017 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Dokploy includes multiple features to make your life easier. - **Backups**: Automate backups for databases to an external storage destination. - **Docker Compose**: Native support for Docker Compose to manage complex applications. - **Multi Node**: Scale applications to multiple nodes using Docker Swarm to manage the cluster. -- **Templates**: Deploy open-source templates (Plausible, Pocketbase, Calcom, etc.) with a single click. +- **Templates**: Deploy open-source templates (Plausible, Pocketbase, Calcom, etc.) with a single click +600 Templates. - **Traefik Integration**: Automatically integrates with Traefik for routing and load balancing. - **Real-time Monitoring**: Monitor CPU, memory, storage, and network usage for every resource. - **Logs & Metrics**: Ship container logs and host/container metrics to Grafana (Loki, Prometheus/Mimir), Datadog, New Relic, InfluxDB, VictoriaMetrics, Better Stack, Elasticsearch/OpenSearch, Splunk, or AWS CloudWatch, tagged by project/environment/application. From 40e818b0e0d8e448e7a30c559ebf4e146e5932ae Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 10:41:10 +0100 Subject: [PATCH 10/84] fix(security): address review findings on org/server boundaries - git providers: update the stored provider, not the client-supplied id - web-server backups: bind one/update/remove/manual run to the org's destination - compose restore: accept the service backup folder, reject '..' - listen-deployment: authorize backup, volume backup and schedule logs - traefik settings and network actions: enforce accessed servers - patch repo: read files from the git tree so symlinks can't reach host files - volume restore: bind volume and server to the service, run tar without a shell string - reset email origin: honor the https setting --- .../patch/read-repo-file-traversal.test.ts | 3 +- .../traefik-files-server-organization.test.ts | 23 +++- .../traefik/update-traefik-cloud.test.ts | 23 +++- .../traefik/update-traefik-router.test.ts | 21 +++- apps/dokploy/server/api/routers/backup.ts | 72 +++++------ apps/dokploy/server/api/routers/gitea.ts | 12 +- apps/dokploy/server/api/routers/github.ts | 9 +- apps/dokploy/server/api/routers/gitlab.ts | 14 +-- apps/dokploy/server/api/routers/network.ts | 4 + apps/dokploy/server/api/routers/settings.ts | 112 ++++-------------- .../server/api/routers/volume-backups.ts | 45 ++++--- apps/dokploy/server/wss/listen-deployment.ts | 21 +++- packages/server/src/lib/auth.ts | 2 +- packages/server/src/services/deployment.ts | 27 ++++- packages/server/src/services/patch-repo.ts | 5 +- .../src/utils/volume-backups/restore.ts | 2 +- 16 files changed, 204 insertions(+), 191 deletions(-) diff --git a/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts b/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts index 026cb5e22bd..4f407c57603 100644 --- a/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts +++ b/apps/dokploy/__test__/patch/read-repo-file-traversal.test.ts @@ -46,9 +46,10 @@ describe("patch.readRepoFile path traversal", () => { it("still reads a normal file inside the repo", async () => { const out = await readPatchRepoFile("a", "application", "Dockerfile"); expect(execMocks.execAsync).toHaveBeenCalledTimes(1); - const command = execMocks.execAsync.mock.calls[0][0] as string; + const command = execMocks.execAsync.mock.calls[0]?.[0] ?? ""; const { PATCH_REPOS_PATH } = paths(false); expect(command).toContain(join(PATCH_REPOS_PATH, "application", "app1")); + expect(command).toMatch(/--filters HEAD\\?:Dockerfile/); expect(out).toBe("ROOT:x:0:0"); }); }); diff --git a/apps/dokploy/__test__/traefik/traefik-files-server-organization.test.ts b/apps/dokploy/__test__/traefik/traefik-files-server-organization.test.ts index c9c2167b4cc..5130983d9b6 100644 --- a/apps/dokploy/__test__/traefik/traefik-files-server-organization.test.ts +++ b/apps/dokploy/__test__/traefik/traefik-files-server-organization.test.ts @@ -16,11 +16,24 @@ vi.mock("@dokploy/server/services/permission", () => ({ checkPermission: vi.fn(async () => undefined), })); -vi.mock("@dokploy/server", () => ({ - IS_CLOUD: false, - paths: () => ({ MAIN_TRAEFIK_PATH: traefikPath }), - ...mocks, -})); +vi.mock("@dokploy/server", async () => { + const { TRPCError } = await import("@trpc/server"); + return { + IS_CLOUD: false, + paths: () => ({ MAIN_TRAEFIK_PATH: traefikPath }), + ...mocks, + assertServerAccess: async ( + session: { activeOrganizationId: string }, + serverId?: string | null, + ) => { + if (!serverId) return; + const server = await mocks.findServerById(serverId); + if (server.organizationId !== session.activeOrganizationId) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + }, + }; +}); vi.mock("@dokploy/server/lib/auth", () => ({ validateRequest: vi.fn(), diff --git a/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts b/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts index c50188c6101..80524acb982 100644 --- a/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts +++ b/apps/dokploy/__test__/traefik/update-traefik-cloud.test.ts @@ -9,10 +9,25 @@ const mocks = vi.hoisted(() => ({ writeTraefikSetup: vi.fn(), })); -vi.mock("@dokploy/server", () => ({ - IS_CLOUD: true, - ...mocks, -})); +vi.mock("@dokploy/server", async () => { + const { TRPCError } = await import("@trpc/server"); + return { + IS_CLOUD: true, + ...mocks, + assertServerAccess: async ( + session: { activeOrganizationId: string }, + serverId?: string | null, + ) => { + if (!serverId) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + const server = await mocks.findServerById(serverId); + if (server.organizationId !== session.activeOrganizationId) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + }, + }; +}); vi.mock("@dokploy/server/lib/auth", () => ({ validateRequest: vi.fn(), diff --git a/apps/dokploy/__test__/traefik/update-traefik-router.test.ts b/apps/dokploy/__test__/traefik/update-traefik-router.test.ts index 2fc93d1852c..e9ec7e39537 100644 --- a/apps/dokploy/__test__/traefik/update-traefik-router.test.ts +++ b/apps/dokploy/__test__/traefik/update-traefik-router.test.ts @@ -9,10 +9,23 @@ const mocks = vi.hoisted(() => ({ writeTraefikSetup: vi.fn(), })); -vi.mock("@dokploy/server", () => ({ - IS_CLOUD: false, - ...mocks, -})); +vi.mock("@dokploy/server", async () => { + const { TRPCError } = await import("@trpc/server"); + return { + IS_CLOUD: false, + ...mocks, + assertServerAccess: async ( + session: { activeOrganizationId: string }, + serverId?: string | null, + ) => { + if (!serverId) return; + const server = await mocks.findServerById(serverId); + if (server.organizationId !== session.activeOrganizationId) { + throw new TRPCError({ code: "UNAUTHORIZED" }); + } + }, + }; +}); vi.mock("@dokploy/server/lib/auth", () => ({ validateRequest: vi.fn(), diff --git a/apps/dokploy/server/api/routers/backup.ts b/apps/dokploy/server/api/routers/backup.ts index 5df2fbf1783..372ab39a85a 100644 --- a/apps/dokploy/server/api/routers/backup.ts +++ b/apps/dokploy/server/api/routers/backup.ts @@ -73,6 +73,22 @@ import { } from "@/server/db/schema"; import { removeJob, schedule, updateJob } from "@/server/utils/backup"; +const assertWebServerBackupAccess = async ( + ctx: { user: { role: string }; session: { activeOrganizationId: string } }, + destinationId: string, +) => { + if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Only owners and admins can manage web-server backups", + }); + } + await findDestinationByIdForOrganization( + destinationId, + ctx.session.activeOrganizationId, + ); +}; + export const backupRouter = createTRPCRouter({ create: protectedProcedure .input(apiCreateBackup) @@ -94,16 +110,7 @@ export const backupRouter = createTRPCRouter({ ctx.session.activeOrganizationId, ); } else { - if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "Only owners and admins can manage web-server backups", - }); - } - await findDestinationByIdForOrganization( - input.destinationId, - ctx.session.activeOrganizationId, - ); + await assertWebServerBackupAccess(ctx, input.destinationId); } if (IS_CLOUD) { @@ -195,11 +202,8 @@ export const backupRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, serviceId, { backup: ["read"], }); - } else if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "Only owners and admins can read web-server backups", - }); + } else { + await assertWebServerBackupAccess(ctx, backup.destinationId); } return backup; @@ -225,16 +229,8 @@ export const backupRouter = createTRPCRouter({ ctx.session.activeOrganizationId, ); } else { - if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "Only owners and admins can manage web-server backups", - }); - } - await findDestinationByIdForOrganization( - input.destinationId, - ctx.session.activeOrganizationId, - ); + await assertWebServerBackupAccess(ctx, existing.destinationId); + await assertWebServerBackupAccess(ctx, input.destinationId); } await updateBackupById(input.backupId, input); @@ -292,11 +288,8 @@ export const backupRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, serviceId, { backup: ["delete"], }); - } else if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "Only owners and admins can manage web-server backups", - }); + } else { + await assertWebServerBackupAccess(ctx, backup.destinationId); } const value = await removeBackupById(input.backupId); @@ -493,13 +486,8 @@ export const backupRouter = createTRPCRouter({ manualBackupWebServer: withPermission("backup", "create") .input(apiFindOneBackup) .mutation(async ({ input, ctx }) => { - if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "Only owners and admins can run a web-server backup", - }); - } const backup = await findBackupById(input.backupId); + await assertWebServerBackupAccess(ctx, backup.destinationId); await runWebServerBackup(backup); await keepLatestNBackups(backup); await audit(ctx, { @@ -660,10 +648,10 @@ export const backupRouter = createTRPCRouter({ const queue: string[] = []; let done = false; const onLog = (log: string) => queue.push(log); - const assertBackupFileInService = (appName: string) => { + const assertBackupFileInService = (...folders: string[]) => { if ( - input.backupFile !== appName && - !input.backupFile.startsWith(`${appName}/`) + input.backupFile.includes("..") || + !folders.some((folder) => input.backupFile.startsWith(`${folder}/`)) ) { throw new TRPCError({ code: "UNAUTHORIZED", @@ -698,7 +686,11 @@ export const backupRouter = createTRPCRouter({ } } else if (input.backupType === "compose") { const compose = await findComposeById(input.databaseId); - assertBackupFileInService(compose.appName); + const serviceName = input.metadata?.serviceName; + assertBackupFileInService( + compose.appName, + ...(serviceName ? [`${compose.appName}_${serviceName}`] : []), + ); await restoreComposeBackup(compose, destination, input, onLog); } }; diff --git a/apps/dokploy/server/api/routers/gitea.ts b/apps/dokploy/server/api/routers/gitea.ts index 0849d341f36..73d4bdaacbe 100644 --- a/apps/dokploy/server/api/routers/gitea.ts +++ b/apps/dokploy/server/api/routers/gitea.ts @@ -189,20 +189,14 @@ export const giteaRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { const existing = await findGiteaById(input.giteaId); await assertGitProviderAccess(ctx.session, existing.gitProvider); + const { gitProviderId, ...data } = input; if (input.name) { - await updateGitProvider(input.gitProviderId, { + await updateGitProvider(existing.gitProvider.gitProviderId, { name: input.name, organizationId: ctx.session.activeOrganizationId, }); - - await updateGitea(input.giteaId, { - ...input, - }); - } else { - await updateGitea(input.giteaId, { - ...input, - }); } + await updateGitea(input.giteaId, data); await audit(ctx, { action: "update", diff --git a/apps/dokploy/server/api/routers/github.ts b/apps/dokploy/server/api/routers/github.ts index 2671f0c0f73..8086b376f84 100644 --- a/apps/dokploy/server/api/routers/github.ts +++ b/apps/dokploy/server/api/routers/github.ts @@ -108,19 +108,18 @@ export const githubRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { const existing = await findGithubById(input.githubId); await assertGitProviderAccess(ctx.session, existing.gitProvider); - await updateGitProvider(input.gitProviderId, { + const { gitProviderId, ...data } = input; + await updateGitProvider(existing.gitProvider.gitProviderId, { name: input.name, organizationId: ctx.session.activeOrganizationId, }); - await updateGithub(input.githubId, { - ...input, - }); + await updateGithub(input.githubId, data); await audit(ctx, { action: "update", resourceType: "gitProvider", - resourceId: input.gitProviderId, + resourceId: existing.gitProvider.gitProviderId, resourceName: input.name, }); }), diff --git a/apps/dokploy/server/api/routers/gitlab.ts b/apps/dokploy/server/api/routers/gitlab.ts index 7679238a8a6..0bf14600837 100644 --- a/apps/dokploy/server/api/routers/gitlab.ts +++ b/apps/dokploy/server/api/routers/gitlab.ts @@ -138,25 +138,19 @@ export const gitlabRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { const existing = await findGitlabById(input.gitlabId); await assertGitProviderAccess(ctx.session, existing.gitProvider); + const { gitProviderId, ...data } = input; if (input.name) { - await updateGitProvider(input.gitProviderId, { + await updateGitProvider(existing.gitProvider.gitProviderId, { name: input.name, organizationId: ctx.session.activeOrganizationId, }); - - await updateGitlab(input.gitlabId, { - ...input, - }); - } else { - await updateGitlab(input.gitlabId, { - ...input, - }); } + await updateGitlab(input.gitlabId, data); await audit(ctx, { action: "update", resourceType: "gitProvider", - resourceId: input.gitProviderId, + resourceId: existing.gitProvider.gitProviderId, resourceName: input.name, }); }), diff --git a/apps/dokploy/server/api/routers/network.ts b/apps/dokploy/server/api/routers/network.ts index b0ed0a1b6e0..d4e02b11c24 100644 --- a/apps/dokploy/server/api/routers/network.ts +++ b/apps/dokploy/server/api/routers/network.ts @@ -111,6 +111,7 @@ export const networkRouter = createTRPCRouter({ message: "Network not found", }); } + await assertServerAccess(ctx.session, network.serverId); return inspectNetwork(input.networkId); }), @@ -124,6 +125,7 @@ export const networkRouter = createTRPCRouter({ message: "Network not found", }); } + await assertServerAccess(ctx.session, network.serverId); const recreated = await recreateNetwork(input.networkId); await audit(ctx, { action: "reload", @@ -144,6 +146,7 @@ export const networkRouter = createTRPCRouter({ message: "Network not found", }); } + await assertServerAccess(ctx.session, network.serverId); const resynced = await resyncNetwork( input.networkId, ctx.session.activeOrganizationId, @@ -167,6 +170,7 @@ export const networkRouter = createTRPCRouter({ message: "Not authorized to delete this network", }); } + await assertServerAccess(ctx.session, network.serverId); const removed = await removeNetwork(input.networkId); await audit(ctx, { action: "delete", diff --git a/apps/dokploy/server/api/routers/settings.ts b/apps/dokploy/server/api/routers/settings.ts index baab76d4ddf..b1a1372c974 100644 --- a/apps/dokploy/server/api/routers/settings.ts +++ b/apps/dokploy/server/api/routers/settings.ts @@ -1,5 +1,6 @@ import path from "node:path"; import { + assertServerAccess, CLEANUP_CRON_JOB, checkGPUStatus, checkPortInUse, @@ -122,20 +123,6 @@ const resolveTraefikFilePath = ( const traefikUpdateLocks = new Map(); const traefikUpdateErrors = new Map(); -const assertTraefikAccess = async ( - serverId: string | undefined, - organizationId: string, -) => { - if (serverId) { - const server = await findServerById(serverId); - if (server.organizationId !== organizationId) { - throw new TRPCError({ code: "UNAUTHORIZED" }); - } - } else if (IS_CLOUD) { - throw new TRPCError({ code: "UNAUTHORIZED" }); - } -}; - export const settingsRouter = createTRPCRouter({ getWebServerSettings: protectedProcedure.query(async () => { if (IS_CLOUD) { @@ -171,10 +158,7 @@ export const settingsRouter = createTRPCRouter({ reloadTraefik: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); // Run in background so the request returns immediately; avoids proxy timeouts. void reloadDockerResource("dokploy-traefik", input?.serverId).catch( (err) => { @@ -191,10 +175,7 @@ export const settingsRouter = createTRPCRouter({ toggleDashboard: adminProcedure .input(apiEnableDashboard) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); const ports = await readPorts("dokploy-traefik", input.serverId); const env = await readEnvironmentVariables( "dokploy-traefik", @@ -243,10 +224,7 @@ export const settingsRouter = createTRPCRouter({ cleanUnusedImages: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await cleanupImages(input?.serverId); await audit(ctx, { action: "delete", @@ -258,10 +236,7 @@ export const settingsRouter = createTRPCRouter({ cleanUnusedVolumes: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await cleanupVolumes(input?.serverId); await audit(ctx, { action: "delete", @@ -273,10 +248,7 @@ export const settingsRouter = createTRPCRouter({ cleanStoppedContainers: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await cleanupContainers(input?.serverId); await audit(ctx, { action: "delete", @@ -288,10 +260,7 @@ export const settingsRouter = createTRPCRouter({ cleanDockerBuilder: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await cleanupBuilders(input?.serverId); await audit(ctx, { action: "delete", @@ -302,10 +271,7 @@ export const settingsRouter = createTRPCRouter({ cleanDockerPrune: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await cleanupSystem(input?.serverId); await cleanupBuilders(input?.serverId); await audit(ctx, { @@ -318,10 +284,7 @@ export const settingsRouter = createTRPCRouter({ cleanAll: adminProcedure .input(apiServerSchema) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); // Execute cleanup in background and return immediately to avoid gateway timeouts const result = await cleanupAllBackground(input?.serverId); await audit(ctx, { @@ -691,10 +654,7 @@ export const settingsRouter = createTRPCRouter({ readDirectories: protectedProcedure .input(apiServerSchema) .query(async ({ ctx, input }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); try { await checkPermission(ctx, { traefikFiles: ["read"] }); if (input?.serverId) { @@ -714,10 +674,7 @@ export const settingsRouter = createTRPCRouter({ updateTraefikFile: protectedProcedure .input(apiModifyTraefikConfig) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await checkPermission(ctx, { traefikFiles: ["write"] }); if (input.serverId) { const server = await findServerById(input.serverId); @@ -742,10 +699,7 @@ export const settingsRouter = createTRPCRouter({ readTraefikFile: protectedProcedure .input(apiReadTraefikConfig) .query(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); await checkPermission(ctx, { traefikFiles: ["read"] }); if (input.serverId) { @@ -874,10 +828,7 @@ export const settingsRouter = createTRPCRouter({ readTraefikEnv: adminProcedure .input(apiServerSchema) .query(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); const envVars = await readEnvironmentVariables( "dokploy-traefik", input?.serverId, @@ -888,10 +839,7 @@ export const settingsRouter = createTRPCRouter({ writeTraefikEnv: adminProcedure .input(z.object({ env: z.string(), serverId: z.string().optional() })) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); const envs = prepareEnvironmentVariables(input.env); const ports = await readPorts("dokploy-traefik", input?.serverId); @@ -958,10 +906,7 @@ export const settingsRouter = createTRPCRouter({ haveTraefikDashboardPortEnabled: adminProcedure .input(apiServerSchema) .query(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); const ports = await readPorts("dokploy-traefik", input?.serverId); return ports.some((port) => port.targetPort === 8080); }), @@ -1130,10 +1075,7 @@ export const settingsRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); if (IS_CLOUD && !input.serverId) { throw new Error("Select a server to enable the GPU Setup"); } @@ -1158,10 +1100,7 @@ export const settingsRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); if (IS_CLOUD && !input.serverId) { return { driverInstalled: false, @@ -1203,10 +1142,7 @@ export const settingsRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); try { if (IS_CLOUD && !input.serverId) { throw new TRPCError({ @@ -1264,20 +1200,14 @@ export const settingsRouter = createTRPCRouter({ getTraefikPorts: adminProcedure .input(apiServerSchema) .query(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); const ports = await readPorts("dokploy-traefik", input?.serverId); return ports; }), getTraefikOverview: adminProcedure .input(apiServerSchema) .query(async ({ input, ctx }) => { - await assertTraefikAccess( - input?.serverId, - ctx.session.activeOrganizationId, - ); + await assertServerAccess(ctx.session, input?.serverId); const key = input?.serverId ?? "local"; const overview = await getTraefikOverview(input?.serverId); return { @@ -1290,7 +1220,7 @@ export const settingsRouter = createTRPCRouter({ .input(apiServerSchema) .mutation(async ({ input, ctx }) => { const serverId = input?.serverId; - await assertTraefikAccess(serverId, ctx.session.activeOrganizationId); + await assertServerAccess(ctx.session, serverId); const lockKey = serverId ?? "local"; if (traefikUpdateLocks.has(lockKey)) { diff --git a/apps/dokploy/server/api/routers/volume-backups.ts b/apps/dokploy/server/api/routers/volume-backups.ts index 13a153641a7..7ea79eb6651 100644 --- a/apps/dokploy/server/api/routers/volume-backups.ts +++ b/apps/dokploy/server/api/routers/volume-backups.ts @@ -17,12 +17,13 @@ import { VOLUME_NAME_REGEX, volumeBackups, } from "@dokploy/server/db/schema"; +import { findApplicationById } from "@dokploy/server/services/application"; +import { findComposeById } from "@dokploy/server/services/compose"; import { findDestinationById, findDestinationByIdForOrganization, } from "@dokploy/server/services/destination"; import { checkServicePermissionAndAccess } from "@dokploy/server/services/permission"; -import { findServerById } from "@dokploy/server/services/server"; import { execAsyncRemote, execAsyncStream, @@ -299,9 +300,12 @@ export const volumeBackupsRouter = createTRPCRouter({ backupFileName: z .string() .min(1) - .regex( - /^[A-Za-z0-9._/-]+$/, - "Invalid backup file name: only letters, numbers, '.', '_', '-' and '/' are allowed", + .refine( + (name) => + !name.startsWith("/") && + !name.split("/").includes("..") && + !/[\0\r\n]/.test(name), + "Invalid backup file name", ), destinationId: z.string().min(1), volumeName: z @@ -324,15 +328,24 @@ export const volumeBackupsRouter = createTRPCRouter({ message: "You don't have access to this destination.", }); } - if (input.serverId) { - const targetServer = await findServerById(input.serverId); - if (targetServer.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You don't have access to this server.", - }); - } + const service = + input.serviceType === "application" + ? await findApplicationById(input.id) + : await findComposeById(input.id); + const ownsVolume = + service.mounts.some( + (mount) => + mount.type === "volume" && mount.volumeName === input.volumeName, + ) || + (input.serviceType === "compose" && + input.volumeName.startsWith(`${service.appName}_`)); + if (!ownsVolume) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "This volume does not belong to the service.", + }); } + const serverId = service.serverId ?? undefined; return observable((emit) => { const runRestore = async () => { try { @@ -348,7 +361,7 @@ export const volumeBackupsRouter = createTRPCRouter({ input.destinationId, input.volumeName, input.backupFileName, - input.serverId || "", + serverId || "", input.serviceType, ); @@ -357,9 +370,9 @@ export const volumeBackupsRouter = createTRPCRouter({ emit.next(""); // Empty line // Execute the restore command with real-time output - if (input.serverId) { - emit.next(`🌐 Executing on remote server: ${input.serverId}`); - await execAsyncRemote(input.serverId, restoreCommand, (data) => { + if (serverId) { + emit.next(`🌐 Executing on remote server: ${serverId}`); + await execAsyncRemote(serverId, restoreCommand, (data) => { emit.next(data); }); } else { diff --git a/apps/dokploy/server/wss/listen-deployment.ts b/apps/dokploy/server/wss/listen-deployment.ts index e3d4262cadf..b29cc334939 100644 --- a/apps/dokploy/server/wss/listen-deployment.ts +++ b/apps/dokploy/server/wss/listen-deployment.ts @@ -73,10 +73,28 @@ export const setupDeploymentLogsWebSocketServer = ( session: { activeOrganizationId: session.activeOrganizationId }, } as Parameters[0]; + const { backup, volumeBackup, schedule } = deployment; const serviceId = deployment.applicationId ?? deployment.composeId ?? deployment.previewDeployment?.applicationId ?? + schedule?.applicationId ?? + schedule?.composeId ?? + backup?.postgresId ?? + backup?.mysqlId ?? + backup?.mariadbId ?? + backup?.mongoId ?? + backup?.libsqlId ?? + backup?.composeId ?? + (volumeBackup && + (volumeBackup.applicationId ?? + volumeBackup.postgresId ?? + volumeBackup.mysqlId ?? + volumeBackup.mariadbId ?? + volumeBackup.mongoId ?? + volumeBackup.redisId ?? + volumeBackup.libsqlId ?? + volumeBackup.composeId)) ?? null; if (serviceId) { @@ -86,7 +104,8 @@ export const setupDeploymentLogsWebSocketServer = ( } else { const org = deployment.server?.organizationId ?? - deployment.schedule?.organizationId ?? + schedule?.organizationId ?? + backup?.destination?.organizationId ?? null; if (!org || org !== session.activeOrganizationId) { ws.close(4003, "Not authorized"); diff --git a/packages/server/src/lib/auth.ts b/packages/server/src/lib/auth.ts index 5fcf0b72b73..f83ed7d8328 100644 --- a/packages/server/src/lib/auth.ts +++ b/packages/server/src/lib/auth.ts @@ -75,7 +75,7 @@ const rewriteToCanonicalOrigin = async (url: string): Promise => { if (!origin) { const settings = await getWebServerSettings(); origin = settings?.host - ? `https://${settings.host}` + ? `${settings.https ? "https" : "http"}://${settings.host}` : settings?.serverIp ? `http://${settings.serverIp}:3000` : null; diff --git a/packages/server/src/services/deployment.ts b/packages/server/src/services/deployment.ts index 1035a139db3..06c94af171a 100644 --- a/packages/server/src/services/deployment.ts +++ b/packages/server/src/services/deployment.ts @@ -1113,8 +1113,33 @@ export const findDeploymentByLogPath = async (logPath: string) => { columns: { applicationId: true, composeId: true }, with: { server: { columns: { organizationId: true } }, - schedule: { columns: { organizationId: true } }, + schedule: { + columns: { organizationId: true, applicationId: true, composeId: true }, + }, previewDeployment: { columns: { applicationId: true } }, + backup: { + columns: { + postgresId: true, + mysqlId: true, + mariadbId: true, + mongoId: true, + libsqlId: true, + composeId: true, + }, + with: { destination: { columns: { organizationId: true } } }, + }, + volumeBackup: { + columns: { + applicationId: true, + postgresId: true, + mysqlId: true, + mariadbId: true, + mongoId: true, + redisId: true, + libsqlId: true, + composeId: true, + }, + }, }, }); }; diff --git a/packages/server/src/services/patch-repo.ts b/packages/server/src/services/patch-repo.ts index d9c73c69761..bfcf513a3ae 100644 --- a/packages/server/src/services/patch-repo.ts +++ b/packages/server/src/services/patch-repo.ts @@ -1,4 +1,4 @@ -import { join, resolve, sep } from "node:path"; +import { join, relative, resolve, sep } from "node:path"; import { paths } from "@dokploy/server/constants"; import { TRPCError } from "@trpc/server"; import { quote } from "shell-quote"; @@ -200,7 +200,8 @@ export const readPatchRepoFile = async ( }); } - const command = `cat ${quote([fullPath])}`; + // Read from the git tree so symlinks in the repo can't point at host files. + const command = `git -C ${quote([repoPath])} cat-file --filters ${quote([`HEAD:${relative(resolvedRepo, resolvedFull)}`])}`; if (serverId) { const result = await execAsyncRemote(serverId, command); diff --git a/packages/server/src/utils/volume-backups/restore.ts b/packages/server/src/utils/volume-backups/restore.ts index 6f7162ff3c8..cb3ff41efc5 100644 --- a/packages/server/src/utils/volume-backups/restore.ts +++ b/packages/server/src/utils/volume-backups/restore.ts @@ -41,7 +41,7 @@ export const restoreVolume = async ( -v ${volumeName}:/volume_data \ -v ${volumeBackupPath}:/backup \ ubuntu \ - bash -c "cd /volume_data && tar xvf /backup/${quote([backupFileName])} ." + tar -C /volume_data -xvf ${quote([`/backup/${backupFileName}`])} echo "Volume restore completed ✅" `; From 291ddaa9523c76ed0729d6bd09f32fd3a162a0df Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Sat, 7 Nov 2026 09:47:44 +0000 Subject: [PATCH 11/84] [autofix.ci] apply automated fixes --- .../backup-destination-organization.test.ts | 6 ++++-- .../domain/domain-create-authz.test.ts | 9 +++++++-- .../git-provider/github-update-authz.test.ts | 4 +++- .../permissions/member-role-ceiling.test.ts | 18 ++++++++++++++---- 4 files changed, 28 insertions(+), 9 deletions(-) diff --git a/apps/dokploy/__test__/backups/backup-destination-organization.test.ts b/apps/dokploy/__test__/backups/backup-destination-organization.test.ts index 00ba9bf70fd..efd0f652c14 100644 --- a/apps/dokploy/__test__/backups/backup-destination-organization.test.ts +++ b/apps/dokploy/__test__/backups/backup-destination-organization.test.ts @@ -229,7 +229,8 @@ describe("restore access by role", () => { for (const role of ["owner", "admin"]) { it(`${role} can run a web-server restore`, async () => { mocks.findDestinationRow.mockResolvedValue(ownDestination); - const stream = await callerAs(role).restoreBackupWithLogs(webServerRestore); + const stream = + await callerAs(role).restoreBackupWithLogs(webServerRestore); await drain(stream); expect(mocks.restoreWebServerBackup).toHaveBeenCalledTimes(1); }); @@ -237,7 +238,8 @@ describe("restore access by role", () => { it("a member cannot run a web-server restore (panel wipe)", async () => { mocks.findDestinationRow.mockResolvedValue(ownDestination); - const stream = await callerAs("member").restoreBackupWithLogs(webServerRestore); + const stream = + await callerAs("member").restoreBackupWithLogs(webServerRestore); await expect(drain(stream)).rejects.toMatchObject({ code: "UNAUTHORIZED" }); expect(mocks.restoreWebServerBackup).not.toHaveBeenCalled(); }); diff --git a/apps/dokploy/__test__/domain/domain-create-authz.test.ts b/apps/dokploy/__test__/domain/domain-create-authz.test.ts index 1274252394c..8e1eececa9f 100644 --- a/apps/dokploy/__test__/domain/domain-create-authz.test.ts +++ b/apps/dokploy/__test__/domain/domain-create-authz.test.ts @@ -14,7 +14,9 @@ vi.mock("@dokploy/server/services/permission", () => ({ checkServicePermissionAndAccess: mocks.checkServiceAccess, checkPermission: vi.fn(async () => undefined), })); -vi.mock("@/server/api/utils/audit", () => ({ audit: vi.fn(async () => undefined) })); +vi.mock("@/server/api/utils/audit", () => ({ + audit: vi.fn(async () => undefined), +})); const { domainRouter } = await import("@/server/api/routers/domain"); @@ -26,7 +28,10 @@ const callerAs = (role: string) => beforeEach(() => { vi.clearAllMocks(); - mocks.createDomain.mockResolvedValue({ domainId: "d1", host: "x.example.com" }); + mocks.createDomain.mockResolvedValue({ + domainId: "d1", + host: "x.example.com", + }); mocks.findPreviewDeploymentById.mockResolvedValue({ applicationId: "app-1" }); }); diff --git a/apps/dokploy/__test__/git-provider/github-update-authz.test.ts b/apps/dokploy/__test__/git-provider/github-update-authz.test.ts index ed8a153d8e6..5ecde7cd12a 100644 --- a/apps/dokploy/__test__/git-provider/github-update-authz.test.ts +++ b/apps/dokploy/__test__/git-provider/github-update-authz.test.ts @@ -18,7 +18,9 @@ vi.mock("@dokploy/server", () => ({ vi.mock("@dokploy/server/services/permission", () => ({ checkPermission: vi.fn(async () => undefined), })); -vi.mock("@/server/api/utils/audit", () => ({ audit: vi.fn(async () => undefined) })); +vi.mock("@/server/api/utils/audit", () => ({ + audit: vi.fn(async () => undefined), +})); const { githubRouter } = await import("@/server/api/routers/github"); diff --git a/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts b/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts index e9bcdad8784..88bf8b5ed1e 100644 --- a/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts +++ b/apps/dokploy/__test__/permissions/member-role-ceiling.test.ts @@ -31,12 +31,16 @@ vi.mock("@dokploy/server/services/permission", () => ({ checkPermission: vi.fn(async () => undefined), })); -vi.mock("@/server/api/utils/audit", () => ({ audit: vi.fn(async () => undefined) })); +vi.mock("@/server/api/utils/audit", () => ({ + audit: vi.fn(async () => undefined), +})); vi.mock("@/server/api/utils/plan-limits", () => ({ assertMemberLimit: vi.fn(async () => undefined), })); -const { organizationRouter } = await import("@/server/api/routers/organization"); +const { organizationRouter } = await import( + "@/server/api/routers/organization" +); const callerAs = (role: string, userId = "caller-1") => organizationRouter.createCaller({ @@ -63,7 +67,10 @@ describe("updateMemberRole — privileged roles keep working", () => { it("owner can promote a member to admin", async () => { mocks.memberFindFirst.mockResolvedValue(targetMember("member")); await expect( - callerAs("owner").updateMemberRole({ memberId: "member-2", role: "admin" }), + callerAs("owner").updateMemberRole({ + memberId: "member-2", + role: "admin", + }), ).resolves.toBe(true); expect(mocks.updateSet).toHaveBeenCalledWith({ role: "admin" }); }); @@ -71,7 +78,10 @@ describe("updateMemberRole — privileged roles keep working", () => { it("admin can promote a member to admin", async () => { mocks.memberFindFirst.mockResolvedValue(targetMember("member")); await expect( - callerAs("admin").updateMemberRole({ memberId: "member-2", role: "admin" }), + callerAs("admin").updateMemberRole({ + memberId: "member-2", + role: "admin", + }), ).resolves.toBe(true); }); From 5ca96f95d5c632b2a46637cfb6ec71dfe281bf69 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 10:58:06 +0100 Subject: [PATCH 12/84] fix(security): allow restoring named compose volumes and dotted backup names - volume restore also accepts volumes the service already backs up, covering compose volumes with an explicit or external name - backup restore rejects '..' path segments instead of any two dots --- apps/dokploy/server/api/routers/backup.ts | 2 +- .../server/api/routers/volume-backups.ts | 25 +++-------- .../server/src/services/volume-backups.ts | 42 ++++++++++++++++++- 3 files changed, 48 insertions(+), 21 deletions(-) diff --git a/apps/dokploy/server/api/routers/backup.ts b/apps/dokploy/server/api/routers/backup.ts index 372ab39a85a..5fca290233e 100644 --- a/apps/dokploy/server/api/routers/backup.ts +++ b/apps/dokploy/server/api/routers/backup.ts @@ -650,7 +650,7 @@ export const backupRouter = createTRPCRouter({ const onLog = (log: string) => queue.push(log); const assertBackupFileInService = (...folders: string[]) => { if ( - input.backupFile.includes("..") || + input.backupFile.split("/").includes("..") || !folders.some((folder) => input.backupFile.startsWith(`${folder}/`)) ) { throw new TRPCError({ diff --git a/apps/dokploy/server/api/routers/volume-backups.ts b/apps/dokploy/server/api/routers/volume-backups.ts index 7ea79eb6651..36606fe2235 100644 --- a/apps/dokploy/server/api/routers/volume-backups.ts +++ b/apps/dokploy/server/api/routers/volume-backups.ts @@ -1,5 +1,6 @@ import { createVolumeBackup, + findServiceOwningVolume, findVolumeBackupById, IS_CLOUD, removeVolumeBackup, @@ -17,8 +18,6 @@ import { VOLUME_NAME_REGEX, volumeBackups, } from "@dokploy/server/db/schema"; -import { findApplicationById } from "@dokploy/server/services/application"; -import { findComposeById } from "@dokploy/server/services/compose"; import { findDestinationById, findDestinationByIdForOrganization, @@ -328,23 +327,11 @@ export const volumeBackupsRouter = createTRPCRouter({ message: "You don't have access to this destination.", }); } - const service = - input.serviceType === "application" - ? await findApplicationById(input.id) - : await findComposeById(input.id); - const ownsVolume = - service.mounts.some( - (mount) => - mount.type === "volume" && mount.volumeName === input.volumeName, - ) || - (input.serviceType === "compose" && - input.volumeName.startsWith(`${service.appName}_`)); - if (!ownsVolume) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "This volume does not belong to the service.", - }); - } + const service = await findServiceOwningVolume( + input.id, + input.serviceType, + input.volumeName, + ); const serverId = service.serverId ?? undefined; return observable((emit) => { const runRestore = async () => { diff --git a/packages/server/src/services/volume-backups.ts b/packages/server/src/services/volume-backups.ts index 359ccf5f0d4..0d4ec5f14ab 100644 --- a/packages/server/src/services/volume-backups.ts +++ b/packages/server/src/services/volume-backups.ts @@ -1,5 +1,5 @@ import { TRPCError } from "@trpc/server"; -import { eq } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import type { z } from "zod"; import { db } from "../db"; import { @@ -7,6 +7,8 @@ import { type updateVolumeBackupSchema, volumeBackups, } from "../db/schema"; +import { findApplicationById } from "./application"; +import { findComposeById } from "./compose"; export const findVolumeBackupById = async (volumeBackupId: string) => { const volumeBackup = await db.query.volumeBackups.findFirst({ @@ -137,3 +139,41 @@ export const updateVolumeBackup = async ( .returning() .then((e) => e[0]); }; + +// Compose volumes can be renamed (`name:`) or external, so a volume this +// service already backs up also counts as its own. +export const findServiceOwningVolume = async ( + id: string, + serviceType: "application" | "compose", + volumeName: string, +) => { + const service = + serviceType === "application" + ? await findApplicationById(id) + : await findComposeById(id); + const backedUp = await db.query.volumeBackups.findFirst({ + where: and( + eq( + serviceType === "application" + ? volumeBackups.applicationId + : volumeBackups.composeId, + id, + ), + eq(volumeBackups.volumeName, volumeName), + ), + columns: { volumeBackupId: true }, + }); + const ownsVolume = + !!backedUp || + service.mounts.some( + (mount) => mount.type === "volume" && mount.volumeName === volumeName, + ) || + (serviceType === "compose" && volumeName.startsWith(`${service.appName}_`)); + if (!ownsVolume) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "This volume does not belong to the service.", + }); + } + return service; +}; From fd9bac4bc600c9211a10f02a0b208802f44159fc Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 11:06:23 +0100 Subject: [PATCH 13/84] fix(security): update server mock to include remote docker instance retrieval --- apps/dokploy/__test__/setup/monitoring-setup.real.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts b/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts index 590d67b2117..91ed179b159 100644 --- a/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts +++ b/apps/dokploy/__test__/setup/monitoring-setup.real.test.ts @@ -13,7 +13,6 @@ vi.mock("@dokploy/server/services/server", () => ({ findServerById: vi.fn().mockResolvedValue({ serverId: "test-server", serverType: "deploy", - sshKeyId: null, // -> getRemoteDocker returns the local docker instance metricsConfig: { server: { type: "Remote", @@ -30,6 +29,11 @@ vi.mock("@dokploy/server/services/server", () => ({ }), })); +vi.mock("@dokploy/server/utils/servers/remote-docker", async () => { + const { docker } = await import("@dokploy/server/constants"); + return { getRemoteDocker: vi.fn(async () => docker) }; +}); + vi.mock("@dokploy/server/services/settings", () => ({ getDokployImageTag: vi.fn(() => "latest"), })); From 0fa3101a7e76173c60a3015d37a02e7c892b9ab3 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 11:45:55 +0100 Subject: [PATCH 14/84] fix(security): stop client-controlled schedule appName reaching the shell appName and organizationId are no longer accepted from schedule create/update input, and the schedule paths used in rm/mkdir/script writes are shell-quoted so rows stored before this fix stay harmless. --- packages/server/src/db/schema/schedule.ts | 2 +- packages/server/src/services/deployment.ts | 5 +++-- packages/server/src/services/schedule.ts | 15 +++++++++------ 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/packages/server/src/db/schema/schedule.ts b/packages/server/src/db/schema/schedule.ts index 55c831f548c..2d6cb910528 100644 --- a/packages/server/src/db/schema/schedule.ts +++ b/packages/server/src/db/schema/schedule.ts @@ -81,7 +81,7 @@ export const schedulesRelations = relations(schedules, ({ one, many }) => ({ export const createScheduleSchema = createInsertSchema(schedules, { scheduleType: z.enum(["application", "compose", "server", "dokploy-server"]), -}); +}).omit({ appName: true, organizationId: true }); export const updateScheduleSchema = createScheduleSchema.extend({ scheduleId: z.string().min(1), diff --git a/packages/server/src/services/deployment.ts b/packages/server/src/services/deployment.ts index 06c94af171a..bc6e9b8f4a9 100644 --- a/packages/server/src/services/deployment.ts +++ b/packages/server/src/services/deployment.ts @@ -27,6 +27,7 @@ import { trackDeploymentResult } from "@dokploy/server/utils/tracking/posthog"; import { TRPCError } from "@trpc/server"; import { format } from "date-fns"; import { and, desc, eq, inArray, or, sql } from "drizzle-orm"; +import { quote } from "shell-quote"; import type { z } from "zod"; import { type Application, @@ -480,8 +481,8 @@ export const createDeploymentSchedule = async ( const server = await findServerById(serverId); const command = ` - mkdir -p ${SCHEDULES_PATH}/${schedule.appName}; - echo "Initializing schedule" >> ${logFilePath}; + mkdir -p ${quote([path.join(SCHEDULES_PATH, schedule.appName)])}; + echo "Initializing schedule" >> ${quote([logFilePath])}; `; await execAsyncRemote(server.serverId, command); diff --git a/packages/server/src/services/schedule.ts b/packages/server/src/services/schedule.ts index 59b75cc0da4..511b1572b0c 100644 --- a/packages/server/src/services/schedule.ts +++ b/packages/server/src/services/schedule.ts @@ -1,6 +1,7 @@ import path from "node:path"; import { TRPCError } from "@trpc/server"; import { eq } from "drizzle-orm"; +import { quote } from "shell-quote"; import type { z } from "zod"; import { IS_CLOUD, paths } from "../constants"; import { db } from "../db"; @@ -147,7 +148,7 @@ export const deleteSchedule = async (scheduleId: string) => { const { SCHEDULES_PATH } = paths(!!serverId); const fullPath = path.join(SCHEDULES_PATH, schedule?.appName || ""); - const command = `rm -rf ${fullPath}`; + const command = `rm -rf ${quote([fullPath])}`; if (serverId) { await execAsyncRemote(serverId, command); } else { @@ -203,12 +204,14 @@ const handleScript = async (schedule: Schedule) => { ${schedule?.script || ""}`; const encodedContent = encodeBase64(scriptWithPid); + const dir = quote([fullPath]); + const file = quote([path.join(fullPath, "script.sh")]); const script = ` - mkdir -p ${fullPath} - rm -f ${fullPath}/script.sh - touch ${fullPath}/script.sh - chmod +x ${fullPath}/script.sh - echo "${encodedContent}" | base64 -d > ${fullPath}/script.sh + mkdir -p ${dir} + rm -f ${file} + touch ${file} + chmod +x ${file} + echo "${encodedContent}" | base64 -d > ${file} `; if (schedule?.scheduleType === "dokploy-server") { From 861a1fbfc9f847b706cae65c5312655a53eb8f7c Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 11:49:45 +0100 Subject: [PATCH 15/84] fix(security): delete local file mounts without a shell removeFileOrDirectory and removeDirectoryIfExistsContent ran an unquoted rm -rf, so a file mount filePath like x$(cmd) executed on the host when the mount was removed. Use fs.rm instead. --- packages/server/src/utils/filesystem/directory.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/server/src/utils/filesystem/directory.ts b/packages/server/src/utils/filesystem/directory.ts index 6865c576d3f..361cb98e83b 100644 --- a/packages/server/src/utils/filesystem/directory.ts +++ b/packages/server/src/utils/filesystem/directory.ts @@ -31,13 +31,13 @@ export const removeDirectoryIfExistsContent = async ( path: string, ): Promise => { if (fs.existsSync(path) && fs.readdirSync(path).length !== 0) { - await execAsync(`rm -rf ${path}`); + await fsPromises.rm(path, { recursive: true, force: true }); } }; export const removeFileOrDirectory = async (path: string) => { try { - await execAsync(`rm -rf ${path}`); + await fsPromises.rm(path, { recursive: true, force: true }); } catch (error) { console.error(`Error removing ${path}: ${error}`); throw error; From 549cdada79a8ddf9bd9d1f153159626d050b4b6a Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 11:54:29 +0100 Subject: [PATCH 16/84] fix(security): quote backup prefix, bucket and compose serviceName The rclone destination was double-quoted (still expands $(...)), the retention path was unquoted and compose serviceName went raw into the docker ps filter. Also block web-server backups on cloud, where the retention cleanup ran on the shared host, and stop logging the backup command (it carries DB passwords). --- apps/dokploy/server/api/routers/backup.ts | 6 ++++++ packages/server/src/utils/backups/index.ts | 8 +++++--- packages/server/src/utils/backups/utils.ts | 9 ++++----- packages/server/src/utils/backups/web-server.ts | 3 ++- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/apps/dokploy/server/api/routers/backup.ts b/apps/dokploy/server/api/routers/backup.ts index 5fca290233e..6a8a52bd5b8 100644 --- a/apps/dokploy/server/api/routers/backup.ts +++ b/apps/dokploy/server/api/routers/backup.ts @@ -77,6 +77,12 @@ const assertWebServerBackupAccess = async ( ctx: { user: { role: string }; session: { activeOrganizationId: string } }, destinationId: string, ) => { + if (IS_CLOUD) { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Web-server backups are not available in the cloud version", + }); + } if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { throw new TRPCError({ code: "UNAUTHORIZED", diff --git a/packages/server/src/utils/backups/index.ts b/packages/server/src/utils/backups/index.ts index c82dcb8acae..4855cfb416f 100644 --- a/packages/server/src/utils/backups/index.ts +++ b/packages/server/src/utils/backups/index.ts @@ -1,4 +1,4 @@ -import { CLEANUP_CRON_JOB } from "@dokploy/server/constants"; +import { CLEANUP_CRON_JOB, IS_CLOUD } from "@dokploy/server/constants"; import { member } from "@dokploy/server/db/schema"; import type { BackupSchedule } from "@dokploy/server/services/backup"; import { findDestinationById } from "@dokploy/server/services/destination"; @@ -6,6 +6,7 @@ import { getAllServers } from "@dokploy/server/services/server"; import { getWebServerSettings } from "@dokploy/server/services/web-server-settings"; import { eq } from "drizzle-orm"; import { scheduleJob } from "node-schedule"; +import { quote } from "shell-quote"; import { db } from "../../db/index"; import { startLogCleanup } from "../access-log/handler"; import { cleanupAll } from "../docker/utils"; @@ -110,6 +111,7 @@ export const keepLatestNBackups = async ( // 0 also immediately returns which is good as the empty "keep latest" field in the UI // is saved as 0 in the database if (!backup.keepLatestCount) return; + if (IS_CLOUD && !serverId) return; try { const destination = await findDestinationById(backup.destinationId); @@ -118,12 +120,12 @@ export const keepLatestNBackups = async ( // --include "*.bson.gz" or "*.sql.gz" or "*.zip" ensures nothing else other than the dokploy backup files are touched by rclone // sort by server mtime: custom names break lexical order - const rcloneList = `rclone lsf ${rcloneFlags.join(" ")} --include "*${backup.databaseType === "web-server" ? ".zip" : ".{sql.gz,bson.gz}"}" --format "tp" --use-server-modtime ${backupFilesPath}`; + const rcloneList = `rclone lsf ${rcloneFlags.join(" ")} --include "*${backup.databaseType === "web-server" ? ".zip" : ".{sql.gz,bson.gz}"}" --format "tp" --use-server-modtime ${quote([backupFilesPath])}`; // when we pipe the above command with this one, we only get the list of files we want to delete const sortAndPickUnwantedBackups = `sort -r | tail -n +$((${backup.keepLatestCount}+1)) | cut -d';' -f2- | xargs -I{}`; // this command deletes the files // to test the deletion before actually deleting we can add --dry-run before ${backupFilesPath}{} - const rcloneDelete = `rclone delete ${rcloneFlags.join(" ")} ${backupFilesPath}{}`; + const rcloneDelete = `rclone delete ${rcloneFlags.join(" ")} ${quote([backupFilesPath])}{}`; const rcloneCommand = `${rcloneList} | ${sortAndPickUnwantedBackups} ${rcloneDelete}`; diff --git a/packages/server/src/utils/backups/utils.ts b/packages/server/src/utils/backups/utils.ts index e68d492c3f8..3bf3d147eaf 100644 --- a/packages/server/src/utils/backups/utils.ts +++ b/packages/server/src/utils/backups/utils.ts @@ -147,9 +147,9 @@ export const getComposeContainerCommand = ( composeType: "stack" | "docker-compose" | undefined, ) => { if (composeType === "stack") { - return `docker ps -q --filter "status=running" --filter "label=com.docker.stack.namespace=${appName}" --filter "label=com.docker.swarm.service.name=${appName}_${serviceName}" | head -n 1`; + return `docker ps -q --filter "status=running" --filter ${quote([`label=com.docker.stack.namespace=${appName}`])} --filter ${quote([`label=com.docker.swarm.service.name=${appName}_${serviceName}`])} | head -n 1`; } - return `docker ps -q --filter "status=running" --filter "label=com.docker.compose.project=${appName}" --filter "label=com.docker.compose.service=${serviceName}" | head -n 1`; + return `docker ps -q --filter "status=running" --filter ${quote([`label=com.docker.compose.project=${appName}`])} --filter ${quote([`label=com.docker.compose.service=${serviceName}`])} | head -n 1`; }; const getContainerSearchCommand = (backup: BackupSchedule) => { @@ -272,13 +272,12 @@ export const getBackupCommand = ( ) => { const containerSearch = getContainerSearchCommand(backup); const backupCommand = generateBackupCommand(backup); - const rcloneCommand = `rclone rcat ${rcloneFlags.join(" ")} "${rcloneDestination}"`; - const rcloneDeleteCommand = `rclone deletefile ${rcloneFlags.join(" ")} "${rcloneDestination}"`; + const rcloneCommand = `rclone rcat ${rcloneFlags.join(" ")} ${quote([rcloneDestination])}`; + const rcloneDeleteCommand = `rclone deletefile ${rcloneFlags.join(" ")} ${quote([rcloneDestination])}`; logger.info( { containerSearch, - backupCommand, rcloneCommand: redactRcloneCredentials(rcloneCommand), logPath, }, diff --git a/packages/server/src/utils/backups/web-server.ts b/packages/server/src/utils/backups/web-server.ts index 5d89428592d..e04a8a05549 100644 --- a/packages/server/src/utils/backups/web-server.ts +++ b/packages/server/src/utils/backups/web-server.ts @@ -13,6 +13,7 @@ import { updateDeploymentStatus, } from "@dokploy/server/services/deployment"; import { findDestinationById } from "@dokploy/server/services/destination"; +import { quote } from "shell-quote"; import { sendDokployBackupNotifications } from "../notifications/dokploy-backup"; import { execAsync } from "../process/execAsync"; import { redactRcloneCredentials } from "./redact"; @@ -118,7 +119,7 @@ export const runWebServerBackup = async (backup: BackupSchedule) => { // If stat fails, keep undefined } - const uploadCommand = `rclone copyto ${rcloneFlags.join(" ")} "${zipPath}" "${s3Path}"`; + const uploadCommand = `rclone copyto ${rcloneFlags.join(" ")} ${quote([zipPath, s3Path])}`; writeStream.write("Running command to upload backup to S3\n"); await execAsync(uploadCommand); writeStream.write("Uploaded backup to S3 ✅\n"); From ad98bf014e18d98c7a16138381bb0b428bfceb64 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:08:34 +0100 Subject: [PATCH 17/84] fix(security): validate and quote volume backup prefix/serviceName/appName appName is no longer accepted from input, serviceName must be a valid service name, and prefix/serviceName/paths are shell-quoted in the backup, retention and cleanup commands. --- .../server/src/db/schema/volume-backups.ts | 5 +++++ .../server/src/utils/volume-backups/backup.ts | 22 +++++++++++++------ .../server/src/utils/volume-backups/utils.ts | 7 +++--- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/packages/server/src/db/schema/volume-backups.ts b/packages/server/src/db/schema/volume-backups.ts index bf025126d08..5c73801ded2 100644 --- a/packages/server/src/db/schema/volume-backups.ts +++ b/packages/server/src/db/schema/volume-backups.ts @@ -119,8 +119,13 @@ export const volumeBackupsRelations = relations( export const createVolumeBackupSchema = createInsertSchema(volumeBackups, { volumeName: z.string().regex(VOLUME_NAME_REGEX, VOLUME_NAME_MESSAGE), + serviceName: z + .string() + .regex(/^([a-zA-Z0-9][a-zA-Z0-9_.-]*)?$/, "Invalid service name") + .nullish(), }).omit({ volumeBackupId: true, + appName: true, }); export const updateVolumeBackupSchema = createVolumeBackupSchema.extend({ diff --git a/packages/server/src/utils/volume-backups/backup.ts b/packages/server/src/utils/volume-backups/backup.ts index 5a17e9aa7bc..d7aa33dc028 100644 --- a/packages/server/src/utils/volume-backups/backup.ts +++ b/packages/server/src/utils/volume-backups/backup.ts @@ -3,6 +3,7 @@ import { paths } from "@dokploy/server/constants"; import { findComposeById } from "@dokploy/server/services/compose"; import { findDestinationById } from "@dokploy/server/services/destination"; import type { findVolumeBackupById } from "@dokploy/server/services/volume-backups"; +import { quote } from "shell-quote"; import { getBackupTimestamp, getS3Credentials, @@ -80,7 +81,7 @@ export const backupVolume = async ( const rcloneDestination = `:s3:${destination.bucket}/${bucketDestination}`; const volumeBackupPath = path.join(VOLUME_BACKUPS_PATH, volumeBackup.appName); - const rcloneCommand = `rclone copyto ${rcloneFlags.join(" ")} "${volumeBackupPath}/${backupFileName}" "${rcloneDestination}"`; + const rcloneCommand = `rclone copyto ${rcloneFlags.join(" ")} ${quote([`${volumeBackupPath}/${backupFileName}`, rcloneDestination])}`; // GNU tar exits 1 when a file changes while being read, which is expected on a live volume const backupCommand = ` @@ -124,7 +125,7 @@ export const backupVolume = async ( const lockWrapper = (body: string) => ` set -e - LOCK_PATH="${lockPath}" + LOCK_PATH=${quote([lockPath])} echo "Waiting for volume backup lock: $LOCK_PATH" @@ -177,21 +178,28 @@ export const backupVolume = async ( let stopCommand = ""; let startCommand = ""; + const serviceName = quote([ + `${compose.appName}_${volumeBackup.serviceName}`, + ]); + const serviceLabel = quote([ + `label=com.docker.compose.service=${volumeBackup.serviceName}`, + ]); + if (compose.composeType === "stack") { stopCommand = ` echo "Stopping compose to 0 replicas" - echo "Service name: ${compose.appName}_${volumeBackup.serviceName}" - ACTUAL_REPLICAS=$(docker service inspect ${compose.appName}_${volumeBackup.serviceName} --format "{{.Spec.Mode.Replicated.Replicas}}") + echo "Service name: ${serviceName}" + ACTUAL_REPLICAS=$(docker service inspect ${serviceName} --format "{{.Spec.Mode.Replicated.Replicas}}") echo "Actual replicas: $ACTUAL_REPLICAS" - docker service update --replicas=0 ${compose.appName}_${volumeBackup.serviceName}`; + docker service update --replicas=0 ${serviceName}`; startCommand = ` echo "Starting compose to $ACTUAL_REPLICAS replicas" - docker service update --replicas=$ACTUAL_REPLICAS --with-registry-auth ${compose.appName}_${volumeBackup.serviceName}`; + docker service update --replicas=$ACTUAL_REPLICAS --with-registry-auth ${serviceName}`; } else { stopCommand = ` echo "Stopping compose container" - ID=$(docker ps -q --filter "label=com.docker.compose.project=${compose.appName}" --filter "label=com.docker.compose.service=${volumeBackup.serviceName}") + ID=$(docker ps -q --filter "label=com.docker.compose.project=${compose.appName}" --filter ${serviceLabel}) docker stop $ID`; startCommand = ` diff --git a/packages/server/src/utils/volume-backups/utils.ts b/packages/server/src/utils/volume-backups/utils.ts index 9dd6996e470..f0b3dcc6243 100644 --- a/packages/server/src/utils/volume-backups/utils.ts +++ b/packages/server/src/utils/volume-backups/utils.ts @@ -14,6 +14,7 @@ import { execAsyncRemote, } from "@dokploy/server/utils/process/execAsync"; import { scheduledJobs, scheduleJob } from "node-schedule"; +import { quote } from "shell-quote"; import { getS3Credentials, normalizeS3Path } from "../backups/utils"; import { sendVolumeBackupNotifications } from "../notifications/volume-backup"; import { backupVolume, getVolumeServiceAppName } from "./backup"; @@ -90,9 +91,9 @@ const cleanupOldVolumeBackups = async ( const rcloneFlags = getS3Credentials(destination); const s3AppName = getVolumeServiceAppName(volumeBackup); const backupFilesPath = `:s3:${destination.bucket}/${s3AppName}/${normalizeS3Path(prefix || "")}`; - const listCommand = `rclone lsf ${rcloneFlags.join(" ")} --include \"${volumeName}-*.tar\" ${backupFilesPath}`; + const listCommand = `rclone lsf ${rcloneFlags.join(" ")} --include "${volumeName}-*.tar" ${quote([backupFilesPath])}`; const sortAndPick = `sort -r | tail -n +$((${keepLatestCount}+1)) | xargs -I{}`; - const deleteCommand = `rclone delete ${rcloneFlags.join(" ")} ${backupFilesPath}{}`; + const deleteCommand = `rclone delete ${rcloneFlags.join(" ")} ${quote([backupFilesPath])}{}`; const fullCommand = `${listCommand} | ${sortAndPick} ${deleteCommand}`; if (serverId) { @@ -164,7 +165,7 @@ export const runVolumeBackup = async (volumeBackupId: string) => { volumeBackup.appName, ); // delete all the .tar files - const command = `rm -rf ${volumeBackupPath}/*.tar`; + const command = `rm -rf ${quote([volumeBackupPath])}/*.tar`; if (serverId) { await execAsyncRemote(serverId, command); } else { From accc2ffbda3e698bad328cc6e9fe5837a7bafba6 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:16:25 +0100 Subject: [PATCH 18/84] fix(security): shell-quote database changePassword commands The new password (backticks allowed by DATABASE_PASSWORD_REGEX) sat in double quotes and databaseUser / stored credentials were unquoted or single-quoted. Pass every docker exec argument through quote(). --- apps/dokploy/server/api/routers/mariadb.ts | 10 +++++++++- apps/dokploy/server/api/routers/mongo.ts | 13 ++++++++++++- apps/dokploy/server/api/routers/mysql.ts | 10 +++++++++- apps/dokploy/server/api/routers/postgres.ts | 11 ++++++++++- apps/dokploy/server/api/routers/redis.ts | 11 ++++++++++- 5 files changed, 50 insertions(+), 5 deletions(-) diff --git a/apps/dokploy/server/api/routers/mariadb.ts b/apps/dokploy/server/api/routers/mariadb.ts index 98932f8af68..c81bf8ce56c 100644 --- a/apps/dokploy/server/api/routers/mariadb.ts +++ b/apps/dokploy/server/api/routers/mariadb.ts @@ -33,6 +33,7 @@ import { import { TRPCError } from "@trpc/server"; import { observable } from "@trpc/server/observable"; import { and, desc, eq, ilike, or, sql } from "drizzle-orm"; +import { quote } from "shell-quote"; import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc"; import { audit } from "@/server/api/utils/audit"; @@ -420,7 +421,14 @@ export const mariadbRouter = createTRPCRouter({ const targetUser = type === "root" ? "root" : databaseUser; - const command = `docker exec ${container.Id} mariadb -u root -p'${databaseRootPassword}' -e "ALTER USER '${targetUser}'@'%' IDENTIFIED BY '${password}'; FLUSH PRIVILEGES;"`; + const command = `docker exec ${container.Id} ${quote([ + "mariadb", + "-u", + "root", + `-p${databaseRootPassword}`, + "-e", + `ALTER USER '${targetUser}'@'%' IDENTIFIED BY '${password}'; FLUSH PRIVILEGES;`, + ])}`; await db.transaction(async (tx) => { const setData = diff --git a/apps/dokploy/server/api/routers/mongo.ts b/apps/dokploy/server/api/routers/mongo.ts index 42b4107856d..568a93ef7f2 100644 --- a/apps/dokploy/server/api/routers/mongo.ts +++ b/apps/dokploy/server/api/routers/mongo.ts @@ -32,6 +32,7 @@ import { } from "@dokploy/server/services/permission"; import { TRPCError } from "@trpc/server"; import { and, desc, eq, ilike, or, sql } from "drizzle-orm"; +import { quote } from "shell-quote"; import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc"; import { audit } from "@/server/api/utils/audit"; @@ -439,7 +440,17 @@ export const mongoRouter = createTRPCRouter({ }); } - const command = `docker exec ${container.Id} mongosh -u '${databaseUser}' -p '${databasePassword}' --authenticationDatabase admin --eval "db.getSiblingDB('admin').changeUserPassword('${databaseUser}', '${password}')"`; + const command = `docker exec ${container.Id} ${quote([ + "mongosh", + "-u", + databaseUser, + "-p", + databasePassword, + "--authenticationDatabase", + "admin", + "--eval", + `db.getSiblingDB('admin').changeUserPassword('${databaseUser}', '${password}')`, + ])}`; await db.transaction(async (tx) => { await tx diff --git a/apps/dokploy/server/api/routers/mysql.ts b/apps/dokploy/server/api/routers/mysql.ts index c315ec5d452..e79da9dbd9b 100644 --- a/apps/dokploy/server/api/routers/mysql.ts +++ b/apps/dokploy/server/api/routers/mysql.ts @@ -32,6 +32,7 @@ import { } from "@dokploy/server/services/permission"; import { TRPCError } from "@trpc/server"; import { and, desc, eq, ilike, or, sql } from "drizzle-orm"; +import { quote } from "shell-quote"; import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc"; import { audit } from "@/server/api/utils/audit"; @@ -438,7 +439,14 @@ export const mysqlRouter = createTRPCRouter({ const targetUser = type === "root" ? "root" : databaseUser; - const command = `docker exec ${container.Id} mysql -u root -p'${databaseRootPassword}' -e "ALTER USER '${targetUser}'@'%' IDENTIFIED BY '${password}'; FLUSH PRIVILEGES;"`; + const command = `docker exec ${container.Id} ${quote([ + "mysql", + "-u", + "root", + `-p${databaseRootPassword}`, + "-e", + `ALTER USER '${targetUser}'@'%' IDENTIFIED BY '${password}'; FLUSH PRIVILEGES;`, + ])}`; await db.transaction(async (tx) => { const setData = diff --git a/apps/dokploy/server/api/routers/postgres.ts b/apps/dokploy/server/api/routers/postgres.ts index 97e39812358..7eb927680c2 100644 --- a/apps/dokploy/server/api/routers/postgres.ts +++ b/apps/dokploy/server/api/routers/postgres.ts @@ -33,6 +33,7 @@ import { } from "@dokploy/server/services/permission"; import { TRPCError } from "@trpc/server"; import { and, desc, eq, ilike, or, sql } from "drizzle-orm"; +import { quote } from "shell-quote"; import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc"; import { audit } from "@/server/api/utils/audit"; @@ -445,7 +446,15 @@ export const postgresRouter = createTRPCRouter({ }); } - const command = `docker exec ${container.Id} psql -U ${databaseUser} -d postgres -c "ALTER USER \\"${databaseUser}\\" WITH PASSWORD '${password}';"`; + const command = `docker exec ${container.Id} ${quote([ + "psql", + "-U", + databaseUser, + "-d", + "postgres", + "-c", + `ALTER USER "${databaseUser}" WITH PASSWORD '${password}';`, + ])}`; await db.transaction(async (tx) => { await tx diff --git a/apps/dokploy/server/api/routers/redis.ts b/apps/dokploy/server/api/routers/redis.ts index fb0d8301ccf..94220e4a8b5 100644 --- a/apps/dokploy/server/api/routers/redis.ts +++ b/apps/dokploy/server/api/routers/redis.ts @@ -31,6 +31,7 @@ import { } from "@dokploy/server/services/permission"; import { TRPCError } from "@trpc/server"; import { and, desc, eq, ilike, or, sql } from "drizzle-orm"; +import { quote } from "shell-quote"; import { z } from "zod"; import { createTRPCRouter, protectedProcedure } from "@/server/api/trpc"; import { audit } from "@/server/api/utils/audit"; @@ -426,7 +427,15 @@ export const redisRouter = createTRPCRouter({ }); } - const command = `docker exec ${container.Id} redis-cli -a '${databasePassword}' CONFIG SET requirepass '${password}'`; + const command = `docker exec ${container.Id} ${quote([ + "redis-cli", + "-a", + databasePassword, + "CONFIG", + "SET", + "requirepass", + password, + ])}`; await db.transaction(async (tx) => { await tx From 2cd86b2447daba8fefec1272718d40463e18d6a3 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:29:03 +0100 Subject: [PATCH 19/84] fix(security): validate application build path, stage and version fields dockerfile, build paths, dockerContextPath, publishDirectory and dropBuildPath must be safe relative paths (no spaces, leading '-' or '..'); dockerBuildStage, railpackVersion and herokuVersion are restricted to [a-zA-Z0-9._-]. They were interpolated unquoted into the builder shell commands. --- .../dokploy/server/api/routers/application.ts | 7 +++++- packages/server/src/db/schema/application.ts | 24 ++++++++++++++----- packages/server/src/db/schema/utils.ts | 13 ++++++++++ 3 files changed, 37 insertions(+), 7 deletions(-) diff --git a/apps/dokploy/server/api/routers/application.ts b/apps/dokploy/server/api/routers/application.ts index 79f02936038..f67ae7af020 100644 --- a/apps/dokploy/server/api/routers/application.ts +++ b/apps/dokploy/server/api/routers/application.ts @@ -69,7 +69,9 @@ import { apiSaveGitProvider, apiUpdateApplication, applications, + BUILD_PATH_MESSAGE, environments, + isSafeBuildPath, projects, } from "@/server/db/schema"; import type { DeploymentJob } from "@/server/queues/queue-types"; @@ -911,7 +913,10 @@ export const applicationRouter = createTRPCRouter({ zfd.formData({ applicationId: z.string(), zip: zfd.file(), - dropBuildPath: z.string().optional(), + dropBuildPath: z + .string() + .refine(isSafeBuildPath, BUILD_PATH_MESSAGE) + .optional(), }), ) .mutation(async ({ input, ctx }) => { diff --git a/packages/server/src/db/schema/application.ts b/packages/server/src/db/schema/application.ts index def6c344544..40e1bc6ea69 100644 --- a/packages/server/src/db/schema/application.ts +++ b/packages/server/src/db/schema/application.ts @@ -54,9 +54,16 @@ import { sshKeys } from "./ssh-key"; import { APP_NAME_MESSAGE, APP_NAME_REGEX, + BUILD_PATH_MESSAGE, + BUILD_TOKEN_MESSAGE, + BUILD_TOKEN_REGEX, encryptedText, generateAppName, + isSafeBuildPath, } from "./utils"; + +const buildPath = z.string().refine(isSafeBuildPath, BUILD_PATH_MESSAGE); +const buildToken = z.string().regex(BUILD_TOKEN_REGEX, BUILD_TOKEN_MESSAGE); export const sourceType = pgEnum("sourceType", [ "docker", "git", @@ -332,12 +339,17 @@ const createSchema = createInsertSchema(applications, { registryUrl: z.string().optional(), customGitSSHKeyId: z.string().optional(), repository: z.string().optional(), - dockerfile: z.string().optional(), + dockerfile: buildPath.optional(), branch: z.string().optional(), customGitBranch: z.string().optional(), - customGitBuildPath: z.string().optional(), + customGitBuildPath: buildPath.optional(), customGitUrl: z.string().optional(), - buildPath: z.string().optional(), + buildPath: buildPath.optional(), + gitlabBuildPath: buildPath.nullable().optional(), + giteaBuildPath: buildPath.nullable().optional(), + bitbucketBuildPath: buildPath.nullable().optional(), + dockerContextPath: buildPath.nullable().optional(), + dockerBuildStage: buildToken.nullable().optional(), environmentId: z.string(), sourceType: z .enum(["github", "docker", "git", "gitlab", "bitbucket", "gitea", "drop"]) @@ -352,9 +364,9 @@ const createSchema = createInsertSchema(applications, { "static", "railpack", ]), - railpackVersion: z.string().optional(), - herokuVersion: z.string().optional(), - publishDirectory: z.string().optional(), + railpackVersion: buildToken.nullable().optional(), + herokuVersion: buildToken.nullable().optional(), + publishDirectory: buildPath.nullable().optional(), isStaticSpa: z.boolean().optional(), createEnvFile: z.boolean().optional(), owner: z.string(), diff --git a/packages/server/src/db/schema/utils.ts b/packages/server/src/db/schema/utils.ts index 4bf14073816..fb3c97bdce1 100644 --- a/packages/server/src/db/schema/utils.ts +++ b/packages/server/src/db/schema/utils.ts @@ -54,6 +54,19 @@ export const DATABASE_PASSWORD_REGEX = export const DATABASE_PASSWORD_MESSAGE = "Password contains invalid characters. Please avoid: $ ! ' \" \\ / and space characters for database compatibility"; +export const BUILD_PATH_REGEX = /^([a-zA-Z0-9._@+/][a-zA-Z0-9._@+/-]*)?$/; + +export const BUILD_PATH_MESSAGE = + "Path can only contain letters, numbers and . _ - @ + / (no spaces, no leading '-', no '..')"; + +export const isSafeBuildPath = (value: string) => + BUILD_PATH_REGEX.test(value) && !value.split("/").includes(".."); + +export const BUILD_TOKEN_REGEX = /^([a-zA-Z0-9][a-zA-Z0-9._-]*)?$/; + +export const BUILD_TOKEN_MESSAGE = + "Can only contain letters, numbers, dots, underscores and hyphens"; + export const generateAppName = (type: string) => { const verb = faker.hacker.verb().replace(/ /g, "-"); const adjective = faker.hacker.adjective().replace(/ /g, "-"); From 45abd005ce6cd31eca32264537eee7eddce28696 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:41:14 +0100 Subject: [PATCH 20/84] fix(security): validate composePath and quote it in compose shell commands composePath went unquoted into cat (remote), double-quoted into the base64 write and, via the docker command, into the double-quoted log banner echo. Restrict it to a safe relative path and quote those sinks. --- packages/server/src/db/schema/compose.ts | 6 +++++- packages/server/src/utils/builders/compose.ts | 4 ++-- packages/server/src/utils/docker/domain.ts | 4 ++-- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/server/src/db/schema/compose.ts b/packages/server/src/db/schema/compose.ts index 445303fa121..8a9303f3e81 100644 --- a/packages/server/src/db/schema/compose.ts +++ b/packages/server/src/db/schema/compose.ts @@ -199,7 +199,11 @@ const createSchema = createInsertSchema(compose, { customGitSSHKeyId: z.string().optional(), command: z.string().optional(), createEnvFile: z.boolean().optional(), - composePath: z.string().min(1), + composePath: z + .string() + .min(1) + .regex(/^[a-zA-Z0-9._@+/][a-zA-Z0-9._@+/-]*$/, "Invalid compose path") + .refine((p) => !p.split("/").includes(".."), "Invalid compose path"), composeType: z.enum(["docker-compose", "stack"]).optional(), watchPaths: z.array(z.string()).optional(), sourceType: z diff --git a/packages/server/src/utils/builders/compose.ts b/packages/server/src/utils/builders/compose.ts index d81eecf0a49..6092a574147 100644 --- a/packages/server/src/utils/builders/compose.ts +++ b/packages/server/src/utils/builders/compose.ts @@ -53,13 +53,13 @@ Compose Type: ${composeType} ✅`; const bashCommand = ` set -e { - echo "${logBox}"; + echo ${quote([logBox])}; ${newCompose} ${envCommand} - cd "${projectPath}"; + cd ${quote([projectPath])}; ${compose.isolatedDeployment ? `docker network inspect ${compose.appName} >/dev/null 2>&1 || docker network create ${compose.composeType === "stack" ? "--driver overlay" : ""} --attachable ${compose.appName}` : ""} env -i PATH="$PATH" HOME="$HOME" ${exportEnvCommand} docker ${command.split(" ").join(" ")} 2>&1 || { echo "Error: ❌ Docker command failed"; exit 1; } diff --git a/packages/server/src/utils/docker/domain.ts b/packages/server/src/utils/docker/domain.ts index 846d9ac3c01..b338c33d304 100644 --- a/packages/server/src/utils/docker/domain.ts +++ b/packages/server/src/utils/docker/domain.ts @@ -87,7 +87,7 @@ export const loadDockerComposeRemote = async ( } const { stdout, stderr } = await execAsyncRemote( compose.serverId, - `cat ${path}`, + `cat ${quote([path])}`, ); if (stderr) { @@ -130,7 +130,7 @@ exit 1; const composeString = stringify(composeConverted, { lineWidth: 1000 }); const encodedContent = encodeBase64(composeString); - return `echo "${encodedContent}" | base64 -d > "${path}";`; + return `echo "${encodedContent}" | base64 -d > ${quote([path])};`; } catch (error) { const message = error instanceof Error ? error.message : String(error ?? ""); From e9910d76f0dbfdded052f5c2320045ca707a1e08 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:44:52 +0100 Subject: [PATCH 21/84] fix(security): stop returning the web server SSH key from getWebServerSettings Any authenticated user could read the host SSH private key and the metrics token. The key is never returned now, and the metrics token is only returned to owners and admins. --- apps/dokploy/server/api/routers/settings.ts | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/dokploy/server/api/routers/settings.ts b/apps/dokploy/server/api/routers/settings.ts index b1a1372c974..ef9b75fd093 100644 --- a/apps/dokploy/server/api/routers/settings.ts +++ b/apps/dokploy/server/api/routers/settings.ts @@ -124,12 +124,26 @@ const traefikUpdateLocks = new Map(); const traefikUpdateErrors = new Map(); export const settingsRouter = createTRPCRouter({ - getWebServerSettings: protectedProcedure.query(async () => { + getWebServerSettings: protectedProcedure.query(async ({ ctx }) => { if (IS_CLOUD) { return null; } - const settings = await getWebServerSettings(); - return settings; + const current = await getWebServerSettings(); + if (!current) { + return current; + } + const { sshPrivateKey: _, ...settings } = current; + if (ctx.user.role === "owner" || ctx.user.role === "admin") { + return settings; + } + const { metricsConfig } = settings; + return { + ...settings, + metricsConfig: { + ...metricsConfig, + server: { ...metricsConfig.server, token: "" }, + }, + }; }), reloadServer: adminProcedure.mutation(async ({ ctx }) => { if (IS_CLOUD) { From 4e7c2801af120a4ff9e93b21ca47f51c71386ade Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:47:09 +0100 Subject: [PATCH 22/84] fix(security): restrict user.update to profile fields apiUpdateUser was the full partial insert schema, so a user could set server-managed columns on their own row (stripeCustomerId, serversQuantity, banned, role, ...). Only accept what the profile form sends. --- packages/server/src/db/schema/user.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/server/src/db/schema/user.ts b/packages/server/src/db/schema/user.ts index 375b7097b72..ea72cea748b 100644 --- a/packages/server/src/db/schema/user.ts +++ b/packages/server/src/db/schema/user.ts @@ -232,7 +232,9 @@ export const apiReadStatsLogs = z.object({ .optional(), }); -export const apiUpdateUser = createSchema.partial().extend({ +export const apiUpdateUser = z.object({ + image: z.string().nullable().optional(), + allowImpersonation: z.boolean().optional(), email: z .string() .email("Please enter a valid email address") From 4db8c9b79a06ab01569a25895c66afcc53883bfb Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:57:14 +0100 Subject: [PATCH 23/84] fix(security): block moving projects, environments and services across organizations project.update accepted organizationId, environment.update accepted projectId and the service update schemas accepted environmentId; move never checked targetEnvironmentId; project.duplicate cloned any service id. Narrow the update schemas, check the target environment's org (and member access) in every move, and authorize each service before duplicating it. --- apps/dokploy/server/api/routers/application.ts | 2 ++ apps/dokploy/server/api/routers/compose.ts | 2 ++ apps/dokploy/server/api/routers/libsql.ts | 2 ++ apps/dokploy/server/api/routers/mariadb.ts | 2 ++ apps/dokploy/server/api/routers/mongo.ts | 2 ++ apps/dokploy/server/api/routers/mysql.ts | 2 ++ apps/dokploy/server/api/routers/postgres.ts | 2 ++ apps/dokploy/server/api/routers/project.ts | 9 +++++++++ apps/dokploy/server/api/routers/redis.ts | 2 ++ packages/server/src/db/schema/application.ts | 2 +- packages/server/src/db/schema/compose.ts | 2 +- packages/server/src/db/schema/environment.ts | 1 - packages/server/src/db/schema/libsql.ts | 2 +- packages/server/src/db/schema/mariadb.ts | 2 +- packages/server/src/db/schema/mongo.ts | 2 +- packages/server/src/db/schema/mysql.ts | 2 +- packages/server/src/db/schema/postgres.ts | 2 +- packages/server/src/db/schema/project.ts | 5 ++++- packages/server/src/db/schema/redis.ts | 2 +- packages/server/src/services/permission.ts | 15 +++++++++++++++ 20 files changed, 52 insertions(+), 10 deletions(-) diff --git a/apps/dokploy/server/api/routers/application.ts b/apps/dokploy/server/api/routers/application.ts index 79f02936038..2cc305946cc 100644 --- a/apps/dokploy/server/api/routers/application.ts +++ b/apps/dokploy/server/api/routers/application.ts @@ -37,6 +37,7 @@ import { db } from "@dokploy/server/db"; import { canEditDeployGitSource } from "@dokploy/server/services/git-provider"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -1007,6 +1008,7 @@ export const applicationRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/compose.ts b/apps/dokploy/server/api/routers/compose.ts index 7c9591f1ab2..42a40dee4fc 100644 --- a/apps/dokploy/server/api/routers/compose.ts +++ b/apps/dokploy/server/api/routers/compose.ts @@ -38,6 +38,7 @@ import { db } from "@dokploy/server/db"; import { canEditDeployGitSource } from "@dokploy/server/services/git-provider"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -781,6 +782,7 @@ export const composeRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.composeId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/libsql.ts b/apps/dokploy/server/api/routers/libsql.ts index 3fdfcf55b79..0616e491f30 100644 --- a/apps/dokploy/server/api/routers/libsql.ts +++ b/apps/dokploy/server/api/routers/libsql.ts @@ -21,6 +21,7 @@ import { } from "@dokploy/server"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, } from "@dokploy/server/services/permission"; @@ -429,6 +430,7 @@ export const libsqlRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.libsqlId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/mariadb.ts b/apps/dokploy/server/api/routers/mariadb.ts index 98932f8af68..33fae5ac6df 100644 --- a/apps/dokploy/server/api/routers/mariadb.ts +++ b/apps/dokploy/server/api/routers/mariadb.ts @@ -26,6 +26,7 @@ import { import { db } from "@dokploy/server/db"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -456,6 +457,7 @@ export const mariadbRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.mariadbId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/mongo.ts b/apps/dokploy/server/api/routers/mongo.ts index 42b4107856d..69a6c62cd0c 100644 --- a/apps/dokploy/server/api/routers/mongo.ts +++ b/apps/dokploy/server/api/routers/mongo.ts @@ -26,6 +26,7 @@ import { import { db } from "@dokploy/server/db"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -471,6 +472,7 @@ export const mongoRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.mongoId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/mysql.ts b/apps/dokploy/server/api/routers/mysql.ts index c315ec5d452..c88410bf88d 100644 --- a/apps/dokploy/server/api/routers/mysql.ts +++ b/apps/dokploy/server/api/routers/mysql.ts @@ -26,6 +26,7 @@ import { import { db } from "@dokploy/server/db"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -474,6 +475,7 @@ export const mysqlRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.mysqlId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/postgres.ts b/apps/dokploy/server/api/routers/postgres.ts index 97e39812358..607819a2c2a 100644 --- a/apps/dokploy/server/api/routers/postgres.ts +++ b/apps/dokploy/server/api/routers/postgres.ts @@ -27,6 +27,7 @@ import { import { db } from "@dokploy/server/db"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -477,6 +478,7 @@ export const postgresRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.postgresId, { service: ["create"], }); diff --git a/apps/dokploy/server/api/routers/project.ts b/apps/dokploy/server/api/routers/project.ts index 7085b3bef3d..52013c26529 100644 --- a/apps/dokploy/server/api/routers/project.ts +++ b/apps/dokploy/server/api/routers/project.ts @@ -37,6 +37,7 @@ import { addNewProject, checkPermission, checkProjectAccess, + checkServicePermissionAndAccess, findMemberByUserId, } from "@dokploy/server/services/permission"; import { serviceColumns } from "@dokploy/server/services/project"; @@ -868,6 +869,14 @@ export const projectRouter = createTRPCRouter({ try { await checkProjectAccess(ctx, "create"); + if (input.includeServices) { + for (const service of input.selectedServices || []) { + await checkServicePermissionAndAccess(ctx, service.id, { + service: ["read"], + }); + } + } + const sourceEnvironment = input.duplicateInSameProject ? await findEnvironmentById(input.sourceEnvironmentId) : null; diff --git a/apps/dokploy/server/api/routers/redis.ts b/apps/dokploy/server/api/routers/redis.ts index fb0d8301ccf..c63e65f16e9 100644 --- a/apps/dokploy/server/api/routers/redis.ts +++ b/apps/dokploy/server/api/routers/redis.ts @@ -25,6 +25,7 @@ import { import { db } from "@dokploy/server/db"; import { addNewService, + checkEnvironmentAccess, checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, @@ -458,6 +459,7 @@ export const redisRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await checkEnvironmentAccess(ctx, input.targetEnvironmentId, "read"); await checkServicePermissionAndAccess(ctx, input.redisId, { service: ["create"], }); diff --git a/packages/server/src/db/schema/application.ts b/packages/server/src/db/schema/application.ts index def6c344544..df75a995816 100644 --- a/packages/server/src/db/schema/application.ts +++ b/packages/server/src/db/schema/application.ts @@ -551,4 +551,4 @@ export const apiUpdateApplication = createSchema .extend({ applicationId: z.string().min(1), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); diff --git a/packages/server/src/db/schema/compose.ts b/packages/server/src/db/schema/compose.ts index 445303fa121..5aeb836ecbf 100644 --- a/packages/server/src/db/schema/compose.ts +++ b/packages/server/src/db/schema/compose.ts @@ -278,7 +278,7 @@ export const apiUpdateCompose = createSchema composeFile: z.string().optional(), command: z.string().optional(), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiSaveEnvironmentVariablesCompose = createSchema .pick({ diff --git a/packages/server/src/db/schema/environment.ts b/packages/server/src/db/schema/environment.ts index f8b38c087d2..07fbc1f5b3b 100644 --- a/packages/server/src/db/schema/environment.ts +++ b/packages/server/src/db/schema/environment.ts @@ -66,7 +66,6 @@ export const apiUpdateEnvironment = z.object({ environmentId: z.string().min(1), name: z.string().min(1).optional(), description: z.string().optional(), - projectId: z.string().optional(), env: z.string().optional(), }); diff --git a/packages/server/src/db/schema/libsql.ts b/packages/server/src/db/schema/libsql.ts index 9658ad93a23..4e3a81e77a4 100644 --- a/packages/server/src/db/schema/libsql.ts +++ b/packages/server/src/db/schema/libsql.ts @@ -248,7 +248,7 @@ export const apiUpdateLibsql = createSchema .extend({ libsqlId: z.string().min(1), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiRebuildLibsql = createSchema .pick({ diff --git a/packages/server/src/db/schema/mariadb.ts b/packages/server/src/db/schema/mariadb.ts index 48b48f5b633..63abe84a87f 100644 --- a/packages/server/src/db/schema/mariadb.ts +++ b/packages/server/src/db/schema/mariadb.ts @@ -220,7 +220,7 @@ export const apiUpdateMariaDB = createSchema mariadbId: z.string().min(1), dockerImage: z.string().optional(), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiRebuildMariadb = createSchema .pick({ diff --git a/packages/server/src/db/schema/mongo.ts b/packages/server/src/db/schema/mongo.ts index 5e91a72d128..35c1c7cf18b 100644 --- a/packages/server/src/db/schema/mongo.ts +++ b/packages/server/src/db/schema/mongo.ts @@ -204,7 +204,7 @@ export const apiUpdateMongo = createSchema dockerImage: z.string().optional(), replicaSets: z.boolean().optional(), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiResetMongo = createSchema .pick({ diff --git a/packages/server/src/db/schema/mysql.ts b/packages/server/src/db/schema/mysql.ts index 3a58f5aad2d..ef70bbff7c2 100644 --- a/packages/server/src/db/schema/mysql.ts +++ b/packages/server/src/db/schema/mysql.ts @@ -217,7 +217,7 @@ export const apiUpdateMySql = createSchema mysqlId: z.string().min(1), dockerImage: z.string().optional(), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiRebuildMysql = createSchema .pick({ diff --git a/packages/server/src/db/schema/postgres.ts b/packages/server/src/db/schema/postgres.ts index 067b83e43b3..b4d72c55e66 100644 --- a/packages/server/src/db/schema/postgres.ts +++ b/packages/server/src/db/schema/postgres.ts @@ -211,7 +211,7 @@ export const apiUpdatePostgres = createSchema postgresId: z.string().min(1), dockerImage: z.string().optional(), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiRebuildPostgres = createSchema .pick({ diff --git a/packages/server/src/db/schema/project.ts b/packages/server/src/db/schema/project.ts index 907bf70dd9d..1910e273ad1 100644 --- a/packages/server/src/db/schema/project.ts +++ b/packages/server/src/db/schema/project.ts @@ -65,7 +65,10 @@ export const apiRemoveProject = createSchema // }) // .required(); -export const apiUpdateProject = createSchema.partial().extend({ +export const apiUpdateProject = z.object({ projectId: z.string().min(1), + name: z.string().min(1).optional(), + description: z.string().nullable().optional(), + env: z.string().optional(), }); // .omit({ serverId: true }); diff --git a/packages/server/src/db/schema/redis.ts b/packages/server/src/db/schema/redis.ts index 95ffd8503e8..d8d8274383c 100644 --- a/packages/server/src/db/schema/redis.ts +++ b/packages/server/src/db/schema/redis.ts @@ -198,7 +198,7 @@ export const apiUpdateRedis = createSchema redisId: z.string().min(1), dockerImage: z.string().optional(), }) - .omit({ serverId: true }); + .omit({ serverId: true, environmentId: true }); export const apiRebuildRedis = createSchema .pick({ diff --git a/packages/server/src/services/permission.ts b/packages/server/src/services/permission.ts index b756221b28c..7492458c385 100644 --- a/packages/server/src/services/permission.ts +++ b/packages/server/src/services/permission.ts @@ -266,9 +266,19 @@ const findProjectOrganizationId = async (projectId: string) => { return project?.organizationId; }; +const findEnvironmentOrganizationId = async (environmentId: string) => { + const [row] = await db + .select({ organizationId: projects.organizationId }) + .from(environments) + .innerJoin(projects, eq(environments.projectId, projects.projectId)) + .where(eq(environments.environmentId, environmentId)); + return row?.organizationId; +}; + const notFoundMessages = { service: "Service not found", project: "Project not found", + environment: "Environment not found", }; const assertOrganizationOwns = ( @@ -402,6 +412,11 @@ export const checkEnvironmentAccess = async ( const organizationId = ctx.session.activeOrganizationId; const memberRecord = await findMemberByUserId(userId, organizationId); + assertOrganizationOwns( + ctx, + "environment", + await findEnvironmentOrganizationId(environmentId), + ); await checkPermission(ctx, { environment: [action] }); if ( From 8db4cc5a6e0de954720da9059a146eddbc1a0d4c Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 12:59:30 +0100 Subject: [PATCH 24/84] fix(security): only allow attaching SSH keys from the caller's organization to servers server.create and server.update stored any sshKeyId without checking which organization owns the key. --- apps/dokploy/server/api/routers/server.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/apps/dokploy/server/api/routers/server.ts b/apps/dokploy/server/api/routers/server.ts index 3d49bc89fcb..cfbc3c55740 100644 --- a/apps/dokploy/server/api/routers/server.ts +++ b/apps/dokploy/server/api/routers/server.ts @@ -28,6 +28,7 @@ import { hasPermission, } from "@dokploy/server/services/permission"; import { hasValidLicense } from "@dokploy/server/services/proprietary/license-key"; +import { findSSHKeyById } from "@dokploy/server/services/ssh-key"; import { TRPCError } from "@trpc/server"; import { observable } from "@trpc/server/observable"; import { and, desc, eq, getTableColumns, isNotNull, sql } from "drizzle-orm"; @@ -74,6 +75,20 @@ const toServerOptions = async ( })); }; +const assertSshKeyInOrganization = async ( + sshKeyId: string | null | undefined, + organizationId: string, +) => { + if (!sshKeyId) return; + const sshKey = await findSSHKeyById(sshKeyId); + if (sshKey.organizationId !== organizationId) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to use this SSH key", + }); + } +}; + export const serverRouter = createTRPCRouter({ create: withPermission("server", "create") .input(apiCreateServer) @@ -87,6 +102,10 @@ export const serverRouter = createTRPCRouter({ message: "You cannot create more servers", }); } + await assertSshKeyInOrganization( + input.sshKeyId, + ctx.session.activeOrganizationId, + ); const project = await createServer( input, ctx.session.activeOrganizationId, @@ -559,6 +578,10 @@ export const serverRouter = createTRPCRouter({ message: "Server is inactive", }); } + await assertSshKeyInOrganization( + input.sshKeyId, + ctx.session.activeOrganizationId, + ); const currentServer = await updateServerById(input.serverId, { ...input, }); From 257cf1a7d2d16c09b7d2829c33b7776d4ade0ea8 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:11:14 +0100 Subject: [PATCH 25/84] fix(security): authorize every deployment type in deployment router and bind compose.readLogs killProcess, removeDeployment and readLogs only checked application and compose deployments; backup, volume backup, preview and schedule deployments had no check. Reuse the owner resolution from listen-deployment (now a shared helper), require owner/admin for serviceless deployments, only kill running deployments, and make compose.readLogs verify the container belongs to the compose. --- apps/dokploy/server/api/routers/compose.ts | 13 ++++ apps/dokploy/server/api/routers/deployment.ts | 61 +++++---------- .../server/api/utils/deployment-access.ts | 70 +++++++++++++++++ apps/dokploy/server/wss/listen-deployment.ts | 54 ++----------- packages/server/src/services/deployment.ts | 78 +++++++++++-------- 5 files changed, 155 insertions(+), 121 deletions(-) create mode 100644 apps/dokploy/server/api/utils/deployment-access.ts diff --git a/apps/dokploy/server/api/routers/compose.ts b/apps/dokploy/server/api/routers/compose.ts index 7c9591f1ab2..c8e327e9843 100644 --- a/apps/dokploy/server/api/routers/compose.ts +++ b/apps/dokploy/server/api/routers/compose.ts @@ -78,6 +78,7 @@ import { myQueue, } from "@/server/queues/queueSetup"; import { cancelDeployment, deploy } from "@/server/utils/deploy"; +import { containerBelongsToService } from "@/server/wss/container-ownership"; import { generatePassword } from "@/templates/utils"; import { createTRPCRouter, protectedProcedure } from "../trpc"; import { audit } from "../utils/audit"; @@ -1246,6 +1247,18 @@ export const composeRouter = createTRPCRouter({ message: "You are not authorized to access this compose", }); } + if ( + !(await containerBelongsToService( + input.composeId, + input.containerId, + compose.serverId, + )) + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "Container does not belong to this compose", + }); + } return await getContainerLogs( input.containerId, input.tail, diff --git a/apps/dokploy/server/api/routers/deployment.ts b/apps/dokploy/server/api/routers/deployment.ts index f2b47097d38..34c578aff2d 100644 --- a/apps/dokploy/server/api/routers/deployment.ts +++ b/apps/dokploy/server/api/routers/deployment.ts @@ -7,6 +7,7 @@ import { findAllDeploymentsCentralized, findBackupById, findDeploymentById, + findDeploymentOwnerById, findPreviewDeploymentById, findScheduleById, findVolumeBackupById, @@ -27,6 +28,7 @@ import { TRPCError } from "@trpc/server"; import { desc, eq } from "drizzle-orm"; import { z } from "zod"; import { audit } from "@/server/api/utils/audit"; +import { assertDeploymentAccess } from "@/server/api/utils/deployment-access"; import { apiFindAllByApplication, apiFindAllByCompose, @@ -209,23 +211,14 @@ export const deploymentRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertDeploymentAccess( + ctx, + await findDeploymentOwnerById(input.deploymentId), + "cancel", + ); const deployment = await findDeploymentById(input.deploymentId); - const serviceId = deployment.applicationId || deployment.composeId; - if (serviceId) { - await checkServicePermissionAndAccess(ctx, serviceId, { - deployment: ["cancel"], - }); - } else if (deployment.schedule?.serverId) { - const targetServer = await findServerById(deployment.schedule.serverId); - if (targetServer.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You don't have access to this deployment.", - }); - } - } - if (!deployment.pid) { + if (!deployment.pid || deployment.status !== "running") { throw new TRPCError({ code: "BAD_REQUEST", message: "Deployment is not running", @@ -254,21 +247,12 @@ export const deploymentRouter = createTRPCRouter({ }), ) .mutation(async ({ input, ctx }) => { + await assertDeploymentAccess( + ctx, + await findDeploymentOwnerById(input.deploymentId), + "cancel", + ); const deployment = await findDeploymentById(input.deploymentId); - const serviceId = deployment.applicationId || deployment.composeId; - if (serviceId) { - await checkServicePermissionAndAccess(ctx, serviceId, { - deployment: ["cancel"], - }); - } else if (deployment.schedule?.serverId) { - const targetServer = await findServerById(deployment.schedule.serverId); - if (targetServer.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You don't have access to this deployment.", - }); - } - } const result = await removeDeployment(input.deploymentId); await audit(ctx, { action: "delete", @@ -286,21 +270,12 @@ export const deploymentRouter = createTRPCRouter({ }), ) .query(async ({ input, ctx }) => { + await assertDeploymentAccess( + ctx, + await findDeploymentOwnerById(input.deploymentId), + "read", + ); const deployment = await findDeploymentById(input.deploymentId); - const serviceId = deployment.applicationId || deployment.composeId; - if (serviceId) { - await checkServicePermissionAndAccess(ctx, serviceId, { - deployment: ["read"], - }); - } else if (deployment.schedule?.serverId) { - const targetServer = await findServerById(deployment.schedule.serverId); - if (targetServer.organizationId !== ctx.session.activeOrganizationId) { - throw new TRPCError({ - code: "UNAUTHORIZED", - message: "You don't have access to this deployment.", - }); - } - } if (!deployment.logPath) { return ""; diff --git a/apps/dokploy/server/api/utils/deployment-access.ts b/apps/dokploy/server/api/utils/deployment-access.ts new file mode 100644 index 00000000000..9d8d1a191b9 --- /dev/null +++ b/apps/dokploy/server/api/utils/deployment-access.ts @@ -0,0 +1,70 @@ +import type { DeploymentOwner } from "@dokploy/server/services/deployment"; +import { + checkServicePermissionAndAccess, + findMemberByUserId, +} from "@dokploy/server/services/permission"; +import { TRPCError } from "@trpc/server"; + +type Ctx = Parameters[0]; + +const getOwningServiceId = (deployment: DeploymentOwner) => { + const { backup, volumeBackup, schedule } = deployment; + return ( + deployment.applicationId ?? + deployment.composeId ?? + deployment.previewDeployment?.applicationId ?? + schedule?.applicationId ?? + schedule?.composeId ?? + backup?.postgresId ?? + backup?.mysqlId ?? + backup?.mariadbId ?? + backup?.mongoId ?? + backup?.libsqlId ?? + backup?.composeId ?? + volumeBackup?.applicationId ?? + volumeBackup?.postgresId ?? + volumeBackup?.mysqlId ?? + volumeBackup?.mariadbId ?? + volumeBackup?.mongoId ?? + volumeBackup?.redisId ?? + volumeBackup?.libsqlId ?? + volumeBackup?.composeId ?? + null + ); +}; + +export const assertDeploymentAccess = async ( + ctx: Ctx, + deployment: DeploymentOwner | undefined, + action: "read" | "cancel", +) => { + if (!deployment) { + throw new TRPCError({ code: "NOT_FOUND", message: "Deployment not found" }); + } + const serviceId = getOwningServiceId(deployment); + if (serviceId) { + await checkServicePermissionAndAccess(ctx, serviceId, { + deployment: [action], + }); + return; + } + const organizationId = + deployment.server?.organizationId ?? + deployment.schedule?.server?.organizationId ?? + deployment.schedule?.organizationId ?? + deployment.backup?.destination?.organizationId ?? + null; + const member = await findMemberByUserId( + ctx.user.id, + ctx.session.activeOrganizationId, + ); + if ( + organizationId !== ctx.session.activeOrganizationId || + (member.role !== "owner" && member.role !== "admin") + ) { + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "You don't have access to this deployment.", + }); + } +}; diff --git a/apps/dokploy/server/wss/listen-deployment.ts b/apps/dokploy/server/wss/listen-deployment.ts index b29cc334939..ca753c976f0 100644 --- a/apps/dokploy/server/wss/listen-deployment.ts +++ b/apps/dokploy/server/wss/listen-deployment.ts @@ -6,11 +6,11 @@ import { IS_CLOUD, validateRequest, } from "@dokploy/server"; -import { checkServicePermissionAndAccess } from "@dokploy/server/services/permission"; import { encodeBase64 } from "@dokploy/server/utils/docker/utils"; import { readValidDirectory } from "@dokploy/server/wss/utils"; import { Client } from "ssh2"; import { WebSocketServer } from "ws"; +import { assertDeploymentAccess } from "../api/utils/deployment-access"; export const setupDeploymentLogsWebSocketServer = ( server: http.Server, @@ -63,55 +63,15 @@ export const setupDeploymentLogsWebSocketServer = ( } try { - const deployment = await findDeploymentByLogPath(logPath); - if (!deployment) { - ws.close(4003, "Not authorized"); - return; - } const ctxLike = { user: { id: user.id }, session: { activeOrganizationId: session.activeOrganizationId }, - } as Parameters[0]; - - const { backup, volumeBackup, schedule } = deployment; - const serviceId = - deployment.applicationId ?? - deployment.composeId ?? - deployment.previewDeployment?.applicationId ?? - schedule?.applicationId ?? - schedule?.composeId ?? - backup?.postgresId ?? - backup?.mysqlId ?? - backup?.mariadbId ?? - backup?.mongoId ?? - backup?.libsqlId ?? - backup?.composeId ?? - (volumeBackup && - (volumeBackup.applicationId ?? - volumeBackup.postgresId ?? - volumeBackup.mysqlId ?? - volumeBackup.mariadbId ?? - volumeBackup.mongoId ?? - volumeBackup.redisId ?? - volumeBackup.libsqlId ?? - volumeBackup.composeId)) ?? - null; - - if (serviceId) { - await checkServicePermissionAndAccess(ctxLike, serviceId, { - deployment: ["read"], - }); - } else { - const org = - deployment.server?.organizationId ?? - schedule?.organizationId ?? - backup?.destination?.organizationId ?? - null; - if (!org || org !== session.activeOrganizationId) { - ws.close(4003, "Not authorized"); - return; - } - } + } as Parameters[0]; + await assertDeploymentAccess( + ctxLike, + await findDeploymentByLogPath(logPath), + "read", + ); } catch { ws.close(4003, "Not authorized"); return; diff --git a/packages/server/src/services/deployment.ts b/packages/server/src/services/deployment.ts index 06c94af171a..6111a9f26af 100644 --- a/packages/server/src/services/deployment.ts +++ b/packages/server/src/services/deployment.ts @@ -1107,39 +1107,55 @@ export const clearOldDeployments = async ( } }; -export const findDeploymentByLogPath = async (logPath: string) => { - return db.query.deployments.findFirst({ - where: (fields, { eq }) => eq(fields.logPath, logPath), - columns: { applicationId: true, composeId: true }, - with: { - server: { columns: { organizationId: true } }, - schedule: { - columns: { organizationId: true, applicationId: true, composeId: true }, - }, - previewDeployment: { columns: { applicationId: true } }, - backup: { - columns: { - postgresId: true, - mysqlId: true, - mariadbId: true, - mongoId: true, - libsqlId: true, - composeId: true, - }, - with: { destination: { columns: { organizationId: true } } }, +const deploymentOwnerQuery = { + columns: { applicationId: true, composeId: true }, + with: { + server: { columns: { organizationId: true } }, + schedule: { + columns: { organizationId: true, applicationId: true, composeId: true }, + with: { server: { columns: { organizationId: true } } }, + }, + previewDeployment: { columns: { applicationId: true } }, + backup: { + columns: { + postgresId: true, + mysqlId: true, + mariadbId: true, + mongoId: true, + libsqlId: true, + composeId: true, }, - volumeBackup: { - columns: { - applicationId: true, - postgresId: true, - mysqlId: true, - mariadbId: true, - mongoId: true, - redisId: true, - libsqlId: true, - composeId: true, - }, + with: { destination: { columns: { organizationId: true } } }, + }, + volumeBackup: { + columns: { + applicationId: true, + postgresId: true, + mysqlId: true, + mariadbId: true, + mongoId: true, + redisId: true, + libsqlId: true, + composeId: true, }, }, + }, +} as const; + +export const findDeploymentByLogPath = async (logPath: string) => { + return db.query.deployments.findFirst({ + where: (fields, { eq }) => eq(fields.logPath, logPath), + ...deploymentOwnerQuery, }); }; + +export const findDeploymentOwnerById = async (deploymentId: string) => { + return db.query.deployments.findFirst({ + where: (fields, { eq }) => eq(fields.deploymentId, deploymentId), + ...deploymentOwnerQuery, + }); +}; + +export type DeploymentOwner = NonNullable< + Awaited> +>; From f83c771b3f033f0c82b94d90261205d7b76a10d9 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:13:30 +0100 Subject: [PATCH 26/84] fix(security): validate domain path and internalPath Both were free-form strings interpolated into the Traefik PathPrefix rule. Require a leading '/' and reject spaces and backticks. --- packages/server/src/db/validations/domain.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/server/src/db/validations/domain.ts b/packages/server/src/db/validations/domain.ts index 059e3cae25a..76b9a638cce 100644 --- a/packages/server/src/db/validations/domain.ts +++ b/packages/server/src/db/validations/domain.ts @@ -4,6 +4,13 @@ import { VALID_HOSTNAME_REGEX, } from "../../utils/hostname-validation"; +const domainPath = z + .string() + .regex( + /^(\/[^`\s]*)?$/, + "Path must start with '/' and cannot contain spaces or backticks", + ); + export const domain = z .object({ host: z @@ -16,8 +23,8 @@ export const domain = z .refine((val) => VALID_HOSTNAME_REGEX.test(val), { message: INVALID_HOSTNAME_MESSAGE, }), - path: z.string().min(1).optional(), - internalPath: z.string().optional(), + path: domainPath.min(1).optional(), + internalPath: domainPath.optional(), stripPath: z.boolean().optional(), port: z .number() @@ -82,8 +89,8 @@ export const domainCompose = z .refine((val) => VALID_HOSTNAME_REGEX.test(val), { message: INVALID_HOSTNAME_MESSAGE, }), - path: z.string().min(1).optional(), - internalPath: z.string().optional(), + path: domainPath.min(1).optional(), + internalPath: domainPath.optional(), stripPath: z.boolean().optional(), port: z .number() From 55b109db6ff1f5f2e62b7b4dbf941060ffa1d3f6 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:16:10 +0100 Subject: [PATCH 27/84] fix(security): only owners and admins can create or edit bind mounts Any member with volume access to one service could bind-mount an arbitrary host path (e.g. /) into it and get root on the host. --- apps/dokploy/server/api/routers/mount.ts | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/apps/dokploy/server/api/routers/mount.ts b/apps/dokploy/server/api/routers/mount.ts index 55c7696a7d0..3b9ca60ba59 100644 --- a/apps/dokploy/server/api/routers/mount.ts +++ b/apps/dokploy/server/api/routers/mount.ts @@ -19,6 +19,7 @@ import type { ServiceType } from "@dokploy/server/db/schema/mount"; import { checkServiceAccess, checkServicePermissionAndAccess, + findMemberByUserId, } from "@dokploy/server/services/permission"; import { TRPCError } from "@trpc/server"; import { z } from "zod"; @@ -74,6 +75,24 @@ async function getServiceOrganizationId( } } +const assertCanUseBindMount = async ( + ctx: { user: { id: string }; session: { activeOrganizationId: string } }, + type: string | null | undefined, + hostPath: string | null | undefined, +) => { + if (type !== "bind" && !hostPath) return; + const member = await findMemberByUserId( + ctx.user.id, + ctx.session.activeOrganizationId, + ); + if (member.role !== "owner" && member.role !== "admin") { + throw new TRPCError({ + code: "FORBIDDEN", + message: "Only owners and admins can manage bind mounts", + }); + } +}; + export const mountRouter = createTRPCRouter({ create: protectedProcedure .input(apiCreateMount) @@ -81,6 +100,7 @@ export const mountRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.serviceId, { volume: ["create"], }); + await assertCanUseBindMount(ctx, input.type, input.hostPath); const mount = await createMount(input); await audit(ctx, { action: "create", @@ -174,6 +194,11 @@ export const mountRouter = createTRPCRouter({ volume: ["create"], }); } + await assertCanUseBindMount( + ctx, + input.type ?? mount.type, + input.hostPath ?? mount.hostPath, + ); const { expectedContent, ...mountData } = input; if (mount.type === "file" && expectedContent !== undefined) { const currentContent = await readFileMountContent(input.mountId); From 0f31dcce92a3e89304f1b62a526dab16c86e8ac7 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:18:00 +0100 Subject: [PATCH 28/84] fix(security): stop mounts.update from re-pointing a mount at another service apiUpdateMount was the full partial insert schema, so applicationId, composeId, the database ids and serviceType could be changed while access was only checked against the mount's current service. --- packages/server/src/db/schema/mount.ts | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/server/src/db/schema/mount.ts b/packages/server/src/db/schema/mount.ts index e6cad1497be..0baa061124b 100644 --- a/packages/server/src/db/schema/mount.ts +++ b/packages/server/src/db/schema/mount.ts @@ -157,7 +157,17 @@ export const apiFindMountByApplicationId = z.object({ serviceId: z.string().min(1), }); -export const apiUpdateMount = createSchema.partial().extend({ - mountId: z.string().min(1), - expectedContent: z.string().nullable().optional(), -}); +export const apiUpdateMount = createSchema + .pick({ + type: true, + hostPath: true, + volumeName: true, + content: true, + mountPath: true, + filePath: true, + }) + .partial() + .extend({ + mountId: z.string().min(1), + expectedContent: z.string().nullable().optional(), + }); From 1959dac79efac913ddd384f48711907c78fb8ac6 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:23:42 +0100 Subject: [PATCH 29/84] fix(security): stop returning SSH private keys from sshKey.all, and from sshKey.one to non-admins Any role with sshKeys:read received every private key of the organization. The list never needs it; the edit form still gets it for owners and admins. --- apps/dokploy/server/api/routers/ssh-key.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/apps/dokploy/server/api/routers/ssh-key.ts b/apps/dokploy/server/api/routers/ssh-key.ts index aa758a0ea3f..949925f3055 100644 --- a/apps/dokploy/server/api/routers/ssh-key.ts +++ b/apps/dokploy/server/api/routers/ssh-key.ts @@ -79,10 +79,14 @@ export const sshRouter = createTRPCRouter({ message: "You are not allowed to access this SSH key", }); } + if (ctx.user.role !== "owner" && ctx.user.role !== "admin") { + return { ...sshKey, privateKey: "" }; + } return sshKey; }), all: withPermission("sshKeys", "read").query(async ({ ctx }) => { return await db.query.sshKeys.findMany({ + columns: { privateKey: false }, where: eq(sshKeys.organizationId, ctx.session.activeOrganizationId), orderBy: desc(sshKeys.createdAt), }); From 29c6cb9936949bca4c31c4dda99eb0329fd9c3f1 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:25:37 +0100 Subject: [PATCH 30/84] fix(security): do not return rollback fullContext in deployment lists The rollback snapshot includes registry credentials and was sent with every deployment list to anyone with deployment:read. --- apps/dokploy/server/api/routers/deployment.ts | 2 +- packages/server/src/services/deployment.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/dokploy/server/api/routers/deployment.ts b/apps/dokploy/server/api/routers/deployment.ts index f2b47097d38..84f68031e7c 100644 --- a/apps/dokploy/server/api/routers/deployment.ts +++ b/apps/dokploy/server/api/routers/deployment.ts @@ -197,7 +197,7 @@ export const deploymentRouter = createTRPCRouter({ where: eq(deployments[`${input.type}Id`], input.id), orderBy: desc(deployments.createdAt), with: { - rollback: true, + rollback: { columns: { fullContext: false } }, }, }); return deploymentsList; diff --git a/packages/server/src/services/deployment.ts b/packages/server/src/services/deployment.ts index 06c94af171a..7bda6ad6b24 100644 --- a/packages/server/src/services/deployment.ts +++ b/packages/server/src/services/deployment.ts @@ -675,7 +675,7 @@ const getDeploymentsByType = async ( where: eq(deployments[`${type}Id`], id), orderBy: desc(deployments.createdAt), with: { - rollback: true, + rollback: { columns: { fullContext: false } }, }, }); return deploymentList; From c6db58435a91c0d70e6279609b5941de40cf5acc Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:31:06 +0100 Subject: [PATCH 31/84] fix(security): hide docker registry password and webhook token from roles that cannot use them application.one returned the Docker-source registry password to anyone with read access, and application.one / compose.one returned the deploy webhook refreshToken even to roles without deployment:create. --- apps/dokploy/server/api/routers/application.ts | 6 ++++++ apps/dokploy/server/api/routers/compose.ts | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/apps/dokploy/server/api/routers/application.ts b/apps/dokploy/server/api/routers/application.ts index 79f02936038..bcb9e9d29dd 100644 --- a/apps/dokploy/server/api/routers/application.ts +++ b/apps/dokploy/server/api/routers/application.ts @@ -40,7 +40,9 @@ import { checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, + hasPermission, } from "@dokploy/server/services/permission"; + import { TRPCError } from "@trpc/server"; import { and, desc, eq, ilike, or, sql } from "drizzle-orm"; import { nanoid } from "nanoid"; @@ -298,8 +300,12 @@ export const applicationRouter = createTRPCRouter({ } } + const canEdit = await hasPermission(ctx, { service: ["create"] }); + const canDeploy = await hasPermission(ctx, { deployment: ["create"] }); return { ...application, + password: canEdit ? application.password : null, + refreshToken: canDeploy ? application.refreshToken : null, hasGitProviderAccess, unauthorizedProvider, }; diff --git a/apps/dokploy/server/api/routers/compose.ts b/apps/dokploy/server/api/routers/compose.ts index 7c9591f1ab2..604078b6cb4 100644 --- a/apps/dokploy/server/api/routers/compose.ts +++ b/apps/dokploy/server/api/routers/compose.ts @@ -41,7 +41,9 @@ import { checkServiceAccess, checkServicePermissionAndAccess, findMemberByUserId, + hasPermission, } from "@dokploy/server/services/permission"; + import { type CompleteTemplate, fetchTemplateFiles, @@ -184,8 +186,10 @@ export const composeRouter = createTRPCRouter({ } } + const canDeploy = await hasPermission(ctx, { deployment: ["create"] }); return { ...compose, + refreshToken: canDeploy ? compose.refreshToken : null, hasGitProviderAccess, unauthorizedProvider, }; From 3d0c60ebda40e08de1e93d3c052919836074aff5 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:36:31 +0100 Subject: [PATCH 32/84] fix(security): check notification organization on every update, not only on cloud updateGotify/Ntfy/Mattermost/Lark/Teams/Pushover skipped the org check on self-hosted, so an owner/admin of another organization could edit (and move into their org) any notification by id. --- .../server/api/routers/notification.ts | 31 ++++--------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/apps/dokploy/server/api/routers/notification.ts b/apps/dokploy/server/api/routers/notification.ts index 47b5b786a8a..6c8aa9773f4 100644 --- a/apps/dokploy/server/api/routers/notification.ts +++ b/apps/dokploy/server/api/routers/notification.ts @@ -13,7 +13,6 @@ import { createTelegramNotification, findNotificationById, getWebServerSettings, - IS_CLOUD, removeNotificationById, sendCustomNotification, sendDiscordNotification, @@ -603,10 +602,7 @@ export const notificationRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { try { const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { + if (notification.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized to update this notification", @@ -674,10 +670,7 @@ export const notificationRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { try { const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { + if (notification.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized to update this notification", @@ -753,10 +746,7 @@ export const notificationRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { try { const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { + if (notification.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized to update this notification", @@ -892,10 +882,7 @@ export const notificationRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { try { const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { + if (notification.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized to update this notification", @@ -964,10 +951,7 @@ export const notificationRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { try { const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { + if (notification.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized to update this notification", @@ -1037,10 +1021,7 @@ export const notificationRouter = createTRPCRouter({ .mutation(async ({ input, ctx }) => { try { const notification = await findNotificationById(input.notificationId); - if ( - IS_CLOUD && - notification.organizationId !== ctx.session.activeOrganizationId - ) { + if (notification.organizationId !== ctx.session.activeOrganizationId) { throw new TRPCError({ code: "UNAUTHORIZED", message: "You are not authorized to update this notification", From 2b40ff0cea901bdeaca3aa6a44a72cabf2742ac8 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:39:34 +0100 Subject: [PATCH 33/84] fix(security): require re-entering vault credentials when connection settings change Echoing the "********" mask restored the stored secret even when the caller changed the URL/endpoint, so the secret was sent to a caller-chosen host on update or testConnection. --- .../server/src/services/vault-provider.ts | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/server/src/services/vault-provider.ts b/packages/server/src/services/vault-provider.ts index 6bd7dfa1209..803a5705ca8 100644 --- a/packages/server/src/services/vault-provider.ts +++ b/packages/server/src/services/vault-provider.ts @@ -44,7 +44,10 @@ export const mergeVaultProviderConfig = ( existing: VaultProviderConfig, ): VaultProviderConfig => { const merged: Record = { ...incoming }; - for (const field of SENSITIVE_FIELDS[incoming.providerType]) { + const previous = existing as Record; + const sensitive = SENSITIVE_FIELDS[incoming.providerType]; + let restored = false; + for (const field of sensitive) { if (merged[field] === VAULT_SECRET_MASK) { if (incoming.providerType !== existing.providerType) { throw new TRPCError({ @@ -53,7 +56,24 @@ export const mergeVaultProviderConfig = ( "Credentials must be re-entered when changing the provider type", }); } - merged[field] = (existing as Record)[field]; + merged[field] = previous[field]; + restored = true; + } + } + if (restored) { + const keys = new Set([...Object.keys(merged), ...Object.keys(previous)]); + for (const key of keys) { + if (sensitive.includes(key)) continue; + if ( + JSON.stringify(merged[key] ?? null) !== + JSON.stringify(previous[key] ?? null) + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: + "Credentials must be re-entered when changing the connection settings", + }); + } } } return merged as VaultProviderConfig; From f2c2e3448aa8277388c84e7220694ef18637e05f Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:47:00 +0100 Subject: [PATCH 34/84] fix(security): verify git provider, SSH key and registry ids belong to the caller's organization application save*Provider / update and compose.update stored githubId, gitlabId, bitbucketId, giteaId, customGitSSHKeyId and the registry ids without checking who owns them, letting a service clone or push with another organization's credentials. --- .../application/provider-status.test.ts | 1 + .../dokploy/server/api/routers/application.ts | 7 +++ apps/dokploy/server/api/routers/compose.ts | 2 + packages/server/src/index.ts | 1 + .../src/services/service-credentials.ts | 63 +++++++++++++++++++ 5 files changed, 74 insertions(+) create mode 100644 packages/server/src/services/service-credentials.ts diff --git a/apps/dokploy/__test__/application/provider-status.test.ts b/apps/dokploy/__test__/application/provider-status.test.ts index 427b6e6ddc1..5a9e9813b02 100644 --- a/apps/dokploy/__test__/application/provider-status.test.ts +++ b/apps/dokploy/__test__/application/provider-status.test.ts @@ -12,6 +12,7 @@ vi.mock("@dokploy/server/index", () => ({ IS_CLOUD: true, hasValidLicense: vi.fn(async () => false), updateApplication: mockUpdateApplication, + assertServiceCredentialAccess: vi.fn(async () => {}), findApplicationById: vi.fn(async () => ({ applicationId: "app-1", appName: "example-app", diff --git a/apps/dokploy/server/api/routers/application.ts b/apps/dokploy/server/api/routers/application.ts index 79f02936038..b6cf0785ec0 100644 --- a/apps/dokploy/server/api/routers/application.ts +++ b/apps/dokploy/server/api/routers/application.ts @@ -1,4 +1,5 @@ import { + assertServiceCredentialAccess, clearOldDeployments, createApplication, createDomain, @@ -539,6 +540,7 @@ export const applicationRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); await updateApplication(input.applicationId, { repository: input.repository, branch: input.branch, @@ -565,6 +567,7 @@ export const applicationRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); await updateApplication(input.applicationId, { gitlabRepository: input.gitlabRepository, gitlabOwner: input.gitlabOwner, @@ -592,6 +595,7 @@ export const applicationRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); await updateApplication(input.applicationId, { bitbucketRepository: input.bitbucketRepository, bitbucketRepositorySlug: input.bitbucketRepositorySlug, @@ -618,6 +622,7 @@ export const applicationRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); await updateApplication(input.applicationId, { giteaRepository: input.giteaRepository, giteaOwner: input.giteaOwner, @@ -665,6 +670,7 @@ export const applicationRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); await updateApplication(input.applicationId, { customGitBranch: input.customGitBranch, customGitBuildPath: input.customGitBuildPath, @@ -756,6 +762,7 @@ export const applicationRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.applicationId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); if (input.buildServerId) { const accessibleIds = await getAccessibleServerIds(ctx.session); diff --git a/apps/dokploy/server/api/routers/compose.ts b/apps/dokploy/server/api/routers/compose.ts index 7c9591f1ab2..85cfd98b1a6 100644 --- a/apps/dokploy/server/api/routers/compose.ts +++ b/apps/dokploy/server/api/routers/compose.ts @@ -1,6 +1,7 @@ import { join } from "node:path"; import { addDomainToCompose, + assertServiceCredentialAccess, clearOldDeployments, cloneCompose, createCommand, @@ -197,6 +198,7 @@ export const composeRouter = createTRPCRouter({ await checkServicePermissionAndAccess(ctx, input.composeId, { service: ["create"], }); + await assertServiceCredentialAccess(ctx.session, input); const updated = await updateCompose(input.composeId, input); await audit(ctx, { action: "update", diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index f642b26bd4a..af44ad1cc19 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -60,6 +60,7 @@ export * from "./services/security"; export * from "./services/server"; export * from "./services/server-health"; export * from "./services/server-security"; +export * from "./services/service-credentials"; export * from "./services/settings"; export * from "./services/ssh-key"; export * from "./services/transfer"; diff --git a/packages/server/src/services/service-credentials.ts b/packages/server/src/services/service-credentials.ts new file mode 100644 index 00000000000..04d6338ee1d --- /dev/null +++ b/packages/server/src/services/service-credentials.ts @@ -0,0 +1,63 @@ +import { TRPCError } from "@trpc/server"; +import { findBitbucketById } from "./bitbucket"; +import { assertGitProviderAccess } from "./git-provider"; +import { findGiteaById } from "./gitea"; +import { findGithubById } from "./github"; +import { findGitlabById } from "./gitlab"; +import { findRegistryById } from "./registry"; +import { findSSHKeyById } from "./ssh-key"; + +type CredentialIds = { + githubId?: string | null; + gitlabId?: string | null; + bitbucketId?: string | null; + giteaId?: string | null; + customGitSSHKeyId?: string | null; + registryId?: string | null; + buildRegistryId?: string | null; + rollbackRegistryId?: string | null; +}; + +const forbidden = () => + new TRPCError({ + code: "UNAUTHORIZED", + message: "You are not authorized to use this credential", + }); + +export const assertServiceCredentialAccess = async ( + session: { userId: string; activeOrganizationId: string }, + input: CredentialIds, +) => { + const providers = [ + input.githubId && (await findGithubById(input.githubId)).gitProvider, + input.gitlabId && (await findGitlabById(input.gitlabId)).gitProvider, + input.bitbucketId && + (await findBitbucketById(input.bitbucketId)).gitProvider, + input.giteaId && (await findGiteaById(input.giteaId)).gitProvider, + ]; + for (const provider of providers) { + if (provider) { + await assertGitProviderAccess(session, provider); + } + } + + if (input.customGitSSHKeyId) { + const sshKey = await findSSHKeyById(input.customGitSSHKeyId); + if (sshKey.organizationId !== session.activeOrganizationId) { + throw forbidden(); + } + } + + for (const registryId of [ + input.registryId, + input.buildRegistryId, + input.rollbackRegistryId, + ]) { + if (registryId) { + const registry = await findRegistryById(registryId); + if (registry.organizationId !== session.activeOrganizationId) { + throw forbidden(); + } + } + } +}; From f0f26c78070dfe8f66b0500426bbcc3d562f1c3b Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:48:41 +0100 Subject: [PATCH 35/84] fix(security): validate appName on the docker stats websocket appName is used to build the monitoring stats path on disk; a value with '/' or '..' could create directories and write files outside it. --- apps/dokploy/server/wss/docker-stats.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/dokploy/server/wss/docker-stats.ts b/apps/dokploy/server/wss/docker-stats.ts index e86b5e691b2..ef164e8b75b 100644 --- a/apps/dokploy/server/wss/docker-stats.ts +++ b/apps/dokploy/server/wss/docker-stats.ts @@ -102,6 +102,14 @@ export const setupDockerStatsMonitoringSocketServer = ( return; } + if ( + !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(appName) || + appName.includes("..") + ) { + ws.close(4000, "Invalid appName"); + return; + } + if (!user || !session) { ws.close(); return; From fb140a9552ad1df362fcca5cea31471a057cf3f3 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:53:01 +0100 Subject: [PATCH 36/84] fix(security): require volume backups to target a volume owned by their service volumeBackups.create/update accepted any volumeName on a service the caller could access, so a member could back up (and later restore over) volumes of other services, including Dokploy's own database. --- .../server/api/routers/volume-backups.ts | 63 +++++++++++++++++-- .../server/src/services/volume-backups.ts | 54 ++++++++++++++++ 2 files changed, 111 insertions(+), 6 deletions(-) diff --git a/apps/dokploy/server/api/routers/volume-backups.ts b/apps/dokploy/server/api/routers/volume-backups.ts index 36606fe2235..f82765a54b2 100644 --- a/apps/dokploy/server/api/routers/volume-backups.ts +++ b/apps/dokploy/server/api/routers/volume-backups.ts @@ -1,4 +1,5 @@ import { + assertVolumeBelongsToService, createVolumeBackup, findServiceOwningVolume, findVolumeBackupById, @@ -98,11 +99,21 @@ export const volumeBackupsRouter = createTRPCRouter({ ] as const ).find((type) => input[`${type}Id`]); const serviceId = serviceType ? input[`${serviceType}Id`] : undefined; - if (serviceId) { - await checkServicePermissionAndAccess(ctx, serviceId, { - volumeBackup: ["create"], + if (!serviceType || !serviceId) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "A service is required for a volume backup", }); } + await checkServicePermissionAndAccess(ctx, serviceId, { + volumeBackup: ["create"], + }); + await assertVolumeBelongsToService({ + serviceType, + serviceId, + volumeName: input.volumeName, + serviceName: input.serviceName, + }); await findDestinationByIdForOrganization( input.destinationId, ctx.session.activeOrganizationId, @@ -203,9 +214,49 @@ export const volumeBackupsRouter = createTRPCRouter({ existingVb.redisId || existingVb.libsqlId || existingVb.composeId; - if (serviceId) { - await checkServicePermissionAndAccess(ctx, serviceId, { - volumeBackup: ["update"], + const serviceTypes = [ + "application", + "postgres", + "mysql", + "mariadb", + "mongo", + "redis", + "libsql", + "compose", + ] as const; + const serviceType = serviceTypes.find((type) => existingVb[`${type}Id`]); + if (!serviceType || !serviceId) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Volume backup is not attached to a service", + }); + } + if ( + serviceTypes.some( + (type) => + input[`${type}Id`] !== undefined && + input[`${type}Id`] !== existingVb[`${type}Id`], + ) + ) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "A volume backup cannot be moved to another service", + }); + } + await checkServicePermissionAndAccess(ctx, serviceId, { + volumeBackup: ["update"], + }); + const volumeName = input.volumeName ?? existingVb.volumeName; + const serviceName = input.serviceName ?? existingVb.serviceName; + if ( + volumeName !== existingVb.volumeName || + serviceName !== existingVb.serviceName + ) { + await assertVolumeBelongsToService({ + serviceType, + serviceId, + volumeName, + serviceName, }); } await findDestinationByIdForOrganization( diff --git a/packages/server/src/services/volume-backups.ts b/packages/server/src/services/volume-backups.ts index 0d4ec5f14ab..a54be2331bf 100644 --- a/packages/server/src/services/volume-backups.ts +++ b/packages/server/src/services/volume-backups.ts @@ -7,6 +7,8 @@ import { type updateVolumeBackupSchema, volumeBackups, } from "../db/schema"; +import { mounts } from "../db/schema/mount"; +import { getComposeContainer } from "../utils/docker/utils"; import { findApplicationById } from "./application"; import { findComposeById } from "./compose"; @@ -177,3 +179,55 @@ export const findServiceOwningVolume = async ( } return service; }; + +type VolumeServiceType = + | "application" + | "postgres" + | "mysql" + | "mariadb" + | "mongo" + | "redis" + | "libsql" + | "compose"; + +export const assertVolumeBelongsToService = async ({ + serviceType, + serviceId, + volumeName, + serviceName, +}: { + serviceType: VolumeServiceType; + serviceId: string; + volumeName: string; + serviceName?: string | null; +}) => { + const mounted = await db.query.mounts.findFirst({ + where: and( + eq(mounts[`${serviceType}Id`], serviceId), + eq(mounts.type, "volume"), + eq(mounts.volumeName, volumeName), + ), + columns: { mountId: true }, + }); + if (mounted) return; + + if (serviceType === "compose") { + const compose = await findComposeById(serviceId); + if (volumeName.startsWith(`${compose.appName}_`)) return; + if (serviceName) { + const container = await getComposeContainer(compose, serviceName); + if ( + container?.Mounts.some( + (mount) => mount.Type === "volume" && mount.Name === volumeName, + ) + ) { + return; + } + } + } + + throw new TRPCError({ + code: "UNAUTHORIZED", + message: "This volume does not belong to the service.", + }); +}; From 7037e451ccfecb3d68898865b161549bd6c3f386 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:55:34 +0100 Subject: [PATCH 37/84] test: mock assertVolumeBelongsToService in volume backup destination tests --- .../backups/volume-backup-destination-organization.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts b/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts index 78cd5e2422b..f0d316bf024 100644 --- a/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts +++ b/apps/dokploy/__test__/backups/volume-backup-destination-organization.test.ts @@ -26,6 +26,7 @@ vi.mock("@dokploy/server", () => ({ removeVolumeBackup: vi.fn(), restoreVolume: vi.fn(), runVolumeBackup: vi.fn(), + assertVolumeBelongsToService: vi.fn(async () => {}), })); vi.mock("@dokploy/server/lib/auth", () => ({ From 30dd59691c84e2d4b852d3eff3100328741ea152 Mon Sep 17 00:00:00 2001 From: Mauricio Siu Date: Sat, 7 Nov 2026 13:58:26 +0100 Subject: [PATCH 38/84] fix(security): escape every '<' in whitelabeling customCss The single-pass removal could be bypassed by nesting the tag (le>), breaking out of the style block. CSS-escape '<' instead so the block can never be closed. --- apps/dokploy/pages/_document.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/dokploy/pages/_document.tsx b/apps/dokploy/pages/_document.tsx index 5e6b6948be3..096070fb804 100644 --- a/apps/dokploy/pages/_document.tsx +++ b/apps/dokploy/pages/_document.tsx @@ -127,9 +127,9 @@ Document.getInitialProps = async ( appName = config.appName; appDescription = config.appDescription; ogImageUrl = config.ogImageUrl; - // Remove any tags to prevent XSS breakout + // A raw "<" could close the