Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(secret-sync): keep portainer git settings, skip unchanged writes and wait for redeploys
Yeongjin Lee2824f1fd4cc4
diff --git a/backend/src/services/secret-sync/portainer/portainer-sync-fns.test.ts b/backend/src/services/secret-sync/portainer/portainer-sync-fns.test.tsnew file mode 100644index 0000000000..3256450c15--- /dev/null+++ b/backend/src/services/secret-sync/portainer/portainer-sync-fns.test.ts@@ -0,0 +1,299 @@+/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-argument */+import { beforeEach, describe, expect, it, vi } from "vitest";++// `vi.mock` factories are hoisted above imports — the spies they reference must come from `vi.hoisted`.+const { safeRequestMock } = vi.hoisted(() => ({+ safeRequestMock: vi.fn()+}));++vi.mock("@app/lib/validator/safe-request", () => ({+ safeRequest: { request: (...args: unknown[]) => (safeRequestMock as any)(...args) },+ getSharedHttpsAgent: vi.fn()+}));+vi.mock("@app/lib/config/request", () => ({ request: { request: vi.fn() } }));+vi.mock("@app/lib/config/env", () => ({ getConfig: () => ({}) }));+vi.mock("@app/lib/logger", () => ({+ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() },+ sanitizeUrlForLog: (url: string) => url+}));+vi.mock("@app/lib/crypto", () => ({ crypto: {} }));+vi.mock("@app/lib/gateway-v2/types", () => ({ GatewayProxyProtocol: { Tcp: "tcp", Http: "http" } }));+vi.mock("@app/lib/gateway-v2/gateway-v2", () => ({ withGatewayV2Proxy: vi.fn() }));+vi.mock("@app/ee/services/dynamic-secret/dynamic-secret-fns", () => ({+ verifyHostInputValidity: vi.fn(async () => ["host"])+}));+vi.mock("@app/lib/delay", () => ({ delay: vi.fn(async () => {}) }));+// Without a key schema every variable on the stack counts as managed by the sync+vi.mock("@app/services/secret-sync/secret-sync-fns", () => ({+ matchesSchema: (_key: string, _environment: string, schema?: string) => !schema+}));++/* eslint-disable import/first */+import { PortainerStackStatus, PortainerStackType } from "@app/services/app-connection/portainer";++import { SecretSyncError } from "../secret-sync-errors";+import {+ areEnvVarsEqual,+ buildPortainerGitUpdatePayload,+ decodePortainerEnvValue,+ encodePortainerEnvValue,+ PortainerSyncFns+} from "./portainer-sync-fns";+/* eslint-enable import/first */++const gatewayV2Service = { getPlatformConnectionDetailsByGatewayId: vi.fn() };+const gatewayPoolService = { resolveEffectiveGatewayId: vi.fn() };++const secretSync = {+ connection: {+ credentials: { instanceUrl: "https://portainer.example.com", apiToken: "token" },+ gatewayId: null,+ gatewayPoolId: null+ },+ destinationConfig: { environmentId: 1, stackId: 4 },+ environment: { slug: "prod" },+ syncOptions: { disableSecretDeletion: false }+} as any;++const payloadOf = (secrets: Record<string, string>) => ({+ flatten: () => Object.fromEntries(Object.entries(secrets).map(([key, value]) => [key, { value }]))+});++const fileStack = (overrides: Record<string, unknown> = {}) => ({+ Id: 4,+ Name: "web",+ Type: PortainerStackType.Compose,+ EndpointId: 1,+ Status: PortainerStackStatus.Active,+ Env: [{ name: "A", value: "1" }],+ Option: { Prune: true },+ ...overrides+});++const gitStack = (overrides: Record<string, unknown> = {}) =>+ fileStack({+ WorkflowID: 7,+ GitSourceId: 3,+ GitConfig: { URL: "https://git.example.com/repo.git", ReferenceName: "refs/heads/main" },+ AutoUpdate: { Interval: "5m", Webhook: "" },+ ...overrides+ });++// Resolves each request by HTTP method and path; later entries for the same key answer later calls+const respondWith = (responses: Record<string, unknown[]>) => {+ const remaining = Object.fromEntries(Object.entries(responses).map(([key, values]) => [key, [...values]]));++ safeRequestMock.mockImplementation(async ({ method, url }: { method: string; url: string }) => {+ const key = `${method} ${new URL(url).pathname}`;+ const queue = remaining[key];+ if (!queue?.length) throw new Error(`Unexpected request ${key}`);++ return { data: queue.length > 1 ? queue.shift() : queue[0] };+ });+};++type TRequestConfig = { method: string; url: string; params?: Record<string, string>; data?: unknown };++const requestConfigs = () => safeRequestMock.mock.calls.map((call: any[]) => call[0] as TRequestConfig);++const requestsMade = () =>+ requestConfigs().map((config) => {+ const url = new URL(config.url);+ const query = new URLSearchParams(config.params).toString();+ return `${config.method} ${url.pathname}${query ? `?${query}` : ""}`;+ });++describe("encodePortainerEnvValue / decodePortainerEnvValue", () => {+ it("quotes and escapes a multiline value for a Compose stack", () => {+ const encoded = encodePortainerEnvValue('line1\nline2 "quoted" back\\slash\r\n', PortainerStackType.Compose);++ expect(encoded).toBe('"line1\\nline2 \\"quoted\\" back\\\\slash\\r\\n"');+ expect(decodePortainerEnvValue(encoded, PortainerStackType.Compose)).toBe('line1\nline2 "quoted" back\\slash\r\n');+ });++ it("leaves single-line values and Swarm stacks untouched", () => {+ expect(encodePortainerEnvValue("plain", PortainerStackType.Compose)).toBe("plain");+ expect(encodePortainerEnvValue("line1\nline2", PortainerStackType.Swarm)).toBe("line1\nline2");+ expect(decodePortainerEnvValue('"line1\\nline2"', PortainerStackType.Swarm)).toBe('"line1\\nline2"');+ });++ it("does not unwrap a single-line value a user quoted by hand", () => {+ expect(decodePortainerEnvValue('"hello"', PortainerStackType.Compose)).toBe('"hello"');+ expect(decodePortainerEnvValue('"C:\\\\new"', PortainerStackType.Compose)).toBe('"C:\\\\new"');+ });+});++describe("areEnvVarsEqual", () => {+ it("ignores order but not values or missing keys", () => {+ const current = [+ { name: "A", value: "1" },+ { name: "B", value: "2" }+ ];++ expect(+ areEnvVarsEqual(current, [+ { name: "B", value: "2" },+ { name: "A", value: "1" }+ ])+ ).toBe(true);+ expect(+ areEnvVarsEqual(current, [+ { name: "A", value: "1" },+ { name: "B", value: "changed" }+ ])+ ).toBe(false);+ expect(areEnvVarsEqual(current, [{ name: "A", value: "1" }])).toBe(false);+ });+});++describe("buildPortainerGitUpdatePayload", () => {+ it("references the Source and skips the deprecated repository fields when Portainer exposes one", () => {+ const payload = buildPortainerGitUpdatePayload(gitStack() as any, [{ name: "A", value: "1" }]);++ expect(payload).toEqual({+ env: [{ name: "A", value: "1" }],+ prune: true,+ repositoryReferenceName: "refs/heads/main",+ autoUpdate: { Interval: "5m", Webhook: "" },+ sourceID: 3+ });+ });++ it("echoes the stored authentication settings on releases without Sources so the credentials survive", () => {+ const stack = gitStack({+ WorkflowID: undefined,+ GitSourceId: undefined,+ GitConfig: {+ URL: "https://git.example.com/repo.git",+ ReferenceName: "refs/heads/main",+ TLSSkipVerify: true,+ Authentication: { Username: "deploy" }+ },+ AutoUpdate: { Interval: "", Webhook: "" },+ Option: null+ });++ expect(buildPortainerGitUpdatePayload(stack as any, [])).toEqual({+ env: [],+ prune: false,+ repositoryReferenceName: "refs/heads/main",+ autoUpdate: null,+ repositoryAuthentication: true,+ repositoryUsername: "deploy",+ tlsSkipVerify: true+ });+ });+});++describe("PortainerSyncFns", () => {+ beforeEach(() => {+ safeRequestMock.mockReset();+ });++ it("skips the update when the stack already holds the same variables", async () => {+ respondWith({+ "GET /api/stacks/4": [+ fileStack({+ Env: [+ { name: "A", value: "1" },+ { name: "B", value: "2" }+ ]+ })+ ]+ });++ await PortainerSyncFns.syncSecrets(+ secretSync,+ payloadOf({ B: "2", A: "1" }) as any,+ gatewayV2Service,+ gatewayPoolService+ );++ expect(requestsMade()).toEqual(["GET /api/stacks/4"]);+ });++ it("resubmits the compose file with the merged variables and waits for the redeploy to finish", async () => {+ respondWith({+ "GET /api/stacks/4": [+ fileStack(),+ fileStack({ Status: PortainerStackStatus.Deploying }),+ fileStack({ Status: PortainerStackStatus.Active })+ ],+ "GET /api/stacks/4/file": [{ StackFileContent: "services: {}" }],+ "PUT /api/stacks/4": [{}]+ });++ await PortainerSyncFns.syncSecrets(+ secretSync,+ payloadOf({ B: "x\ny" }) as any,+ gatewayV2Service,+ gatewayPoolService+ );++ expect(requestsMade()).toEqual([+ "GET /api/stacks/4",+ "GET /api/stacks/4/file",+ "PUT /api/stacks/4?endpointId=1",+ "GET /api/stacks/4",+ "GET /api/stacks/4"+ ]);++ const putConfig = requestConfigs().find((config) => config.method === "PUT");+ // A is managed by the sync (no key schema) and absent from the source, so it is dropped+ expect(putConfig?.data).toEqual({+ env: [{ name: "B", value: '"x\\ny"' }],+ stackFileContent: "services: {}",+ prune: true+ });+ });++ it("fails the sync when Portainer reports the redeploy failed", async () => {+ respondWith({+ "GET /api/stacks/4": [+ fileStack(),+ fileStack({+ Status: PortainerStackStatus.Error,+ DeploymentStatus: [{ Status: PortainerStackStatus.Error, Time: 1, Message: "image pull failed" }]+ })+ ],+ "GET /api/stacks/4/file": [{ StackFileContent: "services: {}" }],+ "PUT /api/stacks/4": [{}]+ });++ await expect(+ PortainerSyncFns.syncSecrets(secretSync, payloadOf({ A: "2" }) as any, gatewayV2Service, gatewayPoolService)+ ).rejects.toMatchObject({ message: expect.stringContaining("image pull failed"), shouldRetry: false });+ });++ it("updates a Git-backed stack through the git endpoint without touching the compose file", async () => {+ respondWith({+ "GET /api/stacks/4": [gitStack()],+ "POST /api/stacks/4/git": [{}]+ });++ await PortainerSyncFns.syncSecrets(secretSync, payloadOf({ A: "2" }) as any, gatewayV2Service, gatewayPoolService);++ expect(requestsMade()).toEqual(["GET /api/stacks/4", "POST /api/stacks/4/git?endpointId=1"]);+ });++ it("rejects a Kubernetes stack with a non-retryable error", async () => {+ respondWith({ "GET /api/stacks/4": [fileStack({ Type: PortainerStackType.Kubernetes })] });++ await expect(PortainerSyncFns.getSecrets(secretSync, gatewayV2Service, gatewayPoolService)).rejects.toMatchObject({+ name: "SecretSyncError",+ message: expect.stringContaining("Kubernetes stack"),+ shouldRetry: false+ });+ await expect(PortainerSyncFns.getSecrets(secretSync, gatewayV2Service, gatewayPoolService)).rejects.toBeInstanceOf(+ SecretSyncError+ );+ });++ it("decodes multiline Compose values on import", async () => {+ respondWith({ "GET /api/stacks/4": [fileStack({ Env: [{ name: "PEM", value: '"a\\nb"' }] })] });++ await expect(PortainerSyncFns.getSecrets(secretSync, gatewayV2Service, gatewayPoolService)).resolves.toEqual({+ PEM: { value: "a\nb" }+ });+ });+});diff --git a/backend/src/services/secret-sync/portainer/portainer-sync-fns.ts b/backend/src/services/secret-sync/portainer/portainer-sync-fns.tsindex e97be94c88..bf4bf5ae77 100644--- a/backend/src/services/secret-sync/portainer/portainer-sync-fns.ts+++ b/backend/src/services/secret-sync/portainer/portainer-sync-fns.ts@@ -1,41 +1,126 @@-import { safeRequest } from "@app/lib/validator";-import { getPortainerInstanceUrl, getPortainerRequestHeaders } from "@app/services/app-connection/portainer";+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";+import { delay } from "@app/lib/delay";+import { BadRequestError } from "@app/lib/errors";+import {+ getPortainerErrorMessage,+ isPortainerGitStack,+ portainerRequest,+ PortainerStackStatus,+ PortainerStackType,+ TPortainerEnvVar,+ TPortainerGatewayDeps,+ TPortainerStackResponse+} from "@app/services/app-connection/portainer";import { matchesSchema } from "@app/services/secret-sync/secret-sync-fns";import { SecretSyncError } from "../secret-sync-errors";import { TSecretSyncPayload } from "../secret-sync-payload";import { TSecretMap } from "../secret-sync-types";-import {- TPortainerEnvVar,- TPortainerStackFileResponse,- TPortainerStackResponse,- TPortainerSyncWithCredentials-} from "./portainer-sync-types";+import { TPortainerStackFileResponse, TPortainerSyncWithCredentials } from "./portainer-sync-types";-const getPortainerClientDetails = (secretSync: TPortainerSyncWithCredentials) => {- const { connection, destinationConfig } = secretSync;+const PORTAINER_DEPLOYMENT_POLL_INTERVAL_MS = 5_000;+const PORTAINER_DEPLOYMENT_TIMEOUT_MS = 10 * 60_000;+// Portainer releases before the background deployer run the redeploy inside the update request itself+const PORTAINER_STACK_UPDATE_TIMEOUT_MS = PORTAINER_DEPLOYMENT_TIMEOUT_MS;++const DOTENV_ESCAPES: Record<string, string> = { '"': '"', "\\": "\\", n: "\n", r: "\r" };++/**+ * Portainer writes a Compose stack's variables to a `stack.env` file one `NAME=VALUE` line at a time,+ * so a value with line breaks has to use the dotenv double-quoted form or the file stops parsing and+ * the redeploy fails. Swarm stacks receive their variables through the process environment, where+ * line breaks are fine as-is.+ */+export const encodePortainerEnvValue = (value: string, stackType: PortainerStackType) => {+ if (stackType !== PortainerStackType.Compose || !/[\r\n]/.test(value)) return value;++ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\r/g, "\\r").replace(/\n/g, "\\n");++ return `"${escaped}"`;+};++export const decodePortainerEnvValue = (value: string, stackType: PortainerStackType) => {+ if (stackType !== PortainerStackType.Compose) return value;+ if (value.length < 2 || !value.startsWith('"') || !value.endsWith('"')) return value;++ const decoded = value.slice(1, -1).replace(/\\(["\\nr])/g, (_, escape: string) => DOTENV_ESCAPES[escape]);++ // Only unwrap what the encoder above produces; a single-line value a user quoted by hand is left alone+ return /[\r\n]/.test(decoded) ? decoded : value;+};++const toSortedPairs = (env: TPortainerEnvVar[]) =>+ env+ .map(({ name, value }) => [name, value ?? ""] as const)+ .sort(([nameA, valueA], [nameB, valueB]) => nameA.localeCompare(nameB) || valueA.localeCompare(valueB));++export const areEnvVarsEqual = (current: TPortainerEnvVar[], next: TPortainerEnvVar[]) => {+ if (current.length !== next.length) return false;++ const currentPairs = toSortedPairs(current);+ const nextPairs = toSortedPairs(next);++ return currentPairs.every(([name, value], index) => name === nextPairs[index][0] && value === nextPairs[index][1]);+};++/**+ * The Git update endpoint replaces every setting it carries, so the stack's current settings are echoed+ * back alongside the new variables. On Portainer 2.45+ the repository URL and credentials live on a+ * Source and only its ID is needed; older releases wipe the stored credentials unless the+ * authentication flags are sent again.+ */+export const buildPortainerGitUpdatePayload = (+ stack: TPortainerStackResponse & { GitConfig: NonNullable<TPortainerStackResponse["GitConfig"]> },+ env: TPortainerEnvVar[]+) => {+ const { GitConfig: gitConfig, AutoUpdate: autoUpdate } = stack;+ const hasAutoUpdate = Boolean(autoUpdate?.Webhook || autoUpdate?.Interval);return {- instanceUrl: getPortainerInstanceUrl(connection),- headers: getPortainerRequestHeaders(connection.credentials.apiToken),- environmentId: destinationConfig.environmentId,- stackId: destinationConfig.stackId+ env,+ prune: stack.Option?.Prune ?? false,+ repositoryReferenceName: gitConfig.ReferenceName ?? "",+ autoUpdate: hasAutoUpdate ? autoUpdate : null,+ ...(stack.GitSourceId+ ? { sourceID: stack.GitSourceId }+ : {+ repositoryAuthentication: Boolean(gitConfig.Authentication),+ repositoryUsername: gitConfig.Authentication?.Username ?? "",+ tlsSkipVerify: gitConfig.TLSSkipVerify ?? false+ })};};-const getPortainerStack = async (secretSync: TPortainerSyncWithCredentials): Promise<TPortainerStackResponse> => {- const { instanceUrl, headers, environmentId, stackId } = getPortainerClientDetails(secretSync);+const getGatewayDeps = (+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">+): TPortainerGatewayDeps => ({ gatewayV2Service, gatewayPoolService });- let stack: TPortainerStackResponse;- try {- const { data } = await safeRequest.get<TPortainerStackResponse>(`${instanceUrl}/api/stacks/${stackId}`, {- headers- });+const toSyncError = (error: unknown, message: string) => {+ // A gateway that cannot be reached is a configuration problem a retry will not fix+ if (error instanceof BadRequestError) return new SecretSyncError({ message: error.message, shouldRetry: false });++ return new SecretSyncError({ error, message: `${message}: ${getPortainerErrorMessage(error, "unknown error")}` });+};++const fetchPortainerStack = async (secretSync: TPortainerSyncWithCredentials, deps: TPortainerGatewayDeps) => {+ const { connection, destinationConfig } = secretSync;- stack = data;+ try {+ return await portainerRequest<TPortainerStackResponse>(+ connection,+ { method: "GET", path: `/stacks/${destinationConfig.stackId}` },+ deps+ );} catch (error) {- throw new SecretSyncError({ error });+ throw toSyncError(error, `Failed to read Portainer stack with ID '${destinationConfig.stackId}'`);}+};++const getPortainerStack = async (secretSync: TPortainerSyncWithCredentials, deps: TPortainerGatewayDeps) => {+ const { environmentId, stackId } = secretSync.destinationConfig;+ const stack = await fetchPortainerStack(secretSync, deps);if (stack.EndpointId !== environmentId) {throw new SecretSyncError({@@ -44,75 +129,186 @@ const getPortainerStack = async (secretSync: TPortainerSyncWithCredentials): Pro});}+ if (stack.Type === PortainerStackType.Kubernetes) {+ throw new SecretSyncError({+ message: `Stack '${stack.Name}' is a Kubernetes stack. Portainer does not apply environment variables to Kubernetes stacks, so Infisical cannot sync to it. Choose a Compose or Swarm stack instead.`,+ shouldRetry: false+ });+ }+return stack;};-/**- * Stack environment variables are stored as a single list, so every write replaces the whole- * list. Git-backed stacks store it without redeploying; file-based stacks require the compose- * file on every update and redeploy as a result.- */-const writeStackEnv = async (+const waitForPortainerDeployment = async (secretSync: TPortainerSyncWithCredentials,stack: TPortainerStackResponse,- env: TPortainerEnvVar[]+ deps: TPortainerGatewayDeps) => {- const { instanceUrl, headers, environmentId, stackId } = getPortainerClientDetails(secretSync);+ const deadline = Date.now() + PORTAINER_DEPLOYMENT_TIMEOUT_MS;+ let current = stack;- try {- if (stack.GitConfig?.URL) {- // The Git settings are replaced wholesale, so the existing reference and auto-update config are echoed back- await safeRequest.post(- `${instanceUrl}/api/stacks/${stackId}/git?endpointId=${environmentId}`,- {- env,- repositoryReferenceName: stack.GitConfig.ReferenceName,- autoUpdate: stack.AutoUpdate ?? null,- prune: false- },- { headers }- );-- return;+ while (current.Status === PortainerStackStatus.Deploying) {+ if (Date.now() >= deadline) {+ throw new SecretSyncError({+ message: `Portainer is still deploying stack '${stack.Name}' after ${PORTAINER_DEPLOYMENT_TIMEOUT_MS / 60_000} minutes. Check the stack in Portainer, then sync again.`,+ shouldRetry: false+ });}- const { data } = await safeRequest.get<TPortainerStackFileResponse>(`${instanceUrl}/api/stacks/${stackId}/file`, {- headers+ // eslint-disable-next-line no-await-in-loop+ await delay(PORTAINER_DEPLOYMENT_POLL_INTERVAL_MS);+ // eslint-disable-next-line no-await-in-loop+ current = await fetchPortainerStack(secretSync, deps);+ }++ return current;+};++// Portainer answers a stack update with 409 while a deployment is in flight, so wait for it to settle first+const getSettledPortainerStack = async (secretSync: TPortainerSyncWithCredentials, deps: TPortainerGatewayDeps) => {+ const stack = await getPortainerStack(secretSync, deps);++ return waitForPortainerDeployment(secretSync, stack, deps);+};++const writeGitStackEnv = async (+ secretSync: TPortainerSyncWithCredentials,+ stack: TPortainerStackResponse,+ env: TPortainerEnvVar[],+ deps: TPortainerGatewayDeps+) => {+ const { connection, destinationConfig } = secretSync;++ if (!stack.GitConfig) {+ throw new SecretSyncError({+ message: `Infisical could not read the Git settings of stack '${stack.Name}'. Make sure the API token's user can access the stack's Git source in Portainer.`,+ shouldRetry: false});+ }- await safeRequest.put(- `${instanceUrl}/api/stacks/${stackId}?endpointId=${environmentId}`,+ try {+ await portainerRequest(+ connection,{- env,- stackFileContent: data.StackFileContent,- prune: false,- pullImage: false+ method: "POST",+ path: `/stacks/${destinationConfig.stackId}/git`,+ params: { endpointId: String(destinationConfig.environmentId) },+ data: buildPortainerGitUpdatePayload({ ...stack, GitConfig: stack.GitConfig }, env)},- { headers }+ deps);} catch (error) {- throw new SecretSyncError({ error });+ throw toSyncError(error, `Failed to update the variables of Portainer stack '${stack.Name}'`);}};-const toEnvVars = (secretMap: TSecretMap): TPortainerEnvVar[] =>- Object.entries(secretMap).map(([name, secret]) => ({ name, value: secret.value ?? "" }));+const writeFileStackEnv = async (+ secretSync: TPortainerSyncWithCredentials,+ stack: TPortainerStackResponse,+ env: TPortainerEnvVar[],+ deps: TPortainerGatewayDeps+) => {+ const { connection, destinationConfig } = secretSync;++ let stackFileContent: string;+ try {+ ({ StackFileContent: stackFileContent } = await portainerRequest<TPortainerStackFileResponse>(+ connection,+ { method: "GET", path: `/stacks/${destinationConfig.stackId}/file` },+ deps+ ));+ } catch (error) {+ throw toSyncError(error, `Failed to read the compose file of Portainer stack '${stack.Name}'`);+ }++ try {+ await portainerRequest(+ connection,+ {+ method: "PUT",+ path: `/stacks/${destinationConfig.stackId}`,+ params: { endpointId: String(destinationConfig.environmentId) },+ data: { env, stackFileContent, prune: stack.Option?.Prune ?? false },+ timeoutMs: PORTAINER_STACK_UPDATE_TIMEOUT_MS+ },+ deps+ );+ } catch (error) {+ throw toSyncError(error, `Failed to update the variables of Portainer stack '${stack.Name}'`);+ }++ // Recent Portainer releases redeploy in the background after answering, so a 200 only means the+ // update was accepted; the stack status tells whether the containers actually came up+ const deployed = await waitForPortainerDeployment(secretSync, await fetchPortainerStack(secretSync, deps), deps);++ if (deployed.Status === PortainerStackStatus.Error) {+ const reason = [...(deployed.DeploymentStatus ?? [])].reverse().find((entry) => entry.Message)?.Message;++ throw new SecretSyncError({+ message: `Portainer failed to redeploy stack '${stack.Name}' with the updated variables${reason ? `: ${reason}` : ""}. The variables are saved on the stack; check the stack in Portainer and redeploy it.`,+ shouldRetry: false+ });+ }+};++/**+ * A stack stores its variables as a single list, so every write replaces the whole list. Git-backed+ * stacks store it without redeploying; file-based stacks need the compose file on every update and+ * redeploy as a result, so the write is skipped when it would not change anything.+ */+const writeStackEnvIfChanged = async (+ secretSync: TPortainerSyncWithCredentials,+ stack: TPortainerStackResponse,+ env: TPortainerEnvVar[],+ deps: TPortainerGatewayDeps+) => {+ const isGitStack = isPortainerGitStack(stack);+ const isUnchanged = areEnvVarsEqual(stack.Env ?? [], env);++ // A file-based stack whose last deployment failed is redeployed anyway, so the sync reports the real state+ if (isUnchanged && (isGitStack || stack.Status !== PortainerStackStatus.Error)) return;++ if (isGitStack) {+ await writeGitStackEnv(secretSync, stack, env, deps);+ return;+ }++ await writeFileStackEnv(secretSync, stack, env, deps);+};++const toEnvVars = (secretMap: TSecretMap, stackType: PortainerStackType): TPortainerEnvVar[] =>+ Object.entries(secretMap).map(([name, secret]) => ({+ name,+ value: encodePortainerEnvValue(secret.value ?? "", stackType)+ }));export const PortainerSyncFns = {- async getSecrets(secretSync: TPortainerSyncWithCredentials): Promise<TSecretMap> {- const stack = await getPortainerStack(secretSync);+ async getSecrets(+ secretSync: TPortainerSyncWithCredentials,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">+ ): Promise<TSecretMap> {+ const stack = await getPortainerStack(secretSync, getGatewayDeps(gatewayV2Service, gatewayPoolService));- return Object.fromEntries((stack.Env ?? []).map(({ name, value }) => [name, { value: value ?? "" }]));+ return Object.fromEntries(+ (stack.Env ?? []).map(({ name, value }) => [name, { value: decodePortainerEnvValue(value ?? "", stack.Type) }])+ );},- async syncSecrets(secretSync: TPortainerSyncWithCredentials, payload: TSecretSyncPayload) {+ async syncSecrets(+ secretSync: TPortainerSyncWithCredentials,+ payload: TSecretSyncPayload,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">+ ) {const secretMap = payload.flatten();const {environment,syncOptions: { disableSecretDeletion, keySchema }} = secretSync;+ const deps = getGatewayDeps(gatewayV2Service, gatewayPoolService);- const stack = await getPortainerStack(secretSync);+ const stack = await getSettledPortainerStack(secretSync, deps);const retainedEnv = (stack.Env ?? []).filter(({ name }) => {if (name in secretMap) return false;@@ -123,15 +319,22 @@ export const PortainerSyncFns = {return true;});- await writeStackEnv(secretSync, stack, [...retainedEnv, ...toEnvVars(secretMap)]);+ await writeStackEnvIfChanged(secretSync, stack, [...retainedEnv, ...toEnvVars(secretMap, stack.Type)], deps);},- async removeSecrets(secretSync: TPortainerSyncWithCredentials, payload: TSecretSyncPayload) {+ async removeSecrets(+ secretSync: TPortainerSyncWithCredentials,+ payload: TSecretSyncPayload,+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">+ ) {const secretMap = payload.flatten();- const stack = await getPortainerStack(secretSync);+ const deps = getGatewayDeps(gatewayV2Service, gatewayPoolService);++ const stack = await getSettledPortainerStack(secretSync, deps);const remainingEnv = (stack.Env ?? []).filter(({ name }) => !(name in secretMap));- await writeStackEnv(secretSync, stack, remainingEnv);+ await writeStackEnvIfChanged(secretSync, stack, remainingEnv, deps);}};diff --git a/backend/src/services/secret-sync/portainer/portainer-sync-types.ts b/backend/src/services/secret-sync/portainer/portainer-sync-types.tsindex a3b1027f7d..ac779542cf 100644--- a/backend/src/services/secret-sync/portainer/portainer-sync-types.ts+++ b/backend/src/services/secret-sync/portainer/portainer-sync-types.ts@@ -14,29 +14,6 @@ export type TPortainerSyncWithCredentials = TPortainerSync & {connection: TPortainerConnection;};-export type TPortainerEnvVar = {- name: string;- value: string;-};--export type TPortainerStackResponse = {- Id: number;- Name: string;- EndpointId: number;- Env?: TPortainerEnvVar[] | null;- GitConfig?: {- URL: string;- ReferenceName?: string;- ConfigFilePath?: string;- } | null;- AutoUpdate?: {- Interval?: string;- Webhook?: string;- ForceUpdate?: boolean;- ForcePullImage?: boolean;- } | null;-};-export type TPortainerStackFileResponse = {StackFileContent: string;};diff --git a/backend/src/services/secret-sync/secret-sync-fns.ts b/backend/src/services/secret-sync/secret-sync-fns.tsindex f52f1046f7..6d19b89574 100644--- a/backend/src/services/secret-sync/secret-sync-fns.ts+++ b/backend/src/services/secret-sync/secret-sync-fns.ts@@ -370,7 +370,7 @@ export const SecretSyncFns = {case SecretSync.Rundeck:return RundeckSyncFns.syncSecrets(secretSync, payload);case SecretSync.Portainer:- return PortainerSyncFns.syncSecrets(secretSync, payload);+ return PortainerSyncFns.syncSecrets(secretSync, payload, gatewayV2Service, gatewayPoolService);case SecretSync.DigitalOceanAppPlatform:return DigitalOceanAppPlatformSyncFns.syncSecrets(secretSync, payload);case SecretSync.Netlify:@@ -536,7 +536,7 @@ export const SecretSyncFns = {secretMap = await RundeckSyncFns.getSecrets(secretSync);break;case SecretSync.Portainer:- secretMap = await PortainerSyncFns.getSecrets(secretSync);+ secretMap = await PortainerSyncFns.getSecrets(secretSync, gatewayV2Service, gatewayPoolService);break;case SecretSync.DigitalOceanAppPlatform:secretMap = await DigitalOceanAppPlatformSyncFns.getSecrets(secretSync);@@ -697,7 +697,7 @@ export const SecretSyncFns = {case SecretSync.Rundeck:return RundeckSyncFns.removeSecrets(secretSync, payload);case SecretSync.Portainer:- return PortainerSyncFns.removeSecrets(secretSync, payload);+ return PortainerSyncFns.removeSecrets(secretSync, payload, gatewayV2Service, gatewayPoolService);case SecretSync.DigitalOceanAppPlatform:return DigitalOceanAppPlatformSyncFns.removeSecrets(secretSync, payload);case SecretSync.Netlify:diff --git a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/PortainerSyncFields.tsx b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/PortainerSyncFields.tsxindex 769d7c781c..17abc2a806 100644--- a/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/PortainerSyncFields.tsx+++ b/frontend/src/components/secret-syncs/forms/SecretSyncDestinationFields/PortainerSyncFields.tsx@@ -25,7 +25,7 @@ const GIT_STACK_HELP_TEXT ="Variables are stored on the stack's Git configuration. The running containers are left untouched - the new values apply on the stack's next deployment.";const FILE_STACK_HELP_TEXT =- "Portainer requires the compose file on every update to a file-based stack, so syncing re-deploys it. Use a Git-backed stack to update variables without a redeploy.";+ "Portainer requires the compose file on every update to a file-based stack, so syncing re-deploys it whenever the variables change. Use a Git-backed stack to update variables without a redeploy.";export const PortainerSyncFields = () => {const { control, setValue } = useFormContext<