/** * Runs the real `dotnet` CLI for tests: an isolated HOME (so the user-wide NuGet.Config and * the package cache are the test's own), one SDK picked per run through `global.json`, and a * local folder feed packed on the fly so nothing reaches nuget.org. * * With `CI` set a missing SDK fails the run instead of skipping it, so a runner without .NET * cannot pass these tests silently. */ 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"; /** Installed SDK versions whose major version is one of `majors` (10 and 11 are the ones tested). */ export function cliSdks(majors: number[] = [10, 11]): string[] { const out = spawnSync("dotnet", ["--list-sdks"], { encoding: "utf8" }); if (out.status !== 0) { if (process.env.CI) throw new Error("dotnet is required in CI but was not found"); return []; } const versions = out.stdout .split(/\r?\n/) .map((l) => l.split(" ")[0]!) .filter((v) => majors.includes(Number(v.split(".")[0]))); // One SDK per major: the newest installed one. return majors.flatMap((m) => versions.filter((v) => v.startsWith(`${m}.`)).slice(-1)); } export interface Sandbox { /** Workspace root; its global.json pins the SDK. */ root: string; /** The test's HOME: holds the user-wide NuGet.Config. */ home: string; major: number; run(args: string[], cwd?: string): { code: number; out: string }; /** Like `run` but throws on a non-zero exit, as the IDE's `dotnet()` does. */ ok(args: string[], cwd?: string): string; /** Packs `id` at each version into `feed` (a local folder feed). */ pack(feed: string, id: string, versions: string[], deps?: Array<[id: string, version: string]>): void; dispose(): void; } export function sandbox(sdk: string): Sandbox { // realpath: the CLI prints resolved paths (macOS /var -> /private/var). const base = realpathSync(mkdtempSync(join(tmpdir(), "oi-nuget-"))); const root = join(base, "ws"); const home = join(base, "home"); mkdirSync(root); mkdirSync(home); writeFileSync(join(root, "global.json"), JSON.stringify({ sdk: { version: sdk, rollForward: "disable" } })); const major = Number(sdk.split(".")[0]); const env = { ...process.env, HOME: home, USERPROFILE: home, APPDATA: join(home, "AppData"), DOTNET_CLI_HOME: home, NUGET_PACKAGES: join(base, "packages"), DOTNET_CLI_UI_LANGUAGE: "en", DOTNET_NOLOGO: "1", DOTNET_CLI_TELEMETRY_OPTOUT: "1", DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1", MSBUILDDISABLENODEREUSE: "1", }; const run = (args: string[], cwd = root) => { const r = spawnSync("dotnet", args, { cwd, env, encoding: "utf8", timeout: 180_000 }); return { code: r.status ?? -1, out: `${r.stdout}${r.stderr}` }; }; const ok = (args: string[], cwd = root) => { const r = run(args, cwd); if (r.code !== 0) throw new Error(`dotnet ${args.join(" ")} exited with ${r.code}\n${r.out}`); return r.out; }; return { root, home, major, run, ok, pack(feed, id, versions, deps = []) { const dir = join(base, `pack-${id}`); mkdirSync(dir, { recursive: true }); mkdirSync(feed, { recursive: true }); writeFileSync( join(dir, `${id}.csproj`), `net${major}.0` + `falsetruefalsefalsefalseNU5128;NU5127` + `` + deps.map(([d, v]) => ``).join("") + ``, ); // Only the feed itself (for dependencies): the user's and the test's sources stay out of packing. writeFileSync( join(dir, "NuGet.Config"), ``, ); writeFileSync(join(dir, "content.txt"), id); for (const v of versions) ok(["pack", dir, "-p:PackageVersion=" + v, "-o", feed, "--nologo"], dir); }, 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 = {}, deprecations: Record = {}, ): Promise { const child = spawn( process.execPath, ["-e", FEED_SERVER, folder, JSON.stringify(vulnerabilities), JSON.stringify(deprecations)], { stdio: ["ignore", "pipe", "inherit"] }, ); const base = await new Promise((resolve, reject) => { child.once("error", reject); child.stdout.once("data", (d: Buffer) => resolve(String(d).trim())); }); return { url: `${base}/index.json`, close: () => { child.kill(); }, }; }