fix: handle quoted script paths and stabilize lifecycle tests

Parse literal shell arguments for script navigation and pass preloader hook paths as process arguments. Use the actual task entry for ts-node hooks.

Isolate unused history dependencies in the spawn-failure test while preserving its 3-second timeout and real child-process assertions. Add regression coverage for quoting, hooks and navigation safety.

Validated formatting, 240 dev regressions, 45 preload-related regressions, 19 CLI checks, 10 lifecycle repeat runs, and both image variants with 20 execution and navigation scenarios.
This commit is contained in:
whyour committed 2026-11-22 14:00:31 +08:00
1 parent c5458596c8
commit 188f8805cb
6 files changed
+224 -39

No files matched your search

+25 -13
View File
@@ -1,4 +1,4 @@
const { execSync } = require('child_process');
const { execFileSync } = require('child_process');
const Module = require('module');
const path = require('path');
const client = require('./client.js');
@@ -73,15 +73,19 @@ function run() {
process.env.NODE_OPTIONS = PREV_NODE_OPTIONS;
const splitStr = '__sitecustomize__';
const fileName = process.argv[1].replace(`${dir_scripts}/`, '');
// ts-node is argv[1] during preload; the task runner knows the actual script.
const fileName = (process.env.QL_SCRIPT_ENTRY || process.argv[1]).replace(
`${dir_scripts}/`,
'',
);
const tempFile = `/tmp/env_${process.pid}.json`;
const commands = [
`source ${file_task_before} ${fileName}`,
task_before ? `eval '${task_before.replace(/'/g, "'\\''")}'` : null,
`echo -e '${splitStr}'`,
`node -e "require('fs').writeFileSync('${tempFile}', JSON.stringify(process.env))"`,
].filter(Boolean);
// Pass paths as arguments: shell syntax in a filename must stay literal.
const command = `file="$1"; output="$2"; inline="$3"; shift 3
source "$file" "$@" &&
{ if [ -n "$inline" ]; then eval "$inline"; fi; } &&
printf '%s\\n' '__sitecustomize__' &&
node -e 'require("fs").writeFileSync(process.argv[1], JSON.stringify(process.env))' "$output"`;
if (task_before) {
console.log(
@@ -91,11 +95,19 @@ function run() {
);
}
const res = execSync(commands.join(' && '), {
encoding: 'utf-8',
maxBuffer: 50 * 1024 * 1024,
shell: '/bin/bash',
});
const res = execFileSync(
'/bin/bash',
[
'-c',
command,
'ql-before',
file_task_before,
tempFile,
task_before || '',
fileName,
],
{ encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 },
);
const [output] = res.split(splitStr);
+13 -19
View File
@@ -37,6 +37,7 @@ def expand_range(range_str, max_value):
def run():
task_before = os.getenv("task_before", "")
try:
prev_pythonpath = os.getenv("PREV_PYTHONPATH", "")
os.environ["PYTHONPATH"] = prev_pythonpath
@@ -47,27 +48,20 @@ def run():
# 创建临时文件路径
temp_file = f"/tmp/env_{os.getpid()}.json"
# 构建命令数组
commands = [
f'source {os.getenv("file_task_before")} {file_name}'
]
task_before = os.getenv("task_before")
if task_before:
escaped_task_before = task_before.replace('"', '\\"').replace("$", "\\$")
commands.append(f"eval '{escaped_task_before}'")
print("Executing before command\n" if os.environ.get("QL_LANG") == "en" else "执行前置命令\n")
commands.append(f"echo -e '{split_str}'")
# 修改 Python 命令,使用单行并正确处理引号
python_cmd = f"python3 -c 'import os,json; f=open(\\\"{temp_file}\\\",\\\"w\\\"); json.dump(dict(os.environ),f); f.close()'"
commands.append(python_cmd)
command = " && ".join(cmd for cmd in commands if cmd)
command = f'bash -c "{command}"'
res = subprocess.check_output(command, shell=True, encoding="utf-8")
# Pass paths as arguments, without interpreting filename shell syntax.
command = """file="$1"; output="$2"; inline="$3"; shift 3
source "$file" "$@" &&
{ if [ -n "$inline" ]; then eval "$inline"; fi; } &&
printf '%s\\n' '__sitecustomize__' &&
python3 -c 'import os,json,sys; f=open(sys.argv[1],"w"); json.dump(dict(os.environ),f); f.close()' "$output"
"""
res = subprocess.check_output(
["/bin/bash", "-c", command, "ql-before", os.environ["file_task_before"],
temp_file, task_before, file_name],
encoding="utf-8",
)
output = res.split(split_str)[0]
try:
+45 -2
View File
@@ -308,12 +308,55 @@ export function logEnded(log: string): boolean {
export function getCommandScript(
command: string,
): [string, string] | string | undefined {
const cmd = command.split(' ') as string[];
// Read shell arguments without evaluating substitutions or expanding paths.
// Quoted and unquoted fragments can form one argument (task 'my dir'/a.js).
const cmd: string[] = [];
const raw: string[] = [];
let value = '',
source = '',
quote = '',
active = false;
for (let i = 0; i < command.length; i++) {
const c = command[i];
if (c === '\n' || c === '\r') return;
if (!quote && /\s/.test(c)) {
if (active) {
cmd.push(value);
raw.push(source);
}
value = source = '';
active = false;
continue;
}
source += c;
active = true;
if (c === quote) {
quote = '';
} else if (!quote && (c === "'" || c === '"')) {
quote = c;
} else if (c === '\\' && quote !== "'") {
const next = command[++i];
if (next === undefined || /[\r\n]/.test(next)) return;
source += next;
if (quote === '"' && !/[$`"\\]/.test(next)) value += '\\';
value += next;
} else {
value += c;
}
}
if (quote) return;
if (active) {
cmd.push(value);
raw.push(source);
}
if (cmd[1] === 'repo' || cmd[1] === 'raw') {
// Keep ambiguous escaped URLs out of browser navigation, even if removing
// the shell escape would turn them into a syntactically valid web URL.
if (raw[2]?.includes('\\')) return;
return cmd[2];
}
let scriptsPart = cmd.find((x) =>
['.js', '.ts', '.sh', '.py'].some((y) => x.endsWith(y)),
['.js', '.mjs', '.cjs', '.ts', '.sh', '.py'].some((y) => x.endsWith(y)),
);
if (!scriptsPart) return;
const scriptDir = `${window.__ENV__QL_DIR}/data/scripts`;
+14 -2
View File
@@ -20,6 +20,14 @@ test(
let releases = 0;
let active = 0;
const { runCron } = load(path.resolve('back/cron/execution/runCron.ts'), {
// This case has no trigger/history. Avoid compiling the entire history
// and scheduler graph inside the lifecycle timeout on constrained hosts.
'../history': {
triggerHistory: () => {
assert.fail('a run without a trigger must not access history');
},
},
'../../shared/i18n': { t: (message) => message },
'cross-spawn': {
spawn: () => spawn('true', { shell: '/nonexistent-ql-test-shell' }),
},
@@ -45,8 +53,12 @@ test(
},
'../../config/util': { killTask: async () => {} },
});
await runCron('true', { id: '1' });
await runCron('true', { id: '2' });
for (const id of ['1', '2']) {
const result = await runCron('true', { id });
assert.equal(result.error.code, 'ENOENT');
assert.equal(result.signal, null);
assert.equal(active, 0);
}
assert.equal(active, 0);
assert.equal(releases, 2);
},
+58 -2
View File
@@ -48,8 +48,12 @@ function fixture(t, language) {
ACCOUNTS: 'first&second&third',
};
const write = (name, text) => fs.writeFileSync(path.join(root, name), text);
const run = (body, extensionOverride = extension) => {
const entry = path.join(root, `entry.${extensionOverride}`);
const run = (
body,
extensionOverride = extension,
filename = `entry.${extensionOverride}`,
) => {
const entry = path.join(root, filename);
write(path.basename(entry), body);
const python = language === 'python';
const result = spawnSync(
@@ -65,6 +69,58 @@ function fixture(t, language) {
return { root, env, write, run };
}
for (const extension of ['js', 'mjs', 'py']) {
test(`${extension} before hooks receive quoted filenames literally and preserve exported variables`, (t) => {
const f = fixture(t, extension === 'py' ? 'python' : 'javascript');
const hook = `before ' " #.sh`;
f.write(
hook,
'export HOOK_FILE="$1"\nexport HOOK_COUNT="$#"\nexport FROM_SHELL=before\n',
);
f.env.file_task_before = path.join(f.root, hook);
f.env.task_before = `export FROM_COMMAND='literal "quotes" $value'`;
for (const name of [
'space #?&%+',
`single' double"`,
'literal $(touch injected)',
'literal `touch injected` ;',
]) {
const filename = `${name}.${extension}`;
const body =
extension === 'py'
? `import os\nassert os.environ['HOOK_FILE'] == ${JSON.stringify(
filename,
)}\nassert os.environ['HOOK_COUNT'] == '1'\nassert os.environ['FROM_SHELL'] == 'before'\nassert os.environ['FROM_COMMAND'] == 'literal "quotes" $value'\nprint('HOOK_OK')\n`
: `${
extension === 'mjs'
? 'import assert from "node:assert/strict";'
: 'const assert = require("node:assert/strict");'
}\nassert.equal(process.env.HOOK_FILE, ${JSON.stringify(
filename,
)});\nassert.equal(process.env.HOOK_COUNT, '1');\nassert.equal(process.env.FROM_SHELL, 'before');\nassert.equal(process.env.FROM_COMMAND, 'literal "quotes" $value');\nconsole.log('HOOK_OK');`;
const output = f.run(body, extension, filename);
assert.match(output, /HOOK_OK/);
assert.doesNotMatch(
output,
/Failed to parse environment|run task before error/,
);
assert.equal(fs.existsSync(path.join(f.root, 'injected')), false);
}
});
}
test('Node launcher preload passes the runner script entry to the before hook', (t) => {
const f = fixture(t, 'javascript');
const filename = `actual ' " #.ts`;
f.env.QL_SCRIPT_ENTRY = path.join(f.root, filename);
f.write('before.sh', 'export HOOK_FILE="$1"\n');
f.run(
`require('node:assert/strict').equal(process.env.HOOK_FILE, ${JSON.stringify(
filename,
)});`,
);
});
for (const extension of ['js', 'mjs']) {
test(`${extension} startup preserves hooks, environment selection and client without importing notifications`, (t) => {
const f = fixture(t, 'javascript');
+69 -1
View File
@@ -115,7 +115,9 @@ test('script navigation preserves filenames as data without injecting query para
];
for (const [parent, file] of files) {
const n = navigation();
n.go({ command: `task ${parent ? `${parent}/` : ''}${file}` });
n.go({
command: `task ${JSON.stringify(parent ? `${parent}/${file}` : file)}`,
});
assert.equal(n.paths.length, 1);
const target = new URL(n.paths[0], 'https://panel.example');
assert.equal(target.origin, 'https://panel.example');
@@ -155,3 +157,69 @@ test('SSH repository addresses remain intact without being treated as browser UR
assert.deepEqual(n.paths, []);
}
});
test('quoted script operands navigate to the same literal file used by the task editor', () => {
const cases = [
['task "脚本.js"', '脚本.js', ''],
[
"task 'my dir/脚本 #?&%+.py' -- 'arg with spaces'",
'脚本 #?&%+.py',
'my dir',
],
['task "my dir"/script.js now', 'script.js', 'my dir'],
[String.raw`task my\ dir/script\ name.sh`, 'script name.sh', 'my dir'],
[String.raw`task "repo/a\"b.js"`, 'a"b.js', 'repo'],
[String.raw`task 'repo/a'\''b.js'`, "a'b.js", 'repo'],
[String.raw`task 'repo/a\b.js'`, String.raw`a\b.js`, 'repo'],
[String.raw`task "repo/a\b.js"`, String.raw`a\b.js`, 'repo'],
['task\t-l\t"/ql/data/scripts/my dir/main.mjs"', 'main.mjs', '/my dir'],
['node "repo/main.cjs"', 'main.cjs', 'repo'],
['task "" "script.ts"', 'script.ts', ''],
];
for (const [command, file, parent] of cases) {
assert.deepEqual(getCommandScript(command), [file, parent], command);
const n = navigation();
n.go({ command });
assert.equal(n.paths.length, 1, command);
const target = new URL(n.paths[0], 'https://panel.example');
assert.equal(target.searchParams.get('s'), file, command);
assert.equal(target.searchParams.get('p'), parent, command);
assert.equal(target.hash, '');
}
});
test('incomplete quoting does not navigate to a different script', () => {
for (const command of [
'task "script.js',
"task 'script.js",
'task script.js\\',
'task script.js\necho other',
'task "script.js" "unfinished',
]) {
assert.equal(getCommandScript(command), undefined, command);
const n = navigation();
n.go({ command });
assert.deepEqual(n.paths, [], command);
assert.deepEqual(n.external, [], command);
}
});
test('quoted repository targets retain the web navigation safety checks', () => {
for (const quote of ["'", '"']) {
const safe = navigation();
safe.go({
command: `ql repo ${quote}https://example.com/a?x=1&y=2${quote}`,
});
assert.deepEqual(safe.external, ['https://example.com/a?x=1&y=2']);
for (const target of [
'javascript:alert(1)',
'data:text/html,hello',
'https://trusted.example\\@attacker.example/a.js',
]) {
const n = navigation();
n.go({ command: `ql raw ${quote}${target}${quote}` });
assert.deepEqual(n.paths, []);
assert.deepEqual(n.external, []);
}
}
});