Skip to content

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

fix: resolved multi line yaml pasting issue

=89a2cb4e9506
diff --git a/frontend/src/components/utilities/parseSecrets.test.ts b/frontend/src/components/utilities/parseSecrets.test.ts
new file mode 100644
index 0000000000..2348e793b9
--- /dev/null
+++ b/frontend/src/components/utilities/parseSecrets.test.ts
@@ -0,0 +1,164 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+
+import { parseDotEnv, parsePastedSecrets, parseYaml } from "./parseSecrets";
+
+describe("parseYaml", () => {
+ it("keeps line breaks in literal block scalars", () => {
+ const env = parseYaml(
+ [
+ "FOO: |",
+ " first line",
+ " second",
+ " and so on",
+ "BAR: |",
+ " one",
+ " more",
+ " time"
+ ].join("\n")
+ );
+
+ assert.deepEqual(Object.keys(env), ["FOO", "BAR"]);
+ assert.equal(env.FOO.value, "first line\nsecond\nand so on\n");
+ assert.equal(env.BAR.value, "one\nmore\ntime\n");
+ });
+
+ it("applies block scalar chomping", () => {
+ const clipped = parseYaml(["A: |", " one", " two", ""].join("\n"));
+ const stripped = parseYaml(["A: |-", " one", " two", ""].join("\n"));
+ const kept = parseYaml(["A: |+", " one", "", "", "B: x"].join("\n"));
+
+ assert.equal(clipped.A.value, "one\ntwo\n");
+ assert.equal(stripped.A.value, "one\ntwo");
+ assert.equal(kept.A.value, "one\n\n\n");
+ assert.equal(kept.B.value, "x");
+ });
+
+ it("folds folded block scalars", () => {
+ const folded = parseYaml(["A: >", " one", " two", "", " three"].join("\n"));
+ const foldedStripped = parseYaml(["A: >-", " one", " two"].join("\n"));
+
+ assert.equal(folded.A.value, "one two\nthree\n");
+ assert.equal(foldedStripped.A.value, "one two");
+ });
+
+ it("handles a block scalar whose first body line is blank", () => {
+ const env = parseYaml(["A: |", "", " one", " two", "B: two"].join("\n"));
+
+ assert.equal(env.A.value, "\none\ntwo\n");
+ assert.equal(env.B.value, "two");
+ });
+
+ it("handles an explicit indentation indicator", () => {
+ const env = parseYaml(["A: |2", " indented", " base", "B: b"].join("\n"));
+
+ assert.equal(env.A.value, " indented\nbase\n");
+ assert.equal(env.B.value, "b");
+ });
+
+ it("strips quotes and inline comments from flat values", () => {
+ const env = parseYaml(
+ [
+ "# leading comment",
+ "# second line",
+ 'QUOTED: "a value" # trailing',
+ "SINGLE: 'it''s here'",
+ "COLONS: postgres://user:pass@host:5432/db",
+ "EMPTY:",
+ "NUMBER: 3000",
+ "BOOL: true"
+ ].join("\n")
+ );
+
+ assert.deepEqual(env.QUOTED.comments, ["leading comment", "second line", "trailing"]);
+ assert.equal(env.QUOTED.value, "a value");
+ assert.equal(env.SINGLE.value, "it's here");
+ assert.equal(env.COLONS.value, "postgres://user:pass@host:5432/db");
+ assert.equal(env.EMPTY.value, "");
+ assert.equal(env.NUMBER.value, "3000");
+ assert.equal(env.BOOL.value, "true");
+ });
+
+ it("stringifies nested maps and sequences", () => {
+ const env = parseYaml(["MAP:", " a: 1", "LIST:", " - one", " - two"].join("\n"));
+
+ assert.equal(env.MAP.value, '{"a":1}');
+ assert.equal(env.LIST.value, '["one","two"]');
+ });
+
+ it("returns nothing for documents that are not maps", () => {
+ assert.deepEqual(parseYaml(""), {});
+ assert.deepEqual(parseYaml("- one\n- two"), {});
+ });
+
+ it("throws on invalid yaml", () => {
+ assert.throws(() => parseYaml(["A: 1", " B: 2", "C: 3"].join("\n")));
+ assert.throws(() => parseYaml("A: 1\nA: 2"));
+ });
+});
+
+describe("parseDotEnv", () => {
+ it("parses assignments, exports and quoted values", () => {
+ const env = parseDotEnv(
+ [
+ "# a comment",
+ 'APP_NAME="example-service"',
+ "export TOKEN=abc123",
+ 'MULTI="one\\ntwo"',
+ "BARE=plain # trailing"
+ ].join("\n")
+ );
+
+ assert.deepEqual(env.APP_NAME, { value: "example-service", comments: ["a comment"] });
+ assert.equal(env.TOKEN.value, "abc123");
+ assert.equal(env.MULTI.value, "one\ntwo");
+ assert.equal(env.BARE.value, "plain");
+ });
+});
+
+describe("parsePastedSecrets", () => {
+ it("parses json", () => {
+ const env = parsePastedSecrets('{"A":"1","B":{"c":2}}');
+
+ assert.equal(env.A.value, "1");
+ assert.equal(env.B.value, '{"c":2}');
+ });
+
+ it("parses yaml block scalars rather than falling back to dotenv", () => {
+ const env = parsePastedSecrets(["FOO: |", " first line", " second"].join("\n"));
+
+ assert.deepEqual(Object.keys(env), ["FOO"]);
+ assert.equal(env.FOO.value, "first line\nsecond\n");
+ });
+
+ it("treats assignments inside a block scalar as part of its value", () => {
+ const env = parsePastedSecrets(["ENV_FILE: |", " A=1", " B=2"].join("\n"));
+
+ assert.deepEqual(Object.keys(env), ["ENV_FILE"]);
+ assert.equal(env.ENV_FILE.value, "A=1\nB=2\n");
+ });
+
+ it("still parses dotenv content as dotenv", () => {
+ const env = parsePastedSecrets(["A=1", "export B=2", 'C="three"'].join("\n"));
+
+ assert.equal(env.A.value, "1");
+ assert.equal(env.B.value, "2");
+ assert.equal(env.C.value, "three");
+ });
+
+ it("parses flat yaml", () => {
+ const env = parsePastedSecrets(
+ ["APP_NAME: example-service", "NODE_ENV: production"].join("\n")
+ );
+
+ assert.equal(env.APP_NAME.value, "example-service");
+ assert.equal(env.NODE_ENV.value, "production");
+ });
+
+ it("falls back to dotenv when yaml is invalid", () => {
+ const env = parsePastedSecrets(["A: 1", " B: 2"].join("\n"));
+
+ assert.equal(env.A.value, "1");
+ assert.equal(env.B.value, "2");
+ });
+});
diff --git a/frontend/src/components/utilities/parseSecrets.ts b/frontend/src/components/utilities/parseSecrets.ts
index 0e8732410f..d365ca0817 100644
--- a/frontend/src/components/utilities/parseSecrets.ts
+++ b/frontend/src/components/utilities/parseSecrets.ts
@@ -1,6 +1,11 @@
+import { isMap, isNode, isScalar, isSeq, parseDocument } from "yaml";
+
const LINE =
/(?:^|^)\s*(?:export\s+)?([\w.:-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
+const decodeSource = (src: ArrayBuffer | string) =>
+ typeof src === "string" ? src : new TextDecoder("utf-8").decode(src);
+
/**
* Return text that is the buffer parsed
* @param {ArrayBuffer} src - source buffer
@@ -89,89 +94,53 @@ export const parseJson = (src: ArrayBuffer | string) => {
};
/**
- * Parses simple flat YAML with support for multiline strings using |, |-, and >.
+ * Parses a flat YAML document into secrets. Block scalars, folding, chomping,
+ * quoting and comments are all handled by the parser, so multiline values keep
+ * their line breaks. Nested maps and sequences are stringified, matching parseJson.
+ * Throws on invalid YAML so callers can fall back to another format or report it.
* @param {ArrayBuffer | string} src
* @returns {Record<string, { value: string, comments: string[] }>}
*/
export function parseYaml(src: ArrayBuffer | string) {
const result: Record<string, { value: string; comments: string[] }> = {};
- const content = src.toString().replace(/\r\n?/g, "\n");
- const lines = content.split("\n");
-
- let i = 0;
- let comments: string[] = [];
+ const doc = parseDocument(decodeSource(src));
+ if (doc.errors.length) {
+ throw new Error(doc.errors[0].message);
+ }
- while (i < lines.length) {
- const line = lines[i].trim();
+ const root = doc.contents;
+ if (!isMap(root)) {
+ return result;
+ }
- // Collect comment
- if (line.startsWith("#")) {
- comments.push(line.slice(1).trim());
- i += 1; // move to next line
- } else {
- // Match key: value or key: |, key: >, etc.
- const keyMatch = lines[i].match(/^([\w.-]+)\s*:\s*(.*)$/);
- if (keyMatch) {
- const [, key, rawValue] = keyMatch;
- let value = rawValue.trim();
-
- // Multiline string handling
- if (value === "|-" || value === "|" || value === ">") {
- const isFolded = value === ">";
-
- const baseIndent = lines[i + 1]?.match(/^(\s*)/)?.[1]?.length ?? 0;
- const collectedLines: string[] = [];
-
- i += 1; // move to first content line
-
- while (i < lines.length) {
- const current = lines[i];
- const currentIndent = current.match(/^(\s*)/)?.[1]?.length ?? 0;
-
- if (current.trim() === "" || currentIndent >= baseIndent) {
- collectedLines.push(current.slice(baseIndent));
- i += 1; // move to next line
- } else {
- break;
- }
- }
+ root.items.forEach((pair) => {
+ const keyNode = pair.key;
+ if (!isScalar(keyNode)) {
+ return;
+ }
- if (isFolded) {
- // Join lines with space for `>` folded style
- value = collectedLines.map((l) => l.trim()).join(" ");
- } else {
- // Keep lines with newlines for `|` and `|-`
- value = collectedLines.join("\n");
- }
- } else {
- // Inline value — strip quotes and inline comment
- const commentIndex = value.indexOf(" #");
- if (commentIndex !== -1) {
- value = value.slice(0, commentIndex).trim();
- }
+ const key = String(keyNode.value ?? "").trim();
+ if (!key) {
+ return;
+ }
- // Remove surrounding quotes
- if (
- (value.startsWith('"') && value.endsWith('"')) ||
- (value.startsWith("'") && value.endsWith("'"))
- ) {
- value = value.slice(1, -1);
- }
+ const valueNode = pair.value;
+ let value = "";
+ if (isMap(valueNode) || isSeq(valueNode)) {
+ value = JSON.stringify(valueNode.toJSON());
+ } else if (isScalar(valueNode) && valueNode.value !== null && valueNode.value !== undefined) {
+ value = String(valueNode.value);
+ }
- i += 1; // advance to next line
- }
+ const comments = [keyNode.commentBefore, isNode(valueNode) ? valueNode.comment : null]
+ .filter((comment): comment is string => Boolean(comment))
+ .flatMap((comment) => comment.split("\n"))
+ .map((comment) => comment.trim())
+ .filter(Boolean);
- result[key] = {
- value,
- comments: [...comments]
- };
- comments = []; // reset
- } else {
- i += 1; // skip unknown line
- }
- }
- }
+ result[key] = { value, comments };
+ });
return result;
}
@@ -197,12 +166,7 @@ export function parseCsvToMatrix(src: ArrayBuffer | string): {
matrix: string[][];
delimiter: CsvDelimiter;
} {
- let csvContent: string;
- if (typeof src === "string") {
- csvContent = src;
- } else {
- csvContent = new TextDecoder("utf-8").decode(src);
- }
+ const csvContent = decodeSource(src);
const separator = detectSeparator(csvContent);
const normalized = csvContent.replace(/\r\n?/g, "\n");
@@ -247,3 +211,43 @@ export function parseCsvToMatrix(src: ArrayBuffer | string): {
return { matrix, delimiter: separator };
}
+
+export type TParsedSecrets = Record<string, { value: string; comments: string[] }>;
+
+// A "key: |" / "key: >" header is the one construct .env cannot express, so it is
+// checked before the .env assignment test: an assignment can legitimately appear
+// inside a block scalar's body, which is why that test rejects indented lines.
+const YAML_BLOCK_SCALAR = /^[^\s#][^\n]*:[ \t]*[|>][-+]?\d*[ \t]*(?:#.*)?$/m;
+const DOTENV_ASSIGNMENT = /^(?:export\s+)?[\w.:-]+\s*=/m;
+
+const parseOrNull = (parse: () => TParsedSecrets) => {
+ try {
+ const parsed = parse();
+ return Object.keys(parsed).length ? parsed : null;
+ } catch {
+ return null;
+ }
+};
+
+/**
+ * Detects the format of pasted secrets (.json, .yml or .env) and parses it.
+ */
+export const parsePastedSecrets = (value: string): TParsedSecrets => {
+ const json = parseOrNull(() => parseJson(value));
+ if (json) {
+ return json;
+ }
+
+ if (YAML_BLOCK_SCALAR.test(value)) {
+ const yaml = parseOrNull(() => parseYaml(value));
+ if (yaml) {
+ return yaml;
+ }
+ }
+
+ if (DOTENV_ASSIGNMENT.test(value)) {
+ return parseDotEnv(value);
+ }
+
+ return parseOrNull(() => parseYaml(value)) ?? parseDotEnv(value);
+};
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx
index 84ef913428..f1e33c82b9 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/ImportSecretsModal.tsx
@@ -550,7 +550,7 @@ const ImportSecretsContent = ({
)}
</div>
</TableCell>
- <TableCell isTruncatable className="w-1/2 font-mono text-xs">
+ <TableCell isTruncatable className="w-1/2 font-mono text-xs whitespace-pre">
{isVisible ? (
secretData.value || <span className="text-muted">EMPTY</span>
) : (
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/PasteSecretsDialog.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/PasteSecretsDialog.tsx
index 877f06529e..edab24e45a 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/PasteSecretsDialog.tsx
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/PasteSecretsDialog.tsx
@@ -3,7 +3,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { InfoIcon } from "lucide-react";
import { z } from "zod";
-import { parseDotEnv, parseJson } from "@app/components/utilities/parseSecrets";
+import { parsePastedSecrets } from "@app/components/utilities/parseSecrets";
import {
Button,
Dialog,
@@ -47,12 +47,7 @@ const PasteSecretsContent = ({ onParsedSecrets, onClose }: ContentProps) => {
} = useForm<TForm>({ defaultValues: { value: "" }, resolver: zodResolver(formSchema) });
const onSubmit = ({ value }: TForm) => {
- let env: TParsedEnv;
- try {
- env = parseJson(value);
- } catch {
- env = parseDotEnv(value);
- }
+ const env = parsePastedSecrets(value);
if (!Object.keys(env).length) {
setError("value", {
diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/parseSecretFile.ts b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/parseSecretFile.ts
index 258809ebe2..2581124cb0 100644
--- a/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/parseSecretFile.ts
+++ b/frontend/src/pages/secret-manager/OverviewPage/components/SecretDropzone/parseSecretFile.ts
@@ -100,18 +100,30 @@ export const parseSecretFile = (
return;
}
- const src = event.target.result as ArrayBuffer;
+ const src = event.target.result as string;
+
+ // Browsers frequently report an empty type for .yml/.yaml/.csv, so the extension
+ // has to be considered too, otherwise the file falls through to the dotenv
+ // parser and its contents get mangled.
+ const isYaml =
+ extension === "yml" ||
+ extension === "yaml" ||
+ file.type === "text/yaml" ||
+ file.type === "application/x-yaml" ||
+ file.type === "application/yaml";
+
+ try {
+ if (isYaml) {
+ onParsedSecrets(parseYaml(src));
+ return;
+ }
- switch (file.type) {
- case "application/json":
+ if (extension === "json" || file.type === "application/json") {
onParsedSecrets(parseJson(src));
- break;
- case "text/yaml":
- case "application/x-yaml":
- case "application/yaml":
- onParsedSecrets(parseYaml(src));
- break;
- case "text/csv": {
+ return;
+ }
+
+ if (extension === "csv" || file.type === "text/csv") {
const { matrix: fullMatrix, delimiter } = parseCsvToMatrix(src);
if (!fullMatrix.length) {
createNotification({
@@ -123,9 +135,16 @@ export const parseSecretFile = (
onCsvData({ headers: fullMatrix[0], matrix: fullMatrix.slice(1), delimiter });
return;
}
- default:
- onParsedSecrets(parseDotEnv(src));
- break;
+
+ onParsedSecrets(parseDotEnv(src));
+ } catch (error) {
+ createNotification({
+ type: "error",
+ text:
+ error instanceof Error
+ ? `Failed to parse ${file.name}: ${error.message}`
+ : `Failed to parse ${file.name}.`
+ });
}
};