diff --git a/Extension/src/Debugger/ParsedEnvironmentFile.ts b/Extension/src/Debugger/ParsedEnvironmentFile.ts index 9018a540b..e0557e77e 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,77 @@ 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, except inside a Windows path, where it + // separates segments instead. Only a drive letter or a UNC prefix makes the value a path: + // in ordinary text \${ is an escape, on any platform. + const windowsPath: 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) === "{" && !windowsPath) { + const end: number = value.indexOf("}", i + 3); + if (end !== -1) { + 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; + } + + /** + * 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..185374ee1 100644 --- a/Extension/test/scenarios/SingleRootProject/tests/ParsedEnvironmentFile.test.ts +++ b/Extension/test/scenarios/SingleRootProject/tests/ParsedEnvironmentFile.test.ts @@ -100,4 +100,153 @@ 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("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"); + }); });