Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

fix issues

Matheus Nogueira869522b3276a
diff --git a/backend/src/lib/dotenv/index.test.ts b/backend/src/lib/dotenv/index.test.ts
new file mode 100644
index 0000000000..e543dee5f7
--- /dev/null
+++ b/backend/src/lib/dotenv/index.test.ts
@@ -0,0 +1,124 @@
+import { parseEnvFile, serializeEnvFile } from "./index";
+
+describe("serializeEnvFile", () => {
+ test("serializes simple key-value pairs", () => {
+ expect(serializeEnvFile({ FOO: "bar", BAZ: "qux" })).toBe("FOO=bar\nBAZ=qux");
+ });
+
+ test("leaves plain values unquoted", () => {
+ expect(serializeEnvFile({ KEY: "simple" })).toBe("KEY=simple");
+ });
+
+ test("quotes values containing newlines", () => {
+ expect(serializeEnvFile({ KEY: "line1\nline2" })).toBe('KEY="line1\\nline2"');
+ });
+
+ test("quotes values containing carriage returns", () => {
+ expect(serializeEnvFile({ KEY: "a\rb" })).toBe('KEY="a\\rb"');
+ });
+
+ test("escapes backslashes inside values", () => {
+ expect(serializeEnvFile({ KEY: "path\\to\\file" })).toBe('KEY="path\\\\to\\\\file"');
+ });
+
+ test("escapes double quotes inside values", () => {
+ expect(serializeEnvFile({ KEY: 'say "hello"' })).toBe('KEY="say \\"hello\\""');
+ });
+
+ test("handles empty value", () => {
+ expect(serializeEnvFile({ KEY: "" })).toBe("KEY=");
+ });
+
+ test("handles empty map", () => {
+ expect(serializeEnvFile({})).toBe("");
+ });
+
+ test("rejects keys with spaces", () => {
+ expect(() => serializeEnvFile({ "BAD KEY": "val" })).toThrow("Invalid environment variable name");
+ });
+
+ test("rejects keys starting with a digit", () => {
+ expect(() => serializeEnvFile({ "1KEY": "val" })).toThrow("Invalid environment variable name");
+ });
+
+ test("rejects keys containing equals", () => {
+ expect(() => serializeEnvFile({ "K=V": "val" })).toThrow("Invalid environment variable name");
+ });
+
+ test("rejects keys containing newlines", () => {
+ expect(() => serializeEnvFile({ "K\nV": "val" })).toThrow("Invalid environment variable name");
+ });
+
+ test("allows underscores and dots in keys", () => {
+ expect(serializeEnvFile({ "MY_KEY.sub": "val" })).toBe("MY_KEY.sub=val");
+ });
+});
+
+describe("parseEnvFile", () => {
+ test("parses simple key-value pairs", () => {
+ expect(parseEnvFile("FOO=bar\nBAZ=qux")).toEqual({ FOO: "bar", BAZ: "qux" });
+ });
+
+ test("parses double-quoted values and unescapes sequences", () => {
+ expect(parseEnvFile('KEY="line1\\nline2"')).toEqual({ KEY: "line1\nline2" });
+ });
+
+ test("unescapes backslashes in quoted values", () => {
+ expect(parseEnvFile('KEY="path\\\\to\\\\file"')).toEqual({ KEY: "path\\to\\file" });
+ });
+
+ test("unescapes double quotes in quoted values", () => {
+ expect(parseEnvFile('KEY="say \\"hello\\""')).toEqual({ KEY: 'say "hello"' });
+ });
+
+ test("unescapes carriage returns", () => {
+ expect(parseEnvFile('KEY="a\\rb"')).toEqual({ KEY: "a\rb" });
+ });
+
+ test("skips empty lines and comments", () => {
+ expect(parseEnvFile("# comment\n\nKEY=val\n \n# another")).toEqual({ KEY: "val" });
+ });
+
+ test("handles value containing equals sign", () => {
+ expect(parseEnvFile("KEY=a=b=c")).toEqual({ KEY: "a=b=c" });
+ });
+
+ test("handles empty value", () => {
+ expect(parseEnvFile("KEY=")).toEqual({ KEY: "" });
+ });
+
+ test("handles empty input", () => {
+ expect(parseEnvFile("")).toEqual({});
+ });
+
+ test("does not strip unquoted values", () => {
+ expect(parseEnvFile("KEY=hello world")).toEqual({ KEY: "hello world" });
+ });
+});
+
+describe("round-trip", () => {
+ const cases: Record<string, string>[] = [
+ { SIMPLE: "value" },
+ { NEWLINE: "line1\nline2\nline3" },
+ { CRLF: "a\r\nb" },
+ { QUOTES: 'say "hello"' },
+ { BACKSLASH: "C:\\Users\\test" },
+ { MIXED: 'val with "quotes" and\nnewlines and \\backslash' },
+ { EMPTY: "" },
+ { A: "1", B: "2", C: "3" }
+ ];
+
+ test.each(cases)("round-trips %j", (input) => {
+ const serialized = serializeEnvFile(input);
+ const parsed = parseEnvFile(serialized);
+ expect(parsed).toEqual(input);
+ });
+
+ test("newline injection is neutralized", () => {
+ const malicious = { LEGIT: "original\nOTHER_KEY=attacker-value" };
+ const serialized = serializeEnvFile(malicious);
+ const parsed = parseEnvFile(serialized);
+ expect(parsed).toEqual(malicious);
+ expect(Object.keys(parsed)).toEqual(["LEGIT"]);
+ });
+});
diff --git a/backend/src/lib/dotenv/index.ts b/backend/src/lib/dotenv/index.ts
new file mode 100644
index 0000000000..57ded52348
--- /dev/null
+++ b/backend/src/lib/dotenv/index.ts
@@ -0,0 +1,52 @@
+import RE2 from "re2";
+
+const ENV_KEY_RE = new RE2(/^[A-Za-z_][A-Za-z0-9_.]*$/);
+
+const escapeValue = (value: string): string => {
+ if (/[\n\r"\\]/.test(value)) {
+ const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");
+ return `"${escaped}"`;
+ }
+ return value;
+};
+
+const unescapeValue = (raw: string): string => {
+ if (raw.startsWith('"') && raw.endsWith('"') && raw.length >= 2) {
+ return raw
+ .slice(1, -1)
+ .replace(/\\r/g, "\r")
+ .replace(/\\n/g, "\n")
+ .replace(/\\"/g, '"')
+ .replace(/\\\\/g, "\\");
+ }
+ return raw;
+};
+
+export const serializeEnvFile = (map: Record<string, string>): string => {
+ return Object.entries(map)
+ .map(([key, value]) => {
+ if (!ENV_KEY_RE.test(key)) {
+ throw new Error(`Invalid environment variable name: ${key}`);
+ }
+ return `${key}=${escapeValue(value)}`;
+ })
+ .join("\n");
+};
+
+export const parseEnvFile = (content: string): Record<string, string> => {
+ const result: Record<string, string> = {};
+
+ for (const line of content.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed && !trimmed.startsWith("#")) {
+ const eqIndex = trimmed.indexOf("=");
+ if (eqIndex !== -1) {
+ const key = trimmed.substring(0, eqIndex);
+ const value = unescapeValue(trimmed.substring(eqIndex + 1));
+ result[key] = value;
+ }
+ }
+ }
+
+ return result;
+};
diff --git a/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts b/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts
index bb48458267..2448b5062c 100644
--- a/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts
+++ b/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts
@@ -1,4 +1,5 @@
/* eslint-disable no-await-in-loop */
+import { parseEnvFile, serializeEnvFile } from "@app/lib/dotenv";
import { removeTrailingSlash } from "@app/lib/fn";
import { safeRequest } from "@app/lib/validator";
import { SecretSyncError } from "@app/services/secret-sync/secret-sync-errors";
@@ -12,9 +13,11 @@ type TSpaceliftConfigElement = {
id: string;
value: string;
writeOnly: boolean;
- type?: string;
+ type?: ElementType;
};
+type ElementType = "ENVIRONMENT_VARIABLE" | "FILE_MOUNT"
+
const authenticateSpacelift = async (instanceUrl: string, apiKeyId: string, apiKeySecret: string): Promise<string> => {
const { data } = await safeRequest.post<{
data?: { apiKeyUser?: { jwt: string } };
@@ -72,7 +75,7 @@ const addContextConfigElement = async (
key: string,
value: string,
writeOnly: boolean,
- type: "ENVIRONMENT_VARIABLE" | "FILE_MOUNT" = "ENVIRONMENT_VARIABLE"
+ type: ElementType = "ENVIRONMENT_VARIABLE"
) => {
await graphqlRequest(
instanceUrl,
@@ -99,26 +102,19 @@ const deleteContextConfigElement = async (instanceUrl: string, jwt: string, cont
};
const secretMapToEnvFileContent = (secretMap: TSecretMap): string => {
- return Object.entries(secretMap)
- .map(([key, { value }]) => `${key}=${value}`)
- .join("\n");
+ const flat: Record<string, string> = {};
+ for (const [key, { value }] of Object.entries(secretMap)) {
+ flat[key] = value;
+ }
+ return serializeEnvFile(flat);
};
const envFileContentToSecretMap = (content: string): TSecretMap => {
+ const parsed = parseEnvFile(content);
const secretMap: TSecretMap = {};
-
- for (const line of content.split("\n")) {
- const trimmed = line.trim();
- if (trimmed && !trimmed.startsWith("#")) {
- const eqIndex = trimmed.indexOf("=");
- if (eqIndex !== -1) {
- const key = trimmed.substring(0, eqIndex);
- const value = trimmed.substring(eqIndex + 1);
- secretMap[key] = { value };
- }
- }
+ for (const [key, value] of Object.entries(parsed)) {
+ secretMap[key] = { value };
}
-
return secretMap;
};
@@ -126,7 +122,7 @@ export const SpaceliftSyncFns = {
syncSecrets: async (secretSync: TSpaceliftSyncWithCredentials, secretMap: TSecretMap): Promise<void> => {
const instanceUrl = removeTrailingSlash(secretSync.connection.credentials.apiUrl);
const { apiKeyId, apiKeySecret } = secretSync.connection.credentials;
- const { contextId, configType = SpaceliftConfigType.EnvironmentVariable, mountPath } = secretSync.destinationConfig;
+ const { contextId, configType, mountPath } = secretSync.destinationConfig;
const writeOnly = secretSync.syncOptions?.writeOnly ?? false;
const jwt = await authenticateSpacelift(instanceUrl, apiKeyId, apiKeySecret);
@@ -135,37 +131,25 @@ export const SpaceliftSyncFns = {
if (configType === SpaceliftConfigType.FileMount) {
const filePath = mountPath!;
const existingFile = existingElements.find((e) => e.id === filePath);
+ const hasSecrets = Object.keys(secretMap).length > 0;
- if (existingFile) {
- await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);
- }
+ if (hasSecrets) {
+ if (existingFile) {
+ await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);
+ }
- if (Object.keys(secretMap).length > 0) {
const envContent = secretMapToEnvFileContent(secretMap);
const encoded = Buffer.from(envContent).toString("base64");
await addContextConfigElement(instanceUrl, jwt, contextId, filePath, encoded, writeOnly, "FILE_MOUNT");
- }
-
- if (secretSync.syncOptions.disableSecretDeletion) return;
-
- for (const element of existingElements) {
- if (
- element.id !== filePath &&
- element.type === "FILE_MOUNT" &&
- matchesSchema(element.id, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema)
- ) {
- try {
- await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
- } catch (error) {
- throw new SecretSyncError({ error, secretKey: element.id });
- }
- }
+ } else if (existingFile && !secretSync.syncOptions.disableSecretDeletion) {
+ await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);
}
return;
}
- const existingMap = new Map(existingElements.map((e) => [e.id, e]));
+ const existingSecrets = existingElements.filter((e) => e.type === "ENVIRONMENT_VARIABLE")
+ const existingMap = new Map(existingSecrets.map((e) => [e.id, e]));
for (const key of Object.keys(secretMap)) {
try {
@@ -183,7 +167,7 @@ export const SpaceliftSyncFns = {
if (secretSync.syncOptions.disableSecretDeletion) return;
- for (const element of existingElements) {
+ for (const element of existingSecrets) {
if (
matchesSchema(element.id, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema) &&
!(element.id in secretMap)
@@ -200,7 +184,7 @@ export const SpaceliftSyncFns = {
getSecrets: async (secretSync: TSpaceliftSyncWithCredentials): Promise<TSecretMap> => {
const instanceUrl = removeTrailingSlash(secretSync.connection.credentials.apiUrl);
const { apiKeyId, apiKeySecret } = secretSync.connection.credentials;
- const { contextId, configType = SpaceliftConfigType.EnvironmentVariable, mountPath } = secretSync.destinationConfig;
+ const { contextId, configType, mountPath } = secretSync.destinationConfig;
const jwt = await authenticateSpacelift(instanceUrl, apiKeyId, apiKeySecret);
const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
@@ -218,7 +202,7 @@ export const SpaceliftSyncFns = {
const secretMap: TSecretMap = {};
for (const element of existingElements) {
- if (!element.writeOnly) {
+ if (element.type === "ENVIRONMENT_VARIABLE" && !element.writeOnly) {
secretMap[element.id] = { value: element.value };
}
}
@@ -229,7 +213,7 @@ export const SpaceliftSyncFns = {
removeSecrets: async (secretSync: TSpaceliftSyncWithCredentials, secretMap: TSecretMap): Promise<void> => {
const instanceUrl = removeTrailingSlash(secretSync.connection.credentials.apiUrl);
const { apiKeyId, apiKeySecret } = secretSync.connection.credentials;
- const { contextId, configType = SpaceliftConfigType.EnvironmentVariable, mountPath } = secretSync.destinationConfig;
+ const { contextId, configType, mountPath } = secretSync.destinationConfig;
const jwt = await authenticateSpacelift(instanceUrl, apiKeyId, apiKeySecret);
const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
@@ -249,8 +233,9 @@ export const SpaceliftSyncFns = {
return;
}
- for (const element of existingElements) {
- if (Object.prototype.hasOwnProperty.call(secretMap, element.id)) {
+ const existingSecrets = existingElements.filter((e) => e.type === "ENVIRONMENT_VARIABLE");
+ for (const element of existingSecrets) {
+ if (element.id in secretMap) {
try {
await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
} catch (error) {
diff --git a/backend/src/services/secret-sync/spacelift/spacelift-sync-schemas.ts b/backend/src/services/secret-sync/spacelift/spacelift-sync-schemas.ts
index 2ca6a96ee6..5c418a76fd 100644
--- a/backend/src/services/secret-sync/spacelift/spacelift-sync-schemas.ts
+++ b/backend/src/services/secret-sync/spacelift/spacelift-sync-schemas.ts
@@ -27,7 +27,6 @@ const SpaceliftSyncDestinationConfigSchema = z
.describe(SecretSyncs.DESTINATION_CONFIG.SPACELIFT.contextName),
configType: z
.nativeEnum(SpaceliftConfigType)
- .default(SpaceliftConfigType.EnvironmentVariable)
.describe(SecretSyncs.DESTINATION_CONFIG.SPACELIFT.configType),
mountPath: z.string().trim().optional().describe(SecretSyncs.DESTINATION_CONFIG.SPACELIFT.mountPath)
})
diff --git a/frontend/src/components/secret-syncs/forms/schemas/spacelift-sync-destination-schema.ts b/frontend/src/components/secret-syncs/forms/schemas/spacelift-sync-destination-schema.ts
index 76874337cc..064affde46 100644
--- a/frontend/src/components/secret-syncs/forms/schemas/spacelift-sync-destination-schema.ts
+++ b/frontend/src/components/secret-syncs/forms/schemas/spacelift-sync-destination-schema.ts
@@ -15,10 +15,7 @@ export const SpaceliftSyncDestinationSchema = BaseSecretSyncSchema(
.object({
contextId: z.string().trim().min(1, "Context ID required"),
contextName: z.string().trim().min(1, "Context name required"),
- configType: z
- .nativeEnum(SpaceliftConfigType)
- .optional()
- .default(SpaceliftConfigType.EnvironmentVariable),
+ configType: z.nativeEnum(SpaceliftConfigType),
mountPath: z.string().trim().optional()
})
.superRefine((data, ctx) => {
diff --git a/frontend/src/hooks/api/secretSyncs/types/spacelift-sync.ts b/frontend/src/hooks/api/secretSyncs/types/spacelift-sync.ts
index 520d422f8d..2180efa1e4 100644
--- a/frontend/src/hooks/api/secretSyncs/types/spacelift-sync.ts
+++ b/frontend/src/hooks/api/secretSyncs/types/spacelift-sync.ts
@@ -12,7 +12,7 @@ export type TSpaceliftSync = TRootSecretSync & {
destinationConfig: {
contextId: string;
contextName: string;
- configType?: SpaceliftConfigType;
+ configType: SpaceliftConfigType;
mountPath?: string;
};
syncOptions: RootSyncOptions & {