дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
After a successful restore, packages are audited for known vulnerabilities, deprecations and newer versions; findings show as markers in project and Directory.Packages.props files and as Problems entries. Audits distinguish resolved versions, combine diagnostics for shared central package files, compute multi-line UTF-16 spans correctly, and run only after the actual target restored. Closes #7439 Co-authored-by: wildcatDownstairs <[email protected]>
169 рядки
7.5 KiB
TypeScript
169 рядки
7.5 KiB
TypeScript
// @vitest-environment node
|
|
/** Package audits against the real `dotnet` CLI (SDK 10 and 11) and a local NuGet v3 test feed with advisories. */
|
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import * as diagnostics from "@/editor/lsp/diagnostics";
|
|
import * as platform from "@/platform/dotnet";
|
|
import { commands } from "@/platform/ipc";
|
|
import { resetAudit, runAudit, useAudit } from "./audit";
|
|
import { refreshCentral, resetCentral } from "./central";
|
|
import { type FeedAdvisory, type Sandbox, type V3Feed, cliSdks, sandbox, serveV3Feed } from "./cliTestkit";
|
|
import { resetDotnet, useDotnet } from "./store";
|
|
|
|
// Each test packs and restores with the real CLI, slower on a loaded machine.
|
|
vi.setConfig({ testTimeout: 240_000 });
|
|
|
|
const sdks = cliSdks();
|
|
it.runIf(sdks.length === 0)("has no SDK 10 or 11 here (CI fails on this)", () => {
|
|
expect(process.env.CI).toBeFalsy();
|
|
});
|
|
|
|
const advisory = (severity: FeedAdvisory["severity"], name: string): FeedAdvisory => ({
|
|
severity,
|
|
url: `https://github.com/advisories/GHSA-${name}`,
|
|
versions: ["1.0.0"],
|
|
});
|
|
|
|
describe.each(sdks)("package audit with SDK %s", (sdk) => {
|
|
let sb: Sandbox;
|
|
let feed: V3Feed | undefined;
|
|
let app: string;
|
|
let csproj: string;
|
|
|
|
/** A project referencing `refs` (ids at 1.0.0), restored from the test feed that serves `vulnerabilities` and `deprecations`. */
|
|
const workspace = async (
|
|
refs: string[],
|
|
vulnerabilities: Record<string, FeedAdvisory[]>,
|
|
deprecations: Parameters<typeof serveV3Feed>[2] = {},
|
|
central = false,
|
|
) => {
|
|
const folder = join(sb.root, "feed");
|
|
for (const id of ["Low.Pkg", "Mod.Pkg", "High.Pkg", "Crit.Pkg", "Clean.Pkg", "Child.Pkg"])
|
|
sb.pack(folder, id, ["1.0.0"]);
|
|
sb.pack(folder, "Old.Pkg", ["1.0.0"]);
|
|
sb.pack(folder, "New.Pkg", ["1.0.0", "1.1.0"]);
|
|
sb.pack(folder, "Parent.Pkg", ["1.0.0"], [["Child.Pkg", "1.0.0"]]);
|
|
feed = await serveV3Feed(folder, vulnerabilities, deprecations);
|
|
writeFileSync(
|
|
join(sb.root, "NuGet.Config"),
|
|
`<configuration><packageSources><clear /><add key="http" value="${feed.url}" allowInsecureConnections="true" /></packageSources></configuration>`,
|
|
);
|
|
if (central)
|
|
writeFileSync(
|
|
join(sb.root, "Directory.Packages.props"),
|
|
`<Project>\n<PropertyGroup><ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally></PropertyGroup>\n<ItemGroup>\n${refs.map((r) => ` <PackageVersion Include="${r}" Version="1.0.0" />`).join("\n")}\n</ItemGroup>\n</Project>`,
|
|
);
|
|
app = join(sb.root, "app");
|
|
mkdirSync(app);
|
|
csproj = join(app, "App.csproj");
|
|
writeFileSync(
|
|
csproj,
|
|
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net${sb.major}.0</TargetFramework></PropertyGroup>\n<ItemGroup>\n${refs.map((r) => ` <PackageReference Include="${r}"${central ? "" : ' Version="1.0.0"'} />`).join("\n")}\n</ItemGroup></Project>`,
|
|
);
|
|
sb.ok(["restore", csproj], app);
|
|
vi.spyOn(platform, "dotnet").mockImplementation(async (args, cwd) => sb.ok(args, cwd));
|
|
vi.spyOn(commands, "fsReadText").mockImplementation(async (path) => {
|
|
const { readFileSync } = await import("node:fs");
|
|
return { status: "ok", data: readFileSync(path, "utf8") };
|
|
});
|
|
useDotnet.setState({ selected: csproj, model: { projects: [{ path: csproj } as never], solutions: [] } });
|
|
};
|
|
const published = () => {
|
|
const set = vi.spyOn(diagnostics, "setFileDiagnostics").mockImplementation(() => {});
|
|
return () => new Map(set.mock.calls.map(([file, , items]) => [file, items]));
|
|
};
|
|
|
|
beforeEach(() => {
|
|
sb = sandbox(sdk);
|
|
});
|
|
afterEach(() => {
|
|
feed?.close();
|
|
feed = undefined;
|
|
sb.dispose();
|
|
resetAudit();
|
|
resetCentral();
|
|
resetDotnet();
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("reports a vulnerability of each severity with its advisory, and Problems at each reference line", async () => {
|
|
const problems = published();
|
|
await workspace(["Low.Pkg", "Mod.Pkg", "High.Pkg", "Crit.Pkg", "Clean.Pkg"], {
|
|
"Low.Pkg": [advisory(0, "low")],
|
|
"Mod.Pkg": [advisory(1, "mod")],
|
|
"High.Pkg": [advisory(2, "high")],
|
|
"Crit.Pkg": [advisory(3, "crit")],
|
|
});
|
|
expect(await runAudit()).toBe(true);
|
|
const { vulnerable } = useAudit.getState().results[csproj]!;
|
|
expect(Object.fromEntries(Object.entries(vulnerable).map(([k, v]) => [k, v.advisories[0]!.severity]))).toEqual({
|
|
"low.pkg:1.0.0": "Low",
|
|
"mod.pkg:1.0.0": "Moderate",
|
|
"high.pkg:1.0.0": "High",
|
|
"crit.pkg:1.0.0": "Critical",
|
|
});
|
|
expect(vulnerable["crit.pkg:1.0.0"]!.advisories[0]!.url).toBe("https://github.com/advisories/GHSA-crit");
|
|
const items = problems().get(csproj)!;
|
|
expect(items.map((d) => d.severity).sort()).toEqual(["error", "error", "info", "warning"]);
|
|
// <Project> is line 0, <ItemGroup> line 1: the references start on line 2, Crit.Pkg is the fourth.
|
|
expect(items.find((d) => d.message.includes("Crit.Pkg"))!.range.start.line).toBe(5);
|
|
expect(items.some((d) => d.message.includes("Clean.Pkg"))).toBe(false);
|
|
});
|
|
|
|
it("finds a transitive vulnerability and a deprecated package with its alternative", async () => {
|
|
const problems = published();
|
|
await workspace(
|
|
["Parent.Pkg", "Old.Pkg"],
|
|
{ "Child.Pkg": [advisory(2, "child")] },
|
|
{ "Old.Pkg": { reasons: ["Legacy"], alternate: { id: "New.Pkg", range: "*" } } },
|
|
);
|
|
await runAudit();
|
|
const audit = useAudit.getState().results[csproj]!;
|
|
expect(audit.vulnerable["child.pkg:1.0.0"]).toMatchObject({ transitive: true });
|
|
expect(audit.deprecated["old.pkg:1.0.0"]).toMatchObject({ reasons: ["Legacy"], alternative: "New.Pkg" });
|
|
const items = problems().get(csproj)!;
|
|
expect(items.find((d) => d.message.startsWith("Transitive package"))!.range.start.line).toBe(2);
|
|
expect(items.find((d) => d.code === "NuGetDeprecated")!.message).toContain("New.Pkg");
|
|
});
|
|
|
|
it("under central package management the Problems entry sits on the PackageVersion line", async () => {
|
|
const problems = published();
|
|
await workspace(["Crit.Pkg", "Clean.Pkg"], { "Crit.Pkg": [advisory(3, "crit")] }, {}, true);
|
|
await refreshCentral();
|
|
await runAudit();
|
|
const props = join(sb.root, "Directory.Packages.props");
|
|
const items = problems().get(props)!;
|
|
expect(items).toHaveLength(1);
|
|
expect(items[0]!.range.start.line).toBe(3);
|
|
expect(problems().get(csproj)).toBeUndefined();
|
|
});
|
|
|
|
it("a project without findings reports nothing and clears earlier Problems", async () => {
|
|
const problems = published();
|
|
await workspace(["Clean.Pkg"], {});
|
|
expect(await runAudit()).toBe(true);
|
|
expect(useAudit.getState().results[csproj]).toEqual({ vulnerable: {}, deprecated: {} });
|
|
expect(problems().size).toBe(0);
|
|
});
|
|
|
|
it("an unreachable source is reported, not mistaken for a clean project", async () => {
|
|
published();
|
|
await workspace(["Crit.Pkg"], { "Crit.Pkg": [advisory(3, "crit")] });
|
|
feed!.close();
|
|
await new Promise((r) => setTimeout(r, 300));
|
|
const ok = await runAudit();
|
|
// The CLI either fails (NU1301 from its restore) or reads its cache: it must not claim the project is fine when it failed.
|
|
expect(ok || useAudit.getState().error !== "").toBe(true);
|
|
expect(useAudit.getState().busy).toBe(false);
|
|
});
|
|
|
|
it("a malformed project file is a CLI error", async () => {
|
|
published();
|
|
await workspace(["Clean.Pkg"], {});
|
|
writeFileSync(csproj, "<Project Sdk=");
|
|
expect(await runAudit()).toBe(false);
|
|
expect(useAudit.getState().error).not.toBe("");
|
|
});
|
|
});
|