frontend-quality-gates / merge / static checks (pull_request) Successful in 1m15s
frontend-quality-gates / merge / tests (pull_request) Successful in 13m20s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m16s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped
스크립트 22곳이 argv[1]로 직접 실행을 판정해서, checkout 경로에 공백·한글이 있거나 symlink 절대 경로로 부르면 18곳이 검사 없이 rc=0으로 끝날 수 있다. merge 게이트 명령 셋이 여기 걸린다. isEntryModule(import.meta) 하나로 바꾸고, process.argv 둘째 값 읽기와 helper 밖 판정은 시험으로 막는다. 맨 import.meta.main은 그 값이 없는 Node에서 같은 거짓 통과가 나서 버렸다. realpath 비교는 같은 판정의 사본 22개가 남고, argv 값의 쓰임을 따라가는 시험은 return·대입으로 피할 수 있어 버렸다. 위험·한계: 건너뛰던 검사가 실패하기 시작할 수 있고, 실행 판정이 아닌 process.argv[1] 읽기도 실패한다. import.meta.main이 없는 Node에서 직접 실행하거나 import하면 실패한다. verify-extreme-scale도 그 Node에서는 rc=2보다 먼저 rc=1로 끝나고, 이전 기록(passed일 수 있다)이 그대로 남아 종료 code로 본다. 코드로 읽은 것이고 그 Node로 돌려 보지 않았다. 막는 시험은 process·argv 별칭과 계산한 index를 따라가지 않는다. 검증(노트북, main으로 옮기기 전 트리 a806088b): 새 시험 고치기 전 실패, 고친 뒤 통과. test:unit 3707개, types, lint, check:ci, verify:documentation rc=0. desktop merge 단계는 따로 확인한다. Refs: REV-FE-0040
375 lines
18 KiB
TypeScript
375 lines
18 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { cp, mkdir, mkdtemp, readdir, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
|
|
import { parseSync, traverse, types as t, type Scope } from "@babel/core";
|
|
import { afterEach, describe, expect, it } from "vitest";
|
|
|
|
import { selectRepositoryPaths } from "../../scripts/lib/repository-layout.ts";
|
|
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
|
|
|
|
/**
|
|
* REV-FE-0040. Twenty-two scripts compared `process.argv[1]` with their own
|
|
* path to learn whether they were started directly. In a checkout path with a
|
|
* space or Korean, or through a symlink, the comparison was false and the
|
|
* checker exited 0 without checking. A bare `import.meta.main` does the same
|
|
* on a Node that does not have it. scripts/lib/entry-module.ts is the one
|
|
* judgement, and it fails there.
|
|
*
|
|
* So scripts/ does not read the second value of process.argv at all, whatever
|
|
* the value is for: a rule on what it decides was evaded by a return, an
|
|
* assignment, a switch or a call. The rule knows `process.argv` and `argv`
|
|
* imported from node:process. It follows no other name of either and no
|
|
* computed index.
|
|
*/
|
|
const HELPER = path.resolve("scripts/lib/entry-module.ts");
|
|
const PROCESS_MODULES = new Set(["process", "node:process"]);
|
|
const GUARD_CALL = "isEntryModule(import.meta)";
|
|
const IMPORTER = "write-dev-release-manifest.ts";
|
|
const SCRIPT_FILE = /\.(?:[cm]?[jt]s|[jt]sx)$/u;
|
|
const CHILD_PROCESS_TIMEOUT = childProcessTimeout(1752);
|
|
|
|
const isMember = (node: t.Node): node is t.MemberExpression | t.OptionalMemberExpression =>
|
|
t.isMemberExpression(node) || t.isOptionalMemberExpression(node);
|
|
|
|
function propertyName(property: t.Node, computed: boolean): string | undefined {
|
|
if (t.isIdentifier(property) && !computed) return property.name;
|
|
if (t.isStringLiteral(property)) return property.value;
|
|
return t.isNumericLiteral(property) ? String(property.value) : undefined;
|
|
}
|
|
|
|
/** `process.argv`, or `argv` imported from node:process. A local array named argv is neither. */
|
|
function isProcessArgv(node: t.Node, scope: Scope): boolean {
|
|
if (t.isIdentifier(node)) {
|
|
const imported = scope.getBinding(node.name)?.path;
|
|
const declaration = imported?.parentPath;
|
|
if (!imported?.isImportSpecifier() || !declaration?.isImportDeclaration()) return false;
|
|
return PROCESS_MODULES.has(declaration.node.source.value) && propertyName(imported.node.imported, false) === "argv";
|
|
}
|
|
if (!isMember(node) || !t.isIdentifier(node.object)) return false;
|
|
return node.object.name === "process" && propertyName(node.property, node.computed) === "argv";
|
|
}
|
|
|
|
/** `[1]`, `.at(1)`, or a `.slice()` that starts at or before it. */
|
|
function readsSecondValue(node: t.Node, scope: Scope): boolean {
|
|
if (isMember(node)) {
|
|
return node.computed && propertyName(node.property, true) === "1" && isProcessArgv(node.object, scope);
|
|
}
|
|
if (!t.isCallExpression(node) && !t.isOptionalCallExpression(node)) return false;
|
|
const { callee } = node;
|
|
if (!isMember(callee) || !isProcessArgv(callee.object, scope)) return false;
|
|
const method = propertyName(callee.property, callee.computed);
|
|
const [first] = node.arguments;
|
|
if (method === "at") return t.isNumericLiteral(first) && first.value === 1;
|
|
return method === "slice" && (first === undefined || (t.isNumericLiteral(first) && first.value <= 1));
|
|
}
|
|
|
|
/** `const [, entry] = process.argv`, or a rest element that takes it along. */
|
|
function destructuresSecondValue(target: t.Node, value: t.Node, scope: Scope): boolean {
|
|
if (!t.isArrayPattern(target) || !isProcessArgv(value, scope)) return false;
|
|
return target.elements.some(
|
|
(element, index) => element !== null && (index === 1 || (index === 0 && t.isRestElement(element))),
|
|
);
|
|
}
|
|
|
|
/** By the path it resolves to: another file of the same name is another helper. */
|
|
const isHelperModule = (file: string, specifier: string) => path.resolve(path.dirname(file), specifier) === HELPER;
|
|
|
|
function isGuardCall(file: string, node: t.Node, scope: Scope): boolean {
|
|
if (!t.isCallExpression(node) || !t.isIdentifier(node.callee)) return false;
|
|
if (node.callee.name !== "isEntryModule" || node.arguments.length !== 1) return false;
|
|
const [meta] = node.arguments;
|
|
if (!t.isMetaProperty(meta) || meta.meta.name !== "import") return false;
|
|
const declaration = scope.getBinding("isEntryModule")?.path.parentPath;
|
|
return declaration?.isImportDeclaration() === true && isHelperModule(file, declaration.node.source.value);
|
|
}
|
|
|
|
/**
|
|
* `refused`: the lines that read process.argv[1] or judge "started directly"
|
|
* without the helper. `import.meta` passes as `.filename` and the like or as
|
|
* the helper's argument. `importing`: the file imports the helper. `guarded`:
|
|
* a top-level statement is `if (isEntryModule(import.meta))`.
|
|
*/
|
|
function inspectScript(file: string, source: string) {
|
|
const refused = new Set<string>();
|
|
let importing = false;
|
|
let guarded = false;
|
|
if (!/argv|import\.meta|entry-module/u.test(source)) return { refused: [...refused], importing, guarded };
|
|
const tree = parseSync(source, {
|
|
filename: file,
|
|
babelrc: false,
|
|
configFile: false,
|
|
sourceType: "module",
|
|
parserOpts: { plugins: file.endsWith("x") ? ["typescript", "jsx"] : ["typescript"] },
|
|
});
|
|
if (!tree) throw new Error(`cannot parse ${file}`);
|
|
const refuse = (node: t.Node, what: string) => refused.add(`${node.loc?.start.line}: ${what}`);
|
|
traverse(tree, {
|
|
ImportDeclaration({ node }) {
|
|
if (isHelperModule(file, node.source.value)) importing = true;
|
|
},
|
|
IfStatement({ node, scope, parentPath }) {
|
|
if (parentPath?.isProgram() && isGuardCall(file, node.test, scope)) guarded = true;
|
|
},
|
|
VariableDeclarator({ node, scope }) {
|
|
if (node.init && destructuresSecondValue(node.id, node.init, scope)) refuse(node, "process.argv[1]");
|
|
},
|
|
Expression({ node, parent, scope }) {
|
|
if (
|
|
readsSecondValue(node, scope) ||
|
|
(t.isAssignmentExpression(node) && destructuresSecondValue(node.left, node.right, scope))
|
|
) {
|
|
refuse(node, "process.argv[1]");
|
|
}
|
|
if (!t.isMetaProperty(node) || node.meta.name !== "import") return;
|
|
if (isMember(parent)) {
|
|
if (propertyName(parent.property, parent.computed) === "main") refuse(node, "import.meta.main");
|
|
} else if (!isGuardCall(file, parent, scope)) {
|
|
refuse(node, "import.meta");
|
|
}
|
|
},
|
|
});
|
|
return { refused: [...refused], importing, guarded };
|
|
}
|
|
|
|
function refusalMessage(found: readonly string[]): string {
|
|
return [
|
|
`${found.length} line(s) to change. In scripts/, process.argv[1] is not read:`,
|
|
"- a script's own path is import.meta.filename, and its arguments are process.argv.slice(2);",
|
|
`- "started directly" is ${GUARD_CALL} from scripts/lib/entry-module.ts.`,
|
|
...found,
|
|
].join("\n");
|
|
}
|
|
|
|
type Script = Readonly<{ file: string; source: string }>;
|
|
|
|
/**
|
|
* The files the import-only test may import: importing any other runs its body.
|
|
* A broken guard would only leave this set and pass C3 and C4, so first the
|
|
* set has to be every file that imports the helper.
|
|
*/
|
|
function guardedScripts(scripts: readonly Script[]): string[] {
|
|
const inspected = scripts.map(({ file, source }) => ({ file, ...inspectScript(file, source) }));
|
|
const importing = inspected.filter((script) => script.importing).map(({ file }) => file);
|
|
const guarded = inspected.filter((script) => script.guarded).map(({ file }) => file);
|
|
expect(
|
|
guarded,
|
|
`each script that imports the helper needs a top-level if (${GUARD_CALL}); nothing was imported`,
|
|
).toEqual(importing);
|
|
return guarded;
|
|
}
|
|
|
|
async function scriptSources(): Promise<readonly Script[]> {
|
|
const files = (await readdir("scripts", { recursive: true }))
|
|
.filter((file) => SCRIPT_FILE.test(file))
|
|
.map((file) => path.join("scripts", file))
|
|
.sort();
|
|
return Promise.all(files.map(async (file) => ({ file, source: await readFile(file, "utf8") })));
|
|
}
|
|
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
async function emptyFolder(): Promise<string> {
|
|
const root = await mkdtemp(path.join(tmpdir(), "script-entry-"));
|
|
roots.push(root);
|
|
return root;
|
|
}
|
|
|
|
function runNode(cwd: string, args: readonly string[]) {
|
|
const environment: NodeJS.ProcessEnv = { ...process.env, NODE_NO_WARNINGS: "1" };
|
|
delete environment["RUN_OUTPUT_ROOT"];
|
|
// spawnSync blocks the event loop, so the test's own timeout cannot end a child that hangs.
|
|
const { status, stdout, stderr, error } = spawnSync(process.execPath, args, {
|
|
cwd,
|
|
encoding: "utf8",
|
|
env: environment,
|
|
timeout: CHILD_PROCESS_TIMEOUT,
|
|
killSignal: "SIGKILL",
|
|
});
|
|
return { status, output: `${stdout}${stderr}${error?.message ?? ""}` };
|
|
}
|
|
|
|
/** Imports the files from an entry with the name of one of the scripts. */
|
|
async function importOnly(root: string, files: readonly string[]) {
|
|
const importer = path.join(root, IMPORTER);
|
|
await writeFile(path.join(root, "package.json"), '{ "type": "module" }\n');
|
|
const imports = files.map((file) => `await import(${JSON.stringify(pathToFileURL(path.resolve(file)).href)});`);
|
|
await writeFile(importer, `${imports.join("\n")}\nprocess.stdout.write("imported");\n`);
|
|
return runNode(root, [importer]);
|
|
}
|
|
|
|
const importsHelperFrom = (specifier: string) => `import { isEntryModule } from "${specifier}";\n`;
|
|
|
|
describe("script entry guards", () => {
|
|
it("finds no read of process.argv[1] and no judgement outside the helper (C3, D3)", async () => {
|
|
const scripts = await scriptSources();
|
|
expect(scripts.length).toBeGreaterThan(0);
|
|
const found = scripts.flatMap(({ file, source }) =>
|
|
inspectScript(file, source).refused.map((refusal) => `${file}:${refusal}`),
|
|
);
|
|
|
|
expect(found, refusalMessage(found)).toEqual([]);
|
|
});
|
|
|
|
it.each([
|
|
"if (import.meta.url === `file://${process.argv[1]}`) await main();",
|
|
"if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main();",
|
|
"const invoked = process.argv[1];\nif (invoked !== undefined && import.meta.url === pathToFileURL(invoked).href) await main();",
|
|
'if (process.argv[1]?.endsWith("check.ts")) await main();',
|
|
"if (process.argv[1] && import.meta.url.endsWith(path.basename(process.argv[1]))) await main();",
|
|
"export const invokedAs = (url: string) => pathToFileURL(process.argv.at(1)!).href === url;",
|
|
"if (import.meta.main) await main();",
|
|
"if (import.meta?.main) await main();",
|
|
'if (import.meta["main"]) await main();',
|
|
"const { main: direct } = import.meta;",
|
|
"if (startedDirectly(import.meta)) await main();",
|
|
"const isEntryModule = (meta: ImportMeta) => meta.main;\nif (isEntryModule(import.meta)) await main();",
|
|
// Each of these passed while only a comparison of the value was refused.
|
|
"function entryPath() {\n return process.argv[1];\n}\nif (entryPath() === fileURLToPath(import.meta.url)) await main();",
|
|
"function started(): string {\n return `file://${process.argv[1]}`;\n}\nif (started() === import.meta.url) await main();",
|
|
"let invoked: string | undefined;\ninvoked = process.argv[1];\nif (invoked === fileURLToPath(import.meta.url)) await main();",
|
|
'switch (path.basename(process.argv[1] ?? "")) {\n case "check.ts":\n await main();\n}',
|
|
"const direct = (entry?: string) => entry === fileURLToPath(import.meta.url);\ndirect(process.argv[1]) && (await main());",
|
|
'import { argv } from "node:process";\nif (argv[1] === fileURLToPath(import.meta.url)) await main();',
|
|
'import { argv as given } from "process";\nrun(given.at(1));',
|
|
'run(process["argv"]["1"]);',
|
|
"const [invoked] = process.argv.slice(1);\nif (invoked === fileURLToPath(import.meta.url)) await main();",
|
|
"run(process.argv.slice());",
|
|
"run(process.argv.slice(0));",
|
|
"const [, entry] = process.argv;",
|
|
"const [node, ...rest] = process.argv;",
|
|
"const [...everything] = process.argv;",
|
|
"let entry: string | undefined;\n[, entry] = process.argv;",
|
|
"process.stderr.write(`usage: node ${process.argv[1]} <id>`);",
|
|
"spawnSync(process.execPath, [process.argv[1]!, \"--child\"]);",
|
|
'export const retry = (): unknown => spawn(process.execPath, [process.argv[1]!]).on("exit", retry);',
|
|
])("refuses %j (C3, D3)", (source) => {
|
|
expect(inspectScript("scripts/check.ts", source).refused).not.toEqual([]);
|
|
});
|
|
|
|
it.each([
|
|
'const root = process.argv[2] ?? ".";\nif (root === ".") await main();',
|
|
'if (process.argv.includes("--check")) await check();',
|
|
'const index = process.argv.indexOf("--root");\nif (process.argv[index + 1]) await check();',
|
|
'spawnSync("node", ["-e", "if (process.argv[1] === \'x\') process.exit(1)"]);',
|
|
"// not process.argv[1] === import.meta.url, not import.meta.main\nconst here = import.meta.url;",
|
|
"run(process.argv.slice(2));",
|
|
"const port = Number(process.argv[3] ?? 6006);",
|
|
'const named = process.argv.find((argument) => argument.startsWith("--only="));',
|
|
"const [, , first] = process.argv;",
|
|
"const [, second] = names;",
|
|
'export function parse(argv: readonly string[]) {\n return argv[0] === "--" ? argv.slice(1) : [...argv];\n}',
|
|
"export const second = (argv: readonly string[]) => argv[1];",
|
|
"run(import.meta.filename);",
|
|
])("lets %j pass (C3, D3)", (source) => {
|
|
expect(inspectScript("scripts/check.ts", source).refused).toEqual([]);
|
|
});
|
|
|
|
it.each([
|
|
["scripts/check.ts", "./lib/entry-module.ts"],
|
|
["scripts/scale/check.ts", "../lib/entry-module.ts"],
|
|
["scripts/lib/check.ts", "./entry-module.ts"],
|
|
] as const)("takes the helper that %s imports from %s as the guard (C3, C4)", (file, specifier) => {
|
|
const source = `${importsHelperFrom(specifier)}if (${GUARD_CALL}) await main();`;
|
|
expect(inspectScript(file, source)).toEqual({ refused: [], importing: true, guarded: true });
|
|
});
|
|
|
|
it.each([
|
|
["scripts/scale/check.ts", "./entry-module.ts"],
|
|
["scripts/check.ts", "./entry-module.ts"],
|
|
["scripts/check.ts", "./other/lib/entry-module.ts"],
|
|
] as const)("refuses the other helper that %s imports from %s (C3, D3)", (file, specifier) => {
|
|
const source = `${importsHelperFrom(specifier)}if (${GUARD_CALL}) await main();`;
|
|
expect(inspectScript(file, source)).toEqual({
|
|
refused: [expect.stringContaining("import.meta")],
|
|
importing: false,
|
|
guarded: false,
|
|
});
|
|
});
|
|
|
|
it.each([
|
|
"if (isEntryModule(import.meta) || true) await main();",
|
|
"if (!isEntryModule(import.meta)) await main();",
|
|
"isEntryModule(import.meta);\nawait main();",
|
|
"export function start() {\n if (isEntryModule(import.meta)) return;\n}\nawait main();",
|
|
"await main();",
|
|
])("stops before it imports a script that has the helper and %j (C4)", (body) => {
|
|
const source = `${importsHelperFrom("./lib/entry-module.ts")}${body}`;
|
|
expect(() => guardedScripts([{ file: "scripts/check.ts", source }])).toThrow("nothing was imported");
|
|
});
|
|
|
|
it("says what to use instead (C3)", () => {
|
|
const message = refusalMessage(["scripts/check.ts:3: process.argv[1]"]);
|
|
expect(message).toContain("process.argv[1] is not read");
|
|
expect(message).toContain("import.meta.filename");
|
|
expect(message).toContain(GUARD_CALL);
|
|
expect(message).toContain("scripts/check.ts:3");
|
|
});
|
|
});
|
|
|
|
describe("scripts started as processes", { timeout: CHILD_PROCESS_TIMEOUT }, () => {
|
|
it.each([{ args: [] }, { args: ["--require-bundle"] }])(
|
|
"checks in a folder with a space, Korean, # and % $args (C1)",
|
|
async ({ args }) => {
|
|
const root = path.join(await emptyFolder(), "내 템플릿 #2 %2");
|
|
await mkdir(root);
|
|
for (const entry of selectRepositoryPaths("fixture-copy")) {
|
|
// A removal drill runs this test in a copy that has already lost some.
|
|
if (!existsSync(entry)) continue;
|
|
// Without the generated index the check has no input to judge.
|
|
await cp(entry, path.join(root, entry), {
|
|
recursive: true,
|
|
filter: (source) => !source.includes(`${path.sep}.generated`),
|
|
});
|
|
}
|
|
|
|
expect(runNode(root, ["scripts/check-app-build-input.ts", ...args])).toEqual({
|
|
status: 1,
|
|
output: expect.stringMatching(/ENOENT.*\.generated/u),
|
|
});
|
|
},
|
|
);
|
|
|
|
it.each([
|
|
{ script: "generate-ci-workflow.ts", args: ["--check"], reason: "CI workflow generation failed" },
|
|
{ script: "generate-artifact-schemas.ts", args: ["--check"], reason: "Artifact JSON Schema drift" },
|
|
])("runs $script through an absolute path with a symlink (C2)", async ({ script, args, reason }) => {
|
|
const root = await emptyFolder();
|
|
const checkout = path.join(root, "linked checkout");
|
|
await symlink(process.cwd(), checkout, "dir");
|
|
|
|
expect(runNode(root, [path.join(checkout, "scripts", script), ...args])).toEqual({
|
|
status: 1,
|
|
output: expect.stringContaining(reason),
|
|
});
|
|
});
|
|
|
|
it("runs no body when the scripts are only imported, also by a file of the same name (C4)", async () => {
|
|
const guarded = guardedScripts(await scriptSources());
|
|
expect(guarded.length).toBeGreaterThan(0);
|
|
const root = await emptyFolder();
|
|
|
|
expect(await importOnly(root, guarded)).toEqual({ status: 0, output: "imported" });
|
|
expect((await readdir(root)).sort()).toEqual(["package.json", IMPORTER]);
|
|
});
|
|
|
|
it.each([
|
|
["only a comment names the helper", `// Always started directly, so it has no ${GUARD_CALL} guard.`],
|
|
["it only reads process.argv[1]", "export const named = process.argv[1] !== undefined;"],
|
|
])("does not run a script without a guard when %s (C4)", async (_, line) => {
|
|
const root = await emptyFolder();
|
|
const file = path.join(root, "publish.ts");
|
|
const source = `import { writeFileSync } from "node:fs";\n${line}\nwriteFileSync("body-ran", "");\n`;
|
|
await writeFile(file, source);
|
|
|
|
expect(await importOnly(root, guardedScripts([{ file, source }]))).toEqual({ status: 0, output: "imported" });
|
|
expect((await readdir(root)).sort()).toEqual(["package.json", "publish.ts", IMPORTER]);
|
|
});
|
|
});
|