дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 16:51:16 +02:00
feat(nuget): audit packages for vulnerabilities and deprecations (#7448)
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]>
Цей коміт міститься в:
1 джерело
9ecb664036
коміт
3fe4e12252
11 files changed
+1044
-11
No files matched your search
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* The package audit in the NuGet Packages window and the Problems view (#7439) over a stubbed
|
||||
* `dotnet` host (`dotnetHost.ts`): the spec checks the markers, the Problems entries and the exact
|
||||
* commands it starts; `src/features/dotnet/audit.cli.test.ts` runs the real CLI against a local v3 feed.
|
||||
*/
|
||||
import type { Page } from "@playwright/test";
|
||||
import { expect, test } from "./fixtures";
|
||||
import { dotnetRuns, installDotnetHost, openNuget, PROJECT, shot } from "./dotnetHost";
|
||||
|
||||
const PROPS = "/dev/acme/Directory.Packages.props";
|
||||
const CSPROJ = `<Project Sdk="Microsoft.NET.Sdk">
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Demo.Pkg" Version="1.0.0" />
|
||||
<PackageReference Include="Old.Pkg" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>`;
|
||||
const PROPS_TEXT = `<Project>
|
||||
<ItemGroup>
|
||||
<PackageVersion Include="Demo.Pkg" Version="1.0.0" />
|
||||
<PackageVersion Include="Old.Pkg" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>`;
|
||||
|
||||
async function stubAudit(page: Page, central: boolean) {
|
||||
await installDotnetHost(page);
|
||||
await page.evaluate(
|
||||
({ central, csproj, propsText, project, propsPath }) => {
|
||||
window.__ipc.handlers.fs_read_text = (args) => {
|
||||
if (args.path === project) return central ? csproj.replace(/ Version="1.0.0"/g, "") : csproj;
|
||||
if (args.path === propsPath) return propsText;
|
||||
throw { kind: "notFound", message: String(args.path) };
|
||||
};
|
||||
const json = (value: unknown) => JSON.stringify(value);
|
||||
const framework = (extra: object) => json({ projects: [{ frameworks: [{ framework: "net9.0", ...extra }] }] });
|
||||
const demo = { id: "Demo.Pkg", requestedVersion: "1.0.0", resolvedVersion: "1.0.0" };
|
||||
window.__dotnetOut = (args) => {
|
||||
if (args[0] === "msbuild") {
|
||||
if (!args.some((a) => a.includes("ManagePackageVersionsCentrally")))
|
||||
return json({ Properties: { MSBuildProjectName: "App", TargetFramework: "net9.0" }, Items: {} });
|
||||
return json({
|
||||
Properties: { ManagePackageVersionsCentrally: central ? "true" : "" },
|
||||
Items: {
|
||||
PackageVersion: [
|
||||
{ Identity: "Demo.Pkg", Version: "1.0.0", DefiningProjectFullPath: propsPath },
|
||||
{ Identity: "Old.Pkg", Version: "1.0.0", DefiningProjectFullPath: propsPath },
|
||||
],
|
||||
PackageReference: [],
|
||||
},
|
||||
});
|
||||
}
|
||||
if (args[0] !== "list") return "ok\n";
|
||||
if (args.includes("--vulnerable"))
|
||||
return framework({
|
||||
topLevelPackages: [
|
||||
{
|
||||
...demo,
|
||||
vulnerabilities: [{ severity: "High", advisoryurl: "https://github.com/advisories/GHSA-demo" }],
|
||||
},
|
||||
],
|
||||
transitivePackages: [
|
||||
{
|
||||
id: "Child.Pkg",
|
||||
resolvedVersion: "2.0.0",
|
||||
vulnerabilities: [{ severity: "Moderate", advisoryurl: "https://github.com/advisories/GHSA-child" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
if (args.includes("--deprecated"))
|
||||
return framework({
|
||||
topLevelPackages: [
|
||||
{
|
||||
id: "Old.Pkg",
|
||||
requestedVersion: "1.0.0",
|
||||
resolvedVersion: "1.0.0",
|
||||
deprecationReasons: ["Legacy"],
|
||||
alternativePackage: { id: "New.Pkg", versionRange: ">= 0.0.0" },
|
||||
},
|
||||
],
|
||||
});
|
||||
if (args.includes("--outdated")) return framework({ topLevelPackages: [{ ...demo, latestVersion: "1.1.0" }] });
|
||||
return framework({
|
||||
topLevelPackages: [demo, { id: "Old.Pkg", requestedVersion: "1.0.0", resolvedVersion: "1.0.0" }],
|
||||
transitivePackages: [{ id: "Child.Pkg", resolvedVersion: "2.0.0" }],
|
||||
});
|
||||
};
|
||||
},
|
||||
{ central, csproj: CSPROJ, propsText: PROPS_TEXT, project: PROJECT, propsPath: PROPS },
|
||||
);
|
||||
await openNuget(page);
|
||||
if (central)
|
||||
await page.evaluate(async () => {
|
||||
const central = "/src/features/dotnet/central.ts";
|
||||
const { refreshCentral } = await import(/* @vite-ignore */ central);
|
||||
await refreshCentral();
|
||||
});
|
||||
}
|
||||
|
||||
const row = (page: Page, id: string) => page.getByRole("listitem").filter({ hasText: id }).last();
|
||||
|
||||
async function problems(page: Page) {
|
||||
await page.getByRole("button", { name: "Problems", exact: true }).click();
|
||||
const pane = page.locator('[data-toolwindow="problems"]');
|
||||
await pane.getByRole("tab", { name: /Project Errors/ }).click();
|
||||
return pane.getByRole("tree", { name: "Problems" });
|
||||
}
|
||||
|
||||
test("Audit marks vulnerable, deprecated and outdated packages with their severity, advisory and alternative", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await stubAudit(page, false);
|
||||
await page.getByRole("button", { name: "Audit packages" }).click();
|
||||
await expect(row(page, "Demo.Pkg").getByRole("link", { name: "Vulnerable (High)" })).toHaveAttribute(
|
||||
"href",
|
||||
"https://github.com/advisories/GHSA-demo",
|
||||
);
|
||||
await expect(row(page, "Child.Pkg").getByRole("link", { name: "Vulnerable (Moderate)" })).toBeVisible();
|
||||
await expect(row(page, "Old.Pkg")).toContainText("Deprecated: Legacy, use New.Pkg");
|
||||
await expect(row(page, "Demo.Pkg")).toContainText("Newer version available: 1.1.0");
|
||||
await shot(page, "d3-markers", row(page, "Demo.Pkg"));
|
||||
// One command per filter, vulnerabilities with transitive packages, then the outdated check.
|
||||
const runs = (await dotnetRuns(page)).filter((a) => a[0] === "list" && a.some((x) => /^--(vuln|depr|outd)/.test(x)));
|
||||
expect(runs.map((a) => a.filter((x) => x.startsWith("--") && x !== "--format").join(" "))).toEqual([
|
||||
"--vulnerable --include-transitive",
|
||||
"--deprecated",
|
||||
"--outdated",
|
||||
]);
|
||||
});
|
||||
|
||||
test("Problems lists the audit at the PackageReference lines of the project", async ({ workbench: page }) => {
|
||||
await stubAudit(page, false);
|
||||
await page.getByRole("button", { name: "Audit packages" }).click();
|
||||
await expect(row(page, "Demo.Pkg").getByRole("link", { name: "Vulnerable (High)" })).toBeVisible();
|
||||
const tree = await problems(page);
|
||||
await expect(tree.getByText(/Package Demo\.Pkg 1\.0\.0 has a known High severity vulnerability/)).toBeVisible();
|
||||
await expect(tree).toContainText("App.csproj");
|
||||
await expect(tree).toContainText("GHSA-demo:3");
|
||||
if (process.env.E2E_SHOTS)
|
||||
await page.screenshot({ path: `${process.env.E2E_SHOTS}/d3-problems.png`, animations: "disabled" });
|
||||
});
|
||||
|
||||
test("under central package management Problems points at Directory.Packages.props", async ({ workbench: page }) => {
|
||||
await stubAudit(page, true);
|
||||
await page.getByRole("button", { name: "Audit packages" }).click();
|
||||
await expect(row(page, "Demo.Pkg").getByRole("link", { name: "Vulnerable (High)" })).toBeVisible();
|
||||
const tree = await problems(page);
|
||||
await expect(tree).toContainText("Directory.Packages.props");
|
||||
await expect(tree.getByText(/Package Demo\.Pkg 1\.0\.0 has a known High severity vulnerability/)).toBeVisible();
|
||||
// Line 3 of the props file (the Demo.Pkg PackageVersion); the unpinned transitive package stays on the project.
|
||||
await expect(tree).toContainText("GHSA-demo:3");
|
||||
await expect(tree).toContainText("Directory.Packages.props1 error");
|
||||
});
|
||||
|
||||
test("a failing audit shows the CLI message and no markers", async ({ workbench: page }) => {
|
||||
await stubAudit(page, false);
|
||||
await page.evaluate(() => {
|
||||
const ok = window.__dotnetOut;
|
||||
window.__dotnetOut = (args) => {
|
||||
if (args.includes("--vulnerable")) throw new Error("error: Unable to load the service index for source");
|
||||
return ok(args);
|
||||
};
|
||||
});
|
||||
await page.getByRole("button", { name: "Audit packages" }).click();
|
||||
await expect(page.getByRole("alert")).toContainText("Unable to load the service index");
|
||||
await expect(page.getByRole("link", { name: /Vulnerable/ })).toHaveCount(0);
|
||||
});
|
||||
@@ -53,3 +53,6 @@
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
}
|
||||
.advisory {
|
||||
color: var(--danger);
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { executeAction } from "@/platform/actions";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { isOpenable, openExternalUrl } from "@/platform/openUrl";
|
||||
import { Button, Input } from "@/ui";
|
||||
import { auditPackageKey, useAudit } from "./audit";
|
||||
import { compareVersions, useCentral } from "./central";
|
||||
import { ensureDotnetModel, useDotnet } from "./store";
|
||||
import { SourcesPanel } from "./SourcesPanel";
|
||||
@@ -25,7 +27,9 @@ export function NugetView() {
|
||||
const matches =
|
||||
central.project === s.selected && central.framework === s.framework && central.configuration === s.configuration;
|
||||
const info = matches ? central.info : null;
|
||||
const working = s.busy || central.busy;
|
||||
const audit = useAudit();
|
||||
const findings = audit.results[s.selected];
|
||||
const working = s.busy || central.busy || audit.busy;
|
||||
const knownLatest = (p: { id: string; version: string }) => {
|
||||
const latest = matches ? central.latest[p.id.toLowerCase()] : undefined;
|
||||
return latest && compareVersions(latest, p.version) > 0 ? latest : undefined;
|
||||
@@ -35,10 +39,15 @@ export function NugetView() {
|
||||
const override = info?.overrides[key];
|
||||
const file = baseName(info?.versions[key]?.file ?? "");
|
||||
const latest = knownLatest(p);
|
||||
const deprecation = findings?.deprecated[auditPackageKey(p.id, p.version)];
|
||||
const reasons = deprecation?.reasons.join(", ");
|
||||
const alternative = deprecation?.alternative;
|
||||
const replacement = reasons && alternative ? tx`${reasons}, use ${alternative}` : reasons;
|
||||
return [
|
||||
override ? tx`Version override ${override} in the project` : "",
|
||||
!override && file ? (p.transitive ? tx`Pinned in ${file}` : tx`Defined in ${file}`) : "",
|
||||
latest ? tx`Newer version available: ${latest}` : "",
|
||||
replacement ? tx`Deprecated: ${replacement}` : "",
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
@@ -71,8 +80,16 @@ export function NugetView() {
|
||||
/>
|
||||
{tx("Include prereleases")}
|
||||
</label>
|
||||
<Button disabled={working || !project} onClick={() => action("audit")}>
|
||||
{tx("Audit packages")}
|
||||
</Button>
|
||||
{working && <Button onClick={() => action("cancel")}>{tx("Cancel")}</Button>}
|
||||
</div>
|
||||
{audit.error && (
|
||||
<div role="alert" className={styles.error}>
|
||||
{audit.error}
|
||||
</div>
|
||||
)}
|
||||
{matches && central.error && (
|
||||
<div role="alert" className={styles.error}>
|
||||
{central.error}
|
||||
@@ -150,12 +167,26 @@ export function NugetView() {
|
||||
<ul className={styles.list}>
|
||||
{s.packages.map((p) => {
|
||||
const latest = knownLatest(p);
|
||||
const advisories = findings?.vulnerable[auditPackageKey(p.id, p.version)]?.advisories ?? [];
|
||||
return (
|
||||
<li key={`${p.id}:${p.version}`}>
|
||||
<span>
|
||||
{p.id} {p.version} {p.transitive ? tx("Transitive") : ""}
|
||||
{note(p) && ` · ${note(p)}`}
|
||||
</span>
|
||||
{advisories.map(({ severity, url }) => (
|
||||
<a
|
||||
key={`${severity}:${url}`}
|
||||
href={isOpenable(url) ? url : undefined}
|
||||
className={styles.advisory}
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
void openExternalUrl(url);
|
||||
}}
|
||||
>
|
||||
{tx`Vulnerable (${severity})`}
|
||||
</a>
|
||||
))}
|
||||
{latest && !p.transitive && (project?.frameworks.length ?? 0) <= 1 && (
|
||||
<Button disabled={working} onClick={() => action("packageChange", { id: p.id, version: latest })}>
|
||||
{tx`Update to ${latest}`}
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
// @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("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { afterEach, 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 {
|
||||
type Audit,
|
||||
auditDiagnostics,
|
||||
cancelAudit,
|
||||
findReference,
|
||||
parseDeprecated,
|
||||
parseVulnerable,
|
||||
resetAudit,
|
||||
runAudit,
|
||||
useAudit,
|
||||
} from "./audit";
|
||||
import { resetCentral } from "./central";
|
||||
import { resetDotnet, useDotnet } from "./store";
|
||||
|
||||
afterEach(() => {
|
||||
resetAudit();
|
||||
resetCentral();
|
||||
resetDotnet();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const csproj = `<Project Sdk="Microsoft.NET.Sdk">
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Demo.Pkg" />
|
||||
<PackageReference Update="Other.Pkg" Version="1.0.0" />
|
||||
</ItemGroup>
|
||||
</Project>`;
|
||||
|
||||
describe("parsing dotnet list package", () => {
|
||||
const fw = (top: unknown[], transitive: unknown[] = []): never =>
|
||||
({
|
||||
projects: [{ frameworks: [{ topLevelPackages: top, transitivePackages: transitive }] }],
|
||||
}) as never;
|
||||
it("collects advisories of every severity, direct and transitive", () => {
|
||||
const result = parseVulnerable(
|
||||
fw(
|
||||
[
|
||||
{
|
||||
id: "A",
|
||||
resolvedVersion: "1.0.0",
|
||||
vulnerabilities: [
|
||||
{ severity: "Low", advisoryurl: "u1" },
|
||||
{ severity: "Critical", advisoryurl: "u2" },
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
id: "B",
|
||||
resolvedVersion: "2.0.0",
|
||||
vulnerabilities: [
|
||||
{ severity: "Moderate", advisoryurl: "u3" },
|
||||
{ severity: "High", advisoryurl: "u4" },
|
||||
],
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
expect(result["a:1.0.0"]!.transitive).toBe(false);
|
||||
expect(result["a:1.0.0"]!.advisories.map((a) => a.severity)).toEqual(["Low", "Critical"]);
|
||||
expect(result["b:2.0.0"]).toMatchObject({ transitive: true, version: "2.0.0" });
|
||||
});
|
||||
it("calls a package direct when any target framework references it directly, and merges repeated advisories", () => {
|
||||
const vuln = { severity: "High", advisoryurl: "u" };
|
||||
const result = parseVulnerable({
|
||||
projects: [
|
||||
{
|
||||
frameworks: [
|
||||
{ transitivePackages: [{ id: "A", resolvedVersion: "1", vulnerabilities: [vuln] }] },
|
||||
{ topLevelPackages: [{ id: "A", resolvedVersion: "1", vulnerabilities: [vuln] }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result["a:1"]!.transitive).toBe(false);
|
||||
expect(result["a:1"]!.advisories).toHaveLength(1);
|
||||
});
|
||||
it("reads deprecation reasons and the alternative package, and ignores clean packages", () => {
|
||||
expect(
|
||||
parseDeprecated(
|
||||
fw([
|
||||
{ id: "Old", resolvedVersion: "1", deprecationReasons: ["Legacy"], alternativePackage: { id: "New" } },
|
||||
{ id: "Fine", resolvedVersion: "1" },
|
||||
]),
|
||||
),
|
||||
).toEqual({ "old:1": { id: "Old", version: "1", reasons: ["Legacy"], alternative: "New" } });
|
||||
});
|
||||
it("keeps findings of separate resolved versions of the same package", () => {
|
||||
const packages = fw([
|
||||
{ id: "Constructor", resolvedVersion: "1", vulnerabilities: [{ severity: "High", advisoryurl: "u1" }] },
|
||||
{ id: "Constructor", resolvedVersion: "2", vulnerabilities: [{ severity: "Low", advisoryurl: "u2" }] },
|
||||
]);
|
||||
const result = parseVulnerable(packages);
|
||||
expect(result["constructor:1"]?.advisories).toEqual([{ severity: "High", url: "u1" }]);
|
||||
expect(result["constructor:2"]?.advisories).toEqual([{ severity: "Low", url: "u2" }]);
|
||||
});
|
||||
it("returns nothing for an empty project", () => {
|
||||
expect(parseVulnerable({ projects: [{}] })).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("locating a reference", () => {
|
||||
it("finds Include and Update elements, case-insensitively and with escaped ids", () => {
|
||||
expect(findReference(csproj, "demo.pkg", ["PackageReference"])!.start).toEqual({ line: 2, col: 4 });
|
||||
expect(findReference(csproj, "Other.Pkg", ["PackageReference"])!.start.line).toBe(3);
|
||||
expect(findReference(csproj, "DemoXPkg", ["PackageReference"])).toBeNull();
|
||||
expect(findReference(csproj, "Demo.Pkg", ["PackageVersion"])).toBeNull();
|
||||
});
|
||||
it("uses UTF-16 positions for multiline and single-quoted references", () => {
|
||||
const text = "😀 <PackageReference\n Include='Demo.Pkg' />";
|
||||
expect(findReference(text, "Demo.Pkg", ["PackageReference"])).toEqual({
|
||||
start: { line: 0, col: 3 },
|
||||
end: { line: 1, col: 20 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Problems for an audit", () => {
|
||||
const audit: Audit = {
|
||||
vulnerable: {
|
||||
"demo.pkg": {
|
||||
id: "Demo.Pkg",
|
||||
version: "1.0.0",
|
||||
transitive: false,
|
||||
advisories: [
|
||||
{ severity: "Low", url: "u1" },
|
||||
{ severity: "High", url: "u2" },
|
||||
],
|
||||
},
|
||||
"deep.pkg": {
|
||||
id: "Deep.Pkg",
|
||||
version: "3.0.0",
|
||||
transitive: true,
|
||||
advisories: [{ severity: "Moderate", url: "u3" }],
|
||||
},
|
||||
},
|
||||
deprecated: { "other.pkg": { id: "Other.Pkg", version: "1.0.0", reasons: ["Legacy"], alternative: "New.Pkg" } },
|
||||
};
|
||||
const base = { project: "/r/App.csproj", text: csproj, central: {}, texts: {} };
|
||||
it("reports at the PackageReference line with the severity of the worst advisory", () => {
|
||||
const out = auditDiagnostics(audit, base).get("/r/App.csproj")!;
|
||||
const demo = out.find((d) => d.message.includes("Demo.Pkg"))!;
|
||||
expect(demo.severity).toBe("error");
|
||||
expect(demo.range.start.line).toBe(2);
|
||||
expect(demo.message).toContain("u2");
|
||||
expect(demo.source).toBe("NuGet");
|
||||
const deprecated = out.find((d) => d.code === "NuGetDeprecated")!;
|
||||
expect(deprecated).toMatchObject({ severity: "warning", range: { start: { line: 3 } } });
|
||||
expect(deprecated.message).toContain("New.Pkg");
|
||||
});
|
||||
it("puts a transitive package on the project's first reference unless it is pinned", () => {
|
||||
const out = auditDiagnostics(audit, base).get("/r/App.csproj")!;
|
||||
const deep = out.find((d) => d.message.includes("Deep.Pkg"))!;
|
||||
expect(deep.range.start.line).toBe(2);
|
||||
expect(deep.severity).toBe("warning");
|
||||
expect(deep.message).toMatch(/^Transitive/);
|
||||
const props = `<Project>\n<ItemGroup>\n <PackageVersion Include="Deep.Pkg" Version="3.0.0" />\n</ItemGroup></Project>`;
|
||||
const pinned = auditDiagnostics(audit, {
|
||||
...base,
|
||||
central: { "deep.pkg": { file: "/r/Directory.Packages.props" } },
|
||||
texts: { "/r/Directory.Packages.props": props },
|
||||
});
|
||||
expect(pinned.get("/r/Directory.Packages.props")![0]).toMatchObject({ range: { start: { line: 2 } } });
|
||||
});
|
||||
it("reports at the PackageVersion line of Directory.Packages.props under central management", () => {
|
||||
const props = `<Project>\n<ItemGroup>\n <PackageVersion Include="Demo.Pkg" Version="1.0.0" />\n</ItemGroup></Project>`;
|
||||
const out = auditDiagnostics(
|
||||
{ vulnerable: audit.vulnerable, deprecated: {} },
|
||||
{
|
||||
...base,
|
||||
central: { "demo.pkg": { file: "/r/Directory.Packages.props" } },
|
||||
texts: { "/r/Directory.Packages.props": props },
|
||||
},
|
||||
);
|
||||
const d = out.get("/r/Directory.Packages.props")!.find((x) => x.message.includes("Demo.Pkg"))!;
|
||||
expect(d.range.start.line).toBe(2);
|
||||
});
|
||||
it("maps every severity", () => {
|
||||
const one = (severity: string) =>
|
||||
auditDiagnostics(
|
||||
{
|
||||
vulnerable: {
|
||||
"demo.pkg": { id: "Demo.Pkg", version: "1", transitive: false, advisories: [{ severity, url: "u" }] },
|
||||
},
|
||||
deprecated: {},
|
||||
},
|
||||
base,
|
||||
).get("/r/App.csproj")![0]!.severity;
|
||||
expect([one("Low"), one("Moderate"), one("High"), one("Critical")]).toEqual(["info", "warning", "error", "error"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("running an audit", () => {
|
||||
const select = () =>
|
||||
useDotnet.setState({
|
||||
selected: "/r/App.csproj",
|
||||
model: { projects: [{ path: "/r/App.csproj" } as never], solutions: [] },
|
||||
});
|
||||
const mockFiles = () =>
|
||||
vi.spyOn(commands, "fsReadText").mockImplementation(async () => ({ status: "ok", data: csproj }));
|
||||
const vulnJson = JSON.stringify({
|
||||
projects: [
|
||||
{
|
||||
frameworks: [
|
||||
{
|
||||
topLevelPackages: [
|
||||
{ id: "Demo.Pkg", resolvedVersion: "1.0.0", vulnerabilities: [{ severity: "High", advisoryurl: "u" }] },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const emptyJson = '{"projects":[]}';
|
||||
|
||||
it("caches the result per project and publishes then clears Problems", async () => {
|
||||
select();
|
||||
mockFiles();
|
||||
const set = vi.spyOn(diagnostics, "setFileDiagnostics").mockImplementation(() => {});
|
||||
const run = vi
|
||||
.spyOn(platform, "dotnet")
|
||||
.mockImplementation(async (args) => (args.includes("--vulnerable") ? vulnJson : emptyJson));
|
||||
expect(await runAudit()).toBe(true);
|
||||
expect(run.mock.calls.map((c) => c[0].filter((a) => a.startsWith("--")).join(" "))).toEqual([
|
||||
"--vulnerable --include-transitive --format",
|
||||
"--deprecated --format",
|
||||
]);
|
||||
expect(useAudit.getState().results["/r/App.csproj"]!.vulnerable["demo.pkg:1.0.0"]).toBeTruthy();
|
||||
expect(set).toHaveBeenCalledWith("/r/App.csproj", "NuGet", [expect.objectContaining({ severity: "error" })]);
|
||||
// Fixed: the next run reports nothing and the old Problems go away.
|
||||
run.mockImplementation(async () => emptyJson);
|
||||
await runAudit();
|
||||
expect(set).toHaveBeenLastCalledWith("/r/App.csproj", "NuGet", []);
|
||||
resetAudit();
|
||||
expect(useAudit.getState().results).toEqual({});
|
||||
});
|
||||
it("drops a result after cancellation and after a workspace switch", async () => {
|
||||
select();
|
||||
mockFiles();
|
||||
const set = vi.spyOn(diagnostics, "setFileDiagnostics").mockImplementation(() => {});
|
||||
const pending: Array<(s: string) => void> = [];
|
||||
vi.spyOn(platform, "dotnet").mockImplementation(() => new Promise((r) => pending.push(r)));
|
||||
const tick = () => new Promise((r) => setTimeout(r, 0));
|
||||
const flush = async () => {
|
||||
// One round per awaited CLI call of the audit.
|
||||
for (const _ of [1, 2, 3, 4]) {
|
||||
pending.splice(0).forEach((r) => r(vulnJson));
|
||||
await tick(); // oxlint-disable-line no-await-in-loop
|
||||
}
|
||||
};
|
||||
const first = runAudit();
|
||||
cancelAudit();
|
||||
await flush();
|
||||
expect(await first).toBe(false);
|
||||
const second = runAudit();
|
||||
resetAudit();
|
||||
await flush();
|
||||
expect(await second).toBe(false);
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
expect(useAudit.getState()).toMatchObject({ busy: false, error: "", results: {} });
|
||||
});
|
||||
it("reports a CLI failure and keeps the previous result", async () => {
|
||||
select();
|
||||
mockFiles();
|
||||
vi.spyOn(diagnostics, "setFileDiagnostics").mockImplementation(() => {});
|
||||
vi.spyOn(platform, "dotnet").mockResolvedValueOnce(vulnJson).mockResolvedValueOnce(emptyJson);
|
||||
await runAudit();
|
||||
vi.spyOn(platform, "dotnet").mockRejectedValue(new Error("error: No such host is known"));
|
||||
expect(await runAudit()).toBe(false);
|
||||
expect(useAudit.getState().error).toMatch(/No such host/);
|
||||
expect(useAudit.getState().results["/r/App.csproj"]).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import { create } from "zustand";
|
||||
import type { Diagnostic, Range } from "@/bindings";
|
||||
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { dotnet, jsonOutput } from "@/platform/dotnet";
|
||||
import { dirname } from "@/platform/project";
|
||||
import { useCentral } from "./central";
|
||||
import { selectedProject } from "./store";
|
||||
|
||||
/** The Problems view source of everything the audit reports. */
|
||||
export const AUDIT_SOURCE = "NuGet";
|
||||
|
||||
export interface Advisory {
|
||||
/** `Low`, `Moderate`, `High` or `Critical`, as `dotnet list package --vulnerable` prints it. */
|
||||
severity: string;
|
||||
url: string;
|
||||
}
|
||||
export interface Audit {
|
||||
/** Findings by package id and resolved version. */
|
||||
vulnerable: Record<string, { id: string; version: string; transitive: boolean; advisories: Advisory[] }>;
|
||||
deprecated: Record<string, { id: string; version: string; reasons: string[]; alternative?: string }>;
|
||||
}
|
||||
interface State {
|
||||
/** Per project path: the last audit. Dropped when the workspace changes. */
|
||||
results: Record<string, Audit>;
|
||||
busy: boolean;
|
||||
error: string;
|
||||
}
|
||||
const initial: State = { results: {}, busy: false, error: "" };
|
||||
export const useAudit = create<State>(() => initial);
|
||||
let controller: AbortController | undefined;
|
||||
let generation = 0;
|
||||
const published = new Map<string, Map<string, Diagnostic[]>>();
|
||||
|
||||
function publishDiagnostics(project: string, diagnostics: Map<string, Diagnostic[]>) {
|
||||
const files = new Set([...(published.get(project)?.keys() ?? []), ...diagnostics.keys()]);
|
||||
published.set(project, diagnostics);
|
||||
for (const file of files) {
|
||||
const items = new Map<string, Diagnostic>();
|
||||
for (const result of published.values()) {
|
||||
for (const item of result.get(file) ?? []) items.set(JSON.stringify(item), item);
|
||||
}
|
||||
setFileDiagnostics(file, AUDIT_SOURCE, [...items.values()]);
|
||||
}
|
||||
}
|
||||
export function resetAudit() {
|
||||
generation++;
|
||||
controller?.abort();
|
||||
const files = new Set([...published.values()].flatMap((result) => [...result.keys()]));
|
||||
published.clear();
|
||||
for (const file of files) setFileDiagnostics(file, AUDIT_SOURCE, []);
|
||||
useAudit.setState(initial);
|
||||
}
|
||||
export function cancelAudit() {
|
||||
controller?.abort();
|
||||
}
|
||||
|
||||
interface PackageJson {
|
||||
id: string;
|
||||
resolvedVersion?: string;
|
||||
requestedVersion?: string;
|
||||
vulnerabilities?: Array<{ severity?: string; advisoryurl?: string }>;
|
||||
deprecationReasons?: string[];
|
||||
alternativePackage?: { id: string; versionRange?: string };
|
||||
}
|
||||
interface ListJson {
|
||||
projects?: Array<{ frameworks?: Array<{ topLevelPackages?: PackageJson[]; transitivePackages?: PackageJson[] }> }>;
|
||||
}
|
||||
export function auditPackageKey(id: string, version: string): string {
|
||||
return `${id.toLowerCase()}:${version}`;
|
||||
}
|
||||
|
||||
function packages(data: ListJson): Array<PackageJson & { transitive: boolean }> {
|
||||
return (data.projects ?? []).flatMap((p) =>
|
||||
(p.frameworks ?? []).flatMap((f) => [
|
||||
...(f.topLevelPackages ?? []).map((x) => ({ ...x, transitive: false })),
|
||||
...(f.transitivePackages ?? []).map((x) => ({ ...x, transitive: true })),
|
||||
]),
|
||||
);
|
||||
}
|
||||
export function parseVulnerable(data: ListJson): Audit["vulnerable"] {
|
||||
const result: Audit["vulnerable"] = {};
|
||||
for (const p of packages(data)) {
|
||||
if (!p.vulnerabilities?.length) continue;
|
||||
const version = p.resolvedVersion ?? p.requestedVersion ?? "";
|
||||
const key = auditPackageKey(p.id, version);
|
||||
const entry = (result[key] ??= {
|
||||
id: p.id,
|
||||
version,
|
||||
transitive: p.transitive,
|
||||
advisories: [],
|
||||
});
|
||||
// A package direct in one target framework is direct for the project.
|
||||
entry.transitive &&= p.transitive;
|
||||
for (const v of p.vulnerabilities) {
|
||||
const advisory = { severity: v.severity ?? "Unknown", url: v.advisoryurl ?? "" };
|
||||
if (!entry.advisories.some((a) => a.url === advisory.url && a.severity === advisory.severity))
|
||||
entry.advisories.push(advisory);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function parseDeprecated(data: ListJson): Audit["deprecated"] {
|
||||
const result: Audit["deprecated"] = {};
|
||||
for (const p of packages(data)) {
|
||||
if (!p.deprecationReasons?.length) continue;
|
||||
const version = p.resolvedVersion ?? p.requestedVersion ?? "";
|
||||
result[auditPackageKey(p.id, version)] = {
|
||||
id: p.id,
|
||||
version,
|
||||
reasons: p.deprecationReasons,
|
||||
alternative: p.alternativePackage?.id,
|
||||
};
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The range of the `<tag … Include|Update="id"` element start in `text`, or null. */
|
||||
export function findReference(text: string, id: string | null, tags: string[]): Range | null {
|
||||
const escaped = id?.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const value = escaped === undefined ? `(?:"[^"]+"|'[^']+')` : `(?:"${escaped}"|'${escaped}')`;
|
||||
const re = new RegExp(`<(?:${tags.join("|")})\\b[^>]*?\\s(?:Include|Update)\\s*=\\s*${value}`, "i");
|
||||
const m = re.exec(text);
|
||||
if (!m) return null;
|
||||
const position = (offset: number) => {
|
||||
const before = text.slice(0, offset);
|
||||
return { line: before.split("\n").length - 1, col: offset - (before.lastIndexOf("\n") + 1) };
|
||||
};
|
||||
return { start: position(m.index), end: position(m.index + m[0].length) };
|
||||
}
|
||||
|
||||
const SEVERITY: Record<string, Diagnostic["severity"]> = {
|
||||
critical: "error",
|
||||
high: "error",
|
||||
moderate: "warning",
|
||||
low: "info",
|
||||
};
|
||||
const RANK = ["low", "moderate", "high", "critical"];
|
||||
|
||||
/**
|
||||
* Problems for an audit: one per vulnerable or deprecated package, at its `PackageReference` in the
|
||||
* project, or at its `PackageVersion` in `Directory.Packages.props` when versions are central.
|
||||
* A transitive package goes to its pin when it has one, else to the project's first reference.
|
||||
*/
|
||||
export function auditDiagnostics(
|
||||
audit: Audit,
|
||||
files: { project: string; text: string; central: Record<string, { file: string }>; texts: Record<string, string> },
|
||||
): Map<string, Diagnostic[]> {
|
||||
const out = new Map<string, Diagnostic[]>();
|
||||
const add = (file: string, range: Range, d: Omit<Diagnostic, "range" | "source" | "code">, code: string) => {
|
||||
const list = out.get(file) ?? [];
|
||||
list.push({ ...d, range, source: AUDIT_SOURCE, code });
|
||||
out.set(file, list);
|
||||
};
|
||||
const firstReference = findReference(files.text, null, ["PackageReference"]) ?? {
|
||||
start: { line: 0, col: 0 },
|
||||
end: { line: 0, col: 0 },
|
||||
};
|
||||
const place = (id: string, transitive: boolean): [string, Range] => {
|
||||
const central = files.central[id.toLowerCase()];
|
||||
const props =
|
||||
central && files.texts[central.file] ? findReference(files.texts[central.file]!, id, ["PackageVersion"]) : null;
|
||||
if (central && props) return [central.file, props];
|
||||
if (!transitive) {
|
||||
const own = findReference(files.text, id, ["PackageReference"]);
|
||||
if (own) return [files.project, own];
|
||||
}
|
||||
return [files.project, firstReference];
|
||||
};
|
||||
for (const v of Object.values(audit.vulnerable)) {
|
||||
const id = v.id;
|
||||
const top = [...v.advisories].sort(
|
||||
(a, b) => RANK.indexOf(b.severity.toLowerCase()) - RANK.indexOf(a.severity.toLowerCase()),
|
||||
)[0]!;
|
||||
const [file, range] = place(id, v.transitive);
|
||||
const version = v.version;
|
||||
const severity = top.severity;
|
||||
const url = top.url;
|
||||
const message = v.transitive
|
||||
? tx`Transitive package ${id} ${version} has a known ${severity} severity vulnerability: ${url}`
|
||||
: tx`Package ${id} ${version} has a known ${severity} severity vulnerability: ${url}`;
|
||||
add(file, range, { severity: SEVERITY[severity.toLowerCase()] ?? "warning", message }, "NuGetAudit");
|
||||
}
|
||||
for (const d of Object.values(audit.deprecated)) {
|
||||
const id = d.id;
|
||||
const [file, range] = place(id, false);
|
||||
const version = d.version;
|
||||
const reasons = d.reasons.join(", ");
|
||||
const alternative = d.alternative;
|
||||
const message = alternative
|
||||
? tx`Package ${id} ${version} is deprecated (${reasons}); use ${alternative} instead`
|
||||
: tx`Package ${id} ${version} is deprecated (${reasons})`;
|
||||
add(file, range, { severity: "warning", message }, "NuGetDeprecated");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
async function readText(path: string): Promise<string> {
|
||||
return call(commands.fsReadText(path)).catch(() => "");
|
||||
}
|
||||
|
||||
/** Vulnerable (direct and transitive) and deprecated packages of a project, then its Problems entries. Returns false when cancelled or failed. */
|
||||
export async function runAudit(path?: string): Promise<boolean> {
|
||||
const project = path ?? selectedProject()?.path;
|
||||
if (!project) return false;
|
||||
controller?.abort();
|
||||
const current = ++generation;
|
||||
const abort = new AbortController();
|
||||
controller = abort;
|
||||
const { signal } = abort;
|
||||
useAudit.setState({ busy: true, error: "" });
|
||||
try {
|
||||
const cwd = dirname(project);
|
||||
const list = (flag: string, extra: string[] = []) =>
|
||||
dotnet(["list", project, "package", flag, ...extra, "--format", "json"], cwd, signal).then((o) =>
|
||||
jsonOutput<ListJson>(o),
|
||||
);
|
||||
const vulnerable = parseVulnerable(await list("--vulnerable", ["--include-transitive"]));
|
||||
const deprecated = parseDeprecated(await list("--deprecated"));
|
||||
const central = useCentral.getState();
|
||||
const info = central.project === project ? central.info : null;
|
||||
const versions = Object.fromEntries(Object.entries(info?.versions ?? {}).filter(([id]) => !info?.overrides[id]));
|
||||
const centralFiles = [
|
||||
...new Set(
|
||||
Object.values(versions)
|
||||
.map((v) => v.file)
|
||||
.filter(Boolean),
|
||||
),
|
||||
];
|
||||
const texts = Object.fromEntries(
|
||||
await Promise.all(centralFiles.map(async (file) => [file, await readText(file)] as const)),
|
||||
);
|
||||
const text = await readText(project);
|
||||
signal.throwIfAborted();
|
||||
if (current !== generation) return false;
|
||||
const audit = { vulnerable, deprecated };
|
||||
const diagnostics = auditDiagnostics(audit, { project, text, central: versions, texts });
|
||||
publishDiagnostics(project, diagnostics);
|
||||
useAudit.setState({ results: { ...useAudit.getState().results, [project]: audit } });
|
||||
return true;
|
||||
} catch (e) {
|
||||
if (current === generation && !signal.aborted) useAudit.setState({ error: String(e) });
|
||||
return false;
|
||||
} finally {
|
||||
if (current === generation) {
|
||||
controller = undefined;
|
||||
useAudit.setState({ busy: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
* With `CI` set a missing SDK fails the run instead of skipping it, so a runner without .NET
|
||||
* cannot pass these tests silently.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -100,3 +100,99 @@ export function sandbox(sdk: string): Sandbox {
|
||||
dispose: () => rmSync(base, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
|
||||
// Runs in its own process: the tests drive the CLI with spawnSync, which would block a server in this one.
|
||||
const FEED_SERVER = `
|
||||
const http = require("node:http");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const [folder, vulnJson, depJson] = process.argv.slice(1);
|
||||
const vulnerabilities = JSON.parse(vulnJson);
|
||||
const deprecations = JSON.parse(depJson);
|
||||
const packages = () =>
|
||||
fs.readdirSync(folder)
|
||||
.map((f) => /^(.+?)\\.(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)\\.nupkg$/.exec(f))
|
||||
.filter(Boolean)
|
||||
.map((m) => ({ id: m[1], version: m[2], file: m[0] }));
|
||||
let base = "";
|
||||
const server = http.createServer((req, res) => {
|
||||
const p = (req.url || "").split("?")[0];
|
||||
const json = (body) => { res.setHeader("content-type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
const parts = p.split("/").filter(Boolean);
|
||||
if (p === "/index.json") return json({ version: "3.0.0", resources: [
|
||||
{ "@id": base + "/flat/", "@type": "PackageBaseAddress/3.0.0" },
|
||||
{ "@id": base + "/reg/", "@type": "RegistrationsBaseUrl/3.6.0" },
|
||||
{ "@id": base + "/vuln/index.json", "@type": "VulnerabilityInfo/6.7.0" } ] });
|
||||
if (p === "/vuln/index.json") return json([{ "@name": "base", "@id": base + "/vuln/base.json", "@updated": "2024-01-01T00:00:00Z" }]);
|
||||
// Restore reads the audit data (NU1901-NU1904); \`dotnet list package\` reads the registration entries below.
|
||||
if (p === "/vuln/base.json") return json(Object.fromEntries(Object.entries(vulnerabilities).map(([id, l]) => [id.toLowerCase(),
|
||||
l.flatMap((a) => a.versions.map((v) => ({ severity: a.severity, url: a.url, versions: "[" + v + ", " + v + "]" })))])));
|
||||
if (parts[0] === "flat" && parts[2] === "index.json")
|
||||
return json({ versions: packages().filter((x) => x.id.toLowerCase() === parts[1]).map((x) => x.version.toLowerCase()) });
|
||||
if (parts[0] === "flat" && parts.length === 4) {
|
||||
const hit = packages().find((x) => x.id.toLowerCase() === parts[1] && x.version.toLowerCase() === parts[2]);
|
||||
if (hit) return void fs.createReadStream(path.join(folder, hit.file)).pipe(res);
|
||||
}
|
||||
if (parts[0] === "reg" && parts[2] === "index.json") {
|
||||
const own = packages().filter((x) => x.id.toLowerCase() === parts[1]);
|
||||
const items = own.map((x) => {
|
||||
const dep = deprecations[x.id];
|
||||
return {
|
||||
"@id": base + "/reg/" + parts[1] + "/" + x.version + ".json",
|
||||
catalogEntry: { "@id": base + "/cat/" + x.id + "." + x.version + ".json", id: x.id, version: x.version, listed: true,
|
||||
...(vulnerabilities[x.id] ? { vulnerabilities: vulnerabilities[x.id].filter((a) => a.versions.includes(x.version)).map((a) => ({ advisoryUrl: a.url, severity: String(a.severity) })) } : {}),
|
||||
...(dep ? { deprecation: { message: dep.message, reasons: dep.reasons, ...(dep.alternate ? { alternatePackage: dep.alternate } : {}) } } : {}) },
|
||||
packageContent: base + "/flat/" + parts[1] + "/" + x.version.toLowerCase() + "/" + parts[1] + "." + x.version.toLowerCase() + ".nupkg",
|
||||
};
|
||||
});
|
||||
return json({ count: 1, items: [{ "@id": base + "/reg/" + parts[1] + "/page.json", count: items.length, items, lower: own[0] && own[0].version, upper: own.length ? own[own.length - 1].version : undefined }] });
|
||||
}
|
||||
res.statusCode = 404; res.end();
|
||||
});
|
||||
server.listen(0, "127.0.0.1", () => { base = "http://127.0.0.1:" + server.address().port; console.log(base); });
|
||||
`;
|
||||
|
||||
export interface FeedAdvisory {
|
||||
/** NuGet's numeric severity: 0 low, 1 moderate, 2 high, 3 critical. */
|
||||
severity: 0 | 1 | 2 | 3;
|
||||
url: string;
|
||||
/** The affected versions, listed exactly. */
|
||||
versions: string[];
|
||||
}
|
||||
export interface FeedDeprecation {
|
||||
message?: string;
|
||||
reasons: string[];
|
||||
alternate?: { id: string; range: string };
|
||||
}
|
||||
export interface V3Feed {
|
||||
/** The feed's service index URL (http on 127.0.0.1: the source needs `allowInsecureConnections`). */
|
||||
url: string;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves a folder of `.nupkg` files as a minimal NuGet v3 feed with the vulnerability and
|
||||
* registration resources, so `dotnet list package --vulnerable | --deprecated | --outdated`
|
||||
* have real data to read. A local folder feed has neither.
|
||||
*/
|
||||
export async function serveV3Feed(
|
||||
folder: string,
|
||||
vulnerabilities: Record<string, FeedAdvisory[]> = {},
|
||||
deprecations: Record<string, FeedDeprecation> = {},
|
||||
): Promise<V3Feed> {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
["-e", FEED_SERVER, folder, JSON.stringify(vulnerabilities), JSON.stringify(deprecations)],
|
||||
{ stdio: ["ignore", "pipe", "inherit"] },
|
||||
);
|
||||
const base = await new Promise<string>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.stdout.once("data", (d: Buffer) => resolve(String(d).trim()));
|
||||
});
|
||||
return {
|
||||
url: `${base}/index.json`,
|
||||
close: () => {
|
||||
child.kill();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -16,7 +16,9 @@ import {
|
||||
runTests,
|
||||
searchPackages,
|
||||
selectDotnet,
|
||||
selectedProject,
|
||||
} from "./store";
|
||||
import { cancelAudit, resetAudit, runAudit } from "./audit";
|
||||
import { cancelCentral, checkUpdates, refreshCentral, resetCentral, useCentral } from "./central";
|
||||
import { cancelSources, changeSource, loadSources, resetSources, type SourceOperation } from "./sources";
|
||||
import {
|
||||
@@ -60,6 +62,7 @@ export function activate() {
|
||||
cancelDotnet();
|
||||
cancelSources();
|
||||
cancelCentral();
|
||||
cancelAudit();
|
||||
cancelDotnetEdit();
|
||||
},
|
||||
},
|
||||
@@ -119,8 +122,19 @@ export function activate() {
|
||||
title: op === "build" ? "Build .NET Project" : op === "restore" ? "Restore .NET Project" : "Clean .NET Project",
|
||||
category: "Build",
|
||||
when: "projectOpen",
|
||||
run: ({ arg }: { arg?: unknown }) => buildDotnet(op, arg),
|
||||
run: ({ arg }: { arg?: unknown }) => buildDotnet(op, arg, runAudit),
|
||||
})),
|
||||
{
|
||||
id: "dotnet.audit",
|
||||
title: "Audit NuGet Packages",
|
||||
category: "Build",
|
||||
when: "projectOpen",
|
||||
run: async () => {
|
||||
toolWindowService().show(NUGET, true);
|
||||
const project = selectedProject()?.path;
|
||||
if (project && (await runAudit(project)) && selectedProject()?.path === project) await checkUpdates();
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "dotnet.packages",
|
||||
title: "Refresh NuGet Packages",
|
||||
@@ -238,6 +252,7 @@ export function activate() {
|
||||
resetDotnet();
|
||||
resetSources();
|
||||
resetCentral();
|
||||
resetAudit();
|
||||
}
|
||||
}),
|
||||
// #5635: build / restore / clean act on the right-clicked solution or project.
|
||||
@@ -263,6 +278,7 @@ export function activate() {
|
||||
resetDotnet();
|
||||
resetSources();
|
||||
resetCentral();
|
||||
resetAudit();
|
||||
disposers.reverse().forEach((d) => d());
|
||||
};
|
||||
}
|
||||
@@ -124,7 +124,7 @@ async function contextProject(): Promise<DotnetProject | null> {
|
||||
return isDotnetProjectPath(path) ? evaluateProject(path, s.configuration, "") : null;
|
||||
}
|
||||
|
||||
async function task(work: (signal: AbortSignal) => Promise<Partial<State>>) {
|
||||
async function task(work: (signal: AbortSignal) => Promise<Partial<State>>, afterSuccess?: () => Promise<unknown>) {
|
||||
controller?.abort();
|
||||
const current = ++generation;
|
||||
const abort = new AbortController();
|
||||
@@ -132,7 +132,10 @@ async function task(work: (signal: AbortSignal) => Promise<Partial<State>>) {
|
||||
useDotnet.setState({ busy: true, error: "" });
|
||||
try {
|
||||
const patch = await work(abort.signal);
|
||||
if (current === generation && !abort.signal.aborted) useDotnet.setState(patch);
|
||||
if (current === generation && !abort.signal.aborted) {
|
||||
useDotnet.setState(patch);
|
||||
await afterSuccess?.();
|
||||
}
|
||||
} catch (e) {
|
||||
if (current === generation && !abort.signal.aborted) useDotnet.setState({ error: String(e) });
|
||||
} finally {
|
||||
@@ -202,7 +205,11 @@ export function selectDotnet(path: string, configuration?: string, framework?: s
|
||||
});
|
||||
}
|
||||
|
||||
export async function buildDotnet(operation: "build" | "restore" | "clean", arg?: unknown) {
|
||||
export async function buildDotnet(
|
||||
operation: "build" | "restore" | "clean",
|
||||
arg?: unknown,
|
||||
afterRestore?: (target: string) => Promise<unknown>,
|
||||
) {
|
||||
const target = await contextTarget(arg);
|
||||
if (!target) return;
|
||||
// A solution builds as a whole: `dotnet` takes the `.sln` directly, there is no
|
||||
@@ -223,11 +230,13 @@ export async function buildDotnet(operation: "build" | "restore" | "clean", arg?
|
||||
}
|
||||
const selected = selectedProject();
|
||||
const { framework, configuration } = useDotnet.getState();
|
||||
const afterSuccess = operation === "restore" && afterRestore ? () => afterRestore(target) : undefined;
|
||||
// The selected project keeps its chosen configuration and framework; another
|
||||
// project builds with its own defaults.
|
||||
if (selected?.path !== target)
|
||||
return task(async (signal) => {
|
||||
const output = await dotnet([operation, target, "--configuration", "Debug"], dirname(target), signal);
|
||||
const options = operation === "restore" ? ["-p:Configuration=Debug"] : ["--configuration", "Debug"];
|
||||
const output = await dotnet([operation, target, ...options], dirname(target), signal);
|
||||
const model = useDotnet.getState().model;
|
||||
if (!model.projects.some((p) => p.path === target)) return { output };
|
||||
const project = await evaluateProject(target, "Debug", "", signal);
|
||||
@@ -235,7 +244,7 @@ export async function buildDotnet(operation: "build" | "restore" | "clean", arg?
|
||||
output,
|
||||
model: { ...model, projects: model.projects.map((item) => (item.path === target ? project : item)) },
|
||||
};
|
||||
});
|
||||
}, afterSuccess);
|
||||
return task(async (signal) => {
|
||||
const output = await dotnet(
|
||||
[
|
||||
@@ -254,7 +263,7 @@ export async function buildDotnet(operation: "build" | "restore" | "clean", arg?
|
||||
output,
|
||||
model: { ...model, projects: model.projects.map((item) => (item.path === target ? project : item)) },
|
||||
};
|
||||
});
|
||||
}, afterSuccess);
|
||||
}
|
||||
|
||||
interface PackageJson {
|
||||
|
||||
@@ -5161,5 +5161,14 @@
|
||||
"Background build for code insight failed": "Background build for code insight failed",
|
||||
"Code insight reads what it built. Run shows the whole build log.": "Code insight reads what it built. Run shows the whole build log.",
|
||||
"Increase Preview Font Size": "Increase Preview Font Size",
|
||||
"Decrease Preview Font Size": "Decrease Preview Font Size"
|
||||
"Decrease Preview Font Size": "Decrease Preview Font Size",
|
||||
"{reasons}, use {alternative}": "{reasons}, use {alternative}",
|
||||
"Deprecated: {deprecation}": "Deprecated: {deprecation}",
|
||||
"Audit packages": "Audit packages",
|
||||
"Vulnerable ({severity})": "Vulnerable ({severity})",
|
||||
"Transitive package {id} {version} has a known {severity} severity vulnerability: {url}": "Transitive package {id} {version} has a known {severity} severity vulnerability: {url}",
|
||||
"Package {id} {version} has a known {severity} severity vulnerability: {url}": "Package {id} {version} has a known {severity} severity vulnerability: {url}",
|
||||
"Package {id} {version} is deprecated ({reasons}); use {alternative} instead": "Package {id} {version} is deprecated ({reasons}); use {alternative} instead",
|
||||
"Package {id} {version} is deprecated ({reasons})": "Package {id} {version} is deprecated ({reasons})",
|
||||
"Audit NuGet Packages": "Audit NuGet Packages"
|
||||
}
|
||||
@@ -12053,5 +12053,14 @@
|
||||
"Auto uses 3.0.x for Vue 2 projects and the latest release for Vue 3.": "自动选择时,Vue 2 项目使用 3.0.x,Vue 3 项目使用最新版本。",
|
||||
"Enter latest, 3.0.x, or an exact Vue Language Server version.": "请输入 latest、3.0.x 或 Vue 语言服务器的具体版本。",
|
||||
"Increase Preview Font Size": "增大预览字体",
|
||||
"Decrease Preview Font Size": "减小预览字体"
|
||||
"Decrease Preview Font Size": "减小预览字体",
|
||||
"{reasons}, use {alternative}": "{reasons},请改用 {alternative}",
|
||||
"Deprecated: {deprecation}": "已弃用:{deprecation}",
|
||||
"Audit packages": "审计包",
|
||||
"Vulnerable ({severity})": "存在漏洞({severity})",
|
||||
"Transitive package {id} {version} has a known {severity} severity vulnerability: {url}": "传递依赖包 {id} {version} 存在已知的{severity}级漏洞:{url}",
|
||||
"Package {id} {version} has a known {severity} severity vulnerability: {url}": "包 {id} {version} 存在已知的{severity}级漏洞:{url}",
|
||||
"Package {id} {version} is deprecated ({reasons}); use {alternative} instead": "包 {id} {version} 已弃用({reasons}),请改用 {alternative}",
|
||||
"Package {id} {version} is deprecated ({reasons})": "包 {id} {version} 已弃用({reasons})",
|
||||
"Audit NuGet Packages": "审计 NuGet 包"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача