From 36d09d64c53ba1195d991e5e8bebed0f48fd0ed8 Mon Sep 17 00:00:00 2001 From: Peter Gonda Date: Tue, 20 Oct 2026 13:48:19 +0200 Subject: [PATCH] nomad: read remote git compose over SSH; compose ${VAR:?} / nested defaults MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - getBuildNomadCommand: for a git-sourced compose on a remote server, read the cloned compose file over SSH instead of the stored snapshot (always "" for git sources → "No services found in compose file"). Clear error naming the compose path + server when the file is missing/empty. - substituteEnvVars: add ${VAR:?msg} / ${VAR?msg} (fail the deploy) and nested defaults like ${A:-${B}}; existing forms unchanged. --- .../nomad/nomad-env-substitution.test.ts | 51 +++++++++++ .../nomad/nomad-remote-compose.test.ts | 57 ++++++++++++ .../server/src/utils/builders/nomad-parser.ts | 86 +++++++++++++++---- packages/server/src/utils/builders/nomad.ts | 26 +++++- 4 files changed, 199 insertions(+), 21 deletions(-) create mode 100644 apps/dokploy/__test__/nomad/nomad-env-substitution.test.ts create mode 100644 apps/dokploy/__test__/nomad/nomad-remote-compose.test.ts diff --git a/apps/dokploy/__test__/nomad/nomad-env-substitution.test.ts b/apps/dokploy/__test__/nomad/nomad-env-substitution.test.ts new file mode 100644 index 000000000..58e8df241 --- /dev/null +++ b/apps/dokploy/__test__/nomad/nomad-env-substitution.test.ts @@ -0,0 +1,51 @@ +import { parseComposeToNomadServices } from "@nomploy/server/utils/builders/nomad-parser"; +import { describe, expect, it } from "vitest"; + +// Compose interpolation happens on the raw YAML before parsing; assert through the +// parsed service env so we test what actually reaches the Nomad job. +const envOf = (value: string, vars: Record) => { + const compose = `services:\n web:\n image: nginx\n environment:\n V: "${value}"\n`; + return parseComposeToNomadServices(compose, vars)[0]?.env.V; +}; + +describe("nomad parser — compose variable interpolation", () => { + it("keeps the existing ${VAR}, $VAR and default forms", () => { + expect(envOf("${A}", { A: "x" })).toBe("x"); + expect(envOf("$A-suffix", { A: "x" })).toBe("x-suffix"); + expect(envOf("${A}", {})).toBe(""); + expect(envOf("${A:-d}", { A: "" })).toBe("d"); + expect(envOf("${A-d}", { A: "" })).toBe(""); + expect(envOf("${A-d}", {})).toBe("d"); + expect(envOf("${A:-d}", { A: "x" })).toBe("x"); + }); + + it("resolves nested defaults inner-first", () => { + expect(envOf("${A:-${B}}", { B: "b" })).toBe("b"); + expect(envOf("${A:-${B:-c}}", {})).toBe("c"); + expect(envOf("${A:-${B:-c}}", { A: "a", B: "b" })).toBe("a"); + expect(envOf("${A:-pre-${B}-post}", { B: "b" })).toBe("pre-b-post"); + }); + + it("${VAR:?msg} fails when unset or empty", () => { + expect(() => envOf("${A:?A is required}", {})).toThrow( + "Required variable A is missing a value: A is required", + ); + expect(() => envOf("${A:?A is required}", { A: "" })).toThrow( + "A is required", + ); + expect(envOf("${A:?A is required}", { A: "x" })).toBe("x"); + }); + + it("${VAR?msg} fails only when unset", () => { + expect(() => envOf("${A?need A}", {})).toThrow("need A"); + expect(envOf("${A?need A}", { A: "" })).toBe(""); + expect(envOf("${A?}", { A: "x" })).toBe("x"); + expect(() => envOf("${A?}", {})).toThrow( + "Required variable A is missing a value", + ); + }); + + it("leaves non-variable ${…} text alone", () => { + expect(envOf("${}", {})).toBe("${}"); + }); +}); diff --git a/apps/dokploy/__test__/nomad/nomad-remote-compose.test.ts b/apps/dokploy/__test__/nomad/nomad-remote-compose.test.ts new file mode 100644 index 000000000..4533c602d --- /dev/null +++ b/apps/dokploy/__test__/nomad/nomad-remote-compose.test.ts @@ -0,0 +1,57 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +// A git-sourced compose on a REMOTE server: the clone lives on that server, so the +// builder must read the compose file over SSH (execAsyncRemote) instead of the +// stored composeFile snapshot (which is "" for git sources). +const execAsyncRemote = vi.fn(); +vi.mock("@nomploy/server/utils/process/execAsync", () => ({ + execAsync: vi.fn(async () => ({ stdout: "", stderr: "" })), + execAsyncRemote: (serverId: string, command: string) => + execAsyncRemote(serverId, command), +})); + +import { getBuildNomadCommand } from "@nomploy/server/utils/builders/nomad"; + +const compose = { + appName: "starring", + serverId: "srv-1", + sourceType: "github", + composePath: "./docker-compose.dokploy.yml", + composeFile: "", + env: "", + environment: { project: { env: "" }, env: null }, + mounts: [], + domains: [], +} as any; + +const decodeJob = (cmd: string) => { + const match = cmd.match(/echo "([A-Za-z0-9+/=]+)" \| base64 -d/); + return Buffer.from(match?.[1] ?? "", "base64").toString(); +}; + +describe("nomad builder — remote git compose", () => { + beforeEach(() => { + execAsyncRemote.mockReset(); + }); + + it("reads the cloned compose file from the remote server", async () => { + execAsyncRemote.mockResolvedValue({ + stdout: "services:\n web:\n image: ghcr.io/pipozzz/starring\n", + stderr: "", + }); + const cmd = await getBuildNomadCommand(compose); + const [serverId, command] = execAsyncRemote.mock.calls[0] ?? []; + expect(serverId).toBe("srv-1"); + expect(command).toMatch( + /^cat .*starring\/code\/docker-compose\.dokploy\.yml/, + ); + expect(decodeJob(cmd)).toContain("ghcr.io/pipozzz/starring"); + }); + + it("throws a clear error naming the path and server when unreadable", async () => { + execAsyncRemote.mockRejectedValue(new Error("No such file")); + await expect(getBuildNomadCommand(compose)).rejects.toThrow( + /docker-compose\.dokploy\.yml.*on server srv-1/, + ); + }); +}); diff --git a/packages/server/src/utils/builders/nomad-parser.ts b/packages/server/src/utils/builders/nomad-parser.ts index cdb5f426b..8a472bcd7 100644 --- a/packages/server/src/utils/builders/nomad-parser.ts +++ b/packages/server/src/utils/builders/nomad-parser.ts @@ -508,21 +508,73 @@ const substituteEnvVars = ( content: string, envVars: Record, ): string => { - // Supports `$VAR`, `${VAR}`, and the default forms `${VAR:-default}` (default - // when VAR is unset OR empty) and `${VAR-default}` (default only when unset) — - // a very common compose pattern (e.g. `TZ=${TZ:-UTC}`). The old regex captured - // the `:-default` suffix but the callback discarded it, substituting "" instead - // of the default — which broke apps that relied on it (an empty TZ made a cron - // library throw "invalid date" and crash the container on boot). - return content.replace( - /\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, - (_match, braced, op, defaultVal, bare) => { - const varName = braced || bare; - const val = envVars[varName]; - if (op === ":-") - return val !== undefined && val !== "" ? val : defaultVal; - if (op === "-") return val !== undefined ? val : defaultVal; - return val ?? ""; - }, - ); + // Supports `$VAR`, `${VAR}`, the default forms `${VAR:-default}` (default when + // VAR is unset OR empty) and `${VAR-default}` (default only when unset) — e.g. + // `TZ=${TZ:-UTC}` — and the required forms `${VAR:?msg}` (error when unset or + // empty) and `${VAR?msg}` (error only when unset), which fail the deploy with + // msg like docker compose does. The default/message is itself interpolated, so + // nested defaults such as `${A:-${B:-x}}` resolve. A scanner (not a regex) so the + // closing brace of a nested `${…}` doesn't end the outer one. + const bareVar = /\$([A-Za-z_][A-Za-z0-9_]*)/y; + let out = ""; + let i = 0; + while (i < content.length) { + if (content[i] !== "$") { + out += content[i++]; + continue; + } + if (content[i + 1] === "{") { + // Find the matching `}` (brace depth, so nested `${…}` stay inside). + let depth = 1; + let j = i + 2; + for (; j < content.length; j++) { + if (content[j] === "{") depth++; + else if (content[j] === "}" && --depth === 0) break; + } + if (depth > 0) { + // Unterminated `${` — leave the rest verbatim. + out += content.slice(i); + break; + } + const expr = content + .slice(i + 2, j) + .match(/^([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-?])([\s\S]*))?$/); + if (!expr?.[1]) { + // Not a variable reference (e.g. `${}`) — keep it literally. + out += content.slice(i, j + 1); + i = j + 1; + continue; + } + i = j + 1; + const [, name, op, arg = ""] = expr; + const val = envVars[name]; + const isSet = val !== undefined; + const isSetNonEmpty = isSet && val !== ""; + if (op === ":-" || op === "-") { + out += (op === ":-" ? isSetNonEmpty : isSet) + ? val + : substituteEnvVars(arg, envVars); + } else if (op === ":?" || op === "?") { + if (!(op === ":?" ? isSetNonEmpty : isSet)) { + const msg = substituteEnvVars(arg, envVars); + throw new Error( + `Required variable ${name} is missing a value${msg ? `: ${msg}` : ""}`, + ); + } + out += val; + } else { + out += val ?? ""; + } + continue; + } + bareVar.lastIndex = i; + const bare = bareVar.exec(content); + if (bare?.[1]) { + out += envVars[bare[1]] ?? ""; + i = bareVar.lastIndex; + } else { + out += content[i++]; + } + } + return out; }; diff --git a/packages/server/src/utils/builders/nomad.ts b/packages/server/src/utils/builders/nomad.ts index e9f9e62cc..ace903d0f 100644 --- a/packages/server/src/utils/builders/nomad.ts +++ b/packages/server/src/utils/builders/nomad.ts @@ -7,12 +7,14 @@ import { } from "@nomploy/server/services/cert-resolver"; import type { Domain } from "@nomploy/server/services/domain"; import type { InferResultType } from "@nomploy/server/types/with"; +import { quote } from "shell-quote"; import { CROWDSEC_MIDDLEWARE_REF, isCrowdsecPerServiceActive, } from "../../setup/crowdsec-flag"; import { allServers, readCluster } from "../../setup/nomad-mesh"; import { encodeBase64, getEnvironmentVariablesObject } from "../docker/utils"; +import { execAsyncRemote } from "../process/execAsync"; import { parseComposeToNomadServices } from "./nomad-parser"; export type NomadComposeNested = InferResultType< @@ -278,16 +280,32 @@ export const getBuildNomadCommand = async ( // of truth (edited in the panel). For a GIT source the real compose lives in the // freshly-cloned repo at composePath — the stored composeFile is a stale snapshot, // so a `git push` (e.g. removing a service) would otherwise never change the - // deployed job. Read the cloned file instead. (Control-plane deploys only; a remote - // server's clone isn't on this filesystem — fall back to the stored copy there.) + // deployed job. Read the cloned file instead — locally for control-plane deploys, + // over SSH for a remote server (its clone isn't on this filesystem, and the stored + // snapshot is never filled for git sources, so falling back to it parsed ""). const relComposePath = compose.sourceType === "raw" ? "docker-compose.yml" : compose.composePath || "docker-compose.yml"; let composeFile = compose.composeFile; - if (compose.sourceType !== "raw" && !compose.serverId) { + if (compose.sourceType !== "raw") { const clonedPath = join(projectPath, relComposePath); - if (existsSync(clonedPath)) composeFile = readFileSync(clonedPath, "utf8"); + if (compose.serverId) { + const { stdout } = await execAsyncRemote( + compose.serverId, + `cat ${quote([clonedPath])}`, + ).catch(() => ({ stdout: "" })); + if (stdout.trim()) composeFile = stdout; + } else if (existsSync(clonedPath)) { + composeFile = readFileSync(clonedPath, "utf8"); + } + if (!composeFile?.trim()) { + throw new Error( + `Compose file "${relComposePath}" not found or empty at ${clonedPath}` + + (compose.serverId ? ` on server ${compose.serverId}` : "") + + " — check the compose path and that the repository was cloned.", + ); + } } // Native Nomad jobspec passthrough: if the source is already a Nomad HCL job