diff --git a/Extension/src/Debugger/ParsedEnvironmentFile.ts b/Extension/src/Debugger/ParsedEnvironmentFile.ts index 9018a540b..67ec55d5f 100644 --- a/Extension/src/Debugger/ParsedEnvironmentFile.ts +++ b/Extension/src/Debugger/ParsedEnvironmentFile.ts @@ -57,8 +57,42 @@ export class ParsedEnvironmentFile { value = value.replace(/\\n/gm, "\n"); } + // A single-quoted value is literal, so a reference inside it must not be + // expanded. The quotes come off on the next line, so this has to be read here. + // Whitespace outside the closing quote is not part of the value, and leaving it + // in hid the quote from the check below. + const trimmed: string = value.replace(/\s+$/, ""); + const singleQuoted: boolean = (trimmed.length > 1) && (trimmed.charAt(0) === "'") && (trimmed.charAt(trimmed.length - 1) === "'"); + if (singleQuoted) { + value = trimmed; + } + value = value.replace(/(^['"]|['"]$)/g, ""); + // Resolve ${VAR} references against the variables defined so far in the file, + // then the process environment. A name we don't know is left as-is rather than + // dropped, so ${workspaceFolder} and the other launch variables still resolve + // from the debug configuration. + // + // A reference that has to stay literal is written back as ${dollar}{VAR}. This + // parser's output goes on to expandAllStrings (configurationProvider.expand), + // which substitutes every remaining ${...} it knows and warns about the rest, so + // a bare ${VAR} would be replaced or reported instead of reaching the debuggee. + // ${dollar} is the one form that expansion leaves alone and collapses to a plain + // $ once it is done, which is what makes the literal survive the trip. + // + // The dotenv-style names are not the only ones that expansion touches: it also + // rewrites ${env:...} and runs ${command:...}, both matched on anything up to the + // closing brace. So the protection cannot be limited to [\w\.\-]+ -- every ${ in + // a single-quoted value, and every escaped ${ anywhere, is written back, whatever + // follows it. Unescaped dotenv-style names are the only ones resolved here; an + // unescaped ${env:...} is left for the launch expansion, as before. + if (singleQuoted) { + value = value.replace(/\$\{/g, `\${dollar}{`); + } else { + value = ParsedEnvironmentFile.resolveReferences(value, (name: string) => ParsedEnvironmentFile.lookup(name, env)); + } + env.set(key, value); } else { // Blank lines and lines starting with # are no parse errors @@ -86,4 +120,90 @@ export class ParsedEnvironmentFile { return new ParsedEnvironmentFile(arrayEnv, warning); } + + /** + * Resolve the references the file can actually answer, and leave the others untouched so + * the launch expansion still sees them. + */ + private static resolveReferences(value: string, known: (name: string) => string | undefined): string { + // A backslash in front of a reference escapes it, unless it separates path segments. The + // value as a whole cannot decide: prose can carry another backslash (\${USER} regex\w) and + // a path can be built out of references (${workspaceFolder}\${env:USERNAME}). Each + // occurrence is judged by its neighbours, and a drive or UNC value keeps them all. + const pathValue: boolean = /^[A-Za-z]:[\\/]/.test(value) || /^\\\\/.test(value); + let result: string = ""; + let i: number = 0; + while (i < value.length) { + const char: string = value.charAt(i); + + // An escaped reference is literal. ${dollar} is the form the launch expansion leaves + // alone and collapses back to a plain $ once it is done, so the debuggee is the only + // place that sees the literal. The whole opener has to be there: \$USER} is not a + // reference and must not be rewritten. + if (char === "\\" && value.charAt(i + 1) === "$" && value.charAt(i + 2) === "{") { + const end: number = value.indexOf("}", i + 3); + if (end !== -1 && !pathValue && !ParsedEnvironmentFile.separatesSegments(value, i, end)) { + result += `\${dollar}{${value.substring(i + 3, end)}}`; + i = end + 1; + continue; + } + } + + if (char === "$" && value.charAt(i + 1) === "{") { + const end: number = value.indexOf("}", i + 2); + if (end !== -1) { + const name: string = value.substring(i + 2, end); + const resolved: string | undefined = /^[\w\.\-]+$/.test(name) ? known(name) : undefined; + result += resolved !== undefined ? resolved : value.substring(i, end + 1); + i = end + 1; + continue; + } + } + + result += char; + i += 1; + } + + return result; + } + + /** + * Whether the backslash at index separates path segments instead of escaping the reference that + * ends at end. It continues a path when it follows a reference, a dot or a separator, and it + * starts one when the value goes on with a separator: tools\${env:USERNAME}\bin. In prose + * neither holds, so the backslash escapes. + */ + private static separatesSegments(value: string, index: number, end: number): boolean { + const before: string = index > 0 ? value.charAt(index - 1) : ""; + const after: string = value.charAt(end + 1); + return (before !== "" && "}.\\/:".includes(before)) || after === "\\" || after === "/"; + } + + /** + * Environment variable names are case-insensitive on Windows, and the launch configuration + * may have spelled the name differently than the reference does, so Path and PATH have to + * find each other there. + */ + private static lookup(name: string, env: Map): string | undefined { + if (env.has(name)) { + return env.get(name); + } + + if (process.platform === "win32") { + const folded: string = name.toLowerCase(); + for (const key of env.keys()) { + if (key.toLowerCase() === folded) { + return env.get(key); + } + } + for (const key of Object.keys(process.env)) { + if (key.toLowerCase() === folded) { + return process.env[key]; + } + } + return undefined; + } + + return process.env[name]; + } } diff --git a/Extension/test/scenarios/SingleRootProject/tests/ParsedEnvironmentFile.test.ts b/Extension/test/scenarios/SingleRootProject/tests/ParsedEnvironmentFile.test.ts index a107971ce..352ac34c0 100644 --- a/Extension/test/scenarios/SingleRootProject/tests/ParsedEnvironmentFile.test.ts +++ b/Extension/test/scenarios/SingleRootProject/tests/ParsedEnvironmentFile.test.ts @@ -100,4 +100,197 @@ MyName2=Value2 assertEnvironmentEqual(result.Env, "MyName1", "Value1"); assertEnvironmentEqual(result.Env, "MyName2", "Value2"); }); + + test("Resolve a reference to a variable defined earlier in the file", () => { + const content: string = `USER=admin +EMAIL=\${USER}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "USER", "admin"); + assertEnvironmentEqual(result.Env, "EMAIL", "admin@example.org"); + }); + + test("Resolve a reference from the initial environment", () => { + const initialEnv: Environment[] = [{ name: "USER", value: "admin" }]; + const content: string = `EMAIL=\${USER}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", initialEnv); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "admin@example.org"); + }); + + test("Leave an unknown reference untouched", () => { + const content: string = `EMAIL=\${UNKNOWN_USER}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "${UNKNOWN_USER}@example.org"); + }); + + test("Resolve a reference from the process environment", () => { + const name: string = "CPPTOOLS_ENVFILE_INTERPOLATION_TEST"; + const previous: string | undefined = process.env[name]; + process.env[name] = "from-process"; + try { + const content: string = `EMAIL=\${${name}}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "from-process@example.org"); + } finally { + if (previous === undefined) { + delete process.env[name]; + } else { + process.env[name] = previous; + } + } + }); + + test("Protect a reference inside a single-quoted value from the launch expansion", () => { + const content: string = `USER=admin\nEMAIL='\${USER}@example.org'`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + // ${dollar} is the one form expandAllStrings leaves alone, and it collapses to a plain $ + // when that expansion finishes (expand.ts), so the debuggee still receives the literal. + assertEnvironmentEqual(result.Env, "EMAIL", "${dollar}{USER}@example.org"); + }); + + test("Protect an escaped reference the same way, without the backslash", () => { + const content: string = `USER=admin\nEMAIL=\\\${USER}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "${dollar}{USER}@example.org"); + }); + + test("Protect a launch reference inside a single-quoted value", () => { + // ${env:...} and ${command:...} are matched on anything up to the closing brace, so a + // dotenv-style name filter would let them through and the launch expansion would + // substitute (or run) them even though the value is single-quoted. + const content: string = `HOME_DIR='\${env:HOME}'\nCMD='\${command:workbench.action.files.newUntitledFile}'`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "HOME_DIR", "${dollar}{env:HOME}"); + assertEnvironmentEqual(result.Env, "CMD", "${dollar}{command:workbench.action.files.newUntitledFile}"); + }); + + test("Protect an escaped launch reference, without the backslash", () => { + const content: string = `HOME_DIR=\\\${env:HOME}`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "HOME_DIR", "${dollar}{env:HOME}"); + }); + + test("Leave an unescaped launch reference bare for the expansion", () => { + const content: string = `HOME_DIR=\${env:HOME}`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "HOME_DIR", "${env:HOME}"); + }); + + test("Leave a resolved reference bare, so the expansion can still see it", () => { + const content: string = `USER=admin\nEMAIL=\${USER}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "admin@example.org"); + }); + + test("Keep the separator before a reference in a Windows path", () => { + // The backslash in front of ${ here separates path segments, it does not escape the + // reference. Dropping it turned C:\Users\Alice\project into C:\Users${env:USERNAME}. + const content: string = `USER_DIR=C:\\Users\\\${env:USERNAME}\\project`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "USER_DIR", "C:\\Users\\${env:USERNAME}\\project"); + }); + + test("Keep the separator before a reference in a relative Windows path", () => { + // Without a drive letter the value is still a path: .\ is a separator, and so is the one + // before bin, so the backslash in front of the reference must survive. + const reference: string = "${env:USERNAME}"; + const content: string = "BIN=.\\" + reference + "\\bin"; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "BIN", ".\\" + reference + "\\bin"); + }); + + test("Keep the separator before a reference further down a relative path", () => { + // No drive letter and no .\ opener either: the separator before bin is what shows this + // is a path, so the one before the reference separates segments as well. + const reference: string = "${env:USERNAME}"; + const content: string = "BIN=tools\\" + reference + "\\bin"; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "BIN", "tools\\" + reference + "\\bin"); + }); + + test("Protect an escaped reference when the value carries another backslash", () => { + // The regex\w has nothing to do with the reference: this is prose, not a path. + const reference: string = "${USER}"; + const content: string = "USER=admin\nMESSAGE=prefix\\" + reference + " regex\\w"; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "MESSAGE", "prefix${dollar}{USER} regex\\w"); + }); + + test("Keep the separator where a path is built out of references", () => { + // No drive letter and no separator after the reference: the one in front of it follows a + // closed reference, so it separates, and both references stay for the launch expansion. + const folder: string = "${workspaceFolder}"; + const user: string = "${env:USERNAME}"; + const content: string = "DIR=" + folder + "\\" + user; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "DIR", folder + "\\" + user); + }); + + test("Match an initial environment name regardless of case on Windows", () => { + // Path and PATH are the same variable on Windows, and the launch configuration may use + // either spelling. The name is not in the process environment, so off Windows the + // reference is left bare for the launch expansion instead of resolving to a host value. + const content: string = `COPY=\${TEST_CASE_FOLDER}`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent( + content, "TestEnvFileName", [{ name: "test_case_folder", value: "from-config" }]); + + const expected: string = process.platform === "win32" ? "from-config" : "${TEST_CASE_FOLDER}"; + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "COPY", expected); + }); + + test("Keep an escaped reference inside ordinary text literal", () => { + // The backslash is only a path separator inside a Windows path. In prose it escapes. + const content: string = `USER=admin\nEMAIL=prefix\\\${USER}@example.org`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "prefix${dollar}{USER}@example.org"); + }); + + test("Leave a lone escaped dollar alone", () => { + // There is no reference here, so there is nothing to rewrite. + const content: string = `VALUE=\\$USER}`; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "VALUE", "\\$USER}"); + }); + + test("Protect a quoted value with trailing whitespace", () => { + const content: string = `USER=admin\nEMAIL='\${USER}@example.org' `; + const result: ParsedEnvironmentFile = ParsedEnvironmentFile.CreateFromContent(content, "TestEnvFileName", []); + + assert(!result.Warning, `Failed to assert that Warning was empty: ${result.Warning}`); + assertEnvironmentEqual(result.Env, "EMAIL", "${dollar}{USER}@example.org"); + }); });