Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions openspec/changes/advisories-ncsc-feed/tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- [x] 3.3 Add the `ncsc` row to `lib/Settings/connections.json` and report each read. Verify: `tests/unit/Service/Connection/ConnectionReportServiceTest.php` asserts the report with read and matched counts.
- [x] 3.4 Add the new strings to `l10n/en.json` and `l10n/nl.json`. Verify: `npm run check:l10n-js`.
- [ ] 3.5 Serve a CSAF directory from the fixture forge (`tests/e2e/fixtures/forge/server.mjs`: a `changes.csv` and documents about Nextcloud Server, one with a version range covering the CI server and one with `vers:unknown/*`, switchable through `/control`) and extend `tests/e2e/advisories.spec.ts`: switch NCSC-NL on, `runJob("AdvisoryRefreshJob")`, and see the affected advisory and the "does not state which versions" advisory in the Nextcloud server block. Verify: the spec passes in the Playwright job.
- Written: the forge serves `/csaf/v2/changes.csv` and two Nextcloud Server documents (`NCSC-2099-0001` affected, `NCSC-2099-0002` `vers:unknown/*`), switchable through `POST /control/csaf`; `tests/e2e/advisories.spec.ts` has the "NCSC-NL advisories" block. Left unticked until the Playwright job has run it.

## 4. Close

Expand Down
136 changes: 136 additions & 0 deletions tests/e2e/advisories.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
occ,
openSettings,
openTab,
resetFixture,
resetFixtureApp,
runJob,
sql,
Expand Down Expand Up @@ -446,3 +447,138 @@ test.describe("advisory triage", () => {
}
});
});

/**
* NCSC-NL advisories, read from the fixture forge's CSAF directory.
*
* The forge serves a `changes.csv` and two documents about Nextcloud Server:
* NCSC-2099-0001 with a range covering any server version the CI runs, and
* NCSC-2099-0002 with `vers:unknown/*`. With the switch on, one sweep must put
* the first on the server block as affecting this version and the second with
* the "does not state which versions" line, because an unstated range is
* neither a yes nor a no and must not read as one.
*
* @spec openspec/changes/advisories-ncsc-feed/specs/security-advisory-correlation/spec.md
*/
test.describe("NCSC-NL advisories", () => {
const NCSC_STATE = [
"advisory.ncsc.cursor",
"advisory.ncsc.index",
"advisory.ncsc.caught_up",
];

async function setNcsc(
page: Page,
enabled: boolean,
) {
const res = await page.request.put(
"/ocs/v2.php/apps/versioniq/api/advisory/settings?format=json",
{
headers: {
"OCS-APIRequest": "true",
"Content-Type": "application/json",
},
data: { ncscEnabled: enabled ? "1" : "0" },
},
);
expect(res.ok(), "PUT /api/advisory/settings should answer 200").toBeTruthy();
expect((await res.json())?.ocs?.data?.ncscEnabled).toBe(enabled);
}

async function clearNcscState() {
for (const key of NCSC_STATE) {
await occ("config:app:delete", "versioniq", key);
}
}

test.beforeEach(async ({ page }) => {
test.skip(!(await fixtureAvailable(page)), "forge fixture not running");
await resetFixture(page);
// The base as the INSTANCE reaches the fixture, which differs between
// the local Docker network and the CI runner; both bootstraps store it
// as the forgejo web base. Set through occ, because the settings API
// accepts an https base only and the fixture speaks plain http.
const forgeBase = (
await occ("config:app:get", "versioniq", "forge.forgejo.web_base")
).trim();
expect(forgeBase, "the forge bootstrap stores its base").not.toBe("");
await occ(
"config:app:set",
"versioniq",
"advisory.ncsc_feed_base",
"--value",
`${forgeBase.replace(/\/+$/, "")}/csaf/v2/`,
);
// A cursor left by an earlier run would skip the fixture's documents.
await clearNcscState();
});

test.afterEach(async ({ page }) => {
await setNcsc(page, false);
await occ("config:app:delete", "versioniq", "advisory.ncsc_feed_base");
await clearNcscState();
// Leave a snapshot without the fixture's records for the specs after.
await runJob("AdvisoryRefreshJob");
});

test("switched on, a sweep shows the affected and the version-not-stated advisory on the server", async ({
page,
}) => {
await setNcsc(page, true);
await runJob("AdvisoryRefreshJob");

await openSettings(page);
await openTab(page, "Advisories");

const server = page.getByTestId("advisories-server");
await expect(server).toBeVisible();
// An affected NCSC-NL record makes this version vulnerable.
await expect(server).toContainText(
"This server version is affected by a published advisory.",
);

const details = server.locator("details").first();
if ((await details.getAttribute("open")) === null) {
await details.locator("summary").click();
}
const showAll = server.getByTestId("advisories-show-all");
if (await showAll.isVisible()) {
await showAll.click();
}

const affected = server.locator('[data-advisory="NCSC-2099-0001"]');
await expect(affected).toBeVisible();
await expect(affected).toHaveAttribute("data-source", "ncsc");
await expect(affected.getByTestId("advisory-source")).toHaveText("NCSC-NL");
await expect(affected.getByTestId("advisory-severity")).toHaveAttribute(
"data-severity",
"high",
);
await expect(affected.getByTestId("advisory-cves")).toContainText(
"CVE-2099-0001",
);
await expect(affected.getByTestId("advisory-ratings")).toBeVisible();
await expect(affected.getByTestId("advisory-not-stated")).toHaveCount(0);

const notStated = server.locator('[data-advisory="NCSC-2099-0002"]');
await expect(notStated).toBeVisible();
await expect(notStated).toHaveAttribute("data-source", "ncsc");
await expect(notStated.getByTestId("advisory-not-stated")).toHaveText(
"NCSC-NL does not state which versions are affected.",
);
});

test("switched off, the sweep does not read NCSC-NL", async ({ page }) => {
await setNcsc(page, false);
await runJob("AdvisoryRefreshJob");

await openSettings(page);
await openTab(page, "Advisories");
await expect(page.getByTestId("advisories-server")).toBeVisible();
await expect(page.locator('[data-source="ncsc"]')).toHaveCount(0);
// Nothing was read, so no cursor was written.
expect(
(await occ("config:app:get", "versioniq", "advisory.ncsc.cursor")).trim(),
).toBe("");
});
});
138 changes: 138 additions & 0 deletions tests/e2e/fixtures/forge/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ function freshState() {
assetOverride: {},
// artifact filename -> status code to force (e.g. 404 for a deleted asset)
assetStatus: {},
// The NCSC-NL CSAF directory: forced status on changes.csv, documents.
csaf: { status: null, documents: defaultCsaf() },
};
}

Expand Down Expand Up @@ -202,6 +204,140 @@ function releaseJson(repo) {
});
}

// --- NCSC-NL CSAF directory (advisories-ncsc-feed) -----------------------
// A small CSAF provider directory under /csaf/v2/: a `changes.csv` (newest
// first) and the documents it lists. NcscAdvisoryFeed reads it once
// `advisory.ncsc_feed_base` points here. The defaults are two documents about
// Nextcloud Server: one whose range covers any server the CI runs (so the
// server is affected) and one with `vers:unknown/*` (so NCSC-NL "does not
// state which versions"). Times are relative to now so the feed's 365-day
// first read always includes them. POST /control/csaf replaces the documents
// or forces a status on `changes.csv`.
function csafDocument(id, title, range, cve, severity, ratings) {
const vulnerability = {
cve,
product_status: { known_affected: ["CSAFPID-0001"] },
};
if (severity)
vulnerability.scores = [
{ products: ["CSAFPID-0001"], cvss_v3: { baseSeverity: severity } },
];
return {
document: {
category: "csaf_security_advisory",
csaf_version: "2.0",
title,
tracking: {
id,
initial_release_date: new Date(Date.now() - 86_400_000).toISOString(),
version: "1.00",
},
notes: [
{ category: "other", title: "Kans", text: ratings[0] },
{ category: "other", title: "Schade", text: ratings[1] },
],
},
product_tree: {
branches: [
{
category: "vendor",
name: "Nextcloud",
branches: [
{
category: "product_name",
name: "Nextcloud Server",
branches: [
{
category: "product_version_range",
name: range,
product: {
product_id: "CSAFPID-0001",
name: `Nextcloud Server ${range}`,
},
},
],
},
],
},
],
},
vulnerabilities: [vulnerability],
};
}

function defaultCsaf() {
return [
{
path: "2099/ncsc-2099-0001.json",
doc: csafDocument(
"NCSC-2099-0001",
"Kwetsbaarheid verholpen in Nextcloud Server",
"vers:generic/>=1.0.0|<999.0.0",
"CVE-2099-0001",
"HIGH",
["medium", "high"],
),
},
{
path: "2099/ncsc-2099-0002.json",
doc: csafDocument(
"NCSC-2099-0002",
"Kwetsbaarheid in Nextcloud Server zonder versies",
"vers:unknown/*",
"CVE-2099-0002",
null,
["low", "medium"],
),
},
];
}

function csafChanges(res) {
if (state.csaf.status) {
res.writeHead(state.csaf.status);
return res.end("forced");
}
// Newest first, as NCSC-NL publishes it; every line a minute apart.
const now = Date.now();
const body = state.csaf.documents
.map((d, i) => {
const changed = new Date(
now - 3_600_000 + i * 60_000,
).toISOString();
return `"${d.path}","${d.changed ?? changed}"`;
})
.reverse()
.join("\n");
res.writeHead(200, {
"content-type": "text/csv",
"content-length": Buffer.byteLength(body),
});
return res.end(body);
}

function csafApi(res, path) {
const m = path.match(/^\/csaf\/v2\/(.+)$/);
if (!m) return false;
if (m[1] === "changes.csv") {
csafChanges(res);
return true;
}
const found = state.csaf.documents.find((d) => d.path === m[1]);
if (found) json(res, 200, found.doc);
else json(res, 404, { message: "Not Found" });
return true;
}

async function controlCsaf(req, res) {
// { status?, documents?: [{ path, changed?, doc }] }
const b = await readBody(req);
state.csaf = {
status: b.status ?? null,
documents: b.documents ?? state.csaf.documents,
};
return json(res, 200, { ok: true, documents: state.csaf.documents.length });
}

// --- Control plane (test-only) -------------------------------------------
async function controlRepo(req, res) {
// { repo, status?, releases?, advisories? }
Expand Down Expand Up @@ -233,6 +369,7 @@ const CONTROL_ROUTES = {
},
"/control/repo": controlRepo,
"/control/asset": controlAsset,
"/control/csaf": controlCsaf,
};

// --- Forge API (Forgejo `/api/v1/...` and GitHub `/...` shapes) -----------
Expand Down Expand Up @@ -463,6 +600,7 @@ async function route(req, res) {
const control = CONTROL_ROUTES[path];
if (control && req.method === "POST") return control(req, res);

if (csafApi(res, path)) return;
if (await osvApi(req, res, path)) return;
if (gitlabApi(res, path)) return;
if (forgeApi(req, res, path)) return;
Expand Down
Loading