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 lint and edge cases for .env file
Matheus Nogueira3e8a866afb44
diff --git a/backend/src/lib/dotenv/index.test.ts b/backend/src/lib/dotenv/index.test.tsindex e543dee5f7..3e817927bb 100644--- a/backend/src/lib/dotenv/index.test.ts+++ b/backend/src/lib/dotenv/index.test.ts@@ -33,12 +33,16 @@ describe("serializeEnvFile", () => {expect(serializeEnvFile({})).toBe("");});- test("rejects keys with spaces", () => {- expect(() => serializeEnvFile({ "BAD KEY": "val" })).toThrow("Invalid environment variable name");+ test("allows keys with spaces", () => {+ expect(serializeEnvFile({ "MY KEY": "val" })).toBe("MY KEY=val");});- test("rejects keys starting with a digit", () => {- expect(() => serializeEnvFile({ "1KEY": "val" })).toThrow("Invalid environment variable name");+ test("allows keys starting with a digit", () => {+ expect(serializeEnvFile({ "1KEY": "val" })).toBe("1KEY=val");+ });++ test("allows hyphenated keys", () => {+ expect(serializeEnvFile({ "my-secret": "val" })).toBe("my-secret=val");});test("rejects keys containing equals", () => {@@ -49,6 +53,10 @@ describe("serializeEnvFile", () => {expect(() => serializeEnvFile({ "K\nV": "val" })).toThrow("Invalid environment variable name");});+ test("rejects empty keys", () => {+ expect(() => serializeEnvFile({ "": "val" })).toThrow("Invalid environment variable name");+ });+test("allows underscores and dots in keys", () => {expect(serializeEnvFile({ "MY_KEY.sub": "val" })).toBe("MY_KEY.sub=val");});@@ -94,6 +102,14 @@ describe("parseEnvFile", () => {test("does not strip unquoted values", () => {expect(parseEnvFile("KEY=hello world")).toEqual({ KEY: "hello world" });});++ test("preserves leading and trailing whitespace in quoted values", () => {+ expect(parseEnvFile('KEY=" spaced "')).toEqual({ KEY: " spaced " });+ });++ test("preserves unquoted value with surrounding whitespace", () => {+ expect(parseEnvFile("KEY= spaced ")).toEqual({ KEY: " spaced " });+ });});describe("round-trip", () => {@@ -105,7 +121,13 @@ describe("round-trip", () => {{ BACKSLASH: "C:\\Users\\test" },{ MIXED: 'val with "quotes" and\nnewlines and \\backslash' },{ EMPTY: "" },- { A: "1", B: "2", C: "3" }+ { A: "1", B: "2", C: "3" },+ { "my-secret": "hyphenated" },+ { "2FA_KEY": "digit-start" },+ { LEADING_SPACE: " hello" },+ { TRAILING_SPACE: "hello " },+ { BOTH_SPACES: " hello " },+ { TAB_PADDED: "\tvalue\t" }];test.each(cases)("round-trips %j", (input) => {diff --git a/backend/src/lib/dotenv/index.ts b/backend/src/lib/dotenv/index.tsindex a2b2e0d13a..776f74da34 100644--- a/backend/src/lib/dotenv/index.ts+++ b/backend/src/lib/dotenv/index.ts@@ -1,9 +1,9 @@import RE2 from "re2";-const ENV_KEY_RE = new RE2(/^[A-Za-z_][A-Za-z0-9_.]*$/);+const DOTENV_KEY_RE = new RE2(/^[^\n\r=]+$/);const escapeValue = (value: string): string => {- if (/[\n\r"\\]/.test(value)) {+ if (/[\n\r"\\]/.test(value) || value !== value.trim()) {const escaped = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r");return `"${escaped}"`;}@@ -20,7 +20,7 @@ const unescapeValue = (raw: string): string => {export const serializeEnvFile = (map: Record<string, string>): string => {return Object.entries(map).map(([key, value]) => {- if (!ENV_KEY_RE.test(key)) {+ if (!key || !DOTENV_KEY_RE.test(key)) {throw new Error(`Invalid environment variable name: ${key}`);}return `${key}=${escapeValue(value)}`;@@ -34,10 +34,10 @@ export const parseEnvFile = (content: string): Record<string, string> => {for (const line of content.split("\n")) {const trimmed = line.trim();if (trimmed && !trimmed.startsWith("#")) {- const eqIndex = trimmed.indexOf("=");+ const eqIndex = line.indexOf("=");if (eqIndex !== -1) {- const key = trimmed.substring(0, eqIndex);- const value = unescapeValue(trimmed.substring(eqIndex + 1));+ const key = line.substring(0, eqIndex).trim();+ const value = unescapeValue(line.substring(eqIndex + 1));result[key] = value;}}diff --git a/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts b/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.tsindex ff07da9f47..faab6e0326 100644--- a/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts+++ b/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts@@ -126,39 +126,34 @@ export const SpaceliftSyncFns = {const writeOnly = secretSync.syncOptions?.writeOnly ?? false;const jwt = await authenticateSpacelift(instanceUrl, apiKeyId, apiKeySecret);- const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);if (configType === SpaceliftConfigType.FileMount) {const filePath = mountPath!;- const existingFile = existingElements.find((e) => e.id === filePath && e.type === "FILE_MOUNT");const hasSecrets = Object.keys(secretMap).length > 0;if (hasSecrets) {- if (existingFile) {- await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);- }-const envContent = secretMapToEnvFileContent(secretMap);const encoded = Buffer.from(envContent).toString("base64");await addContextConfigElement(instanceUrl, jwt, contextId, filePath, encoded, writeOnly, "FILE_MOUNT");- } else if (existingFile && !secretSync.syncOptions.disableSecretDeletion) {+ } else if (!secretSync.syncOptions.disableSecretDeletion) {await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);}return;}+ const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);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 {- const existing = existingMap.get(key);+ const existingByKey = new Map(existingSecrets.map((e) => [e.id, e]));- if (existing) {- await deleteContextConfigElement(instanceUrl, jwt, contextId, key);- }+ for (const key of Object.keys(secretMap)) {+ const existing = existingByKey.get(key);+ if (existing && !existing.writeOnly && existing?.value === secretMap[key].value) {+ continue;+ }+ try {await addContextConfigElement(instanceUrl, jwt, contextId, key, secretMap[key].value, writeOnly);} catch (error) {throw new SecretSyncError({ error, secretKey: key });diff --git a/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/helpers/index.ts b/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/helpers/index.tsindex 68e9527611..2e349d4a9c 100644--- a/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/helpers/index.ts+++ b/frontend/src/pages/secret-manager/IntegrationsListPage/components/SecretSyncsTab/SecretSyncTable/helpers/index.ts@@ -291,7 +291,10 @@ export const getSecretSyncDestinationColValues = (secretSync: TSecretSync) => {break;case SecretSync.Spacelift:primaryText = destinationConfig.contextName;- secondaryText = destinationConfig.configType === "environment-variable" ? "environment variables" : "file mount";+ secondaryText =+ destinationConfig.configType === "environment-variable"+ ? "environment variables"+ : "file mount";break;default:throw new Error(`Unhandled Destination Col Values ${destination}`);