diff --git a/.env.example b/.env.example index fae8504..289bffb 100644 --- a/.env.example +++ b/.env.example @@ -133,6 +133,36 @@ GITDB_ENCRYPTION_KEY="development" # Closed incidents older than this are deleted (default 365) # MONITORING_INCIDENT_RETENTION_DAYS=365 +# ─── CVE feed (/org//cves, "CVEs por tecnología" tab; docs/adr/0004-cve-feed.md) ───────── +# Follows the CVEs published in public sources (OSV.dev, NVD, CISA KEV, FIRST EPSS) for the +# technologies each organization chooses, and emits cve_feed.* events. OFF by default: with false +# the server makes no external call at all (also not from "Sincronizar ahora"). +# CVE_FEED_ENABLED=false +# How often the sources are queried: 30m, 2h, 1d (minimum 15m, default 2h). Several instances +# never sync at once (lease in the feed state). +# CVE_FEED_SYNC_INTERVAL=2h +# Only advisories at or above this severity (critical|high|medium|low), or in CISA KEV, or with an +# EPSS score at or above the threshold, are stored. Default high. +# CVE_FEED_MIN_SEVERITY=high +# CVE_FEED_EPSS_THRESHOLD=0.5 +# Advisories not modified for this long are deleted (default 180d): keeps GitDB from growing. +# CVE_FEED_RETENTION=180d +# When a technology starts being followed, the last CVE_FEED_BACKFILL of advisories are loaded +# without emitting events (default 30d). +# CVE_FEED_BACKFILL=30d +# NVD API key (optional; NVD is only queried for technologies looked up by CPE, such as +# PostgreSQL or nginx): raises the rate limit from 5 to 50 requests per 30 s. Without it the first +# backfill of many CPE technologies takes minutes. https://nvd.nist.gov/developers/request-an-api-key +# NVD_API_KEY= +# The feed tables (cve_advisories, cve_feed_state, cve_org_matches) change on every sync. +# RECOMMENDED in production: point them to their own repository so the main history stays clean +# and the feed history can be squashed or recreated; empty: the main repository. The watchlists +# (cve_watchlists) always stay in the main one. +# CVE_FEED_GITDB_REPOSITORY_URL=git@github.com:your-org/gitops-cve-feed-db.git +# CVE_FEED_GITDB_BRANCH=main +# CVE_FEED_GITDB_DATA_PATH=/data/gitdb-cve-feed # default: -cve-feed +# CVE_FEED_GITDB_TOKEN= # https token; default: the GITDB_* credentials + # --- State IaC (docs/adr/0003-state-iac.md) --------------------------------------------------- # Backends (buckets) are configured per organization at /org//settings/state-iac; their # credentials live encrypted in GitDB (GITDB_ENCRYPTION_KEY), not here. Ambient auth uses the diff --git a/CLAUDE.md b/CLAUDE.md index da1c4be..523c6a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -563,6 +563,40 @@ monitors, monitors/new, monitors/[id], monitors/[id]/edit}`, thin routes over `#lib/server/monitoring/page.ts`; components in `#lib/components/monitoring/`; the Code Report service page shows its monitors (`service-monitors.ts`). +## CVE feed + +`$modules/cve-feed` follows the CVEs of public sources for the technologies an organization chooses +(`/org//cves`, tab "CVEs por tecnología"); design in `docs/adr/0004-cve-feed.md`. + +- Off unless `CVE_FEED_ENABLED=true`: with false no timer starts and **no external call is ever + made** (the "Sincronizar ahora" action refuses too). Pages only read GitDB, never a source. + Other variables (all documented in `.env.example`): `CVE_FEED_SYNC_INTERVAL` (2h, min 15m), + `CVE_FEED_MIN_SEVERITY` (global floor, an organization can only raise it), `CVE_FEED_EPSS_THRESHOLD`, + `CVE_FEED_RETENTION`, `CVE_FEED_BACKFILL`, `NVD_API_KEY` (optional, 5 -> 50 requests / 30 s) and + `CVE_FEED_GITDB_*` (dedicated repository, recommended in production). +- Tables (`$lib/database/schemas.ts`): `cve_watchlists` (main GitDB, one per organization), + `cve_advisories`, `cve_org_matches` (dedup state) and `cve_feed_state` (cursors, etags, lease, + backfilled technologies) in the feed repository when configured. **Storage rules**: never the + full feed (filter + retention), trimmed rows, one delete + one insert per table and sync, a row + is rewritten only when its fingerprint changes (the sync without news writes nothing), volatile + status stays in memory. Keep them in any new source. +- Sources implement `CveSource` (`infrastructure/sources/`: OSV, NVD, KEV, EPSS) over the shared + `HttpClient` (retries, backoff, injectable `fetch`) and never write; `CveFeedRuntime` does, behind + a best-effort lease in `cve_feed_state`. Technologies are defined in the catalog + `$lib/cves/technologies.data.ts` or as custom OSV/CPE entries. A technology new to the feed is + backfilled silently (no events). +- Read side: `cveFeedQueryService` (per-organization memoized view; "Te afecta" correlates with the + scans of the projects the user can see, memoized per organization + project set and dropped on + `code_report.analysis.completed`), `cveWatchlistService` (suggestions from Trivy/SBOM packages; + never added without confirmation). +- Permissions: `organization:cves:feed:{read,update,all}`; Organization Admin gets `all` (existing + roles are not migrated). `read` sees the tab and the feed data of the detail (404 for others); + `update` edits the watchlist and runs "Sincronizar ahora". "Te afecta", the occurrences and the + suggestions additionally need `organization:projects:read`. +- Events `cve_feed.advisory.published|escalated|fix_available|affects_project` (alertable, + `readPermission` `organization:cves:feed:read`): one per organization x CVE x change (x project + for `affects_project`), the dedup state is written before publishing. + ## Authorization Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts` diff --git a/docs/adr/0004-cve-feed.md b/docs/adr/0004-cve-feed.md new file mode 100644 index 0000000..3c03154 --- /dev/null +++ b/docs/adr/0004-cve-feed.md @@ -0,0 +1,192 @@ +# ADR 0004: CVE feed by technology, embedded worker on GitDB + +- Status: Accepted +- Date: 2026-11-27 +- Issue: #112 + +## Context + +"Mis CVEs" (`/org//cves`) only knows what the Trivy scans found. Teams also want to follow the +CVEs published for the technologies they use (Node.js, PostgreSQL, Spring Boot…) even when no scan +has seen them yet, be alerted about the serious ones and see which of their projects are hit. + +Constraints, as in the monitoring and State IaC ADRs: GitDB is the only persistence and every +write re-serializes a table and becomes part of a Git history that never shrinks; pages must never +call an external service; the feature is optional and must be able to run without any network. + +## Decision + +An organization follows a **watchlist** (catalog technologies plus custom OSV packages or CPEs). +A worker embedded in the server process syncs public sources into GitDB, matches the advisories +with every watchlist and emits `cve_feed.*` events. The pages only read GitDB. + +### Sources + +| Source | Used for | How | +| ----------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| OSV.dev | packages (`npm`, `PyPI`…) | `POST /v1/querybatch` per watched `{ecosystem, package}` (it returns `{id, modified}` only), then `GET /v1/vulns/{id}` only for ids that are new or modified since what we hold | +| NVD API 2.0 | CPE technologies | `virtualMatchString` + `lastModStartDate`/`lastModEndDate` windows of at most 120 days, paged with `startIndex`. 5 requests / 30 s, 50 with `NVD_API_KEY` (header `apiKey`) | +| CISA KEV | "known exploited" flag | One JSON file, conditional GET (`If-None-Match`/`If-Modified-Since`); a 304 reuses the set kept in memory | +| FIRST EPSS | exploit probability | `GET /data/v1/epss?cve=A,B,…`, 100 ids per request, only for stored advisories with a CVE id whose score is older than 24 h | + +All go through one HTTP client (`infrastructure/http.ts`): 20 s timeout, up to 3 attempts with +exponential backoff and jitter on 429/5xx/network errors, `Retry-After` honoured, plain `fetch` +(the hosts are fixed, so the SSRF guard of user-supplied URLs does not apply). A source that fails +records `lastError` and the others carry on; what a partly failed source did get is used. + +The normalizers (`normalizeOsv`, `normalizeNvd`) trim at the door: CVSS v3.1 over v3.0 over v2, CWE +ids, at most 10 references (NVD/OSV/GHSA/vendor first), `affected` only for the watched +packages/CPEs as compact ranges (`>=1.0.0 <1.2.3`) and `fixedVersions` (`versionEndExcluding` in +NVD; only the vulnerable `cpeMatch` entries of the configurations that match the watched CPE). +Records of the same CVE from several sources are merged (aliases, sources, references and fixed +versions are unioned, the highest severity and CVSS win), so OSV and NVD never produce two rows. + +### What is stored, and why so little + +GitDB keeps one JSON file per table and every write is a commit. The feed therefore **never stores +the full feed**: + +| Table (`$lib/database/schemas.ts`) | Content | Written | +| ---------------------------------- | ------------------------------------------------------------------------------------- | ----------------------------------------------------- | +| `cve_watchlists` (main GitDB) | organization configuration: technologies, minimum severity, `includeKev` | when the user saves | +| `cve_advisories` | advisories that match a watched technology **and** pass the filter and the retention | only rows whose fingerprint changed | +| `cve_org_matches` | `::` → what was already notified (dedup), `silent` | only when the notified state changes | +| `cve_feed_state` | cursors, etags, last error per source, lease (`lock`), `run`, backfilled technologies | when something durable changes, and a daily heartbeat | + +- Filter: severity ≥ `CVE_FEED_MIN_SEVERITY` (the **global floor**: an organization can only raise + it, never lower it), or in KEV, or EPSS ≥ `CVE_FEED_EPSS_THRESHOLD`. Retention + `CVE_FEED_RETENTION` (180 d): older rows are deleted at the end of each sync. +- Trimmed rows: `summary` ≤ 300 characters, `details` ≤ 2 000, ≤ 10 references, no raw payloads. +- **Batched writes**: per table and sync, at most one `delete … where id in (…)` plus one + `insert … values (…)` (same pattern as the monitoring repository), never an update loop. +- **Fingerprint**: a hash of the normalized content stored on the row. A fetched advisory whose + fingerprint equals the stored one is not written, so a sync with no news writes **nothing but + the lease**. The fingerprint leaves out the bookkeeping dates, the EPSS percentile and + `epssUpdatedAt`, and rounds the EPSS score to 0.01. +- Volatile status (last run time, items last run) lives in memory and is persisted only with a + durable change or once a day. +- Advisories rejected by the filter are remembered (`{id: modified}`, pruned by retention, capped) + so they are not downloaded again, until they enter KEV. + +#### Cursors and the refresh dates that must not cost a write + +- **NVD**: the cursor of each target (`|`) is the end of its last successful + window, in the `nvd` state row. It is persisted when there is none or it is at least one day + ahead of the stored one, not on every sync: re-reading a window after a restart is harmless + because advisories that have not changed are skipped (`known`). A window never starts before the + retention (or backfill) cutoff and is split in chunks of at most 119 days. +- **EPSS**: refreshing a score that changed by less than 0.01 must not rewrite the advisory, yet + then `epssUpdatedAt` stays old on disk and the source would ask again at every sync. The + decision "what is due" therefore combines three things: the advisory's own `epssUpdatedAt`, what + this instance asked since it started (memory), and `cursor.refreshedAt` in the `epss` state row, + which says "every advisory stored before this moment was refreshed then" (one small write a + day). Only a score that crosses a 0.01 step, or an advisory written anyway, is rewritten. + EPSS never brings in an advisory that was not stored: it enriches what the other sources and + the filter already accepted. + +### Caching + +- Reads go through `CachedGitDb` (in-memory entity cache). On top, the **per-organization feed view** + (list, chips) is memoized and dropped when a sync wrote something or the watchlist changed. + The status (last run, errors) is never memoized. +- **"Te afecta"** correlates the view with the CVE ids of the scans (`organizationCveProjects`, + `loadCveOccurrences`): an advisory is marked when its id or any alias appears. The scan index is + memoized per organization **and set of visible projects** (the correlation of a page only uses + the projects its user can read), and dropped when `code_report.analysis.completed`, + `code_report.service.created` or `code_report.service.deleted` arrives. Only ids and names are + kept, never the findings. +- **Suggestions** (packages of the Trivy and SBOM analyses matched with the catalog by + ecosystem + package, plus the top 10 widespread packages that are not in the catalog as custom + OSV entries) are ranked once per organization and memoized, with the same invalidation; excluding + what is already followed runs on every call. Nothing is ever added without confirmation. +- HTTP: KEV conditional GET and OSV `modified` checks (above). With `CVE_FEED_ENABLED=false` no + timer is started and no source is ever called, not even by "Sincronizar ahora" (the action + refuses). + +### Worker: embedded, with a best-effort lease + +`CveFeedRuntime` (`start`/`stop`/`syncOnce`/`requestSync`) is transport-agnostic and is started by +`startCveFeed()` in `hooks.server.ts`, next to monitoring. One run: lease → union of the watchlists +→ each source independently → merge → filter → batched upsert → retention → per organization +matching, dedup and events → release. + +The **lease** is the `lock` row of `cve_feed_state` (`holder`, `expiresAt`, 30 min, renewed between +sources). Acquire = read; if free or expired write ours; read it back and proceed only if it is +still ours. Instances that share the repository are only coordinated **best effort**: two that +race can both read "free", and after a GitDB sync the loser may still run once. Every write is +idempotent (fingerprints, dedup state), so the worst case is a duplicate fetch, not duplicate +events. "Sincronizar ahora" writes `requestedAt` in the `run` row; every instance polls it +cheaply and one of them runs early. + +### Backfill and silence + +A technology that is not in `run.backfilledTechnologies` (a new one, or the whole first run) is +fetched for the last `CVE_FEED_BACKFILL` (30 d) and its matches are stored with `silent: true` and +the notified state pre-filled: **no events**. A technology counts as backfilled once every source +that can look it up answered without error (OSV for packages, NVD for CPEs; a failing source keeps +the backfill silent on the next run too). The same applies when an organization starts following a +technology another one already follows: advisories older than the entry's `addedAt` are silent. + +### Events and dedup + +`cve_feed.advisory.published | escalated | fix_available | affects_project`, organization scope, +`alertable`, `readPermission` `organization:cves:feed:read`, filterable by technology, severity, +CVSS, EPSS, KEV and ecosystem. One event per organization × CVE × change type, ever (`escalated` +fires again only if it escalates further than the stored state: higher severity, KEV, or EPSS over +the threshold). + +**Dedup**: the runtime writes the match/notified state first, awaits it, and only then publishes +(`publishAfterWrite`). After a restart the state says what was already sent. The in-process bus is +at-most-once, so a crash between the write and the publish loses an event rather than duplicating +it, the same trade-off as the rest of the event bus (ADR 0001). + +`affects_project` is emitted once per organization × CVE × project, with the `projectId` in the +scope and the `serviceIds`. The projects already told live in `notified.affects_project`. The +runtime reads the occurrences of **every** active project of the organization through an injected +port (no user is involved, so permissions apply later, when alert recipients are filtered by +`readPermission`). A match created silently, or stored before this state existed, only records the +projects it finds. If the scans cannot be read the state is left untouched. + +### Where the data lives + +By default the feed tables share the main GitDB. `CVE_FEED_GITDB_REPOSITORY_URL` (+ `_BRANCH`, +`_DATA_PATH`, `_TOKEN`) moves `cve_advisories`, `cve_feed_state` and `cve_org_matches` to a +**dedicated repository** (`startSecondaryGitDb`), mirroring monitoring: the feed changes on every +sync and its history can be squashed or recreated without touching the configuration. It is +recommended for production. `cve_watchlists` always stays in the main one: it is organization +configuration. + +## Why embedded + +A separate service would need its own deploy, its own GitDB access and a transport for the events, +all for a job that is a few HTTP calls every two hours. The runtime is already transport-agnostic +(the same shape as the monitoring runtime), so moving it to its own process later only means +another `index.ts`; the lease already prevents several instances from syncing at once. + +## Alternatives rejected + +- **Store the whole feed** (NVD alone is hundreds of thousands of CVEs): unaffordable for GitDB. + Only what matches a watchlist and the filter is kept. +- **A row (or a commit) per advisory per sync**, or updating `epssUpdatedAt`/`lastRunAt` on every + run: it turns each sync into commits with no content change. Fingerprints and the daily + heartbeat avoid it. +- **Matching by version** (is the installed version vulnerable?): the watchlist is by technology; + `versions` is stored and shown, never used to filter. "Te afecta" comes from the scans, which + know the real versions. +- **A distributed lock** (Redis, a database): GitDB is the only store. A best-effort lease plus + idempotent writes is enough here. +- **Calling the sources from the page** ("Sincronizar ahora" included): the pages only read + GitDB; the button asks the worker. +- **Webhook/push sources**: none of the four publishes one; polling with conditional requests is + the cheapest option. + +## Consequences + +- The feed is empty until `CVE_FEED_ENABLED=true`; the UI explains it. +- NVD without an API key is slow (5 requests / 30 s): the first backfill of many CPEs takes + minutes. Set `NVD_API_KEY`. +- A CPE configuration with an `AND` of several products is read as "any vulnerable entry that + matches the watched CPE"; the platform entries (`vulnerable: false`) are ignored. +- Package suggestions need a Trivy run with package lists (`--list-all-pkgs`) or an SBOM; a Trivy + report with only vulnerabilities suggests just the vulnerable packages. +- Alerts, notifications and the event log work as for any other event. diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index 7359ed5..8313e90 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -1,7 +1,10 @@ import { apiKeysService, roleService, userAccessService } from '#modules/auth'; import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; -import { codeReportService } from '#modules/code-report'; +import { codeReportAnalysisService, codeReportService } from '#modules/code-report'; +import { CveFeedStoreRepository } from '#modules/cve-feed/infrastructure/repositories/cve-feed-store.repository'; +import type { CveAdvisory } from '#modules/cve-feed'; +import { getGitDb } from '#lib/server/gitdb'; import { NotificationSettingsRepository } from '#modules/notifications/infrastructure/repositories/notification-settings.repository'; import { StateBackendRepository } from '#modules/state-iac/infrastructure/repositories/state-backend.repository'; import { StateBindingRepository } from '#modules/state-iac/infrastructure/repositories/state-binding.repository'; @@ -9,6 +12,9 @@ import { FAKE_S3_BUCKET } from './fake-s3'; import { E2E_S3_ENDPOINT } from '../global-setup'; export const E2E_PASSWORD = 'E2ePassword!123'; +/** A feed advisory seeded for lodash (see the CVE feed spec). */ +export const E2E_FEED_CVE_ID = 'CVE-2099-0001'; +export const E2E_FEED_ALIAS = 'GHSA-e2e0-0001-0001'; export type PersonaKey = | 'clusterAdmin' @@ -19,6 +25,7 @@ export type PersonaKey = | 'orgNone' | 'orgProjectsReadOnly' | 'orgStateIacReader' + | 'orgCveFeedReader' | 'projectAdmin' | 'projectDeveloper' | 'projectViewer' @@ -172,6 +179,64 @@ export async function seedAll(): Promise { email: 'org-stateiac-reader@e2e.test', }); + // sees the CVE feed ("CVEs por tecnología" tab) but can't edit the watchlist or sync + const orgCveFeedReaderRole = await roleService.createRole({ + name: 'E2E Org CVE Feed Reader', + slug: 'e2e-org-cve-feed-reader', + scope: 'organization', + organizationId: primaryOrg.id, + permissions: ['organization:cves:feed:read'], + }); + const orgCveFeedReader = await userAccessService.createOrganizationUser({ + organizationId: primaryOrg.id, + username: 'e2e-org-cve-feed-reader', + password: E2E_PASSWORD, + roleId: orgCveFeedReaderRole.id, + email: 'org-cve-feed-reader@e2e.test', + }); + + // an advisory the feed already stored for lodash (the feed itself stays disabled in the suite, + // so nothing external is ever called); it only shows up once an organization follows lodash + const feedNow = new Date().toISOString(); + const advisory: CveAdvisory = { + id: E2E_FEED_CVE_ID, + aliases: [E2E_FEED_ALIAS], + title: 'Command Injection in lodash', + summary: 'Command injection through the template function', + details: 'lodash versions prior to 4.17.21 are vulnerable to Command Injection.', + severity: 'high', + cvssScore: 7.2, + cvssVector: null, + cwe: ['CWE-77'], + technologyIds: ['lodash'], + affected: [ + { + technologyId: 'lodash', + ecosystem: 'npm', + package: 'lodash', + ranges: ['>=0 <4.17.21'], + fixedVersions: ['4.17.21'], + }, + ], + fixedVersions: ['4.17.21'], + references: ['https://github.com/advisories/GHSA-35jh-r3h4-6jhm'], + sources: ['osv'], + publishedAt: feedNow, + modifiedAt: feedNow, + kev: false, + kevAddedAt: null, + epssScore: null, + epssPercentile: null, + epssUpdatedAt: null, + fingerprint: 'e2e', + firstSeenAt: feedNow, + updatedAt: feedNow, + }; + await new CveFeedStoreRepository(() => getGitDb()).applyAdvisories({ + upsert: [advisory], + deleteIds: [], + }); + // --- primary project under the primary org ---------------------------------------------- const primaryProject = await projectService.createProject({ organizationId: primaryOrg.id, @@ -353,6 +418,21 @@ export async function seedAll(): Promise { project: requireSeedSlug(primaryProject.slug, 'primary project'), name: 'E2E Seeded Service', }); + // a service whose SBOM uses express: the CVE feed suggests it (see the CVE feed spec). Not the + // seeded service: an analysis changes its page, which other specs rely on + const inventoryService = await codeReportService.createService({ + project: requireSeedSlug(primaryProject.slug, 'primary project'), + name: 'E2E Inventory Service', + }); + const sbom = await codeReportAnalysisService.startAnalysis({ + serviceId: inventoryService.id, + tool: 'sbom', + }); + await codeReportAnalysisService.completeAnalysis(sbom.id, { + result: { + components: [{ name: 'express', version: '4.18.2', purl: 'pkg:npm/express@4.18.2' }], + }, + }); const { token: readOnlyApiKeyToken } = await apiKeysService.createProjectApiKey({ projectId: primaryProject.id, @@ -429,6 +509,10 @@ export async function seedAll(): Promise { userId: orgStateIacReader.userId, username: orgStateIacReader.username, }, + orgCveFeedReader: { + userId: orgCveFeedReader.userId, + username: orgCveFeedReader.username, + }, projectAdmin: { userId: projectAdminUser.userId, username: projectAdminUser.username }, projectDeveloper: { userId: projectDeveloperUser.userId, diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index f8739a3..8702064 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -62,6 +62,8 @@ function buildEnv(): Record { GITDB_USERNAME: '', GITDB_TOKEN: '', GITDB_PASSWORD: '', + // the suite assumes the CVE feed is off, whatever the developer's `.env` says + CVE_FEED_ENABLED: 'false', // never reach a real SMTP from a developer's `.env`: the suite runs with email disabled NOTIFICATION_SMTP_HOST: '', NOTIFICATION_SMTP_PORT: '', diff --git a/e2e/specs/cve-feed.spec.ts b/e2e/specs/cve-feed.spec.ts new file mode 100644 index 0000000..cbbe119 --- /dev/null +++ b/e2e/specs/cve-feed.spec.ts @@ -0,0 +1,195 @@ +import type { Page } from '@playwright/test'; +import { test, expect, getSeed } from '../fixtures/auth'; +import { E2E_BASE_URL } from '../global-setup'; +import { E2E_FEED_ALIAS, E2E_FEED_CVE_ID } from '../fixtures/seed'; + +const seed = getSeed(); +const cvesUrl = `/org/${seed.primaryOrgSlug}/cves`; +const technologyUrl = `${cvesUrl}?tab=technology`; + +// the form actions as a browser without JavaScript would call them; the response status is the +// outcome (the feed stays disabled in the suite, so no source is ever reached) +async function postAction(page: Page, action: 'watchlist' | 'sync', form: Record) { + const response = await page.request.post(`${cvesUrl}?/${action}`, { + form, + headers: { origin: E2E_BASE_URL }, + maxRedirects: 0, + }); + return response.status(); +} + +const techTab = (page: Page) => page.getByRole('link', { name: 'CVEs por tecnología' }); + +test.describe.serial('CVE feed — organization admin (read + update)', () => { + test('sees both tabs, the disabled notice and no "Sincronizar ahora"', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + await page.goto(cvesUrl); + await expect(page.getByRole('link', { name: 'Mis CVEs' })).toHaveAttribute( + 'aria-current', + 'page', + ); + await techTab(page).click(); + await expect(page).toHaveURL(/tab=technology/); + await expect(page.getByTestId('cve-feed-disabled')).toContainText('CVE_FEED_ENABLED=true'); + await expect(page.getByRole('button', { name: 'Sincronizar ahora' })).toHaveCount(0); + await expect(page.getByTestId('cve-feed-empty')).toBeVisible(); + }); + + test('follows a technology from the modal and sees its CVE, then opens the detail', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + await page.goto(technologyUrl); + // the dev server hydrates late: a click before that follows the no-JS link instead of the modal + await page.waitForLoadState('networkidle'); + await page.getByRole('link', { name: 'Gestionar tecnologías' }).first().click(); + + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + await dialog.getByRole('searchbox').fill('lodash'); + await expect(dialog.getByText('Redis')).toBeHidden(); + await dialog.getByRole('checkbox', { name: /Lodash/ }).check(); + await dialog.getByRole('button', { name: 'Guardar' }).click(); + + await expect(page.getByText('Tecnologías guardadas').first()).toBeVisible(); + await expect(dialog).toBeHidden(); + await expect(page.getByRole('link', { name: /^Lodash/ }).first()).toBeVisible(); + + const row = page.getByRole('row', { name: new RegExp(E2E_FEED_CVE_ID) }); + await expect(row).toContainText('4.17.21'); + await expect(row).toContainText('Alta'); + + // filters are plain GET params + await page.getByRole('combobox', { name: 'Severidad' }).click(); + await page.getByRole('option', { name: /Crítica/ }).click(); + await page.getByRole('button', { name: 'Filtrar' }).click(); + await expect(page).toHaveURL(/severity=critical/); + await expect(page.getByRole('row', { name: new RegExp(E2E_FEED_CVE_ID) })).toHaveCount(0); + await page.goto(technologyUrl); + + await page.getByRole('link', { name: E2E_FEED_CVE_ID }).click(); + await expect(page).toHaveURL(new RegExp(`/cves/${E2E_FEED_CVE_ID}$`)); + await expect(page.getByRole('heading', { name: E2E_FEED_CVE_ID, level: 1 })).toBeVisible(); + const data = page.getByTestId('cve-feed-data'); + await expect(data).toContainText('>=0 <4.17.21'); + await expect(data).toContainText('4.17.21'); + await expect(data.getByRole('link', { name: 'OSV' })).toBeVisible(); + }); + + test('suggests technologies from the SBOMs of the organization, never adding them on its own', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + await page.goto(`${technologyUrl}&manage=1`); + const inline = page.getByTestId('cve-feed-manage-inline'); + // the catalog lists Express too: the suggestion is the one that says why + const suggestion = inline.getByRole('checkbox', { name: /Usáis `express`/ }); + await expect(inline.getByText('Usáis `express` en 1 servicio')).toBeVisible(); + await expect(suggestion).not.toBeChecked(); + // not followed: it is not among the chips either + await expect(page.getByRole('link', { name: /^Express/ })).toHaveCount(0); + }); + + test('the detail also resolves by alias', async ({ page, loginAs }) => { + await loginAs('orgAdmin'); + const response = await page.goto(`${cvesUrl}/${E2E_FEED_ALIAS}`); + expect(response?.status()).toBe(200); + await expect(page.getByTestId('cve-feed-data')).toBeVisible(); + }); + + test('a CVE in neither the scans nor the feed is a 404', async ({ page, loginAs }) => { + await loginAs('orgAdmin'); + const response = await page.goto(`${cvesUrl}/CVE-2099-9999`); + expect(response?.status()).toBe(404); + }); + + test('"Sincronizar ahora" is rejected by the server while the feed is disabled', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + expect(await postAction(page, 'sync', {})).toBe(409); + }); + + test('the watchlist can be edited without JavaScript', async ({ browser, loginAs }) => { + const context = await browser.newContext({ javaScriptEnabled: false }); + const page = await context.newPage(); + // same cookie the fixture sets, in a JS-less context + const { sessionTokenFor } = await import('../fixtures/auth'); + await context.addCookies([ + { + name: 'pos_session', + value: sessionTokenFor(seed.personas.orgAdmin.userId), + url: E2E_BASE_URL, + }, + ]); + void loginAs; + await page.goto(`${technologyUrl}&manage=1`); + const inline = page.getByTestId('cve-feed-manage-inline'); + await inline.getByRole('checkbox', { name: /Redis/ }).check(); + await inline.getByRole('button', { name: 'Guardar' }).click(); + await expect(page.getByRole('status')).toContainText('Tecnologías guardadas'); + await expect(page.getByRole('link', { name: /^Redis/ })).toBeVisible(); + await context.close(); + }); +}); + +test.describe('CVE feed — read-only role (organization:cves:feed:read)', () => { + test('sees the feed tab and the data but cannot manage or sync', async ({ page, loginAs }) => { + await loginAs('orgCveFeedReader'); + await page.goto(technologyUrl); + await expect(page.getByTestId('cve-feed')).toBeVisible(); + await expect(page.getByRole('link', { name: 'Gestionar tecnologías' })).toHaveCount(0); + await expect(page.getByRole('button', { name: 'Sincronizar ahora' })).toHaveCount(0); + await expect(page.getByRole('link', { name: E2E_FEED_CVE_ID })).toBeVisible(); + }); + + test('the actions answer 403', async ({ page, loginAs }) => { + await loginAs('orgCveFeedReader'); + expect(await postAction(page, 'watchlist', { technology: 'nodejs' })).toBe(403); + expect(await postAction(page, 'sync', {})).toBe(403); + }); + + test('the CVE detail shows the feed data without scan access', async ({ page, loginAs }) => { + await loginAs('orgCveFeedReader'); + const response = await page.goto(`${cvesUrl}/${E2E_FEED_CVE_ID}`); + expect(response?.status()).toBe(200); + await expect(page.getByTestId('cve-feed-data')).toBeVisible(); + }); +}); + +test.describe('CVE feed — role without the feed permission', () => { + test('does not see the tab and "?tab=technology" falls back to "Mis CVEs"', async ({ + page, + loginAs, + }) => { + await loginAs('orgDeveloper'); + await page.goto(technologyUrl); + await expect(page.getByRole('link', { name: 'CVEs por tecnología' })).toHaveCount(0); + await expect(page.getByTestId('cve-feed')).toHaveCount(0); + }); + + test('the actions answer 403', async ({ page, loginAs }) => { + await loginAs('orgDeveloper'); + expect(await postAction(page, 'watchlist', { technology: 'nodejs' })).toBe(403); + expect(await postAction(page, 'sync', {})).toBe(403); + }); + + test('feed CVEs are not exposed in the detail', async ({ page, loginAs }) => { + await loginAs('orgDeveloper'); + const response = await page.goto(`${cvesUrl}/${E2E_FEED_CVE_ID}`); + expect(response?.status()).toBe(404); + }); +}); + +test.describe('CVE feed — users outside the organization', () => { + test('cannot post to the actions', async ({ page, loginAs }) => { + await loginAs('orgOutsider'); + expect(await postAction(page, 'watchlist', { technology: 'nodejs' })).toBe(403); + }); +}); diff --git a/src/env.ts b/src/env.ts index e5a9634..0185460 100644 --- a/src/env.ts +++ b/src/env.ts @@ -50,4 +50,15 @@ export const variables = defineEnvVars({ MONITORING_FLUSH_SECONDS: optional, MONITORING_HOURLY_RETENTION_DAYS: optional, MONITORING_INCIDENT_RETENTION_DAYS: optional, + CVE_FEED_ENABLED: optional, + CVE_FEED_SYNC_INTERVAL: optional, + CVE_FEED_MIN_SEVERITY: optional, + CVE_FEED_EPSS_THRESHOLD: optional, + CVE_FEED_RETENTION: optional, + CVE_FEED_BACKFILL: optional, + NVD_API_KEY: optional, + CVE_FEED_GITDB_REPOSITORY_URL: optional, + CVE_FEED_GITDB_BRANCH: optional, + CVE_FEED_GITDB_DATA_PATH: optional, + CVE_FEED_GITDB_TOKEN: optional, }); diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 4836016..af628e6 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -6,6 +6,7 @@ import { projectService } from '#modules/projects'; import { registerAlertEngine } from '#modules/alerts'; import { registerStateIac } from '#modules/state-iac'; import { getMonitoringConfig, startMonitoring } from '#modules/monitoring'; +import { startCveFeed } from '#modules/cve-feed'; import { isInternalMonitoringRequest, verifyWorkerRequest, @@ -44,6 +45,8 @@ const serverReady = (async () => { startMonitoring().catch((error) => startupLog.error(error, '[startup] monitoring failed to start'), ); + // the CVE feed only schedules work with CVE_FEED_ENABLED=true; otherwise nothing external is called + startCveFeed().catch((error) => startupLog.error(error, '[startup] cve feed failed to start')); })(); serverReady.catch((error) => { diff --git a/src/lib/code-report/package-inventory.test.ts b/src/lib/code-report/package-inventory.test.ts new file mode 100644 index 0000000..6230c83 --- /dev/null +++ b/src/lib/code-report/package-inventory.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from 'vitest'; +import { extractInventoryPackages, parsePurl } from './package-inventory'; + +describe('parsePurl', () => { + it('maps purl types to OSV ecosystems and names', () => { + expect(parsePurl('pkg:npm/express@4.18.2')).toEqual({ ecosystem: 'npm', name: 'express' }); + expect(parsePurl('pkg:npm/%40sveltejs/kit@2.0.0')).toEqual({ + ecosystem: 'npm', + name: '@sveltejs/kit', + }); + expect(parsePurl('pkg:pypi/Django_Rest.Framework@3.0')).toEqual({ + ecosystem: 'PyPI', + name: 'django-rest-framework', + }); + expect(parsePurl('pkg:maven/org.apache.logging.log4j/log4j-core@2.17.0?type=jar')).toEqual({ + ecosystem: 'Maven', + name: 'org.apache.logging.log4j:log4j-core', + }); + expect(parsePurl('pkg:golang/golang.org/x/net@v0.17.0')).toEqual({ + ecosystem: 'Go', + name: 'golang.org/x/net', + }); + expect(parsePurl('pkg:gem/rails@7.0.0')).toEqual({ ecosystem: 'RubyGems', name: 'rails' }); + }); + + it('is null for OS packages and malformed values', () => { + expect(parsePurl('pkg:deb/debian/openssl@3.0')).toBeNull(); + expect(parsePurl('pkg:apk/alpine/musl@1.2')).toBeNull(); + expect(parsePurl('nonsense')).toBeNull(); + expect(parsePurl(undefined)).toBeNull(); + }); +}); + +describe('extractInventoryPackages', () => { + it('reads a Trivy report: packages (with --list-all-pkgs) and vulnerable ones, by result type', () => { + const packages = extractInventoryPackages({ + Results: [ + { + Type: 'npm', + Packages: [{ Name: 'express', Version: '4.18.2' }, { Name: 'express' }], + Vulnerabilities: [{ PkgName: 'lodash' }], + }, + { Type: 'pip', Packages: [{ Name: 'Flask' }] }, + { Type: 'alpine', Packages: [{ Name: 'musl' }] }, + { + Type: 'jar', + Vulnerabilities: [ + { + PkgName: 'org.springframework.boot:spring-boot', + PkgIdentifier: { PURL: 'pkg:maven/org.springframework.boot/spring-boot@3.1.0' }, + }, + ], + }, + ], + }); + expect(packages).toEqual([ + { ecosystem: 'npm', name: 'express' }, + { ecosystem: 'npm', name: 'lodash' }, + { ecosystem: 'PyPI', name: 'flask' }, + { ecosystem: 'Maven', name: 'org.springframework.boot:spring-boot' }, + ]); + }); + + it('reads a CycloneDX and a syft SBOM through the purl of each component', () => { + expect( + extractInventoryPackages({ + components: [ + { name: 'express', purl: 'pkg:npm/express@4.18.2' }, + { name: 'musl', purl: 'pkg:apk/alpine/musl@1' }, + { name: 'no purl' }, + ], + }), + ).toEqual([{ ecosystem: 'npm', name: 'express' }]); + expect( + extractInventoryPackages({ artifacts: [{ name: 'django', purl: 'pkg:pypi/django@4.2' }] }), + ).toEqual([{ ecosystem: 'PyPI', name: 'django' }]); + }); + + it('is empty for anything else', () => { + expect(extractInventoryPackages(null)).toEqual([]); + expect(extractInventoryPackages([])).toEqual([]); + expect(extractInventoryPackages({ Results: 'x' })).toEqual([]); + }); +}); diff --git a/src/lib/code-report/package-inventory.ts b/src/lib/code-report/package-inventory.ts new file mode 100644 index 0000000..9f97359 --- /dev/null +++ b/src/lib/code-report/package-inventory.ts @@ -0,0 +1,126 @@ +// Which packages an analysis says a service uses, as `{ OSV ecosystem, name }`: from a Trivy report +// (`Results[].Packages[]` with `--list-all-pkgs`, else the packages of `Results[].Vulnerabilities[]`) +// or an SBOM (CycloneDX `components[]`, syft `artifacts[]`). Only language ecosystems that OSV +// knows; OS packages (deb, apk…) are left out. +import type { OsvEcosystem } from '#lib/cves/technologies.data'; + +export type InventoryPackage = { ecosystem: OsvEcosystem; name: string }; + +const PURL_ECOSYSTEMS: Record = { + npm: 'npm', + pypi: 'PyPI', + golang: 'Go', + maven: 'Maven', + gem: 'RubyGems', + cargo: 'crates.io', + nuget: 'NuGet', + composer: 'Packagist', +}; + +// Trivy `Results[].Type` +const TRIVY_ECOSYSTEMS: Record = { + npm: 'npm', + yarn: 'npm', + pnpm: 'npm', + bun: 'npm', + 'node-pkg': 'npm', + pip: 'PyPI', + pipenv: 'PyPI', + poetry: 'PyPI', + uv: 'PyPI', + 'python-pkg': 'PyPI', + gomod: 'Go', + gobinary: 'Go', + jar: 'Maven', + pom: 'Maven', + gradle: 'Maven', + sbt: 'Maven', + bundler: 'RubyGems', + gemspec: 'RubyGems', + cargo: 'crates.io', + 'rust-binary': 'crates.io', + nuget: 'NuGet', + 'dotnet-core': 'NuGet', + composer: 'Packagist', + 'composer-vendor': 'Packagist', +}; + +function normalizeName(ecosystem: OsvEcosystem, name: string): string { + // PEP 503: PyPI names are compared lower-case with runs of `-_.` as one dash + return ecosystem === 'PyPI' ? name.toLowerCase().replace(/[-_.]+/g, '-') : name; +} + +/** `pkg:npm/%40sveltejs/kit@2.0.0` -> `{ npm, @sveltejs/kit }`; `null` for anything else. */ +export function parsePurl(purl: unknown): InventoryPackage | null { + if (typeof purl !== 'string') return null; + const match = /^pkg:([a-z]+)\/([^@?#]+)/i.exec(purl); + const ecosystem = match ? PURL_ECOSYSTEMS[match[1].toLowerCase()] : undefined; + if (!match || !ecosystem) return null; + let path: string; + try { + path = decodeURIComponent(match[2]); + } catch { + return null; + } + const parts = path.split('/'); + const name = + ecosystem === 'Maven' && parts.length >= 2 + ? `${parts.slice(0, -1).join('.')}:${parts[parts.length - 1]}` + : path; + return name ? { ecosystem, name: normalizeName(ecosystem, name) } : null; +} + +function record(value: unknown): Record | null { + return value && typeof value === 'object' ? (value as Record) : null; +} + +function purlOf(entry: Record): string | null { + const identifier = record(entry.Identifier) ?? record(entry.PkgIdentifier); + const purl = identifier?.PURL ?? entry.purl; + return typeof purl === 'string' ? purl : null; +} + +/** The distinct packages an analysis result lists (Trivy or SBOM); empty for anything else. */ +export function extractInventoryPackages(result: unknown): InventoryPackage[] { + const root = record(result); + if (!root) return []; + const found = new Map(); + const add = (pkg: InventoryPackage | null) => { + if (pkg) found.set(`${pkg.ecosystem}|${pkg.name}`, pkg); + }; + + if (Array.isArray(root.Results)) { + for (const entry of root.Results) { + const row = record(entry); + if (!row) continue; + const trivyEcosystem = TRIVY_ECOSYSTEMS[String(row.Type ?? '').toLowerCase()]; + const items = [ + ...(Array.isArray(row.Packages) ? row.Packages : []), + ...(Array.isArray(row.Vulnerabilities) ? row.Vulnerabilities : []), + ]; + for (const item of items) { + const pkg = record(item); + if (!pkg) continue; + const fromPurl = parsePurl(purlOf(pkg)); + if (fromPurl) add(fromPurl); + else if (trivyEcosystem) { + const name = pkg.Name ?? pkg.PkgName; + if (typeof name === 'string' && name) + add({ ecosystem: trivyEcosystem, name: normalizeName(trivyEcosystem, name) }); + } + } + } + return [...found.values()]; + } + + const components = Array.isArray(root.components) + ? root.components + : Array.isArray(root.artifacts) + ? root.artifacts + : []; + for (const component of components) { + const row = record(component); + if (row) add(parsePurl(row.purl)); + } + return [...found.values()]; +} diff --git a/src/lib/components/code-report/CveDetailView.svelte b/src/lib/components/code-report/CveDetailView.svelte index 4e8030a..ee03d2f 100644 --- a/src/lib/components/code-report/CveDetailView.svelte +++ b/src/lib/components/code-report/CveDetailView.svelte @@ -45,6 +45,7 @@ + +
+
+
+

+ {$_('org.cves.feed.detail.title')} +

+

{$_('org.cves.feed.detail.description')}

+
+ {#if advisory.kev} + {$_('org.cves.feed.badges.kev')} + {#if advisory.kevAddedAt}· {date(advisory.kevAddedAt)}{/if} + {/if} + {#if affectsMe} + {$_('org.cves.feed.badges.affectsMe')} + {/if} +
+ +
+ {#if technologies.length > 0} +
+
{$_('org.cves.feed.detail.technologies')}
+
+ {#each technologies as technology (technology.id)} + {technology.name} + {/each} +
+
+ {/if} + + {#if occurrences.length > 0} +
+
{$_('org.cves.feed.detail.occurrences')}
+
+
    + {#each occurrences as service (service.serviceId)} +
  • + {service.projectName} + {#if serviceHref} + {service.serviceName} + {:else} + {service.serviceName} + {/if} +
  • + {/each} +
+
+
+ {/if} + +
+
{$_('org.cves.feed.detail.affected')}
+
+ {#if advisory.affected.length > 0} +
    + {#each advisory.affected as item, index (index)} +
  • + + {item.package ?? item.cpe ?? item.technologyId} + {#if item.ecosystem}({item.ecosystem}){/if} + + + {item.ranges.length > 0 ? item.ranges.join(' · ') : '—'} + + + {#if item.fixedVersions.length > 0} + → + {item.fixedVersions.join(', ')} + {:else} + {$_('org.cves.feed.detail.noFix')} + {/if} + +
  • + {/each} +
+ {:else} +

{$_('org.cves.feed.detail.noRanges')}

+ {/if} +
+
+ +
+
+
{$_('org.cves.feed.detail.fixedVersions')}
+
+ {#if advisory.fixedVersions.length > 0} + {advisory.fixedVersions.join(', ')} + {:else} + {$_('org.cves.feed.detail.noFix')} + {/if} +
+
+
+
EPSS
+
+ {advisory.epssScore !== null ? `${(advisory.epssScore * 100).toFixed(2)} %` : '—'} +
+
+
+
{$_('org.cves.feed.detail.sources')}
+
{advisory.sources.join(', ') || '—'}
+
+
+ + {#if advisory.aliases.length > 0} +
+
{$_('org.cves.feed.detail.aliases')}
+
+ {#each advisory.aliases as alias (alias)}{alias}{/each} +
+
+ {/if} + +
+ {#each links as link (link.label)} + + {link.label} + + {/each} +
+
+
diff --git a/src/lib/components/cves/FeedTab.svelte b/src/lib/components/cves/FeedTab.svelte new file mode 100644 index 0000000..6f1cde2 --- /dev/null +++ b/src/lib/components/cves/FeedTab.svelte @@ -0,0 +1,526 @@ + + + +
+ {#if !feed.enabled} +
+ +
+

{$_('org.cves.feed.disabled.title')}

+

+ {$_('org.cves.feed.disabled.description')} + CVE_FEED_ENABLED=true +

+
+
+ {/if} + + {#if form?.success && form.action === 'watchlist'} +

+ {$_('org.cves.feed.watchlistSaved')} +

+ {:else if form?.success && form.action === 'sync'} +

+ {$_('org.cves.feed.syncRequested')} +

+ {:else if form?.error && form.action === 'sync'} + + {/if} + +
+
+
+

+ {$_('org.cves.feed.followed')} +

+

{$_('org.cves.feed.intro')}

+
+
+ {#if feed.canUpdate && feed.enabled} +
+ +
+ {/if} + {#if feed.canUpdate} + + {$_('org.cves.feed.manage')} + + {/if} +
+
+ + {#if following} + + {/if} +
+ + {#if feed.manage && feed.canUpdate} +
+

{$_('org.cves.feed.modal.title')}

+

{$_('org.cves.feed.modal.description')}

+ +
+ {$_('common.cancel')} + +
+
+ {/if} + + {#if !following} +
+ +

{$_('org.cves.feed.empty.title')}

+

+ {$_(feed.canUpdate ? 'org.cves.feed.empty.description' : 'org.cves.feed.empty.readOnly')} +

+ {#if feed.canUpdate && !feed.manage} + + {$_('org.cves.feed.empty.action')} + + {/if} +
+ {:else} +
+ +
+ + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + + +
+
+ + +
+ {#if hasFilters} + {$_('org.cves.feed.filters.clear')} + {/if} + +
+
+
+ +
+
+

+ {$_('org.cves.feed.tableTitle')} + {feed.total} +

+
+
+ + + + + + + + + + + + + + + {#each feed.items as item (item.advisory.id)} + {@const advisory = item.advisory} + + + + + + + + + + + {:else} + + + + {/each} + +
{$_('org.cves.feed.columns.cve')}{$_('org.cves.feed.columns.technology')}{$_('org.cves.feed.columns.severity')}{$_('org.cves.feed.columns.epss')}{$_('org.cves.feed.columns.flags')}{$_('org.cves.feed.columns.published')}{$_('org.cves.feed.columns.updated')}{$_('org.cves.feed.columns.fixed')}
+ {advisory.id} + {#if advisory.title} +

+ {advisory.title} +

+ {/if} +
+ {item.technologyIds.map(technologyName).join(', ')} + {#each advisory.affected.slice(0, 1) as affected (affected.package ?? affected.cpe)} +

{affected.package ?? affected.cpe}

+ {/each} +
+ {severityLabel(advisory.severity)} + {advisory.cvssScore !== null ? advisory.cvssScore.toFixed(1) : '—'} + + {advisory.epssScore !== null + ? `${(advisory.epssScore * 100).toFixed(advisory.epssScore < 0.01 ? 2 : 1)} %` + : '—'} + +
+ {#if advisory.kev} + {$_('org.cves.feed.badges.kev')} + {/if} + {#if item.affectsMe} + {$_('org.cves.feed.badges.affectsMe')} + {/if} +
+
{date(advisory.publishedAt)}{date(advisory.modifiedAt)} + {#if advisory.fixedVersions.length > 0} + {advisory.fixedVersions.slice(0, 2).join(', ')} + {:else} + — + {/if} +
+ {$_(hasFilters ? 'org.cves.feed.noResults' : 'org.cves.feed.noAdvisories')} +
+
+ {#if feed.total > feed.pageSize} + + {/if} +
+ {/if} + +
+

+ {$_('org.cves.feed.status.title')} +

+

+ {$_('org.cves.feed.status.lastRun', { values: { date: dateTime(feed.status.lastRunAt) } })} +

+
    + {#each sources as source (source.id)} +
  • + + {$_(`org.cves.feed.status.sources.${source.id}`)} + + + {$_('org.cves.feed.status.lastSuccess', { + values: { date: dateTime(source.lastSuccessAt) }, + })} + + {#if source.lastError} + + {source.lastError} + {#if source.lastErrorAt}· {dateTime(source.lastErrorAt)}{/if} + + {:else} + {$_('org.cves.feed.status.noErrors')} + {/if} +
  • + {/each} +
+
+
+ +{#if feed.canUpdate} + + + {#snippet footer()} + + + {/snippet} + +{/if} diff --git a/src/lib/components/cves/FormSelect.svelte b/src/lib/components/cves/FormSelect.svelte new file mode 100644 index 0000000..e380acc --- /dev/null +++ b/src/lib/components/cves/FormSelect.svelte @@ -0,0 +1,44 @@ + + + +{#if enhanced} + + {#each options as option (option.value)} + + {/each} + +{/if} diff --git a/src/lib/components/cves/WatchlistForm.svelte b/src/lib/components/cves/WatchlistForm.svelte new file mode 100644 index 0000000..3089a78 --- /dev/null +++ b/src/lib/components/cves/WatchlistForm.svelte @@ -0,0 +1,300 @@ + + + +
+ {#if error} + + {/if} + +
+
+
+
+

+ {$_('org.cves.feed.modal.catalog')} +

+ +
+
    + {#each CVE_TECHNOLOGIES as technology (technology.id)} + + {/each} +
+ {#if query.trim() && !CVE_TECHNOLOGIES.some( (t) => visible(t.name, categoryLabel(t.category)) )} +

{$_('org.cves.feed.modal.noMatches')}

+ {/if} +
+
+
+ {#if suggestedIds.length > 0} + + {/if} +
+
+

+ {$_('org.cves.feed.modal.custom')} +

+

{$_('org.cves.feed.modal.customHelp')}

+
+ {#if customEntries.length > 0} +
    + {#each customEntries as entry (entry.technologyId)} + {#if entry.custom} +
  • + +
  • + {/if} + {/each} +
+ {/if} +
+ + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + +
+
+
+ {@render settings('grid gap-4 sm:grid-cols-2')} +
+
+
+
+ +{#snippet settings(layout: string)} +
+
+ + {#snippet children(control)} + + {/snippet} + + + {#snippet children(control)} + + {/snippet} + +
+

+ {$_('org.cves.feed.modal.floorNotice', { + values: { severity: severityLabel(severityFloor) }, + })} +

+
+{/snippet} diff --git a/src/lib/components/ui/Modal.svelte b/src/lib/components/ui/Modal.svelte index 74a4010..ec0efb1 100644 --- a/src/lib/components/ui/Modal.svelte +++ b/src/lib/components/ui/Modal.svelte @@ -23,7 +23,7 @@ title: string; description?: string; /** Ancho del panel. */ - size?: 'sm' | 'md' | 'lg' | 'xl'; + size?: 'sm' | 'md' | 'lg' | 'xl' | 'full'; /** `right` lo convierte en un drawer lateral. */ placement?: 'center' | 'right'; /** `alertdialog` para confirmaciones destructivas. */ @@ -62,10 +62,18 @@ const descriptionId = `${uid}-description`; const widths = { - center: { sm: 'max-w-md', md: 'max-w-lg', lg: 'max-w-2xl', xl: 'max-w-4xl' }, - right: { sm: 'max-w-sm', md: 'max-w-md', lg: 'max-w-xl', xl: 'max-w-3xl' }, + center: { + sm: 'max-w-md', + md: 'max-w-lg', + lg: 'max-w-2xl', + xl: 'max-w-4xl', + full: 'max-w-none', + }, + right: { sm: 'max-w-sm', md: 'max-w-md', lg: 'max-w-xl', xl: 'max-w-3xl', full: 'max-w-[90vw]' }, }; + const fullCenter = 'w-[calc(100vw-2rem)] sm:w-[calc(100vw-4rem)] max-h-[90vh]'; + function panelTransition(node: Element) { return placement === 'center' ? scale(node, { start: 0.96, duration: 150, easing: cubicOut }) @@ -81,7 +89,7 @@ {#if open}
@@ -96,7 +104,7 @@
@@ -11,6 +13,8 @@ label: string; count?: number | string; disabled?: boolean; + /** Con `href` la pestaña es un enlace (navega, funciona sin JS) y `value` marca la activa. */ + href?: string; }; export const tabId = (prefix: string, value: string) => `${prefix}-tab-${value}`; @@ -66,7 +70,32 @@ } -{#if variant === 'underline'} +{#if variant === 'underline' && items.some((item) => item.href)} + +{:else if variant === 'underline'}
/cves, "CVEs por tecnología" tab): read to see the feed and receive its + // alerts, update to edit the watchlist and run "Sincronizar ahora" + cves: { + resource: 'cves', + sections: { + feed: { + resource: 'feed', + permissions: [ + 'organization:cves:feed:read', + 'organization:cves:feed:update', + 'organization:cves:feed:all', + ], + }, + }, + }, // State IaC (/org//settings/state-iac): the buckets with the IaC state and which // GitOps project sees each Pulumi project. `stacks:read` sees every stack, assigned or not stateiac: { diff --git a/src/lib/cves/feed-view.test.ts b/src/lib/cves/feed-view.test.ts new file mode 100644 index 0000000..26e056b --- /dev/null +++ b/src/lib/cves/feed-view.test.ts @@ -0,0 +1,169 @@ +import { describe, expect, it } from 'vitest'; +import { + advisoryToCveDetail, + feedQuery, + parseCvesTab, + parseFeedFilters, + parseWatchlistForm, + severityAtLeast, +} from './feed-view'; + +const params = (query: string) => new URLSearchParams(query); + +describe('parseFeedFilters', () => { + it('reads valid filters and builds the query service filters', () => { + const { filters, values } = parseFeedFilters( + params( + 'technology=nodejs&severity=high&kev=1&affectsMe=1&from=2026-01-02&to=2026-02-03&page=3', + ), + ); + expect(filters).toEqual({ + technologyId: 'nodejs', + minSeverity: 'high', + kev: true, + affectsMe: true, + from: '2026-01-02T00:00:00.000Z', + to: '2026-02-03T23:59:59.999Z', + }); + expect(values.page).toBe(3); + }); + + it('ignores anything invalid instead of failing', () => { + const { filters, values } = parseFeedFilters( + params('severity=extreme&kev=yes&from=yesterday&to=2026-13-40&page=-4'), + ); + expect(filters).toEqual({}); + expect(values).toMatchObject({ severity: '', kev: false, from: '', to: '', page: 1 }); + }); + + it('swaps an inverted date range and never accepts "unknown" as a threshold', () => { + const { values } = parseFeedFilters(params('from=2026-05-01&to=2026-04-01&severity=unknown')); + expect(values).toMatchObject({ from: '2026-04-01', to: '2026-05-01', severity: '' }); + }); +}); + +describe('feedQuery', () => { + it('keeps the tab and only the values that are set', () => { + expect(feedQuery({ technology: 'redis', kev: true, page: 1 })).toBe( + '?tab=technology&technology=redis&kev=1', + ); + expect(feedQuery({ page: 2 }, { manage: '1' })).toBe('?tab=technology&page=2&manage=1'); + }); +}); + +describe('parseCvesTab', () => { + it('defaults to "mine" and hides the feed tab without permission', () => { + expect(parseCvesTab(params(''), { feed: true, projects: true })).toBe('mine'); + expect(parseCvesTab(params('tab=technology'), { feed: true, projects: true })).toBe( + 'technology', + ); + expect(parseCvesTab(params('tab=technology'), { feed: false, projects: true })).toBe('mine'); + }); + + it('sends someone who can only read the feed to the feed', () => { + expect(parseCvesTab(params(''), { feed: true, projects: false })).toBe('technology'); + }); +}); + +describe('parseWatchlistForm', () => { + const current = { + technologies: [ + { + technologyId: 'custom:osv:npm:left-pad', + custom: { kind: 'osv' as const, ecosystem: 'npm' as const, package: 'left-pad' }, + label: 'Left pad', + addedAt: '2026-01-01T00:00:00Z', + }, + { technologyId: 'redis', minSeverity: 'critical' as const, addedAt: '2026-01-01T00:00:00Z' }, + ], + }; + + function form(entries: [string, string][]) { + const data = new FormData(); + for (const [key, value] of entries) data.append(key, value); + return data; + } + + it('collects catalog ids, kept custom entries and a new custom entry', () => { + const input = parseWatchlistForm( + form([ + ['technology', 'redis'], + ['technology', 'nodejs'], + ['custom', 'osv:npm:left-pad'], + ['newKind', 'cpe'], + ['newEcosystem', 'npm'], + ['newValue', ' cpe:2.3:a:acme:widget '], + ['minSeverity', 'critical'], + ['includeKev', 'on'], + ]), + current, + 'high', + ); + expect(input.technologies).toEqual( + [ + { technologyId: 'redis', label: undefined, minSeverity: 'critical', versions: undefined }, + { technologyId: 'nodejs' }, + { custom: { kind: 'osv', ecosystem: 'npm', package: 'left-pad' }, label: 'Left pad' }, + { custom: { kind: 'cpe', cpe: 'cpe:2.3:a:acme:widget' } }, + ].map((entry) => expect.objectContaining(entry)), + ); + expect(input).toMatchObject({ minSeverity: 'critical', includeKev: true }); + }); + + it('adds an OSV package with the chosen ecosystem, and keeps colons in the package name', () => { + const input = parseWatchlistForm( + form([ + ['custom', 'osv:Maven:org.apache:thing'], + ['newKind', 'osv'], + ['newEcosystem', 'PyPI'], + ['newValue', 'requests'], + ]), + { technologies: [] }, + 'high', + ); + expect(input.technologies).toEqual([ + { custom: { kind: 'osv', ecosystem: 'Maven', package: 'org.apache:thing' } }, + { custom: { kind: 'osv', ecosystem: 'PyPI', package: 'requests' } }, + ]); + }); + + it('lifts a minimum severity below the global floor and unchecks KEV when absent', () => { + const input = parseWatchlistForm(form([['minSeverity', 'low']]), { technologies: [] }, 'high'); + expect(input).toEqual({ technologies: [], minSeverity: 'high', includeKev: false }); + }); +}); + +describe('severityAtLeast', () => { + it('returns the higher of both', () => { + expect(severityAtLeast('low', 'high')).toBe('high'); + expect(severityAtLeast('critical', 'high')).toBe('critical'); + }); +}); + +describe('advisoryToCveDetail', () => { + it('links NVD for CVE ids and OSV otherwise', () => { + const base = { + id: 'CVE-2026-1', + aliases: [], + title: 't', + summary: 's', + details: '', + severity: 'high', + cvssScore: 8, + cwe: [], + references: ['https://x.test'], + epssScore: null, + epssPercentile: null, + publishedAt: null, + modifiedAt: '2026-01-01T00:00:00Z', + } as unknown as Parameters[0]; + expect(advisoryToCveDetail(base)).toMatchObject({ + description: 's', + cveUrl: 'https://nvd.nist.gov/vuln/detail/CVE-2026-1', + primaryUrl: 'https://osv.dev/vulnerability/CVE-2026-1', + }); + expect(advisoryToCveDetail({ ...base, id: 'GHSA-abcd' }).cveUrl).toBe( + 'https://osv.dev/vulnerability/GHSA-abcd', + ); + }); +}); diff --git a/src/lib/cves/feed-view.ts b/src/lib/cves/feed-view.ts new file mode 100644 index 0000000..f733caf --- /dev/null +++ b/src/lib/cves/feed-view.ts @@ -0,0 +1,211 @@ +/** + * Pure helpers of the CVE feed pages (`/org//cves` technology tab and the detail page): + * GET filters, the watchlist form and the mapping of an advisory to the shared CVE detail view. + * No server imports, so the routes and their tests can use it as is. + */ +import { OSV_ECOSYSTEMS, type OsvEcosystem } from '#lib/cves/technologies.data'; +import type { CveDetail } from '#lib/components/code-report/CveDetailView.svelte'; +import type { + CveAdvisory, + CveFeedFilters, + CveWatchlist, + Severity, + WatchlistEntryInput, + WatchlistInput, +} from '#modules/cve-feed'; + +export const FEED_PAGE_SIZE = 25; +/** Severities a user can pick as a minimum (`unknown` is never a useful threshold). */ +export const SELECTABLE_SEVERITIES = ['low', 'medium', 'high', 'critical'] as const; +const RANK: Record = { unknown: 0, low: 1, medium: 2, high: 3, critical: 4 }; +const DATE_PATTERN = /^\d{4}-\d{2}-\d{2}$/; + +export type FeedFilterValues = { + technology: string; + severity: string; + kev: boolean; + affectsMe: boolean; + from: string; + to: string; + page: number; +}; + +export type ParsedFeedFilters = { + /** What goes to the query service (without paging). */ + filters: CveFeedFilters; + /** The normalized values, to fill the form back in. */ + values: FeedFilterValues; +}; + +function validDate(value: string | null): string { + if (!value || !DATE_PATTERN.test(value)) return ''; + return Number.isNaN(Date.parse(`${value}T00:00:00Z`)) ? '' : value; +} + +/** Reads the GET filters of the technology tab; anything invalid is ignored, never an error. */ +export function parseFeedFilters(params: URLSearchParams): ParsedFeedFilters { + const technology = (params.get('technology') ?? '').trim().slice(0, 200); + const severityParam = params.get('severity') ?? ''; + const severity = (SELECTABLE_SEVERITIES as readonly string[]).includes(severityParam) + ? severityParam + : ''; + const kev = params.get('kev') === '1'; + const affectsMe = params.get('affectsMe') === '1'; + let from = validDate(params.get('from')); + let to = validDate(params.get('to')); + if (from && to && from > to) [from, to] = [to, from]; + const pageNumber = Number.parseInt(params.get('page') ?? '1', 10); + const page = Number.isFinite(pageNumber) && pageNumber > 0 ? Math.min(pageNumber, 10_000) : 1; + + const filters: CveFeedFilters = {}; + if (technology) filters.technologyId = technology; + if (severity) filters.minSeverity = severity as Severity; + if (kev) filters.kev = true; + if (affectsMe) filters.affectsMe = true; + if (from) filters.from = `${from}T00:00:00.000Z`; + if (to) filters.to = `${to}T23:59:59.999Z`; + return { filters, values: { technology, severity, kev, affectsMe, from, to, page } }; +} + +/** Query string of the technology tab (only what is set), optionally overriding some values. */ +export function feedQuery( + values: Partial, + extra: Record = {}, +): string { + const params = new URLSearchParams({ tab: 'technology' }); + if (values.technology) params.set('technology', values.technology); + if (values.severity) params.set('severity', values.severity); + if (values.kev) params.set('kev', '1'); + if (values.affectsMe) params.set('affectsMe', '1'); + if (values.from) params.set('from', values.from); + if (values.to) params.set('to', values.to); + if (values.page && values.page > 1) params.set('page', String(values.page)); + for (const [key, value] of Object.entries(extra)) params.set(key, value); + return `?${params.toString()}`; +} + +/** `?tab=` of the cves page; the feed tab needs the feed permission. */ +export function parseCvesTab( + params: URLSearchParams, + access: { feed: boolean; projects: boolean }, +): 'mine' | 'technology' { + const wanted = params.get('tab') === 'technology' ? 'technology' : 'mine'; + if (wanted === 'technology' && !access.feed) return 'mine'; + // someone who can only read the feed has nothing to see in "Mis CVEs" + if (wanted === 'mine' && !access.projects && access.feed) return 'technology'; + return wanted; +} + +export function severityAtLeast(value: string, floor: string): string { + return (RANK[value] ?? 0) >= (RANK[floor] ?? 0) ? value : floor; +} + +function customValue(value: string): WatchlistEntryInput['custom'] | null { + if (value.startsWith('osv:')) { + const rest = value.slice(4); + const index = rest.indexOf(':'); + if (index < 1) return null; + return { + kind: 'osv', + ecosystem: rest.slice(0, index) as OsvEcosystem, + package: rest.slice(index + 1), + }; + } + if (value.startsWith('cpe:')) return { kind: 'cpe', cpe: value.slice(4) }; + return null; +} + +/** The value of the `custom` checkbox that keeps an existing custom entry. */ +export function customFieldValue(custom: NonNullable): string { + return custom.kind === 'osv' ? `osv:${custom.ecosystem}:${custom.package}` : `cpe:${custom.cpe}`; +} + +/** + * Builds the watchlist the form describes. Fields: `technology` (catalog ids, repeated), `custom` + * (custom entries kept, `osv::` or `cpe:`), `newKind`/`newEcosystem`/ + * `newValue` (a custom entry to add), `minSeverity` and `includeKev`. Entries that were already + * followed keep their label, own severity and versions. `severityFloor` is the global + * CVE_FEED_MIN_SEVERITY: the organization can only raise it, so a lower choice is lifted to it. + */ +export function parseWatchlistForm( + form: FormData, + current: Pick, + severityFloor: string, +): WatchlistInput { + const before = new Map(current.technologies.map((entry) => [entry.technologyId, entry])); + const keep = (id: string): Partial => { + const entry = before.get(id); + return entry + ? { label: entry.label, minSeverity: entry.minSeverity, versions: entry.versions } + : {}; + }; + + const technologies: WatchlistEntryInput[] = []; + for (const id of form.getAll('technology')) { + if (typeof id === 'string' && id) technologies.push({ technologyId: id, ...keep(id) }); + } + for (const value of form.getAll('custom')) { + const custom = typeof value === 'string' ? customValue(value) : null; + if (!custom) continue; + const existing = [...before.values()].find( + (entry) => entry.custom && customFieldValue(entry.custom) === value, + ); + technologies.push({ + custom, + ...(existing ? keep(existing.technologyId) : {}), + }); + } + + const newValue = String(form.get('newValue') ?? '').trim(); + if (newValue) { + const kind = form.get('newKind') === 'cpe' ? 'cpe' : 'osv'; + if (kind === 'cpe') technologies.push({ custom: { kind: 'cpe', cpe: newValue } }); + else { + const ecosystem = String(form.get('newEcosystem') ?? ''); + technologies.push({ + // an unknown ecosystem reaches the validator, which rejects it with a clear error + custom: { kind: 'osv', ecosystem: ecosystem as OsvEcosystem, package: newValue }, + }); + } + } + + return { + technologies, + minSeverity: severityAtLeast(String(form.get('minSeverity') ?? severityFloor), severityFloor), + includeKev: form.get('includeKev') === 'on', + }; +} + +export const KNOWN_ECOSYSTEMS: readonly string[] = OSV_ECOSYSTEMS; + +export function nvdUrl(id: string): string | null { + return /^CVE-\d{4}-\d+$/i.test(id) + ? `https://nvd.nist.gov/vuln/detail/${id.toUpperCase()}` + : null; +} + +export function osvUrl(advisory: Pick): string { + return `https://osv.dev/vulnerability/${encodeURIComponent(advisory.id)}`; +} + +export const KEV_CATALOG_URL = 'https://www.cisa.gov/known-exploited-vulnerabilities-catalog'; + +/** The shared detail view's data, built from a feed advisory (when the scans know nothing of it). */ +export function advisoryToCveDetail(advisory: CveAdvisory): CveDetail { + const nvd = nvdUrl(advisory.id); + return { + id: advisory.id, + title: advisory.title, + description: advisory.details || advisory.summary, + severity: advisory.severity, + cvssScore: advisory.cvssScore, + epssScore: advisory.epssScore, + epssPercentile: advisory.epssPercentile, + primaryUrl: osvUrl(advisory), + cveUrl: nvd ?? osvUrl(advisory), + cweIds: advisory.cwe, + references: advisory.references, + publishedDate: advisory.publishedAt, + lastModifiedDate: advisory.modifiedAt, + }; +} diff --git a/src/lib/cves/technologies.data.ts b/src/lib/cves/technologies.data.ts new file mode 100644 index 0000000..1b2fed7 --- /dev/null +++ b/src/lib/cves/technologies.data.ts @@ -0,0 +1,373 @@ +/** + * Catalog of technologies an organization can follow in the CVE feed. Each one says how it is + * looked up in every source: OSV by `{ ecosystem, package }` (ecosystem names are the exact OSV + * ones) and NVD by CPE prefix. Type-only imports: the alert builder UI shares this file. + */ + +export const OSV_ECOSYSTEMS = [ + 'npm', + 'PyPI', + 'Go', + 'Maven', + 'crates.io', + 'RubyGems', + 'NuGet', + 'Packagist', +] as const; + +export type OsvEcosystem = (typeof OSV_ECOSYSTEMS)[number]; + +export type TechnologyCategory = + | 'runtime' + | 'framework' + | 'library' + | 'database' + | 'server' + | 'infrastructure' + | 'security' + | 'os'; + +export type OsvPackageRef = { ecosystem: OsvEcosystem; package: string }; + +export type CveTechnology = { + id: string; + name: string; + /** lucide icon name */ + icon: string; + category: TechnologyCategory; + osv: OsvPackageRef[]; + /** CPE 2.3 prefixes (`cpe:2.3:a:vendor:product`), used by NVD (phase 4) */ + cpe: string[]; +}; + +export const CVE_TECHNOLOGIES: readonly CveTechnology[] = [ + // npm + { + id: 'nodejs', + name: 'Node.js', + icon: 'hexagon', + category: 'runtime', + osv: [], + cpe: ['cpe:2.3:a:nodejs:node.js'], + }, + { + id: 'express', + name: 'Express', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'npm', package: 'express' }], + cpe: [], + }, + { + id: 'next', + name: 'Next.js', + icon: 'triangle', + category: 'framework', + osv: [{ ecosystem: 'npm', package: 'next' }], + cpe: [], + }, + { + id: 'react', + name: 'React', + icon: 'atom', + category: 'library', + osv: [ + { ecosystem: 'npm', package: 'react' }, + { ecosystem: 'npm', package: 'react-dom' }, + ], + cpe: [], + }, + { + id: 'svelte', + name: 'Svelte', + icon: 'flame', + category: 'framework', + osv: [{ ecosystem: 'npm', package: 'svelte' }], + cpe: [], + }, + { + id: 'sveltekit', + name: 'SvelteKit', + icon: 'flame', + category: 'framework', + osv: [{ ecosystem: 'npm', package: '@sveltejs/kit' }], + cpe: [], + }, + { + id: 'vite', + name: 'Vite', + icon: 'zap', + category: 'library', + osv: [{ ecosystem: 'npm', package: 'vite' }], + cpe: [], + }, + { + id: 'lodash', + name: 'Lodash', + icon: 'package', + category: 'library', + osv: [ + { ecosystem: 'npm', package: 'lodash' }, + { ecosystem: 'npm', package: 'lodash-es' }, + ], + cpe: [], + }, + { + id: 'axios', + name: 'Axios', + icon: 'package', + category: 'library', + osv: [{ ecosystem: 'npm', package: 'axios' }], + cpe: [], + }, + { + id: 'nestjs', + name: 'NestJS', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'npm', package: '@nestjs/core' }], + cpe: [], + }, + // PyPI + { + id: 'django', + name: 'Django', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'PyPI', package: 'django' }], + cpe: [], + }, + { + id: 'flask', + name: 'Flask', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'PyPI', package: 'flask' }], + cpe: [], + }, + { + id: 'fastapi', + name: 'FastAPI', + icon: 'zap', + category: 'framework', + osv: [{ ecosystem: 'PyPI', package: 'fastapi' }], + cpe: [], + }, + { + id: 'requests', + name: 'Requests (Python)', + icon: 'package', + category: 'library', + osv: [{ ecosystem: 'PyPI', package: 'requests' }], + cpe: [], + }, + { + id: 'pillow', + name: 'Pillow', + icon: 'package', + category: 'library', + osv: [{ ecosystem: 'PyPI', package: 'pillow' }], + cpe: [], + }, + // Maven + { + id: 'spring-boot', + name: 'Spring Boot', + icon: 'leaf', + category: 'framework', + osv: [{ ecosystem: 'Maven', package: 'org.springframework.boot:spring-boot' }], + cpe: [], + }, + { + id: 'spring-framework', + name: 'Spring Framework', + icon: 'leaf', + category: 'framework', + osv: [{ ecosystem: 'Maven', package: 'org.springframework:spring-core' }], + cpe: [], + }, + { + id: 'log4j', + name: 'Apache Log4j', + icon: 'scroll-text', + category: 'library', + osv: [{ ecosystem: 'Maven', package: 'org.apache.logging.log4j:log4j-core' }], + cpe: [], + }, + { + id: 'jackson', + name: 'Jackson', + icon: 'braces', + category: 'library', + osv: [{ ecosystem: 'Maven', package: 'com.fasterxml.jackson.core:jackson-databind' }], + cpe: [], + }, + // Go + { + id: 'gin', + name: 'Gin', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'Go', package: 'github.com/gin-gonic/gin' }], + cpe: [], + }, + { + id: 'golang-x-net', + name: 'golang.org/x/net', + icon: 'network', + category: 'library', + osv: [{ ecosystem: 'Go', package: 'golang.org/x/net' }], + cpe: [], + }, + { + id: 'golang-x-crypto', + name: 'golang.org/x/crypto', + icon: 'lock', + category: 'library', + osv: [{ ecosystem: 'Go', package: 'golang.org/x/crypto' }], + cpe: [], + }, + // Rust, Ruby, .NET, PHP + { + id: 'tokio', + name: 'Tokio', + icon: 'cog', + category: 'library', + osv: [{ ecosystem: 'crates.io', package: 'tokio' }], + cpe: [], + }, + { + id: 'rails', + name: 'Ruby on Rails', + icon: 'train-front', + category: 'framework', + osv: [ + { ecosystem: 'RubyGems', package: 'rails' }, + { ecosystem: 'RubyGems', package: 'actionpack' }, + ], + cpe: [], + }, + { + id: 'aspnet-core', + name: 'ASP.NET Core', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'NuGet', package: 'Microsoft.AspNetCore.App.Runtime.linux-x64' }], + cpe: [], + }, + { + id: 'laravel', + name: 'Laravel', + icon: 'server', + category: 'framework', + osv: [{ ecosystem: 'Packagist', package: 'laravel/framework' }], + cpe: [], + }, + // Software without a package: CPE + { + id: 'postgresql', + name: 'PostgreSQL', + icon: 'database', + category: 'database', + osv: [], + cpe: ['cpe:2.3:a:postgresql:postgresql'], + }, + { + id: 'mysql', + name: 'MySQL', + icon: 'database', + category: 'database', + osv: [], + cpe: ['cpe:2.3:a:oracle:mysql'], + }, + { + id: 'mongodb', + name: 'MongoDB', + icon: 'database', + category: 'database', + osv: [], + cpe: ['cpe:2.3:a:mongodb:mongodb'], + }, + { + id: 'redis', + name: 'Redis', + icon: 'database-zap', + category: 'database', + osv: [], + cpe: ['cpe:2.3:a:redis:redis'], + }, + { + id: 'nginx', + name: 'nginx', + icon: 'server-cog', + category: 'server', + osv: [], + cpe: ['cpe:2.3:a:f5:nginx', 'cpe:2.3:a:nginx:nginx'], + }, + { + id: 'apache-httpd', + name: 'Apache HTTP Server', + icon: 'server-cog', + category: 'server', + osv: [], + cpe: ['cpe:2.3:a:apache:http_server'], + }, + { + id: 'kubernetes', + name: 'Kubernetes', + icon: 'boxes', + category: 'infrastructure', + osv: [{ ecosystem: 'Go', package: 'k8s.io/kubernetes' }], + cpe: ['cpe:2.3:a:kubernetes:kubernetes'], + }, + { + id: 'docker', + name: 'Docker Engine', + icon: 'container', + category: 'infrastructure', + osv: [{ ecosystem: 'Go', package: 'github.com/docker/docker' }], + cpe: ['cpe:2.3:a:docker:docker'], + }, + { + id: 'terraform', + name: 'Terraform', + icon: 'layers', + category: 'infrastructure', + osv: [{ ecosystem: 'Go', package: 'github.com/hashicorp/terraform' }], + cpe: ['cpe:2.3:a:hashicorp:terraform'], + }, + { + id: 'openssl', + name: 'OpenSSL', + icon: 'lock', + category: 'security', + osv: [], + cpe: ['cpe:2.3:a:openssl:openssl'], + }, + { + id: 'openssh', + name: 'OpenSSH', + icon: 'terminal', + category: 'security', + osv: [], + cpe: ['cpe:2.3:a:openbsd:openssh'], + }, + { + id: 'linux-kernel', + name: 'Linux kernel', + icon: 'cpu', + category: 'os', + osv: [], + cpe: ['cpe:2.3:o:linux:linux_kernel'], + }, +]; + +const BY_ID = new Map(CVE_TECHNOLOGIES.map((technology) => [technology.id, technology])); + +export function getTechnology(id: string): CveTechnology | undefined { + return BY_ID.get(id); +} + +export function isKnownTechnology(id: string): boolean { + return BY_ID.has(id); +} diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 6c5990c..52b7051 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -1,6 +1,7 @@ import { bool, defineRelations, + double, entity, integer, json, @@ -475,7 +476,7 @@ export const SlackWorkspaceEntity = entity('slack_workspaces', { /** Language of the command replies (`es` | `en`). */ locale: text(), installedByUserId: uuid().notNull(), - createdAt: timestamp() + createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), updatedAt: timestamp() @@ -525,6 +526,107 @@ export const StateBindingEntity = entity('state_bindings', { .$defaultFn(() => new Date().toISOString()), }); +// CVE feed (`cve_*`). `cve_watchlists` is organization configuration and always lives in the main +// repository; the three feed tables go to CVE_FEED_GITDB_REPOSITORY_URL when it is set. Never the +// whole feed: only advisories that match a watched technology, pass the filter and are within the +// retention window (docs/adr/0004-cve-feed.md). + +export const CveWatchlistEntity = entity('cve_watchlists', { + id: uuid().primaryKey(), + organizationId: uuid().notNull().unique(), + // { technologyId, custom?, label?, minSeverity?, versions?, addedAt }[] + technologies: json() + .notNull() + .$defaultFn(() => []), + minSeverity: text().notNull().default('high'), + includeKev: bool().notNull().default(true), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + updatedBy: uuid(), +}); + +// global, trimmed advisories (summary and details are cut, no raw payloads) +export const CveAdvisoryEntity = entity('cve_advisories', { + id: text().primaryKey(), + aliases: json() + .notNull() + .$defaultFn(() => []), + title: text().notNull(), + summary: text().notNull().default(''), + details: text().notNull().default(''), + severity: text().notNull().default('unknown'), + cvssScore: double(), + cvssVector: text(), + cwe: json() + .notNull() + .$defaultFn(() => []), + technologyIds: json() + .notNull() + .$defaultFn(() => []), + affected: json() + .notNull() + .$defaultFn(() => []), + fixedVersions: json() + .notNull() + .$defaultFn(() => []), + references: json() + .notNull() + .$defaultFn(() => []), + sources: json() + .notNull() + .$defaultFn(() => []), + publishedAt: timestamp(), + modifiedAt: timestamp().notNull(), + kev: bool().notNull().default(false), + kevAddedAt: text(), + epssScore: double(), + epssPercentile: double(), + epssUpdatedAt: timestamp(), + // hash of the normalized content: an unchanged advisory is never rewritten + fingerprint: text().notNull(), + firstSeenAt: timestamp().notNull(), + updatedAt: timestamp().notNull(), +}); + +// one row per source (`osv`, `nvd`, `kev`, `epss`) plus the `lock` (lease) and `run` rows +export const CveFeedStateEntity = entity('cve_feed_state', { + id: text().primaryKey(), + // source-specific JSON (OSV: ids rejected by the filter; NVD: last end date per CPE) + cursor: json(), + etag: text(), + lastModifiedHeader: text(), + lastRunAt: timestamp(), + lastSuccessAt: timestamp(), + lastError: text(), + lastErrorAt: timestamp(), + itemsLastRun: integer(), + // `lock` row + holder: text(), + acquiredAt: timestamp(), + expiresAt: timestamp(), + // `run` row + requestedAt: timestamp(), + handledRequestedAt: timestamp(), + lastDurationMs: integer(), + // technologyId -> ISO date of its silent backfill + backfilledTechnologies: json(), +}); + +// dedup of the events: written (and awaited) BEFORE the event is published +export const CveOrgMatchEntity = entity('cve_org_matches', { + id: text().primaryKey(), + organizationId: uuid().notNull(), + cveId: text().notNull(), + technologyId: text().notNull(), + firstSeenAt: timestamp().notNull(), + // { published?, escalated?: { severity, kev, epssOver }, fix_available?, affects_project?: string[] } + notified: json() + .notNull() + .$defaultFn(() => ({})), + silent: bool().notNull().default(false), +}); + relations.for(ProjectEntity, ({ one, many }) => ({ roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }), organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), diff --git a/src/lib/events/catalog/cve-feed.events.ts b/src/lib/events/catalog/cve-feed.events.ts new file mode 100644 index 0000000..f409a4d --- /dev/null +++ b/src/lib/events/catalog/cve-feed.events.ts @@ -0,0 +1,110 @@ +import { CVE_TECHNOLOGIES, OSV_ECOSYSTEMS } from '../../cves/technologies.data'; +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions, EventLinkContext } from './types'; +import { organizationPath } from './links'; + +export const CVE_FEED_SEVERITIES = ['critical', 'high', 'medium', 'low', 'unknown'] as const; + +const READ_FEED = 'organization:cves:feed:read'; + +const PUBLISHED = 'cve_feed.advisory.published'; +const ESCALATED = 'cve_feed.advisory.escalated'; +const FIX_AVAILABLE = 'cve_feed.advisory.fix_available'; +const AFFECTS_PROJECT = 'cve_feed.advisory.affects_project'; + +type CveFeedEvent = + typeof PUBLISHED | typeof ESCALATED | typeof FIX_AVAILABLE | typeof AFFECTS_PROJECT; + +function fields(type: K) { + return [ + { + key: 'technologyId', + label: fieldLabel(type, 'technologyId'), + type: 'enum', + options: enumOptions( + 'cveTechnology', + CVE_TECHNOLOGIES.map((technology) => technology.id), + ), + operators: OPERATORS.enum, + }, + { + key: 'severity', + label: fieldLabel(type, 'severity'), + type: 'enum', + options: enumOptions('cveSeverity', CVE_FEED_SEVERITIES), + operators: OPERATORS.enum, + }, + { + key: 'cvssScore', + label: fieldLabel(type, 'cvssScore'), + type: 'number', + operators: OPERATORS.number, + }, + { + key: 'epssScore', + label: fieldLabel(type, 'epssScore'), + type: 'number', + operators: OPERATORS.number, + }, + { key: 'kev', label: fieldLabel(type, 'kev'), type: 'boolean', operators: OPERATORS.boolean }, + { + key: 'ecosystem', + label: fieldLabel(type, 'ecosystem'), + type: 'enum', + options: enumOptions('cveEcosystem', OSV_ECOSYSTEMS), + operators: OPERATORS.enum, + }, + ] as const; +} + +const link = (context: EventLinkContext<{ cveId: string }>) => + organizationPath(context, `/cves/${encodeURIComponent(context.payload.cveId)}?tab=technology`); + +const summary = (payload: { cveId: string; severity: string; kev: boolean }) => ({ + key: 'alerts.email.summary.cveAdvisory', + values: { cveId: payload.cveId, severity: payload.severity, kev: payload.kev ? 'KEV' : '' }, +}); + +// CVEs are followed per organization (its watchlist); only `affects_project` also names a project +export const cveFeedEvents: EventDefinitions = { + [PUBLISHED]: { + link, + mailSummary: summary, + ...eventText(PUBLISHED), + module: 'cve_feed', + scope: 'organization', + readPermission: READ_FEED, + alertable: true, + fields: fields(PUBLISHED), + }, + [ESCALATED]: { + link, + mailSummary: summary, + ...eventText(ESCALATED), + module: 'cve_feed', + scope: 'organization', + readPermission: READ_FEED, + alertable: true, + fields: fields(ESCALATED), + }, + [FIX_AVAILABLE]: { + link, + mailSummary: summary, + ...eventText(FIX_AVAILABLE), + module: 'cve_feed', + scope: 'organization', + readPermission: READ_FEED, + alertable: true, + fields: fields(FIX_AVAILABLE), + }, + [AFFECTS_PROJECT]: { + link, + mailSummary: summary, + ...eventText(AFFECTS_PROJECT), + module: 'cve_feed', + scope: 'organization', + readPermission: READ_FEED, + alertable: true, + fields: fields(AFFECTS_PROJECT), + }, +}; diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts index 5d10c7c..e3e0798 100644 --- a/src/lib/events/catalog/index.ts +++ b/src/lib/events/catalog/index.ts @@ -7,6 +7,7 @@ import { accessEvents } from './access.events'; import { monitoringEvents } from './monitoring.events'; import { notificationEvents } from './notifications.events'; import { stateIacEvents } from './state-iac.events'; +import { cveFeedEvents } from './cve-feed.events'; import type { EventCatalog, EventDefinition, @@ -25,6 +26,7 @@ export { ACCESS_SCOPES } from './access.events'; export { MONITORING_CAUSES } from './monitoring.events'; export { CHANNEL_TYPE_OPTIONS } from './notifications.events'; export { STATE_IAC_BACKEND_CHANGED_FIELDS, STATE_IAC_PROVIDERS } from './state-iac.events'; +export { CVE_FEED_SEVERITIES } from './cve-feed.events'; export { PROJECT_SCOPE_FIELD, isScopeField, @@ -59,6 +61,7 @@ export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ ...monitoringEvents, ...notificationEvents, ...stateIacEvents, + ...cveFeedEvents, }); export function isEventType(value: string): value is EventType { diff --git a/src/lib/events/catalog/types.ts b/src/lib/events/catalog/types.ts index 41f96e1..badd027 100644 --- a/src/lib/events/catalog/types.ts +++ b/src/lib/events/catalog/types.ts @@ -40,7 +40,8 @@ export type EventModule = | 'access' | 'monitoring' | 'notifications' - | 'state_iac'; + | 'state_iac' + | 'cve_feed'; export type EventDefinitionScope = 'organization' | 'project'; diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts index 686e587..728b20a 100644 --- a/src/lib/events/domain-events.ts +++ b/src/lib/events/domain-events.ts @@ -247,6 +247,35 @@ export type StateIacBindingUpdatedPayload = { stacks: string[]; }; +export type CveFeedSeverity = 'critical' | 'high' | 'medium' | 'low' | 'unknown'; + +/** + * A CVE of the public feeds (OSV, CISA KEV…) for a technology the organization follows. `url` is + * the absolute link to the advisory in the app (a path when `ORIGIN` is not set). + */ +export type CveFeedAdvisoryPayload = { + cveId: string; + aliases: string[]; + title: string; + severity: CveFeedSeverity; + cvssScore: number | null; + epssScore: number | null; + kev: boolean; + technologyId: string; + /** `null` for software looked up by CPE */ + ecosystem: string | null; + package: string | null; + fixedVersions: string[]; + sources: string[]; + url: string; +}; + +/** The advisory of a followed technology also shows up in a scan of one of the projects. */ +export type CveFeedAffectsProjectPayload = CveFeedAdvisoryPayload & { + projectId: string; + serviceIds: string[]; +}; + export interface DomainEventMap { 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; @@ -279,6 +308,10 @@ export interface DomainEventMap { 'state_iac.backend.updated': StateIacBackendUpdatedPayload; 'state_iac.backend.deleted': StateIacBackendPayload; 'state_iac.binding.updated': StateIacBindingUpdatedPayload; + 'cve_feed.advisory.published': CveFeedAdvisoryPayload; + 'cve_feed.advisory.escalated': CveFeedAdvisoryPayload; + 'cve_feed.advisory.fix_available': CveFeedAdvisoryPayload; + 'cve_feed.advisory.affects_project': CveFeedAffectsProjectPayload; } export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index c50ccc4..ee10ed9 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -456,7 +456,141 @@ "cves": { "title": "Organization CVEs", "infoMessage": "This list aggregates CVEs from all organization projects using the latest completed analysis for each service.", - "emptyMessage": "No CVEs have been detected in this organization yet." + "emptyMessage": "No CVEs have been detected in this organization yet.", + "tabsLabel": "CVE sections", + "tabMine": "My CVEs", + "tabTechnology": "CVEs by technology", + "feed": { + "infoMessage": "CVEs published for the technologies you follow, even if they do not show up in any of your scans yet.", + "intro": "Pick the technologies in your stack and we show their new CVEs (OSV and CISA KEV) without waiting for a scan to detect them.", + "followed": "Technologies you follow", + "manage": "Manage technologies", + "sync": "Sync now", + "syncRequested": "Sync requested", + "syncRequestedHelp": "The server will update the feed shortly.", + "watchlistSaved": "Technologies saved", + "tableTitle": "Feed CVEs", + "noResults": "No CVE matches the filters.", + "noAdvisories": "There are no CVEs for your technologies yet. If you just added them, the first sync may take a few minutes.", + "disabled": { + "title": "The CVE feed is disabled", + "description": "The server does not query external sources. To turn it on, an administrator must set the environment variable" + }, + "empty": { + "title": "You are not following any technology yet", + "description": "Pick the technologies you use (Node.js, PostgreSQL, Spring…) and we will start showing their CVEs.", + "readOnly": "Ask someone with edit permission to pick the technologies to follow.", + "action": "Pick technologies" + }, + "errors": { + "generic": "The action could not be completed.", + "forbidden": "You do not have permission to do that.", + "disabled": "The CVE feed is disabled on this server.", + "too_many": "You have exceeded the maximum number of technologies that can be followed.", + "unknown_technology": "A technology is not in the catalog.", + "invalid_custom": "The custom technology is not valid (check the ecosystem, package or CPE).", + "invalid_severity": "The minimum severity is not valid.", + "invalid_versions": "The versions are not valid." + }, + "filters": { + "label": "Feed filters", + "technology": "Technology", + "allTechnologies": "All", + "severity": "Severity", + "anySeverity": "Any", + "atLeast": "{severity} or higher", + "from": "Modified from", + "to": "Modified until", + "kev": "Actively exploited only (KEV)", + "affectsMe": "Only those that affect me", + "apply": "Filter", + "clear": "Clear filters" + }, + "columns": { + "cve": "CVE", + "technology": "Technology / package", + "severity": "Severity / CVSS", + "epss": "EPSS", + "flags": "Status", + "published": "Published", + "updated": "Updated", + "fixed": "Fixed version" + }, + "badges": { + "kev": "KEV", + "affectsMe": "Affects you" + }, + "pagination": { + "label": "Pagination", + "summary": "{from}-{to} of {total}", + "previous": "Previous", + "next": "Next" + }, + "status": { + "title": "Feed status", + "lastRun": "Last sync: {date}", + "lastSuccess": "Last successful: {date}", + "never": "never", + "noErrors": "No errors", + "sources": { + "osv": "OSV", + "kev": "CISA KEV", + "nvd": "NVD", + "epss": "EPSS" + } + }, + "categories": { + "runtime": "Runtime", + "framework": "Framework", + "library": "Library", + "database": "Database", + "server": "Server", + "infrastructure": "Infrastructure", + "security": "Security", + "os": "Operating system" + }, + "modal": { + "title": "Manage technologies", + "description": "Choose which technologies the organization follows and from which severity you want to see their CVEs.", + "catalog": "Catalog", + "search": "Search the catalog", + "searchPlaceholder": "Search technology…", + "noMatches": "No technology matches the search.", + "suggestions": "Suggestions", + "suggestionsHelp": "Technologies that appear in your scans and you do not follow yet.", + "suggestionReasonOne": "You use `{package}` in 1 service", + "suggestionReasonMany": "You use `{package}` in {count} services", + "custom": "Custom technology", + "customHelp": "If it is not in the catalog, add an OSV package (ecosystem and name) or a CPE.", + "customKind": "Type", + "kindOsv": "OSV package", + "kindCpe": "CPE", + "ecosystem": "Ecosystem", + "package": "Package", + "packageHelp": "Exact package name in its ecosystem.", + "cpe": "CPE 2.3", + "cpeHelp": "Prefix formatted as cpe:2.3:::.", + "minSeverity": "Minimum severity", + "minSeverityHelp": "You will not see CVEs below this severity.", + "includeKev": "CISA KEV", + "includeKevHelp": "Actively exploited CVEs are always shown, even below the minimum severity.", + "includeKevLabel": "Include KEVs of my technologies", + "floorNotice": "The server sets a global minimum of {severity}: the organization can only raise it.", + "save": "Save" + }, + "detail": { + "title": "Feed data", + "description": "From OSV, NVD and CISA KEV; independent of your scans.", + "technologies": "Technologies you follow", + "affected": "Affected packages and ranges", + "noRanges": "The sources do not list version ranges.", + "occurrences": "Services affected in your scans", + "noFix": "no fixed version", + "fixedVersions": "Fixed versions", + "sources": "Sources", + "aliases": "Other identifiers" + } + } }, "dashboard": { "title": "Dashboard", @@ -628,7 +762,8 @@ "access": "Access", "monitoring": "Monitoring", "notifications": "Notifications", - "state_iac": "State IaC" + "state_iac": "State IaC", + "cve_feed": "CVE feed" } }, "current": "Current", @@ -1452,6 +1587,63 @@ "auth": "Authentication", "credentials": "Credentials", "enabled": "Enabled" + }, + "cveTechnology": { + "nodejs": "Node.js", + "express": "Express", + "next": "Next.js", + "react": "React", + "svelte": "Svelte", + "sveltekit": "SvelteKit", + "vite": "Vite", + "lodash": "Lodash", + "axios": "Axios", + "nestjs": "NestJS", + "django": "Django", + "flask": "Flask", + "fastapi": "FastAPI", + "requests": "Requests (Python)", + "pillow": "Pillow", + "spring-boot": "Spring Boot", + "spring-framework": "Spring Framework", + "log4j": "Apache Log4j", + "jackson": "Jackson", + "gin": "Gin", + "golang-x-net": "golang.org/x/net", + "golang-x-crypto": "golang.org/x/crypto", + "tokio": "Tokio", + "rails": "Ruby on Rails", + "aspnet-core": "ASP.NET Core", + "laravel": "Laravel", + "postgresql": "PostgreSQL", + "mysql": "MySQL", + "mongodb": "MongoDB", + "redis": "Redis", + "nginx": "nginx", + "apache-httpd": "Apache HTTP Server", + "kubernetes": "Kubernetes", + "docker": "Docker Engine", + "terraform": "Terraform", + "openssl": "OpenSSL", + "openssh": "OpenSSH", + "linux-kernel": "Linux kernel" + }, + "cveSeverity": { + "critical": "Critical", + "high": "High", + "medium": "Medium", + "low": "Low", + "unknown": "Unknown" + }, + "cveEcosystem": { + "npm": "npm", + "PyPI": "PyPI", + "Go": "Go", + "Maven": "Maven", + "crates.io": "crates.io", + "RubyGems": "RubyGems", + "NuGet": "NuGet", + "Packagist": "Packagist" } }, "vault": { @@ -1727,6 +1919,58 @@ } } } + }, + "cve_feed": { + "advisory": { + "published": { + "label": "New CVE for a followed technology", + "description": "A CVE appeared for a technology the organization follows.", + "fields": { + "technologyId": "Technology", + "severity": "Severity", + "cvssScore": "CVSS score", + "epssScore": "EPSS score", + "kev": "Actively exploited (CISA KEV)", + "ecosystem": "Ecosystem" + } + }, + "escalated": { + "label": "CVE escalated", + "description": "A followed CVE got more severe, entered CISA KEV or its EPSS crossed the threshold.", + "fields": { + "technologyId": "Technology", + "severity": "Severity", + "cvssScore": "CVSS score", + "epssScore": "EPSS score", + "kev": "Actively exploited (CISA KEV)", + "ecosystem": "Ecosystem" + } + }, + "fix_available": { + "label": "Fix available for a CVE", + "description": "A fixed version was published for a followed CVE.", + "fields": { + "technologyId": "Technology", + "severity": "Severity", + "cvssScore": "CVSS score", + "epssScore": "EPSS score", + "kev": "Actively exploited (CISA KEV)", + "ecosystem": "Ecosystem" + } + }, + "affects_project": { + "label": "Followed CVE affects a project", + "description": "A CVE of a followed technology also appears in a scan of a project.", + "fields": { + "technologyId": "Technology", + "severity": "Severity", + "cvssScore": "CVSS score", + "epssScore": "EPSS score", + "kev": "Actively exploited (CISA KEV)", + "ecosystem": "Ecosystem" + } + } + } } }, "alerts": { @@ -1786,7 +2030,8 @@ "monitorDown": "{name} is down ({cause})", "monitorDegraded": "{name} is degraded", "monitorRecovered": "{name} recovered after {minutes} min", - "channelDisabled": "{name} disabled after {failures} failures" + "channelDisabled": "{name} disabled after {failures} failures", + "cveAdvisory": "{cveId} ({severity}) {kev}" }, "externalFooter": "You receive this email because {organization} added your address to the alert “{alert}”.", "unsubscribe": "Unsubscribe", diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 92c84b7..716ef83 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -456,7 +456,141 @@ "cves": { "title": "CVEs de la organización", "infoMessage": "Este listado agrupa los CVEs de todos los proyectos de la organización usando el último análisis completado de cada servicio.", - "emptyMessage": "Todavía no se han detectado CVEs en esta organización." + "emptyMessage": "Todavía no se han detectado CVEs en esta organización.", + "tabsLabel": "Secciones de CVEs", + "tabMine": "Mis CVEs", + "tabTechnology": "CVEs por tecnología", + "feed": { + "infoMessage": "CVEs publicados para las tecnologías que sigues, aunque todavía no aparezcan en ninguno de tus análisis.", + "intro": "Elige las tecnologías de tu stack y te mostramos sus CVEs nuevos (OSV y CISA KEV), sin esperar a que un análisis los detecte.", + "followed": "Tecnologías que sigues", + "manage": "Gestionar tecnologías", + "sync": "Sincronizar ahora", + "syncRequested": "Sincronización solicitada", + "syncRequestedHelp": "El servidor actualizará el feed en breve.", + "watchlistSaved": "Tecnologías guardadas", + "tableTitle": "CVEs del feed", + "noResults": "Ningún CVE coincide con los filtros.", + "noAdvisories": "Todavía no hay CVEs para tus tecnologías. Si acabas de añadirlas, la primera sincronización puede tardar unos minutos.", + "disabled": { + "title": "El feed de CVEs está desactivado", + "description": "El servidor no consulta fuentes externas. Para activarlo, un administrador debe definir la variable de entorno" + }, + "empty": { + "title": "Aún no sigues ninguna tecnología", + "description": "Elige las tecnologías que usáis (Node.js, PostgreSQL, Spring…) y empezaremos a mostrarte sus CVEs.", + "readOnly": "Pide a alguien con permiso de edición que elija las tecnologías que se van a seguir.", + "action": "Elegir tecnologías" + }, + "errors": { + "generic": "No se ha podido completar la acción.", + "forbidden": "No tienes permiso para hacerlo.", + "disabled": "El feed de CVEs está desactivado en este servidor.", + "too_many": "Has superado el máximo de tecnologías que se pueden seguir.", + "unknown_technology": "Hay una tecnología que no existe en el catálogo.", + "invalid_custom": "La tecnología personalizada no es válida (revisa el ecosistema, el paquete o el CPE).", + "invalid_severity": "La severidad mínima no es válida.", + "invalid_versions": "Las versiones no son válidas." + }, + "filters": { + "label": "Filtros del feed", + "technology": "Tecnología", + "allTechnologies": "Todas", + "severity": "Severidad", + "anySeverity": "Cualquiera", + "atLeast": "{severity} o superior", + "from": "Modificado desde", + "to": "Modificado hasta", + "kev": "Solo explotados activamente (KEV)", + "affectsMe": "Solo los que me afectan", + "apply": "Filtrar", + "clear": "Quitar filtros" + }, + "columns": { + "cve": "CVE", + "technology": "Tecnología / paquete", + "severity": "Severidad / CVSS", + "epss": "EPSS", + "flags": "Estado", + "published": "Publicado", + "updated": "Actualizado", + "fixed": "Versión con fix" + }, + "badges": { + "kev": "KEV", + "affectsMe": "Te afecta" + }, + "pagination": { + "label": "Paginación", + "summary": "{from}-{to} de {total}", + "previous": "Anterior", + "next": "Siguiente" + }, + "status": { + "title": "Estado del feed", + "lastRun": "Última sincronización: {date}", + "lastSuccess": "Última correcta: {date}", + "never": "nunca", + "noErrors": "Sin errores", + "sources": { + "osv": "OSV", + "kev": "CISA KEV", + "nvd": "NVD", + "epss": "EPSS" + } + }, + "categories": { + "runtime": "Runtime", + "framework": "Framework", + "library": "Librería", + "database": "Base de datos", + "server": "Servidor", + "infrastructure": "Infraestructura", + "security": "Seguridad", + "os": "Sistema operativo" + }, + "modal": { + "title": "Gestionar tecnologías", + "description": "Elige qué tecnologías sigue la organización y desde qué severidad quieres ver sus CVEs.", + "catalog": "Catálogo", + "search": "Buscar en el catálogo", + "searchPlaceholder": "Buscar tecnología…", + "noMatches": "Ninguna tecnología coincide con la búsqueda.", + "suggestions": "Sugerencias", + "suggestionsHelp": "Tecnologías que aparecen en tus análisis y todavía no sigues.", + "suggestionReasonOne": "Usáis `{package}` en 1 servicio", + "suggestionReasonMany": "Usáis `{package}` en {count} servicios", + "custom": "Tecnología personalizada", + "customHelp": "Si no está en el catálogo, añade un paquete de OSV (ecosistema y nombre) o un CPE.", + "customKind": "Tipo", + "kindOsv": "Paquete OSV", + "kindCpe": "CPE", + "ecosystem": "Ecosistema", + "package": "Paquete", + "packageHelp": "Nombre exacto del paquete en su ecosistema.", + "cpe": "CPE 2.3", + "cpeHelp": "Prefijo con formato cpe:2.3:::.", + "minSeverity": "Severidad mínima", + "minSeverityHelp": "No verás CVEs por debajo de esta severidad.", + "includeKev": "CISA KEV", + "includeKevHelp": "Los CVEs explotados activamente se muestran siempre, aunque estén por debajo de la severidad mínima.", + "includeKevLabel": "Incluir los KEV de mis tecnologías", + "floorNotice": "El servidor fija un mínimo global de {severity}: la organización solo puede subirlo.", + "save": "Guardar" + }, + "detail": { + "title": "Datos del feed", + "description": "Según OSV, NVD y CISA KEV; no depende de tus análisis.", + "technologies": "Tecnologías que sigues", + "affected": "Paquetes y rangos afectados", + "noRanges": "Las fuentes no indican rangos de versiones.", + "occurrences": "Servicios afectados en tus análisis", + "noFix": "sin versión corregida", + "fixedVersions": "Versiones corregidas", + "sources": "Fuentes", + "aliases": "Otros identificadores" + } + } }, "dashboard": { "title": "Dashboard", @@ -628,7 +762,8 @@ "access": "Accesos", "monitoring": "Monitoring", "notifications": "Notificaciones", - "state_iac": "State IaC" + "state_iac": "State IaC", + "cve_feed": "Feed de CVEs" } }, "current": "Actual", @@ -1452,6 +1587,63 @@ "auth": "Autenticación", "credentials": "Credenciales", "enabled": "Activado" + }, + "cveTechnology": { + "nodejs": "Node.js", + "express": "Express", + "next": "Next.js", + "react": "React", + "svelte": "Svelte", + "sveltekit": "SvelteKit", + "vite": "Vite", + "lodash": "Lodash", + "axios": "Axios", + "nestjs": "NestJS", + "django": "Django", + "flask": "Flask", + "fastapi": "FastAPI", + "requests": "Requests (Python)", + "pillow": "Pillow", + "spring-boot": "Spring Boot", + "spring-framework": "Spring Framework", + "log4j": "Apache Log4j", + "jackson": "Jackson", + "gin": "Gin", + "golang-x-net": "golang.org/x/net", + "golang-x-crypto": "golang.org/x/crypto", + "tokio": "Tokio", + "rails": "Ruby on Rails", + "aspnet-core": "ASP.NET Core", + "laravel": "Laravel", + "postgresql": "PostgreSQL", + "mysql": "MySQL", + "mongodb": "MongoDB", + "redis": "Redis", + "nginx": "nginx", + "apache-httpd": "Apache HTTP Server", + "kubernetes": "Kubernetes", + "docker": "Docker Engine", + "terraform": "Terraform", + "openssl": "OpenSSL", + "openssh": "OpenSSH", + "linux-kernel": "Linux kernel" + }, + "cveSeverity": { + "critical": "Crítica", + "high": "Alta", + "medium": "Media", + "low": "Baja", + "unknown": "Desconocida" + }, + "cveEcosystem": { + "npm": "npm", + "PyPI": "PyPI", + "Go": "Go", + "Maven": "Maven", + "crates.io": "crates.io", + "RubyGems": "RubyGems", + "NuGet": "NuGet", + "Packagist": "Packagist" } }, "vault": { @@ -1727,6 +1919,58 @@ } } } + }, + "cve_feed": { + "advisory": { + "published": { + "label": "Nuevo CVE de una tecnología seguida", + "description": "Ha aparecido un CVE para una tecnología que sigue la organización.", + "fields": { + "technologyId": "Tecnología", + "severity": "Severidad", + "cvssScore": "Puntuación CVSS", + "epssScore": "Puntuación EPSS", + "kev": "Explotado activamente (CISA KEV)", + "ecosystem": "Ecosistema" + } + }, + "escalated": { + "label": "CVE escalado", + "description": "Un CVE seguido ha subido de severidad, ha entrado en CISA KEV o su EPSS supera el umbral.", + "fields": { + "technologyId": "Tecnología", + "severity": "Severidad", + "cvssScore": "Puntuación CVSS", + "epssScore": "Puntuación EPSS", + "kev": "Explotado activamente (CISA KEV)", + "ecosystem": "Ecosistema" + } + }, + "fix_available": { + "label": "Corrección disponible para un CVE", + "description": "Se ha publicado una versión con la corrección de un CVE seguido.", + "fields": { + "technologyId": "Tecnología", + "severity": "Severidad", + "cvssScore": "Puntuación CVSS", + "epssScore": "Puntuación EPSS", + "kev": "Explotado activamente (CISA KEV)", + "ecosystem": "Ecosistema" + } + }, + "affects_project": { + "label": "Un CVE seguido afecta a un proyecto", + "description": "Un CVE de una tecnología seguida aparece también en un análisis de un proyecto.", + "fields": { + "technologyId": "Tecnología", + "severity": "Severidad", + "cvssScore": "Puntuación CVSS", + "epssScore": "Puntuación EPSS", + "kev": "Explotado activamente (CISA KEV)", + "ecosystem": "Ecosistema" + } + } + } } }, "alerts": { @@ -1786,7 +2030,8 @@ "monitorDown": "{name} está caído ({cause})", "monitorDegraded": "{name} responde degradado", "monitorRecovered": "{name} se ha recuperado tras {minutes} min", - "channelDisabled": "{name} deshabilitado tras {failures} fallos" + "channelDisabled": "{name} deshabilitado tras {failures} fallos", + "cveAdvisory": "{cveId} ({severity}) {kev}" }, "externalFooter": "Recibes este email porque {organization} añadió tu dirección a la alerta “{alert}”.", "unsubscribe": "Darme de baja", diff --git a/src/lib/server/cve-feed-access.ts b/src/lib/server/cve-feed-access.ts new file mode 100644 index 0000000..4baf481 --- /dev/null +++ b/src/lib/server/cve-feed-access.ts @@ -0,0 +1,18 @@ +import { cancanService } from '#modules/auth'; + +type SessionUser = Parameters[0]; + +function can(user: SessionUser, organizationId: string, permission: string) { + return cancanService.canSessionUser(user, permission, { scope: 'organization', organizationId }); +} + +/** `organization:cves:feed:read`: sees the "CVEs por tecnología" tab and the feed data. */ +export const canReadCveFeed = (user: SessionUser, organizationId: string) => + can(user, organizationId, 'organization:cves:feed:read'); + +/** `organization:cves:feed:update`: edits the watchlist and runs "Sincronizar ahora". */ +export const canUpdateCveFeed = (user: SessionUser, organizationId: string) => + can(user, organizationId, 'organization:cves:feed:update'); + +export const canReadOrganizationProjects = (user: SessionUser, organizationId: string) => + can(user, organizationId, 'organization:projects:read'); diff --git a/src/modules/alerts/application/alert-engine.cve-feed.test.ts b/src/modules/alerts/application/alert-engine.cve-feed.test.ts new file mode 100644 index 0000000..878a9f8 --- /dev/null +++ b/src/modules/alerts/application/alert-engine.cve-feed.test.ts @@ -0,0 +1,219 @@ +import { describe, expect, it, vi } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { CveFeedRuntime } from '../../cve-feed/application/cve-feed-runtime'; +import { + FakeSource, + InMemoryCveFeedStore, + InMemoryWatchlists, + silentLogger, + testConfig, + watchlist, +} from '../../cve-feed/application/testing'; +import { normalizeOsv } from '../../cve-feed/domain/osv'; +import { LODASH, osvVuln } from '../../cve-feed/domain/fixtures'; +import { CanCanService } from '../../auth/application/cancan.service'; +import { RoleDomain } from '../../auth/domain/role.domain'; +import { UserDomain } from '../../auth/domain/user.domain'; +import { UserAccessDomain } from '../../auth/domain/user-access.domain'; +import { emptyRecipients, type AlertRow } from '../domain/alert.domain'; +import { InMemoryAlertRepository } from '../infrastructure/repositories/in-memory-alert.repository'; +import { AlertEngine, type AlertEmail, type AlertNotifierPort } from './alert-engine'; +import { AlertThrottle } from './alert-throttle'; +import { RecipientResolver } from './recipient-resolver'; +import { FakeAlertDirectory } from './testing'; + +const ORG = 'org-1'; +const TIMESTAMP = '2026-01-01T00:00:00.000Z'; +const T0 = Date.parse('2026-11-01T10:00:00.000Z'); +const HOUR = 3_600_000; + +const feedReader = new RoleDomain({ + id: 'feed-reader', + slug: 'feed-reader', + name: 'feed-reader', + scope: 'organization', + permissions: ['organization:cves:feed:read'], + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, +}); +const noFeed = new RoleDomain({ + id: 'no-feed', + slug: 'no-feed', + name: 'no-feed', + scope: 'organization', + permissions: ['organization:projects:read'], + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, +}); + +function orgAccess(id: string, userId: string, role: RoleDomain) { + return new UserAccessDomain({ + id, + userId, + roleId: role.id, + role, + scope: 'organization', + organizationId: ORG, + projectId: null, + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + }); +} + +/** The alert of the issue: severity critical OR in CISA KEV. */ +const criticalOrKev: AlertRow = { + id: 'cve-alert', + name: 'Críticas o KEV', + description: null, + enabled: true, + scope: 'organization', + organizationId: ORG, + projectId: null, + eventType: 'cve_feed.advisory.published', + match: 'any', + conditions: [ + { field: 'severity', operator: 'eq', value: 'critical' }, + { field: 'kev', operator: 'is_true' }, + ], + recipients: { ...emptyRecipients(), userIds: ['ana', 'bob'], roleIds: [] }, + channels: ['mail'], + channelIds: [], + throttleMinutes: 0, + createdByUserId: 'author', + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, +}; + +class RecordingNotifier implements AlertNotifierPort { + alerts: AlertEmail[] = []; + async sendAlert(email: AlertEmail) { + this.alerts.push(email); + } + async sendSystemNotification() {} +} + +/** + * The alert engine and the CVE feed runtime on one bus: what the feed publishes is what the + * alerts evaluate, so the payload fields (`severity`, `kev`) are the real ones. + */ +function world() { + const repository = new InMemoryAlertRepository(); + repository.rows = [criticalOrKev]; + const directory = new FakeAlertDirectory(); + const member = (userId: string) => ({ + organizationId: ORG, + projectId: null, + userId, + username: userId, + email: `${userId}@example.com`, + disabled: false, + roleIds: [userId === 'ana' ? 'feed-reader' : 'no-feed'], + }); + directory.members = [member('ana'), member('bob')]; + const accessByUser: Record = { + ana: [orgAccess('a1', 'ana', feedReader)], + bob: [orgAccess('a2', 'bob', noFeed)], + }; + const cancan = new CanCanService( + { + findById: async (id: string) => + new UserDomain({ + id, + username: id, + email: null, + password: 'x', + role: null, + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + }), + }, + { findByUserId: async (userId: string) => accessByUser[userId] ?? [] }, + { getProject: async (id: string) => ({ id, organization: { id: ORG } }) }, + ); + const notifier = new RecordingNotifier(); + const clock = { t: T0 }; + const engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, (userId, permission, context) => + cancan.can(userId, permission, context), + ), + notifier, + throttle: new AlertThrottle(() => clock.t), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as never, + now: () => clock.t, + }); + + const bus = new RecordingEventBus(); + engine.attach(bus); + + const store = new InMemoryCveFeedStore(); + const watchlists = new InMemoryWatchlists(); + watchlists.rows = [watchlist(ORG, ['lodash'])]; + const kev = new FakeSource('kev'); + const osv = new FakeSource('osv', ['osv']); + const runtime = new CveFeedRuntime({ + store, + watchlists, + sources: [kev, osv], + config: testConfig, + logger: silentLogger, + events: bus, + now: () => clock.t, + holder: 'runtime-a', + }); + return { bus, notifier, kev, osv, runtime, clock }; +} + +const vuln = (id: string, cve: string, severity: string) => + osvVuln({ + id, + aliases: [cve], + published: '2026-11-01T11:00:00Z', + modified: '2026-11-01T11:00:00Z', + severity: [], + database_specific: { severity }, + }); + +describe('alerts on cve_feed.advisory.published', () => { + it('fires for severity = critical OR kev = true, and for nothing else', async () => { + const w = world(); + // first run: nothing stored yet, so what comes next is news + w.osv.result = { items: 0 }; + await w.runtime.syncOnce(); + w.clock.t += 3 * HOUR; + + const critical = vuln('GHSA-crit-crit-crit', 'CVE-2026-0001', 'CRITICAL'); + const kevOnly = vuln('GHSA-kev0-kev0-kev0', 'CVE-2026-0002', 'MODERATE'); + const high = vuln('GHSA-high-high-high', 'CVE-2026-0003', 'HIGH'); + const medium = vuln('GHSA-medi-medi-medi', 'CVE-2026-0004', 'MODERATE'); + w.kev.result = { kev: new Map([['CVE-2026-0002', '2026-11-01']]), items: 1 }; + w.osv.result = { + candidates: [critical, kevOnly, high, medium].map((item) => ({ + key: item.id, + advisory: normalizeOsv(item, [LODASH])!, + })), + items: 4, + }; + await w.runtime.syncOnce(); + await w.bus.drain(); + + // the feed published for the critical, the KEV one and the high one (medium is filtered out) + expect( + w.bus + .ofType('cve_feed.advisory.published') + .map((event) => event.payload.cveId) + .sort(), + ).toEqual(['CVE-2026-0001', 'CVE-2026-0002', 'CVE-2026-0003']); + + // the alert fires for the critical one and the KEV one, only for the user who can read the feed + const fired = w.notifier.alerts.map((email) => ({ + to: email.recipient.kind === 'member' ? email.recipient.userId : email.recipient.email, + cve: (email.event.payload as { cveId: string }).cveId, + })); + expect(fired.sort((a, b) => a.cve.localeCompare(b.cve))).toEqual([ + { to: 'ana', cve: 'CVE-2026-0001' }, + { to: 'ana', cve: 'CVE-2026-0002' }, + ]); + }); +}); diff --git a/src/modules/audit/application/audit.service.ts b/src/modules/audit/application/audit.service.ts index f0c4fb6..4225dad 100644 --- a/src/modules/audit/application/audit.service.ts +++ b/src/modules/audit/application/audit.service.ts @@ -23,10 +23,14 @@ const DEFAULT_PER_PAGE = 20; /** * Tables written by the system on a timer, not by people: monitoring metrics (`monitoring_*`, * kept in the main repository when MONITORING_GITDB_REPOSITORY_URL is not set). The monitor - * configuration (`monitors`) is audited like any other entity. + * configuration (`monitors`) is audited like any other entity. Same for the CVE feed tables the + * sync writes (`cve_advisories`, `cve_feed_state`, `cve_org_matches`); `cve_watchlists` is + * organization configuration and stays audited. */ +const SYSTEM_FEED_ENTITIES = new Set(['cve_advisories', 'cve_feed_state', 'cve_org_matches']); + export function isSystemMetricsEntity(entity: string | null): boolean { - return entity !== null && entity.startsWith('monitoring_'); + return entity !== null && (entity.startsWith('monitoring_') || SYSTEM_FEED_ENTITIES.has(entity)); } const MAX_PER_PAGE = 100; @@ -41,7 +45,10 @@ export class AuditService { event.action !== 'other' && event.entity !== null && !isSystemMetricsEntity(event.entity), ); - const perPage = Math.min(Math.max(Math.trunc(options.perPage ?? DEFAULT_PER_PAGE), 1), MAX_PER_PAGE); + const perPage = Math.min( + Math.max(Math.trunc(options.perPage ?? DEFAULT_PER_PAGE), 1), + MAX_PER_PAGE, + ); const total = filtered.length; const totalPages = Math.max(Math.ceil(total / perPage), 1); const page = Math.min(Math.max(Math.trunc(options.page ?? 1), 1), totalPages); diff --git a/src/modules/auth/domain/role-permissions.data.ts b/src/modules/auth/domain/role-permissions.data.ts index d5ebb38..807c194 100644 --- a/src/modules/auth/domain/role-permissions.data.ts +++ b/src/modules/auth/domain/role-permissions.data.ts @@ -19,6 +19,7 @@ export const ORGANIZATION_ADMIN_PERMISSIONS = [ 'organization:events:all', 'organization:alerts:all', 'organization:notifications:all', + 'organization:cves:feed:all', 'organization:stateiac:backends:all', 'organization:stateiac:stacks:all', ]; diff --git a/src/modules/code-report/application/code-report-cve.service.ts b/src/modules/code-report/application/code-report-cve.service.ts index f9b21c0..a963ddd 100644 --- a/src/modules/code-report/application/code-report-cve.service.ts +++ b/src/modules/code-report/application/code-report-cve.service.ts @@ -1,3 +1,4 @@ +import { extractInventoryPackages, type InventoryPackage } from '#lib/code-report/package-inventory'; import { collectCveOccurrences, type CompletedAnalysis, type CveOccurrence } from '#lib/code-report/cve-aggregation'; import type { CodeReportService } from './code-report.service'; import type { CodeReportAnalysisService } from './code-report-analysis.service'; @@ -8,6 +9,17 @@ export type OrganizationCveOccurrence = CveOccurrence & { projectName: string; }; +export type ServicePackageInventory = { + serviceId: string; + serviceSlug: string; + serviceName: string; + projectId: string; + packages: InventoryPackage[]; +}; + +// the tools whose latest completed analysis tells which packages a service uses +const INVENTORY_TOOLS = ['trivy', 'sbom', 'syft']; + export class CodeReportCveService { constructor( private readonly codeReportService: CodeReportService, @@ -63,4 +75,38 @@ export class CodeReportCveService { return occurrencesByCve; } + + /** + * The distinct packages of each service of the projects, from the latest completed Trivy, SBOM + * and syft analyses (their union). + */ + async getOrganizationPackages( + projects: { id: string }[], + ): Promise { + const inventory: ServicePackageInventory[] = []; + for (const project of projects) { + const services = await this.codeReportService.listByProject(project.id); + for (const service of services) { + const latest = await this.codeReportAnalysisService.getLatestByTool( + service.id, + INVENTORY_TOOLS, + ); + const packages = new Map(); + for (const tool of INVENTORY_TOOLS) { + const analysis = latest[tool]; + if (analysis?.status !== 'completed') continue; + for (const pkg of extractInventoryPackages(analysis.result)) + packages.set(`${pkg.ecosystem}|${pkg.name}`, pkg); + } + inventory.push({ + serviceId: service.id, + serviceSlug: service.slug, + serviceName: service.name, + projectId: project.id, + packages: [...packages.values()], + }); + } + } + return inventory; + } } diff --git a/src/modules/code-report/index.ts b/src/modules/code-report/index.ts index 03e7fe3..4dc614c 100644 --- a/src/modules/code-report/index.ts +++ b/src/modules/code-report/index.ts @@ -32,4 +32,7 @@ export const codeReportCveService = new CodeReportCveService( codeReportAnalysisService, ); -export type { OrganizationCveOccurrence } from './application/code-report-cve.service'; +export type { + OrganizationCveOccurrence, + ServicePackageInventory, +} from './application/code-report-cve.service'; diff --git a/src/modules/cve-feed/application/cve-feed-query.scans.test.ts b/src/modules/cve-feed/application/cve-feed-query.scans.test.ts new file mode 100644 index 0000000..373b334 --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-query.scans.test.ts @@ -0,0 +1,166 @@ +import { describe, expect, it } from 'vitest'; +import { buildAdvisory } from '../domain/advisory'; +import { normalizeOsv } from '../domain/osv'; +import { LODASH, OSV_LODASH } from '../domain/fixtures'; +import type { CveWatchlist } from '../domain/types'; +import { CveFeedQueryService } from './cve-feed-query.service'; +import type { ProjectRef, ProjectScans, ScanOccurrences, ScanRef } from './ports'; +import { InMemoryCveFeedStore, watchlist } from './testing'; + +const p1: ProjectRef = { id: 'p1', slug: 'alpha', name: 'Alpha' }; +const p2: ProjectRef = { id: 'p2', slug: 'beta', name: 'Beta' }; + +const service = (project: ProjectRef, id: string): ScanRef => ({ + projectId: project.id, + projectSlug: project.slug, + projectName: project.name, + serviceId: id, + serviceSlug: id, + serviceName: id, +}); + +/** Scans by project: `reports[projectId][CVE]`. Counts how often it is asked. */ +class FakeScans implements ProjectScans { + reports: Record> = {}; + calls: string[][] = []; + async occurrences(projects: readonly ProjectRef[]): Promise { + this.calls.push(projects.map((project) => project.id)); + const index: ScanOccurrences = new Map(); + for (const project of projects) { + for (const [cve, refs] of Object.entries(this.reports[project.id] ?? {})) { + index.set(cve.toUpperCase(), [...(index.get(cve.toUpperCase()) ?? []), ...refs]); + } + } + return index; + } +} + +function setup() { + const store = new InMemoryCveFeedStore(); + const advisory = buildAdvisory( + normalizeOsv(OSV_LODASH, [LODASH])!, + {}, + '2026-11-01T00:00:00.000Z', + ); + store.advisories.set(advisory.id, advisory); + const other = buildAdvisory( + normalizeOsv({ ...OSV_LODASH, id: 'GHSA-other-other-oth1', aliases: ['CVE-2026-9'] }, [ + LODASH, + ])!, + {}, + '2026-11-01T00:00:00.000Z', + ); + store.advisories.set(other.id, other); + const watchlists = new Map([['org-1', watchlist('org-1', ['lodash'])]]); + const scans = new FakeScans(); + const query = new CveFeedQueryService({ + store, + watchlists: { findByOrganization: async (id) => watchlists.get(id) ?? null }, + epssThreshold: 0.5, + enabled: true, + status: async () => ({ sources: [], lastRunAt: null }), + scans, + }); + return { query, scans }; +} + +describe('CveFeedQueryService: "Te afecta"', () => { + it('marks an advisory whose id is reported by the scans', async () => { + const { query, scans } = setup(); + scans.reports.p1 = { 'CVE-2021-23337': [service(p1, 's1')] }; + const { items } = await query.list('org-1', {}, { projects: [p1] }); + expect(items.map((item) => [item.advisory.id, item.affectsMe])).toEqual([ + ['CVE-2021-23337', true], + ['CVE-2026-9', false], + ]); + }); + + it('marks it also when the scans report one of its aliases', async () => { + const { query, scans } = setup(); + scans.reports.p1 = { 'GHSA-35JH-R3H4-6JHM': [service(p1, 's1')] }; + const page = await query.list('org-1', { affectsMe: true }, { projects: [p1] }); + expect(page.items.map((item) => item.advisory.id)).toEqual(['CVE-2021-23337']); + expect(page.total).toBe(1); + }); + + it('uses only the projects the user can see', async () => { + const { query, scans } = setup(); + scans.reports.p1 = { 'CVE-2021-23337': [service(p1, 's1')] }; + scans.reports.p2 = { 'CVE-2026-9': [service(p2, 's2')] }; + + const onlyP1 = await query.list('org-1', { affectsMe: true }, { projects: [p1] }); + expect(onlyP1.items.map((item) => item.advisory.id)).toEqual(['CVE-2021-23337']); + const onlyP2 = await query.list('org-1', { affectsMe: true }, { projects: [p2] }); + expect(onlyP2.items.map((item) => item.advisory.id)).toEqual(['CVE-2026-9']); + expect((await query.list('org-1', { affectsMe: true }, { projects: [] })).total).toBe(0); + expect((await query.list('org-1', { affectsMe: true })).total).toBe(0); + expect(scans.calls.flat()).not.toContain('p3'); + }); + + it('memoizes the index per organization and set of projects, until a new analysis arrives', async () => { + const { query, scans } = setup(); + scans.reports.p1 = { 'CVE-2021-23337': [service(p1, 's1')] }; + await query.list('org-1', {}, { projects: [p1] }); + await query.list('org-1', { kev: false }, { projects: [p1] }); + await query.getAdvisory('org-1', 'CVE-2021-23337', { projects: [p1] }); + expect(query.scanComputations).toBe(1); + + // another visible set is another entry, whatever the order of its projects + await query.list('org-1', {}, { projects: [p1, p2] }); + await query.list('org-1', {}, { projects: [p2, p1] }); + expect(query.scanComputations).toBe(2); + + // a new analysis of org-1 drops them; the feed view itself is not recomputed + const views = query.computations; + scans.reports.p1 = { + 'CVE-2021-23337': [service(p1, 's1')], + 'CVE-2026-9': [service(p1, 's1')], + }; + query.invalidateScans('org-1'); + const page = await query.list('org-1', { affectsMe: true }, { projects: [p1] }); + expect(page.total).toBe(2); + expect(query.scanComputations).toBe(3); + expect(query.computations).toBe(views); + }); + + it('does not drop the indexes of another organization', async () => { + const { query } = setup(); + await query.list('org-1', {}, { projects: [p1] }); + await query.list('org-2', {}, { projects: [p1] }); + expect(query.scanComputations).toBe(2); + query.invalidateScans('org-2'); + await query.list('org-1', {}, { projects: [p1] }); + expect(query.scanComputations).toBe(2); + await query.list('org-2', {}, { projects: [p1] }); + expect(query.scanComputations).toBe(3); + query.invalidateScans(); // everything + await query.list('org-1', {}, { projects: [p1] }); + expect(query.scanComputations).toBe(4); + }); + + it('gives the detail the services that report the advisory, by id or alias', async () => { + const { query, scans } = setup(); + scans.reports.p1 = { + 'CVE-2021-23337': [service(p1, 's1')], + 'GHSA-35JH-R3H4-6JHM': [service(p1, 's2'), service(p1, 's1')], + }; + const detail = await query.getAdvisory('org-1', 'ghsa-35jh-r3h4-6jhm', { projects: [p1] }); + expect(detail?.affectsMe).toBe(true); + expect(detail?.occurrences.map((ref) => ref.serviceId).sort()).toEqual(['s1', 's2']); + + const hidden = await query.getAdvisory('org-1', 'CVE-2021-23337', { projects: [p2] }); + expect(hidden).toMatchObject({ affectsMe: false, occurrences: [] }); + }); + + it('never marks anything without a scans source', async () => { + const store = new InMemoryCveFeedStore(); + const query = new CveFeedQueryService({ + store, + watchlists: { findByOrganization: async () => watchlist('org-1', ['lodash']) }, + epssThreshold: 0.5, + enabled: true, + status: async () => ({ sources: [], lastRunAt: null }), + }); + expect((await query.list('org-1', { affectsMe: true }, { projects: [p1] })).total).toBe(0); + }); +}); diff --git a/src/modules/cve-feed/application/cve-feed-query.service.test.ts b/src/modules/cve-feed/application/cve-feed-query.service.test.ts new file mode 100644 index 0000000..f2eb716 --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-query.service.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it } from 'vitest'; +import { buildAdvisory } from '../domain/advisory'; +import { normalizeOsv } from '../domain/osv'; +import { LODASH, OSV_LODASH, osvVuln } from '../domain/fixtures'; +import { CveFeedQueryService } from './cve-feed-query.service'; +import { InMemoryCveFeedStore, watchlist } from './testing'; +import type { CveWatchlist } from '../domain/types'; + +function setup() { + const store = new InMemoryCveFeedStore(); + const advisories = [ + buildAdvisory(normalizeOsv(OSV_LODASH, [LODASH])!, {}, '2026-11-01T00:00:00.000Z'), + buildAdvisory( + normalizeOsv( + osvVuln({ + id: 'GHSA-2', + aliases: ['CVE-2026-9'], + database_specific: { severity: 'LOW' }, + severity: [], + modified: '2026-10-01T00:00:00Z', + }), + [LODASH], + )!, + { kev: true }, + '2026-11-01T00:00:00.000Z', + ), + ]; + for (const advisory of advisories) store.advisories.set(advisory.id, advisory); + const watchlists = new Map([['org-1', watchlist('org-1', ['lodash'])]]); + let reads = 0; + const countingStore = { listAdvisories: () => (reads++, store.listAdvisories()) }; + const service = new CveFeedQueryService({ + store: countingStore, + watchlists: { findByOrganization: async (id) => watchlists.get(id) ?? null }, + epssThreshold: 0.5, + enabled: true, + status: async () => ({ sources: [], lastRunAt: null }), + }); + return { service, watchlists, reads: () => reads }; +} + +describe('CveFeedQueryService', () => { + it('lists what the organization follows, most recently modified first, with chips', async () => { + const { service } = setup(); + const view = await service.getView('org-1'); + expect(view.items.map((i) => i.advisory.id)).toEqual(['CVE-2021-23337', 'CVE-2026-9']); + expect(view.technologies).toEqual([ + { technologyId: 'lodash', name: 'Lodash', custom: false, advisories: 2 }, + ]); + }); + + it('shows nothing to an organization that follows nothing', async () => { + const { service } = setup(); + expect((await service.getView('org-2')).items).toEqual([]); + }); + + it('memoizes per organization and recomputes only after an invalidation', async () => { + const { service, reads } = setup(); + await service.getView('org-1'); + await service.list('org-1', { kev: true }); + await service.getAdvisory('org-1', 'GHSA-2'); + expect(reads()).toBe(1); + expect(service.computations).toBe(1); + + await service.getView('org-2'); + service.invalidate('org-2'); + await service.getView('org-1'); + expect(service.computations).toBe(2); // org-1 stayed cached + + service.invalidate('org-1'); + await service.getView('org-1'); + expect(service.computations).toBe(3); + + service.invalidate(); + await service.getView('org-1'); + expect(service.computations).toBe(4); + }); + + it('filters and pages the memoized list', async () => { + const { service } = setup(); + expect((await service.list('org-1', { kev: true })).items.map((i) => i.advisory.id)).toEqual([ + 'CVE-2026-9', + ]); + expect((await service.list('org-1', { minSeverity: 'high' })).total).toBe(1); + expect((await service.list('org-1', { technologyId: 'react' })).total).toBe(0); + const page = await service.list('org-1', { limit: 1, offset: 1 }); + expect(page.total).toBe(2); + expect(page.items.map((i) => i.advisory.id)).toEqual(['CVE-2026-9']); + }); + + it('finds an advisory by id or alias, only if the organization follows it', async () => { + const { service } = setup(); + expect((await service.getAdvisory('org-1', 'ghsa-35jh-r3h4-6jhm'))?.advisory.id).toBe( + 'CVE-2021-23337', + ); + expect(await service.getAdvisory('org-2', 'CVE-2021-23337')).toBeNull(); + }); +}); diff --git a/src/modules/cve-feed/application/cve-feed-query.service.ts b/src/modules/cve-feed/application/cve-feed-query.service.ts new file mode 100644 index 0000000..dbac37f --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-query.service.ts @@ -0,0 +1,269 @@ +import { getTechnology } from '#lib/cves/technologies.data'; +import { severityRank } from '../domain/severity'; +import type { + CveAdvisory, + CveWatchlist, + FeedSourceState, + Severity, + WatchlistEntry, +} from '../domain/types'; +import { emptyWatchlist, matchesEntry } from '../domain/watchlist'; +import type { CveFeedStore, ProjectRef, ProjectScans, ScanOccurrences, ScanRef } from './ports'; + +function technologyName(entry: WatchlistEntry): string { + if (entry.label) return entry.label; + const known = getTechnology(entry.technologyId); + if (known) return known.name; + if (entry.custom) return entry.custom.kind === 'osv' ? entry.custom.package : entry.custom.cpe; + return entry.technologyId; +} + +export type CveFeedItem = { + advisory: CveAdvisory; + /** Technologies of the organization's watchlist this advisory belongs to. */ + technologyIds: string[]; + /** An id or alias of the advisory is reported by the scans of a project the user can see. */ + affectsMe: boolean; +}; + +/** The projects whose scans a request may correlate with the feed: the ones its user can see. */ +export type FeedScope = { projects: readonly ProjectRef[] }; + +export type CveFeedDetail = CveFeedItem & { + /** Services (of the visible projects) whose latest scans report the advisory. */ + occurrences: ScanRef[]; +}; + +export type FollowedTechnology = { + technologyId: string; + name: string; + custom: boolean; + advisories: number; +}; + +export type OrgFeedView = { + watchlist: CveWatchlist; + technologies: FollowedTechnology[]; + /** Most recently modified first. */ + items: CveFeedItem[]; +}; + +export type FeedStatus = { + enabled: boolean; + sources: FeedSourceState[]; + lastRunAt: string | null; +}; + +export type CveFeedFilters = { + technologyId?: string; + /** at least this severity */ + minSeverity?: Severity; + kev?: boolean; + affectsMe?: boolean; + from?: string; + to?: string; + limit?: number; + offset?: number; +}; + +export type CveFeedPage = { total: number; items: CveFeedItem[] }; + +export type CveFeedQueryDeps = { + store: Pick; + watchlists: { findByOrganization(organizationId: string): Promise }; + epssThreshold: number; + enabled: boolean; + status: () => Promise<{ sources: FeedStatus['sources']; lastRunAt: string | null }>; + /** "Te afecta": the scans of the projects of the request. Without it nothing is correlated. */ + scans?: ProjectScans; +}; + +/** + * The read side for the pages. It only reads GitDB (never an external source). The computed view + * of an organization (list + chips) is memoized per organization and dropped after a sync that + * wrote something or a watchlist change; filtering and paging run on the memoized list. + * + * "Te afecta" is the correlation of the list with the CVE ids of the latest scans. The scans a + * user may use are the ones of the projects they can see, so that index is memoized per + * organization AND set of projects (`projects` ids), and dropped when a new analysis arrives + * (`invalidateScans`). The org-wide view itself never depends on the user. + */ +export class CveFeedQueryService { + private readonly cache = new Map }>(); + private globalVersion = 0; + private readonly orgVersions = new Map(); + private readonly scanCache = new Map< + string, + { version: number; index: Promise } + >(); + private scanVersion = 0; + private readonly scanOrgVersions = new Map(); + /** Computations of views, to tell cache hits from misses in tests and metrics. */ + computations = 0; + /** Scan indexes built, same purpose. */ + scanComputations = 0; + + constructor(private readonly deps: CveFeedQueryDeps) {} + + /** `organizationId` undefined: every organization. */ + invalidate(organizationId?: string): void { + if (!organizationId) { + this.globalVersion++; + this.cache.clear(); + } else { + this.orgVersions.set(organizationId, (this.orgVersions.get(organizationId) ?? 0) + 1); + this.cache.delete(organizationId); + } + } + + /** A new analysis (or a service/project change): the "Te afecta" indexes are rebuilt. */ + invalidateScans(organizationId?: string): void { + if (!organizationId) { + this.scanVersion++; + this.scanCache.clear(); + return; + } + this.scanOrgVersions.set(organizationId, (this.scanOrgVersions.get(organizationId) ?? 0) + 1); + for (const key of [...this.scanCache.keys()]) { + if (key.startsWith(`${organizationId}|`)) this.scanCache.delete(key); + } + } + + private scanIndex(organizationId: string, scope?: FeedScope): Promise { + const projects = scope?.projects ?? []; + if (!this.deps.scans || projects.length === 0) return Promise.resolve(new Map()); + const key = `${organizationId}|${projects + .map((project) => project.id) + .sort() + .join(',')}`; + const version = this.scanVersion * 1_000_000 + (this.scanOrgVersions.get(organizationId) ?? 0); + const hit = this.scanCache.get(key); + if (hit && hit.version === version) return hit.index; + this.scanComputations++; + const index = this.deps.scans.occurrences(projects); + this.scanCache.set(key, { version, index }); + // a handful of permission sets per organization is normal; keep the memo bounded anyway + if (this.scanCache.size > 200) this.scanCache.delete(this.scanCache.keys().next().value!); + index.catch(() => { + if (this.scanCache.get(key)?.index === index) this.scanCache.delete(key); + }); + return index; + } + + private static occurrencesOf(advisory: CveAdvisory, index: ScanOccurrences): ScanRef[] { + const services = new Map(); + for (const id of [advisory.id, ...advisory.aliases]) { + for (const ref of index.get(id.toUpperCase()) ?? []) services.set(ref.serviceId, ref); + } + return [...services.values()]; + } + + getView(organizationId: string): Promise { + const version = this.globalVersion * 1_000_000 + (this.orgVersions.get(organizationId) ?? 0); + const hit = this.cache.get(organizationId); + if (hit && hit.version === version) return hit.view; + const view = this.compute(organizationId); + this.cache.set(organizationId, { version, view }); + view.catch(() => { + if (this.cache.get(organizationId)?.view === view) this.cache.delete(organizationId); + }); + return view; + } + + private async compute(organizationId: string): Promise { + this.computations++; + const watchlist = + (await this.deps.watchlists.findByOrganization(organizationId)) ?? + emptyWatchlist(organizationId); + const entries = new Map(watchlist.technologies.map((entry) => [entry.technologyId, entry])); + const counts = new Map(); + const items: CveFeedItem[] = []; + if (entries.size > 0) { + for (const advisory of await this.deps.store.listAdvisories()) { + const technologyIds = advisory.technologyIds.filter((tech) => { + const entry = entries.get(tech); + return ( + entry !== undefined && matchesEntry(advisory, entry, watchlist, this.deps.epssThreshold) + ); + }); + if (technologyIds.length === 0) continue; + for (const tech of technologyIds) counts.set(tech, (counts.get(tech) ?? 0) + 1); + items.push({ advisory, technologyIds, affectsMe: false }); + } + } + items.sort( + (a, b) => + b.advisory.modifiedAt.localeCompare(a.advisory.modifiedAt) || + a.advisory.id.localeCompare(b.advisory.id), + ); + return { + watchlist, + technologies: watchlist.technologies.map((entry) => ({ + technologyId: entry.technologyId, + name: technologyName(entry), + custom: Boolean(entry.custom), + advisories: counts.get(entry.technologyId) ?? 0, + })), + items, + }; + } + + async list( + organizationId: string, + filters: CveFeedFilters = {}, + scope?: FeedScope, + ): Promise { + const view = await this.getView(organizationId); + const index = await this.scanIndex(organizationId, scope); + const items = view.items.map((item) => ({ + ...item, + affectsMe: CveFeedQueryService.occurrencesOf(item.advisory, index).length > 0, + })); + const matching = items.filter((item) => { + const { advisory } = item; + if (filters.technologyId && !item.technologyIds.includes(filters.technologyId)) return false; + if ( + filters.minSeverity && + severityRank(advisory.severity) < severityRank(filters.minSeverity) + ) + return false; + if (filters.kev !== undefined && advisory.kev !== filters.kev) return false; + if (filters.affectsMe !== undefined && item.affectsMe !== filters.affectsMe) return false; + if (filters.from && advisory.modifiedAt < filters.from) return false; + if (filters.to && advisory.modifiedAt > filters.to) return false; + return true; + }); + const offset = filters.offset ?? 0; + return { + total: matching.length, + items: matching.slice(offset, filters.limit ? offset + filters.limit : undefined), + }; + } + + /** An advisory the organization follows, by its id or any alias; `null` otherwise. */ + async getAdvisory( + organizationId: string, + idOrAlias: string, + scope?: FeedScope, + ): Promise { + const wanted = idOrAlias.toUpperCase(); + const { items } = await this.getView(organizationId); + const item = items.find((candidate) => + [candidate.advisory.id, ...candidate.advisory.aliases].some( + (id) => id.toUpperCase() === wanted, + ), + ); + if (!item) return null; + const occurrences = CveFeedQueryService.occurrencesOf( + item.advisory, + await this.scanIndex(organizationId, scope), + ); + return { ...item, affectsMe: occurrences.length > 0, occurrences }; + } + + /** Never memoized: the status moves on every sync even when nothing else changed. */ + async status(): Promise { + const { sources, lastRunAt } = await this.deps.status(); + return { enabled: this.deps.enabled, sources, lastRunAt }; + } +} diff --git a/src/modules/cve-feed/application/cve-feed-runtime.correlation.test.ts b/src/modules/cve-feed/application/cve-feed-runtime.correlation.test.ts new file mode 100644 index 0000000..dafba22 --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-runtime.correlation.test.ts @@ -0,0 +1,300 @@ +import { describe, expect, it } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { buildAdvisory } from '../domain/advisory'; +import { normalizeOsv } from '../domain/osv'; +import { LODASH, OSV_LODASH, osvVuln } from '../domain/fixtures'; +import type { NormalizedAdvisory } from '../domain/types'; +import { CveFeedRuntime } from './cve-feed-runtime'; +import type { OrganizationScans, ScanOccurrences, ScanRef } from './ports'; +import { + FakeSource, + InMemoryCveFeedStore, + InMemoryWatchlists, + silentLogger, + testConfig, + watchlist, +} from './testing'; + +const T0 = Date.parse('2026-11-01T10:00:00.000Z'); +const HOUR = 3_600_000; + +const ref = (projectId: string, serviceId: string): ScanRef => ({ + projectId, + projectSlug: projectId, + projectName: projectId, + serviceId, + serviceSlug: serviceId, + serviceName: serviceId, +}); + +class FakeScans implements OrganizationScans { + byOrganization = new Map(); + failing = false; + calls = 0; + async occurrences(organizationId: string) { + this.calls++; + if (this.failing) throw new Error('GitDB down'); + return this.byOrganization.get(organizationId) ?? new Map(); + } + report(organizationId: string, cve: string, ...refs: ScanRef[]) { + const index = this.byOrganization.get(organizationId) ?? new Map(); + index.set(cve.toUpperCase(), [...(index.get(cve.toUpperCase()) ?? []), ...refs]); + this.byOrganization.set(organizationId, index); + } +} + +const NEW_VULN = osvVuln({ + id: 'GHSA-new-new-new1', + aliases: ['CVE-2026-1111'], + published: '2026-11-01T11:00:00Z', + modified: '2026-11-01T11:00:00Z', +}); + +const candidate = (vuln = NEW_VULN) => ({ + key: vuln.id, + advisory: normalizeOsv(vuln, [LODASH])!, +}); + +function world() { + const clock = { t: T0 }; + const store = new InMemoryCveFeedStore(); + const watchlists = new InMemoryWatchlists(); + const kev = new FakeSource('kev'); + const osv = new FakeSource('osv', ['osv']); + const epss = new FakeSource('epss'); + const scans = new FakeScans(); + const events = new RecordingEventBus(); + const runtime = (holder = 'runtime-a') => + new CveFeedRuntime({ + store, + watchlists, + sources: [kev, osv, epss], + config: testConfig, + logger: silentLogger, + events, + scans, + organizationSlug: async (id) => `slug-${id}`, + absoluteUrl: (path) => `https://gitops.test${path}`, + now: () => clock.t, + holder, + }); + return { clock, store, watchlists, kev, osv, epss, scans, events, runtime }; +} +type World = ReturnType; + +async function backfill(w: World, runtime: CveFeedRuntime) { + w.osv.result = { candidates: [candidate(osvVuln(OSV_LODASH))], items: 1 }; + await runtime.syncOnce(); + w.clock.t += 3 * HOUR; +} + +describe('CveFeedRuntime: affects_project', () => { + it('emits once per organization x CVE x project, with the project in the scope and its services', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + + w.scans.report('org-1', 'CVE-2026-1111', ref('p1', 's2'), ref('p1', 's1'), ref('p2', 's3')); + w.osv.result = { candidates: [candidate()], items: 1 }; + await runtime.syncOnce(); + + const affects = w.events.ofType('cve_feed.advisory.affects_project'); + expect(affects.map((e) => e.scope)).toEqual([ + { organizationId: 'org-1', projectId: 'p1' }, + { organizationId: 'org-1', projectId: 'p2' }, + ]); + expect(affects[0].payload).toMatchObject({ + cveId: 'CVE-2026-1111', + projectId: 'p1', + serviceIds: ['s1', 's2'], + technologyId: 'lodash', + }); + expect(w.events.ofType('cve_feed.advisory.published')).toHaveLength(1); + expect(w.store.matches.get('org-1:CVE-2026-1111:lodash')!.notified.affects_project).toEqual([ + 'p1', + 'p2', + ]); + }); + + it('stores the state before publishing', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + let stored: string[] | undefined; + w.events.subscribe('cve_feed.advisory.affects_project', () => { + stored = w.store.matches.get('org-1:CVE-2026-1111:lodash')?.notified.affects_project; + }); + w.scans.report('org-1', 'CVE-2026-1111', ref('p1', 's1')); + w.osv.result = { candidates: [candidate()], items: 1 }; + await runtime.syncOnce(); + expect(stored).toEqual(['p1']); + }); + + it('does not repeat after a restart, and only tells about a project that appears later', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const first = w.runtime('runtime-a'); + await backfill(w, first); + w.scans.report('org-1', 'CVE-2026-1111', ref('p1', 's1')); + w.osv.result = { candidates: [candidate()], items: 1 }; + await first.syncOnce(); + expect(w.events.ofType('cve_feed.advisory.affects_project')).toHaveLength(1); + + w.clock.t += 3 * HOUR; + const second = w.runtime('runtime-b'); // restart: new memory, same store + w.osv.result = { items: 0 }; + await second.syncOnce(); + expect(w.events.ofType('cve_feed.advisory.affects_project')).toHaveLength(1); + + // a new analysis of another project reports the same CVE + w.clock.t += 3 * HOUR; + w.scans.report('org-1', 'CVE-2026-1111', ref('p2', 's9')); + await second.syncOnce(); + const affects = w.events.ofType('cve_feed.advisory.affects_project'); + expect(affects).toHaveLength(2); + expect(affects[1].payload).toMatchObject({ projectId: 'p2', serviceIds: ['s9'] }); + }); + + it('matches by alias: the scans may report the GHSA id of a CVE advisory', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + w.scans.report('org-1', 'ghsa-new-new-new1', ref('p1', 's1')); + w.osv.result = { candidates: [candidate()], items: 1 }; + await runtime.syncOnce(); + expect(w.events.ofType('cve_feed.advisory.affects_project')).toHaveLength(1); + }); + + it('only uses the scans of the organization that follows the advisory', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash']), watchlist('org-2', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + w.scans.report('org-2', 'CVE-2026-1111', ref('p7', 's7')); + w.osv.result = { candidates: [candidate()], items: 1 }; + await runtime.syncOnce(); + const affects = w.events.ofType('cve_feed.advisory.affects_project'); + expect(affects.map((e) => e.scope.organizationId)).toEqual(['org-2']); + }); + + it('is silent during the backfill: the projects found are recorded, nothing is emitted', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + w.scans.report('org-1', 'CVE-2021-23337', ref('p1', 's1')); + const runtime = w.runtime(); + await backfill(w, runtime); + expect(w.events.events).toHaveLength(0); + expect(w.store.matches.get('org-1:CVE-2021-23337:lodash')!.notified.affects_project).toEqual([ + 'p1', + ]); + + // later syncs do not turn it into news + w.osv.result = { candidates: [candidate(osvVuln(OSV_LODASH))], items: 1 }; + await runtime.syncOnce(); + expect(w.events.events).toHaveLength(0); + }); + + it('records, without events, the projects of a match stored before this state existed', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + const match = w.store.matches.get('org-1:CVE-2021-23337:lodash')!; + delete match.notified.affects_project; // as the previous phase left it + w.scans.report('org-1', 'CVE-2021-23337', ref('p1', 's1')); + w.osv.result = { items: 0 }; + await runtime.syncOnce(); + expect(w.events.ofType('cve_feed.advisory.affects_project')).toHaveLength(0); + expect(w.store.matches.get(match.id)!.notified.affects_project).toEqual(['p1']); + }); + + it('writes nothing when the scans say the same as last time', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + w.scans.report('org-1', 'CVE-2021-23337', ref('p1', 's1')); + w.osv.result = { items: 0 }; + await runtime.syncOnce(); + w.clock.t += 3 * HOUR; + const before = { ...w.store.writes }; + await runtime.syncOnce(); + expect(w.store.writes.matches).toBe(before.matches); + expect(w.store.writes.advisories).toBe(before.advisories); + }); + + it('carries on when the scans cannot be read, and leaves the state alone', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + w.scans.failing = true; + w.osv.result = { candidates: [candidate()], items: 1 }; + const outcome = await runtime.syncOnce(); + expect(outcome.status).toBe('done'); + expect(w.events.ofType('cve_feed.advisory.published')).toHaveLength(1); + expect(w.events.ofType('cve_feed.advisory.affects_project')).toHaveLength(0); + expect( + w.store.matches.get('org-1:CVE-2026-1111:lodash')!.notified.affects_project, + ).toBeUndefined(); + }); +}); + +describe('CveFeedRuntime: EPSS', () => { + const NOW = '2026-11-01T10:00:00.000Z'; + const base = (): NormalizedAdvisory => normalizeOsv(osvVuln(OSV_LODASH), [LODASH])!; + + async function stored(epssScore: number | null = 0.1) { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + const advisory = w.store.advisories.get('CVE-2021-23337')!; + w.store.advisories.set( + advisory.id, + buildAdvisory(base(), { epssScore, epssPercentile: 0.5, epssUpdatedAt: NOW }, NOW), + ); + w.osv.result = { items: 0 }; + return { w, runtime }; + } + + it('applies a score without writing when nothing relevant changed (same value at 0.01)', async () => { + const { w, runtime } = await stored(0.1); + w.epss.result = { + epss: new Map([['CVE-2021-23337', { score: 0.1004, percentile: 0.51 }]]), + items: 1, + }; + const before = { ...w.store.writes }; + const outcome = await runtime.syncOnce(); + expect(outcome.advisoriesWritten).toBe(0); + expect(w.store.writes.advisories).toBe(before.advisories); + expect(w.store.writes.matches).toBe(before.matches); + }); + + it('writes one batch when the score moves, and emits escalated when it crosses the threshold', async () => { + const { w, runtime } = await stored(0.1); + w.epss.result = { + epss: new Map([['CVE-2021-23337', { score: 0.92, percentile: 0.99 }]]), + items: 1, + }; + const outcome = await runtime.syncOnce(); + expect(outcome.advisoriesWritten).toBe(1); + expect(w.store.advisories.get('CVE-2021-23337')).toMatchObject({ + epssScore: 0.92, + epssPercentile: 0.99, + epssUpdatedAt: new Date(w.clock.t).toISOString(), + }); + // dedup baseline of the match was "EPSS not over": now it is + expect(w.events.ofType('cve_feed.advisory.escalated')).toHaveLength(1); + + // the same score again: nothing to write, no second event + w.clock.t += 3 * HOUR; + const before = { ...w.store.writes }; + await runtime.syncOnce(); + expect(w.store.writes.advisories).toBe(before.advisories); + expect(w.events.ofType('cve_feed.advisory.escalated')).toHaveLength(1); + }); +}); diff --git a/src/modules/cve-feed/application/cve-feed-runtime.sources.test.ts b/src/modules/cve-feed/application/cve-feed-runtime.sources.test.ts new file mode 100644 index 0000000..10f3a48 --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-runtime.sources.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { HttpClient } from '../infrastructure/http'; +import { EpssSource } from '../infrastructure/sources/epss.source'; +import { NvdSource } from '../infrastructure/sources/nvd.source'; +import type { NvdCve } from '../domain/nvd'; +import { CveFeedRuntime } from './cve-feed-runtime'; +import { + FakeSource, + InMemoryCveFeedStore, + InMemoryWatchlists, + silentLogger, + testConfig, + watchlist, +} from './testing'; + +const T0 = Date.parse('2026-11-01T10:00:00.000Z'); +const HOUR = 3_600_000; + +const MYSQL_CVE: NvdCve = { + id: 'CVE-2026-20001', + lastModified: '2026-10-25T09:30:00.000', + published: '2026-10-20T14:15:10.000', + descriptions: [{ lang: 'en', value: 'MySQL Server problem' }], + metrics: { + cvssMetricV31: [ + { + type: 'Primary', + cvssData: { baseScore: 9.8, vectorString: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H' }, + }, + ], + }, + configurations: [ + { + nodes: [ + { + cpeMatch: [ + { + vulnerable: true, + criteria: 'cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*', + versionEndExcluding: '8.0.35', + }, + ], + }, + ], + }, + ], +}; + +/** NVD and EPSS answered by a fake `fetch`, through the real sources. */ +function world(epssScore = '0.2') { + const clock = { t: T0 }; + const requests = { nvd: 0, epss: 0 }; + const http = new HttpClient({ + maxAttempts: 1, + fetch: async (url) => { + if (url.includes('services.nvd.nist.gov')) { + requests.nvd++; + return new Response( + JSON.stringify({ totalResults: 1, vulnerabilities: [{ cve: MYSQL_CVE }] }), + ); + } + requests.epss++; + return new Response( + JSON.stringify({ + data: [{ cve: 'CVE-2026-20001', epss: epssScore, percentile: '0.7' }], + }), + ); + }, + }); + const store = new InMemoryCveFeedStore(); + const watchlists = new InMemoryWatchlists(); + watchlists.rows = [watchlist('org-1', ['mysql'])]; + const events = new RecordingEventBus(); + const runtime = new CveFeedRuntime({ + store, + watchlists, + sources: [ + new FakeSource('kev'), + new FakeSource('osv', ['osv']), + new NvdSource(http, { limiter: { acquire: async () => {} } }), + new EpssSource(http), + ], + config: testConfig, + logger: silentLogger, + events, + now: () => clock.t, + holder: 'runtime-a', + }); + return { clock, requests, store, events, runtime }; +} + +describe('CveFeedRuntime with the NVD and EPSS sources', () => { + it('backfills a CPE technology silently from NVD, and marks it as backfilled', async () => { + const w = world(); + const outcome = await w.runtime.syncOnce(); + expect(outcome.errors).toEqual({}); + expect(w.events.events).toHaveLength(0); + expect(w.store.advisories.get('CVE-2026-20001')).toMatchObject({ + sources: ['nvd'], + technologyIds: ['mysql'], + severity: 'critical', + fixedVersions: ['8.0.35'], + }); + expect(w.store.matches.get('org-1:CVE-2026-20001:mysql')).toMatchObject({ silent: true }); + expect(Object.keys(w.store.states.get('run')!.backfilledTechnologies!)).toEqual(['mysql']); + expect(w.store.states.get('nvd')!.cursor).toEqual({ + cpes: { 'mysql|cpe:2.3:a:oracle:mysql': new Date(T0).toISOString() }, + }); + }); + + it('scores the stored advisory once a day and then writes nothing at all', async () => { + const w = world(); + await w.runtime.syncOnce(); + expect(w.requests.epss).toBe(0); // nothing was stored yet when EPSS ran + + w.clock.t += 3 * HOUR; + const second = await w.runtime.syncOnce(); + expect(second.advisoriesWritten).toBe(1); + expect(w.store.advisories.get('CVE-2026-20001')).toMatchObject({ epssScore: 0.2 }); + expect(w.requests.epss).toBe(1); + expect(w.store.states.get('epss')!.cursor).toEqual({ + refreshedAt: new Date(w.clock.t).toISOString(), + }); + + const before = { ...w.store.writes }; + for (let i = 0; i < 4; i++) { + w.clock.t += 3 * HOUR; + const outcome = await w.runtime.syncOnce(); + expect(outcome.advisoriesWritten + outcome.matchesWritten + outcome.events).toBe(0); + } + // NVD is asked every run (cheap, windowed), EPSS not again within the day + expect(w.requests.nvd).toBe(6); + expect(w.requests.epss).toBe(1); + expect(w.store.writes.advisories).toBe(before.advisories); + expect(w.store.writes.matches).toBe(before.matches); + expect(w.store.writes.state).toBe(before.state); + }); + + it('after a day refreshes EPSS and writes the advisory only if the score moved', async () => { + const w = world('0.2'); + await w.runtime.syncOnce(); + w.clock.t += 3 * HOUR; + await w.runtime.syncOnce(); + const before = { ...w.store.writes }; + + w.clock.t += 25 * HOUR; + await w.runtime.syncOnce(); + expect(w.requests.epss).toBe(2); + // same score: the advisory is untouched; only the small daily state rows move + expect(w.store.writes.advisories).toBe(before.advisories); + expect(w.store.writes.matches).toBe(before.matches); + }); +}); diff --git a/src/modules/cve-feed/application/cve-feed-runtime.test.ts b/src/modules/cve-feed/application/cve-feed-runtime.test.ts new file mode 100644 index 0000000..7c36099 --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-runtime.test.ts @@ -0,0 +1,536 @@ +import { describe, expect, it } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { normalizeOsv } from '../domain/osv'; +import { LODASH, OSV_LODASH, osvVuln } from '../domain/fixtures'; +import type { OsvVulnerability } from '../domain/osv'; +import type { NormalizedAdvisory, WatchTarget } from '../domain/types'; +import { CveFeedRuntime, type CveFeedConfig } from './cve-feed-runtime'; +import { + FakeSource, + InMemoryCveFeedStore, + InMemoryWatchlists, + silentLogger, + testConfig, + watchlist, +} from './testing'; + +const T0 = Date.parse('2026-11-01T10:00:00.000Z'); +const HOUR = 3_600_000; +const DAY = 24 * HOUR; + +const REACT: WatchTarget = { + technologyId: 'react', + kind: 'osv', + ecosystem: 'npm', + package: 'react', +}; + +function candidate( + vuln: OsvVulnerability, + targets: WatchTarget[] = [LODASH], +): { key: string; advisory: NormalizedAdvisory } { + return { key: vuln.id, advisory: normalizeOsv(vuln, targets)! }; +} + +function world(config: Partial = {}) { + const clock = { t: T0 }; + const store = new InMemoryCveFeedStore(); + const watchlists = new InMemoryWatchlists(); + const kev = new FakeSource('kev'); + const osv = new FakeSource('osv', ['osv']); + const events = new RecordingEventBus(); + const runtime = (holder = 'runtime-a') => + new CveFeedRuntime({ + store, + watchlists, + sources: [kev, osv], + config: { ...testConfig, ...config }, + logger: silentLogger, + events, + organizationSlug: async (id) => `slug-${id}`, + absoluteUrl: (path) => `https://gitops.test${path}`, + now: () => clock.t, + holder, + }); + return { clock, store, watchlists, kev, osv, events, runtime }; +} + +type World = ReturnType; + +/** The first run of a technology: the backfill (silent). Moves the clock past the interval. */ +async function backfill( + w: World, + runtime: CveFeedRuntime, + vulns: OsvVulnerability[] = [OSV_LODASH], +) { + w.osv.result = { candidates: vulns.map((vuln) => candidate(vuln)), items: vulns.length }; + const outcome = await runtime.syncOnce(); + w.clock.t += 3 * HOUR; + return outcome; +} + +const NEW_VULN = osvVuln({ + id: 'GHSA-new-new-new1', + aliases: ['CVE-2026-1111'], + published: '2026-11-01T11:00:00Z', + modified: '2026-11-01T11:00:00Z', +}); + +describe('CveFeedRuntime: backfill and publication', () => { + it('stores the first run silently: advisories and matches, no events, technology marked as backfilled', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const outcome = await backfill(w, w.runtime()); + + expect(outcome.status).toBe('done'); + expect(outcome.events).toBe(0); + expect(w.events.events).toHaveLength(0); + expect([...w.store.advisories.keys()]).toEqual(['CVE-2021-23337']); + const [match] = [...w.store.matches.values()]; + expect(match).toMatchObject({ + organizationId: 'org-1', + cveId: 'CVE-2021-23337', + technologyId: 'lodash', + silent: true, + }); + expect(match.notified.published).toBeTruthy(); + expect(Object.keys(w.store.states.get('run')!.backfilledTechnologies!)).toEqual(['lodash']); + }); + + it('publishes one event per organization for an advisory that arrives after the backfill', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash']), watchlist('org-2', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + + w.osv.result = { candidates: [candidate(NEW_VULN)], items: 1 }; + const outcome = await runtime.syncOnce(); + + expect(outcome.events).toBe(2); + const published = w.events.ofType('cve_feed.advisory.published'); + expect(published.map((e) => e.scope.organizationId).sort()).toEqual(['org-1', 'org-2']); + expect(published[0].payload).toMatchObject({ + cveId: 'CVE-2026-1111', + technologyId: 'lodash', + ecosystem: 'npm', + package: 'lodash', + severity: 'high', + fixedVersions: ['4.17.21'], + sources: ['osv'], + }); + expect(published[0].payload.url).toBe( + `https://gitops.test/org/slug-${published[0].scope.organizationId}/cves/CVE-2026-1111?tab=technology`, + ); + }); + + it('writes the match state before publishing', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + let stateWhenPublished: string[] = []; + w.events.subscribe('cve_feed.advisory.published', () => { + stateWhenPublished = [...w.store.matches.keys()]; + }); + w.osv.result = { candidates: [candidate(NEW_VULN)], items: 1 }; + await runtime.syncOnce(); + expect(stateWhenPublished).toContain('org-1:CVE-2026-1111:lodash'); + }); + + it('does not repeat events after a restart (new runtime over the same store)', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const first = w.runtime('runtime-a'); + await backfill(w, first); + w.osv.result = { candidates: [candidate(NEW_VULN)], items: 1 }; + await first.syncOnce(); + expect(w.events.ofType('cve_feed.advisory.published')).toHaveLength(1); + w.clock.t += 3 * HOUR; + + // the process restarts: new runtime, empty memory; the source even reports it as edited + const second = w.runtime('runtime-b'); + w.osv.result = { + candidates: [ + candidate({ ...NEW_VULN, modified: '2026-11-01T12:00:00Z', summary: 'edited summary' }), + ], + items: 1, + }; + const outcome = await second.syncOnce(); + + expect(outcome.advisoriesWritten).toBe(1); // the content did change + expect(outcome.events).toBe(0); + expect(w.events.events).toHaveLength(1); + }); + + it('emits one event for an organization following two technologies hit by the same CVE', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash', 'react'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + const both = osvVuln({ + id: 'GHSA-both-both-both', + aliases: ['CVE-2026-2222'], + modified: '2026-11-01T11:00:00Z', + published: '2026-11-01T11:00:00Z', + affected: [ + { + package: { ecosystem: 'npm', name: 'lodash' }, + ranges: [{ type: 'SEMVER', events: [{ introduced: '0' }, { fixed: '1.0.1' }] }], + }, + { + package: { ecosystem: 'npm', name: 'react' }, + ranges: [{ type: 'SEMVER', events: [{ introduced: '0' }, { fixed: '2.0.1' }] }], + }, + ], + }); + w.osv.result = { candidates: [candidate(both, [LODASH, REACT])], items: 1 }; + await runtime.syncOnce(); + + expect(w.events.ofType('cve_feed.advisory.published')).toHaveLength(1); + expect([...w.store.matches.keys()].filter((id) => id.includes('CVE-2026-2222')).sort()).toEqual( + ['org-1:CVE-2026-2222:lodash', 'org-1:CVE-2026-2222:react'], + ); + }); + + it('is silent for an organization that starts following a technology others already follow', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + + w.watchlists.rows = [ + watchlist('org-1', ['lodash']), + watchlist('org-2', ['lodash'], { addedAt: new Date(w.clock.t - HOUR).toISOString() }), + ]; + w.osv.result = { items: 0 }; + const outcome = await runtime.syncOnce(); + + expect(outcome.events).toBe(0); + expect(w.store.matches.get('org-2:CVE-2021-23337:lodash')).toMatchObject({ silent: true }); + }); +}); + +describe('CveFeedRuntime: changes of a followed advisory', () => { + async function followed() { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + const noFix = osvVuln({ + ...NEW_VULN, + severity: [], + database_specific: { severity: 'HIGH' }, + affected: [ + { + package: { ecosystem: 'npm', name: 'lodash' }, + ranges: [{ type: 'SEMVER', events: [{ introduced: '0' }] }], + }, + ], + }); + await backfill(w, runtime, []); + w.osv.result = { candidates: [candidate(noFix)], items: 1 }; + await runtime.syncOnce(); + w.events.clear(); + return { w, runtime, noFix }; + } + + it('emits escalated once when the severity rises, and not again for further edits', async () => { + const { w, runtime, noFix } = await followed(); + const step = async (patch: Partial, modified: string) => { + w.clock.t += 3 * HOUR; + w.osv.result = { candidates: [candidate({ ...noFix, ...patch, modified })], items: 1 }; + await runtime.syncOnce(); + }; + + await step({ database_specific: { severity: 'CRITICAL' } }, '2026-11-02T00:00:00Z'); + expect(w.events.ofType('cve_feed.advisory.escalated')).toHaveLength(1); + await step( + { database_specific: { severity: 'CRITICAL' }, summary: 'edit' }, + '2026-11-03T00:00:00Z', + ); + expect(w.events.ofType('cve_feed.advisory.escalated')).toHaveLength(1); + }); + + it('emits escalated when the CVE enters CISA KEV, and fix_available when a fix appears', async () => { + const { w, runtime, noFix } = await followed(); + w.clock.t += 3 * HOUR; + w.kev.result = { kev: new Map([['CVE-2026-1111', '2026-11-02']]), items: 1 }; + w.osv.result = { items: 0 }; + await runtime.syncOnce(); + const [escalated] = w.events.ofType('cve_feed.advisory.escalated'); + expect(escalated.payload.kev).toBe(true); + + w.clock.t += 3 * HOUR; + w.osv.result = { + candidates: [ + candidate({ ...noFix, modified: '2026-11-04T00:00:00Z', affected: OSV_LODASH.affected }), + ], + items: 1, + }; + await runtime.syncOnce(); + expect(w.events.ofType('cve_feed.advisory.fix_available')).toHaveLength(1); + expect(w.events.ofType('cve_feed.advisory.escalated')).toHaveLength(1); + + // and nothing more on a repeat + w.clock.t += 3 * HOUR; + await runtime.syncOnce(); + expect(w.events.events).toHaveLength(2); + }); +}); + +describe('CveFeedRuntime: what gets stored', () => { + it('does not store advisories below the filter, remembers them, and lets KEV bring them back', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + const medium = osvVuln({ + id: 'GHSA-med-med-med1', + aliases: ['CVE-2026-3333'], + severity: [], + database_specific: { severity: 'MODERATE' }, + modified: '2026-10-30T00:00:00Z', + }); + await backfill(w, runtime, [medium]); + + expect(w.store.advisories.size).toBe(0); + const osvState = w.store.states.get('osv')!.cursor as { rejected: Record }; + expect(Object.keys(osvState.rejected)).toEqual(['GHSA-med-med-med1']); + + // the next run tells the source it is known: it is not downloaded again + w.osv.result = { items: 0 }; + await runtime.syncOnce(); + expect(w.osv.contexts.at(-1)!.known.get('GHSA-med-med-med1')).toMatchObject({ + technologyIds: null, + }); + + // once it is exploited it is no longer "known as rejected": the source fetches it again + w.clock.t += 3 * HOUR; + w.kev.result = { kev: new Map([['CVE-2026-3333', '2026-11-02']]), items: 1 }; + await runtime.syncOnce(); + expect(w.osv.contexts.at(-1)!.known.has('GHSA-med-med-med1')).toBe(false); + }); + + it('stores a below-filter advisory that is already in KEV', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + w.kev.result = { kev: new Map([['CVE-2026-3333', '2026-11-02']]), items: 1 }; + const medium = osvVuln({ + id: 'GHSA-med-med-med1', + aliases: ['CVE-2026-3333'], + severity: [], + database_specific: { severity: 'MODERATE' }, + }); + await backfill(w, w.runtime(), [medium]); + expect(w.store.advisories.get('CVE-2026-3333')).toMatchObject({ + kev: true, + kevAddedAt: '2026-11-02', + }); + }); + + it('deletes advisories (and their matches) older than the retention, one write per table', async () => { + const w = world({ retentionMs: 30 * DAY }); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime, [osvVuln({ modified: new Date(T0 - 5 * DAY).toISOString() })]); + expect(w.store.advisories.size).toBe(1); + + w.clock.t += 40 * DAY; + w.osv.result = { items: 0 }; + const writes = { ...w.store.writes }; + const outcome = await runtime.syncOnce(); + expect(outcome.advisoriesDeleted).toBe(1); + expect(w.store.advisories.size).toBe(0); + expect(w.store.matches.size).toBe(0); + expect(w.store.writes.advisories - writes.advisories).toBe(1); + expect(w.store.writes.matches - writes.matches).toBe(1); + }); + + it('writes nothing in a sync without changes (only the lease)', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + w.kev.result = { + kev: new Map([['CVE-2020-0001', '2026-01-01']]), + items: 1, + statePatch: { etag: 'W/"a"' }, + }; + const runtime = w.runtime(); + await backfill(w, runtime); + const before = { ...w.store.writes }; + + for (let i = 0; i < 3; i++) { + w.osv.result = { candidates: [candidate(OSV_LODASH)], items: 1 }; + const outcome = await runtime.syncOnce(); + expect(outcome.status).toBe('done'); + expect(outcome.advisoriesWritten + outcome.matchesWritten + outcome.events).toBe(0); + w.clock.t += 3 * HOUR; + } + expect(w.store.writes.advisories).toBe(before.advisories); + expect(w.store.writes.matches).toBe(before.matches); + expect(w.store.writes.state).toBe(before.state); + }); + + it('upserts a batch of new advisories with one write per table', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const many = Array.from({ length: 25 }, (_, i) => + osvVuln({ id: `GHSA-bulk-${i}`, aliases: [`CVE-2026-${5000 + i}`] }), + ); + await backfill(w, w.runtime(), many); + expect(w.store.advisories.size).toBe(25); + expect(w.store.writes.advisories).toBe(1); + expect(w.store.writes.matches).toBe(1); + }); + + it('looks back only the backfill window for a new technology, and not further for a backfilled one', async () => { + const w = world({ backfillMs: 30 * DAY, retentionMs: 180 * DAY }); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + expect(w.osv.contexts[0].cutoffFor('lodash')).toBe(new Date(T0 - 30 * DAY).toISOString()); + + w.osv.result = { items: 0 }; + await runtime.syncOnce(); + expect(w.osv.contexts[1].cutoffFor('lodash')).toBe(new Date(T0 - 30 * DAY).toISOString()); + + // a technology followed from now on gets its own window + w.watchlists.rows = [watchlist('org-1', ['lodash', 'react'])]; + w.clock.t += 3 * HOUR; + await runtime.syncOnce(); + expect(w.osv.contexts[2].cutoffFor('react')).toBe(new Date(w.clock.t - 30 * DAY).toISOString()); + }); +}); + +describe('CveFeedRuntime: lease and scheduling', () => { + it('lets only one of two runtimes sync at the same time', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + w.osv.result = { candidates: [candidate(OSV_LODASH)], items: 1 }; + const [a, b] = await Promise.all([ + w.runtime('runtime-a').syncOnce(), + w.runtime('runtime-b').syncOnce(), + ]); + + expect([a.status, b.status].sort()).toEqual(['done', 'locked']); + expect(w.osv.calls).toBe(1); + expect(w.kev.calls).toBe(1); + }); + + it('respects a live lease of another instance and takes over once it expired', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + await w.runtime('runtime-a').syncOnce(); + expect(w.store.states.get('lock')!.holder).toBe('runtime-a'); + + w.clock.t += 3 * HOUR; + w.store.states.set('lock', { + holder: 'runtime-x', + acquiredAt: new Date(w.clock.t - 3 * HOUR).toISOString(), + expiresAt: new Date(w.clock.t + HOUR).toISOString(), + }); + expect((await w.runtime('runtime-b').syncOnce()).status).toBe('locked'); + + w.clock.t += 2 * HOUR; + expect((await w.runtime('runtime-b').syncOnce()).status).toBe('done'); + expect(w.store.states.get('lock')!.holder).toBe('runtime-b'); + }); + + it('skips a scheduled sync right after another run, but not a forced or requested one', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await runtime.syncOnce(); + w.clock.t += HOUR; + expect((await runtime.syncOnce()).status).toBe('not_due'); + expect((await runtime.syncOnce({ force: true })).status).toBe('done'); + + await runtime.requestSync(); + const calls = w.osv.calls; + await runtime.syncIfRequested(); + expect(w.osv.calls).toBe(calls + 1); + // handled: the next poll does nothing + await runtime.syncIfRequested(); + expect(w.osv.calls).toBe(calls + 1); + }); + + it('makes no call at all with the feed disabled, not even for a requested sync', async () => { + const w = world({ enabled: false }); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await runtime.start(); + expect(await runtime.requestSync()).toBe(false); + expect((await runtime.syncOnce({ force: true })).status).toBe('disabled'); + await runtime.syncIfRequested(); + expect(w.osv.calls + w.kev.calls).toBe(0); + expect(w.store.writes).toEqual({ advisories: 0, matches: 0, state: 0, lock: 0 }); + }); + + it('does nothing when there is nothing to follow', async () => { + const w = world(); + expect((await w.runtime().syncOnce()).status).toBe('no_targets'); + expect(w.osv.calls).toBe(0); + }); +}); + +describe('CveFeedRuntime: failing sources', () => { + it('records the error of a failing source and carries on with the others', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + const runtime = w.runtime(); + await backfill(w, runtime); + w.events.clear(); + + w.osv.error = new Error('HTTP 503 from api.osv.dev'); + w.kev.result = { kev: new Map([['CVE-2021-23337', '2026-11-03']]), items: 1 }; + const outcome = await runtime.syncOnce(); + + expect(outcome.status).toBe('done'); + expect(outcome.errors).toEqual({ osv: 'HTTP 503 from api.osv.dev' }); + expect(w.kev.calls).toBe(2); + // KEV still did its job on the stored advisory + expect(w.store.advisories.get('CVE-2021-23337')!.kev).toBe(true); + expect(w.events.ofType('cve_feed.advisory.escalated')).toHaveLength(1); + + const states = await runtime.sourceStatuses(); + expect(states.find((s) => s.id === 'osv')).toMatchObject({ + lastError: 'HTTP 503 from api.osv.dev', + }); + expect(w.store.states.get('osv')!.lastError).toBe('HTTP 503 from api.osv.dev'); + expect(states.find((s) => s.id === 'kev')!.lastError).toBeNull(); + + // it recovers by itself + w.osv.error = null; + w.osv.result = { items: 0 }; + w.clock.t += 3 * HOUR; + await runtime.syncOnce(); + expect((await runtime.sourceStatuses()).find((s) => s.id === 'osv')!.lastError).toBeNull(); + expect(w.store.states.get('osv')!.lastError).toBeNull(); + }); + + it('does not mark a technology as backfilled while its source is failing', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + w.osv.error = new Error('boom'); + const runtime = w.runtime(); + await runtime.syncOnce(); + expect(w.store.states.get('run')?.backfilledTechnologies ?? {}).toEqual({}); + + w.osv.error = null; + w.osv.result = { candidates: [candidate(OSV_LODASH)], items: 1 }; + w.clock.t += 3 * HOUR; + const outcome = await runtime.syncOnce(); + expect(outcome.events).toBe(0); // still silent: this is the real backfill + expect(Object.keys(w.store.states.get('run')!.backfilledTechnologies!)).toEqual(['lodash']); + }); + + it('uses what a partially failed source did get, and still reports the error', async () => { + const w = world(); + w.watchlists.rows = [watchlist('org-1', ['lodash'])]; + w.osv.result = { + candidates: [candidate(OSV_LODASH)], + items: 1, + partialError: '1 of 2 vulnerabilities failed', + }; + const outcome = await w.runtime().syncOnce(); + expect(outcome.advisoriesWritten).toBe(1); + expect(outcome.errors.osv).toMatch(/1 of 2/); + }); +}); diff --git a/src/modules/cve-feed/application/cve-feed-runtime.ts b/src/modules/cve-feed/application/cve-feed-runtime.ts new file mode 100644 index 0000000..a50f62c --- /dev/null +++ b/src/modules/cve-feed/application/cve-feed-runtime.ts @@ -0,0 +1,726 @@ +/** + * The CVE feed engine of the server process. One sync: + * + * lease ─▶ union of the watchlists ─▶ per source (KEV, OSV, NVD, EPSS; each one independently) + * ─▶ merge ─▶ filter ─▶ batched upsert of what changed ─▶ retention purge + * ─▶ per organization: match rows written (awaited) ─▶ events published ─▶ caches dropped + * + * Storage rules (docs/adr/0004-cve-feed.md): never the whole feed, one delete + one insert per + * table at most, a row is only rewritten when its fingerprint changed, so a sync without changes + * writes nothing but the lease. The volatile status (last run, items) lives in memory and is + * persisted only when something durable changes or once a day as a heartbeat. + * + * Transport-agnostic: nothing here knows it runs inside the web server. + */ +import { hostname } from 'node:os'; +import { randomUUID } from 'node:crypto'; +import type { Logger } from 'pino'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import type { DomainEventMap } from '#lib/events/domain-events'; +import { buildAdvisory, mergeAdvisories, passesFilter, withEnrichment } from '../domain/advisory'; +import { planMatches, type PlannedEvent, type ScanIndex } from '../domain/matching'; +import type { + CveAdvisory, + CveSourceId, + FeedSourceState, + NormalizedAdvisory, +} from '../domain/types'; +import { unionTargets } from '../domain/watchlist'; +import type { + CveFeedStore, + CveSource, + FeedStateRow, + KnownAdvisory, + OrganizationScans, + SourceCandidate, + WatchlistSource, +} from './ports'; + +export type CveFeedConfig = { + enabled: boolean; + intervalMs: number; + minSeverity: CveAdvisory['severity']; + epssThreshold: number; + retentionMs: number; + backfillMs: number; +}; + +export type CveFeedRuntimeDeps = { + store: CveFeedStore; + watchlists: WatchlistSource; + sources: CveSource[]; + config: CveFeedConfig; + logger: Pick; + events?: EventPublisher; + /** Organization slug for the link of the events; `null` when it no longer exists. */ + organizationSlug?: (organizationId: string) => Promise; + /** Absolute URL for a path (`ORIGIN`), `null` without a public origin. */ + absoluteUrl?: (path: string) => string | null; + /** + * Where the scans of an organization report each CVE, for `affects_project`. Without it (or when + * it fails) no project correlation is made and the stored state is left as it was. + */ + scans?: OrganizationScans; + /** Called after a sync changed what the UI shows. */ + onChanged?: () => void; + now?: () => number; + holder?: string; + lockTtlMs?: number; + /** Delay before the first scheduled sync. */ + startDelayMs?: number; + /** How often a "Sincronizar ahora" request is looked for. */ + requestPollMs?: number; +}; + +export type SyncOutcome = { + status: 'disabled' | 'locked' | 'not_due' | 'no_targets' | 'done'; + advisoriesWritten: number; + advisoriesDeleted: number; + matchesWritten: number; + events: number; + errors: Partial>; +}; + +const REJECTED_CAP = 5_000; +const HEARTBEAT_MS = 24 * 3_600_000; +const LOCK = 'lock'; +const RUN = 'run'; +const LOCK_TTL_MS = 30 * 60_000; + +type Rejected = Record; + +const EMPTY_OUTCOME = (status: SyncOutcome['status']): SyncOutcome => ({ + status, + advisoriesWritten: 0, + advisoriesDeleted: 0, + matchesWritten: 0, + events: 0, + errors: {}, +}); + +function sourceState(id: string, row: FeedStateRow | undefined | null): FeedSourceState { + return { + id, + cursor: row?.cursor ?? null, + etag: row?.etag ?? null, + lastModifiedHeader: row?.lastModifiedHeader ?? null, + lastRunAt: row?.lastRunAt ?? null, + lastSuccessAt: row?.lastSuccessAt ?? null, + lastError: row?.lastError ?? null, + lastErrorAt: row?.lastErrorAt ?? null, + itemsLastRun: row?.itemsLastRun ?? null, + }; +} + +const CVE_ID = /^CVE-\d{4}-\d+$/i; + +export class CveFeedRuntime { + private readonly now: () => number; + private readonly holder: string; + private readonly lockTtlMs: number; + private running: Promise | null = null; + private timers: ReturnType[] = []; + private started = false; + /** Last KEV set a source returned: reused when KEV is down on a later run. */ + private kev: ReadonlyMap = new Map(); + private readonly status = new Map(); + private lastRun: { at: string; durationMs: number } | null = null; + + constructor(private readonly deps: CveFeedRuntimeDeps) { + this.now = deps.now ?? Date.now; + this.holder = deps.holder ?? `${hostname()}-${process.pid}-${randomUUID().slice(0, 8)}`; + this.lockTtlMs = deps.lockTtlMs ?? LOCK_TTL_MS; + } + + get enabled(): boolean { + return this.deps.config.enabled; + } + + /** Starts the timers; with the feed disabled nothing is scheduled and nothing is fetched. */ + async start(options: { timers?: boolean } = {}): Promise { + if (this.started || !this.enabled) return; + this.started = true; + if (options.timers === false) return; + const { intervalMs } = this.deps.config; + this.timers.push( + setTimeout(() => void this.syncOnce().catch(() => {}), this.deps.startDelayMs ?? 30_000), + setInterval(() => void this.syncOnce().catch(() => {}), intervalMs), + setInterval( + () => void this.syncIfRequested().catch(() => {}), + this.deps.requestPollMs ?? 60_000, + ), + ); + for (const timer of this.timers) timer.unref?.(); + } + + async stop(): Promise { + for (const timer of this.timers) { + clearTimeout(timer as ReturnType); + clearInterval(timer as ReturnType); + } + this.timers = []; + this.started = false; + await this.running?.catch(() => {}); + // hand the lease over right away when it is ours + const lock = await this.deps.store.getState(LOCK).catch(() => null); + if (lock?.holder === this.holder) { + await this.deps.store + .saveState(LOCK, { holder: null, expiresAt: new Date(this.now()).toISOString() }) + .catch(() => {}); + } + } + + /** "Sincronizar ahora": records the request; the next poll (of any instance) runs it. */ + async requestSync(): Promise { + if (!this.enabled) return false; + await this.deps.store.saveState(RUN, { requestedAt: new Date(this.now()).toISOString() }); + return true; + } + + async syncIfRequested(): Promise { + const run = await this.deps.store.getState(RUN); + if (run?.requestedAt && run.requestedAt !== run.handledRequestedAt) { + await this.syncOnce({ requestedAt: run.requestedAt }); + } + } + + /** Status of each source: the in-memory run data over what is persisted. */ + async sourceStatuses(): Promise { + const rows = await this.deps.store.listStates(); + return this.deps.sources.map((source) => { + const persisted = sourceState(source.id, rows.get(source.id)); + const live = this.status.get(source.id); + return live ? { ...live, cursor: persisted.cursor } : persisted; + }); + } + + lastRunInfo(): { at: string | null; durationMs: number | null } { + return { at: this.lastRun?.at ?? null, durationMs: this.lastRun?.durationMs ?? null }; + } + + syncOnce(options: { requestedAt?: string; force?: boolean } = {}): Promise { + if (!this.enabled) return Promise.resolve(EMPTY_OUTCOME('disabled')); + this.running ??= this.run(options).finally(() => { + this.running = null; + }); + return this.running; + } + + // ─── lease ──────────────────────────────────────────────────────────────── + + /** + * Best effort across instances sharing the repository: read the lock, write ours if it is free + * or expired, read it back and proceed only if it is still ours. Two instances that race can + * both read "free"; the later write wins and the earlier one finds out on the read-back (after + * a GitDB sync the loser may still run once; every write is idempotent, so that is harmless). + */ + private async acquireLease(): Promise { + const { store } = this.deps; + const now = this.now(); + const current = await store.getState(LOCK); + if ( + current?.holder && + current.holder !== this.holder && + current.expiresAt && + Date.parse(current.expiresAt) > now + ) { + return false; + } + await store.saveState(LOCK, { + holder: this.holder, + acquiredAt: new Date(now).toISOString(), + expiresAt: new Date(now + this.lockTtlMs).toISOString(), + }); + return (await store.getState(LOCK))?.holder === this.holder; + } + + private async renewLease(): Promise { + const now = this.now(); + const lock = await this.deps.store.getState(LOCK); + if (lock?.holder !== this.holder) throw new Error('lease lost'); + if (lock.expiresAt && Date.parse(lock.expiresAt) - now > this.lockTtlMs / 2) return; + await this.deps.store.saveState(LOCK, { + expiresAt: new Date(now + this.lockTtlMs).toISOString(), + }); + } + + // ─── one sync ───────────────────────────────────────────────────────────── + + private async run(options: { requestedAt?: string; force?: boolean }): Promise { + const { store, config, logger } = this.deps; + const startedMs = this.now(); + const now = new Date(startedMs).toISOString(); + + try { + const watchlists = await this.deps.watchlists.listAll(); + const targets = unionTargets(watchlists); + const [stored, existingMatches] = await Promise.all([ + store.listAdvisories(), + store.listMatches(), + ]); + if (targets.length === 0 && stored.length === 0 && existingMatches.length === 0) { + return EMPTY_OUTCOME('no_targets'); + } + + const lock = await store.getState(LOCK); + // a scheduled run right after another instance's run is not needed + if ( + !options.force && + !options.requestedAt && + lock?.acquiredAt && + startedMs - Date.parse(lock.acquiredAt) < config.intervalMs * 0.9 + ) { + return EMPTY_OUTCOME('not_due'); + } + if (!(await this.acquireLease())) { + logger.debug('[cve-feed] another instance holds the lease'); + return EMPTY_OUTCOME('locked'); + } + + const outcome = EMPTY_OUTCOME('done'); + const runRow = await store.getState(RUN); + const backfilled: Record = { ...(runRow?.backfilledTechnologies ?? {}) }; + const technologyIds = [...new Set(targets.map((target) => target.technologyId))]; + const newTechs = new Set(technologyIds.filter((tech) => !backfilled[tech])); + + const retentionCutoff = new Date(startedMs - config.retentionMs).toISOString(); + const backfillMs = Math.min(config.backfillMs, config.retentionMs); + // a new technology looks back `backfillMs`; a backfilled one never goes further back than its + // own backfill did, so an old advisory first seen later is not mistaken for a new one + const cutoffFor = (tech: string): string => { + if (newTechs.has(tech)) return new Date(startedMs - backfillMs).toISOString(); + const since = backfilled[tech] + ? new Date(Date.parse(backfilled[tech]) - backfillMs).toISOString() + : retentionCutoff; + return since > retentionCutoff ? since : retentionCutoff; + }; + + // ── sources ── + const states = await store.listStates(); + const osvRow = states.get('osv'); + const rejected: Rejected = { + ...((osvRow?.cursor as { rejected?: Rejected } | null)?.rejected ?? {}), + }; + const candidates: SourceCandidate[] = []; + const succeeded = new Set(); + const epss = new Map(); + const persistPatches: Array<{ id: CveSourceId; row: FeedSourceState }> = []; + const byId = new Map(stored.map((advisory) => [advisory.id, advisory])); + + for (const source of this.deps.sources) { + const previous = sourceState(source.id, states.get(source.id)); + const live: FeedSourceState = { ...previous, lastRunAt: now }; + try { + await this.renewLease(); + const result = await source.sync({ + targets, + now: new Date(startedMs), + cutoffFor, + known: this.knownMap(stored, rejected), + stored, + state: previous, + }); + if (result.kev) this.kev = result.kev; + for (const [cve, value] of result.epss ?? []) epss.set(cve.toUpperCase(), value); + for (const candidate of result.candidates ?? []) candidates.push(candidate); + live.itemsLastRun = result.items; + if (result.partialError) { + live.lastError = result.partialError; + live.lastErrorAt = now; + outcome.errors[source.id] = result.partialError; + } else { + live.lastError = null; + live.lastErrorAt = null; + live.lastSuccessAt = now; + succeeded.add(source.id); + } + if (result.statePatch) Object.assign(live, result.statePatch); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + logger.warn({ err: error, source: source.id }, `[cve-feed] ${source.id} failed`); + live.lastError = message; + live.lastErrorAt = now; + outcome.errors[source.id] = message; + } + this.status.set(source.id, live); + persistPatches.push({ id: source.id, row: live }); + } + + // ── merge candidates (same advisory from several sources/ids) ── + const merged = this.mergeCandidates(candidates); + + // ── apply to the stored set ── + const current = new Map(stored.map((advisory) => [advisory.id, advisory])); + const aliasIndex = new Map(); + for (const advisory of stored) + for (const key of [advisory.id, ...advisory.aliases]) aliasIndex.set(key, advisory.id); + const changed = new Set(); + const filter = { minSeverity: config.minSeverity, epssThreshold: config.epssThreshold }; + + for (const group of merged) { + const storedId = [group.advisory.id, ...group.advisory.aliases] + .map((key) => aliasIndex.get(key)) + .find(Boolean); + const previous = storedId ? byId.get(storedId) : undefined; + const base = this.combine(group.advisory, previous); + const cves = [base.id, ...base.aliases].filter((key) => CVE_ID.test(key)); + const kevKey = cves.find((key) => this.kev.has(key.toUpperCase())); + const next = buildAdvisory( + base, + { + kev: previous?.kev || Boolean(kevKey), + kevAddedAt: + previous?.kevAddedAt ?? (kevKey ? this.kev.get(kevKey.toUpperCase()) || null : null), + epssScore: previous?.epssScore, + epssPercentile: previous?.epssPercentile, + epssUpdatedAt: previous?.epssUpdatedAt, + firstSeenAt: previous?.firstSeenAt, + }, + now, + ); + if (previous && previous.fingerprint === next.fingerprint) continue; + if (previous || passesFilter(next, filter)) { + current.set(next.id, next); + changed.add(next.id); + for (const key of [next.id, ...next.aliases]) aliasIndex.set(key, next.id); + } else { + for (const key of group.keys) { + rejected[key] = { + m: group.advisory.modifiedAt, + c: [group.advisory.id, ...group.advisory.aliases].filter((id) => CVE_ID.test(id)), + }; + } + } + } + + // KEV: stored advisories that entered the catalog since + for (const advisory of [...current.values()]) { + if (advisory.kev) continue; + const key = [advisory.id, ...advisory.aliases].find( + (id) => CVE_ID.test(id) && this.kev.has(id.toUpperCase()), + ); + if (!key) continue; + const next = withEnrichment( + advisory, + { kev: true, kevAddedAt: this.kev.get(key.toUpperCase()) || null }, + now, + ); + if (next.fingerprint !== advisory.fingerprint) { + current.set(next.id, next); + changed.add(next.id); + } + } + + // EPSS: stored advisories with a fresh score. Written only when the fingerprint moves (the + // score rounded to 0.01 crossed, or the advisory is written anyway): `epssUpdatedAt` and the + // percentile are not part of it, and the source remembers on its own what it asked today + if (epss.size > 0) { + for (const advisory of [...current.values()]) { + const cve = [advisory.id, ...advisory.aliases].find( + (id) => CVE_ID.test(id) && epss.has(id.toUpperCase()), + ); + if (!cve) continue; + const value = epss.get(cve.toUpperCase())!; + const next = withEnrichment( + advisory, + { epssScore: value.score, epssPercentile: value.percentile, epssUpdatedAt: now }, + now, + ); + if (changed.has(advisory.id) || next.fingerprint !== advisory.fingerprint) { + current.set(next.id, next); + changed.add(next.id); + } + } + } + + // retention + const purged = [...current.values()].filter( + (advisory) => advisory.modifiedAt < retentionCutoff, + ); + for (const advisory of purged) { + current.delete(advisory.id); + changed.delete(advisory.id); + } + + const upsert = [...changed].map((id) => current.get(id)!); + const deleteIds = purged + .filter((advisory) => byId.has(advisory.id)) + .map((advisory) => advisory.id); + if (upsert.length > 0 || deleteIds.length > 0) + await store.applyAdvisories({ upsert, deleteIds }); + outcome.advisoriesWritten = upsert.length; + outcome.advisoriesDeleted = deleteIds.length; + + // ── matching, dedup, publish ── + const plan = planMatches({ + watchlists, + advisories: [...current.values()], + existing: existingMatches, + backfillTechs: newTechs, + epssThreshold: config.epssThreshold, + now, + scans: await this.loadScans(watchlists, current.size), + }); + if (plan.upsert.length > 0 || plan.deleteIds.length > 0) { + await store.applyMatches({ upsert: plan.upsert, deleteIds: plan.deleteIds }); + } + outcome.matchesWritten = plan.upsert.length; + // the match state is durable: only now can the events go out + outcome.events = await this.publish(plan.events); + + // ── bookkeeping ── + const newlyBackfilled = this.backfilledNow(targets, newTechs, succeeded); + for (const tech of newlyBackfilled) backfilled[tech] = now; + for (const tech of Object.keys(backfilled)) + if (!technologyIds.includes(tech)) delete backfilled[tech]; + + const prunedRejected = this.pruneRejected(rejected, retentionCutoff); + for (const { id, row } of persistPatches) { + const previous = states.get(id); + const patch = this.durableStatePatch( + row, + previous, + id === 'osv' ? prunedRejected : undefined, + startedMs, + ); + if (patch) await store.saveState(id, patch); + } + + const durationMs = this.now() - startedMs; + this.lastRun = { at: now, durationMs }; + const backfillChanged = + JSON.stringify(backfilled) !== JSON.stringify(runRow?.backfilledTechnologies ?? {}); + const runPatch: FeedStateRow = {}; + if (backfillChanged) runPatch.backfilledTechnologies = backfilled; + if (options.requestedAt) runPatch.handledRequestedAt = options.requestedAt; + const lastRunPersisted = runRow?.lastRunAt ? Date.parse(runRow.lastRunAt) : 0; + if (startedMs - lastRunPersisted > HEARTBEAT_MS) { + runPatch.lastRunAt = now; + runPatch.lastDurationMs = durationMs; + } + if (Object.keys(runPatch).length > 0) await store.saveState(RUN, runPatch); + + if (outcome.advisoriesWritten + outcome.advisoriesDeleted + outcome.matchesWritten > 0) { + this.deps.onChanged?.(); + } + logger.info( + { + advisoriesWritten: outcome.advisoriesWritten, + advisoriesDeleted: outcome.advisoriesDeleted, + matchesWritten: outcome.matchesWritten, + events: outcome.events, + errors: Object.keys(outcome.errors), + durationMs, + }, + '[cve-feed] sync finished', + ); + return outcome; + } catch (error) { + logger.error({ err: error }, '[cve-feed] sync failed'); + throw error; + } + } + + // ─── helpers ────────────────────────────────────────────────────────────── + + private knownMap(stored: readonly CveAdvisory[], rejected: Rejected): Map { + const known = new Map(); + // rejected by the filter: skipped while unchanged, unless it has since entered KEV + for (const [key, entry] of Object.entries(rejected)) { + if (entry.c.some((cve) => this.kev.has(cve.toUpperCase()))) continue; + known.set(key, { modifiedAt: entry.m, technologyIds: null }); + } + for (const advisory of stored) { + for (const key of [advisory.id, ...advisory.aliases]) { + known.set(key, { modifiedAt: advisory.modifiedAt, technologyIds: advisory.technologyIds }); + } + } + return known; + } + + /** Candidates that are the same advisory (any shared id or alias) become one. */ + private mergeCandidates( + candidates: readonly SourceCandidate[], + ): Array<{ advisory: NormalizedAdvisory; keys: string[] }> { + const groups: Array<{ advisory: NormalizedAdvisory; keys: string[] }> = []; + for (const candidate of candidates) { + const ids = new Set([candidate.advisory.id, ...candidate.advisory.aliases]); + const group = groups.find((item) => + [item.advisory.id, ...item.advisory.aliases].some((id) => ids.has(id)), + ); + if (group) { + group.advisory = mergeAdvisories(group.advisory, candidate.advisory); + group.keys.push(candidate.key); + } else { + groups.push({ advisory: candidate.advisory, keys: [candidate.key] }); + } + } + return groups; + } + + /** + * A fresh fetch against what is stored: when it comes from every source the row already has it + * replaces the row (so removed ranges and references go away); otherwise it is merged into it. + * The stored id never changes. + */ + private combine( + fresh: NormalizedAdvisory, + previous: CveAdvisory | undefined, + ): NormalizedAdvisory { + if (!previous) return fresh; + const renamed: NormalizedAdvisory = { + ...fresh, + id: previous.id, + aliases: [...new Set([fresh.id, ...fresh.aliases])].filter((id) => id !== previous.id), + }; + if (previous.sources.every((source) => fresh.sources.includes(source))) return renamed; + return mergeAdvisories(renamed, { + id: previous.id, + aliases: previous.aliases, + title: previous.title, + summary: previous.summary, + details: previous.details, + severity: previous.severity, + cvssScore: previous.cvssScore, + cvssVector: previous.cvssVector, + cwe: previous.cwe, + technologyIds: previous.technologyIds, + affected: previous.affected, + fixedVersions: previous.fixedVersions, + references: previous.references, + sources: previous.sources, + publishedAt: previous.publishedAt, + modifiedAt: previous.modifiedAt, + }); + } + + /** A technology counts as backfilled once every source that can look it up has answered. */ + private backfilledNow( + targets: readonly { technologyId: string; kind: 'osv' | 'cpe' }[], + newTechs: ReadonlySet, + succeeded: ReadonlySet, + ): string[] { + const done: string[] = []; + for (const tech of newTechs) { + const kinds = targets + .filter((target) => target.technologyId === tech) + .map((target) => target.kind); + const covered = kinds.every((kind) => + this.deps.sources.some((source) => source.kinds.includes(kind) && succeeded.has(source.id)), + ); + if (covered) done.push(tech); + } + return done; + } + + private pruneRejected(rejected: Rejected, cutoff: string): Rejected { + const entries = Object.entries(rejected).filter(([, value]) => value.m >= cutoff); + entries.sort((a, b) => b[1].m.localeCompare(a[1].m)); + return Object.fromEntries(entries.slice(0, REJECTED_CAP)); + } + + /** + * What of a source's state is worth a commit: a changed cursor, etag, last-modified or error, + * or the daily heartbeat. The last run time and item count stay in memory otherwise. + */ + private durableStatePatch( + live: FeedSourceState, + previous: FeedStateRow | undefined, + rejected: Rejected | undefined, + nowMs: number, + ): FeedStateRow | null { + const cursor = rejected === undefined ? live.cursor : { rejected }; + const changed = + JSON.stringify(cursor ?? null) !== JSON.stringify(previous?.cursor ?? null) || + (live.etag ?? null) !== (previous?.etag ?? null) || + (live.lastModifiedHeader ?? null) !== (previous?.lastModifiedHeader ?? null) || + (live.lastError ?? null) !== (previous?.lastError ?? null); + const stale = + nowMs - (previous?.lastSuccessAt ? Date.parse(previous.lastSuccessAt) : 0) > HEARTBEAT_MS; + if (!changed && !(stale && live.lastSuccessAt)) return null; + return { + cursor: cursor ?? null, + etag: live.etag, + lastModifiedHeader: live.lastModifiedHeader, + lastRunAt: live.lastRunAt, + lastSuccessAt: live.lastSuccessAt, + lastError: live.lastError, + lastErrorAt: live.lastErrorAt, + itemsLastRun: live.itemsLastRun, + }; + } + + /** The scan index of every organization that follows something; one that fails is skipped. */ + private async loadScans( + watchlists: readonly { organizationId: string; technologies: readonly unknown[] }[], + advisories: number, + ): Promise | undefined> { + const { scans, logger } = this.deps; + if (!scans || advisories === 0) return undefined; + const index = new Map(); + for (const watchlist of watchlists) { + if (watchlist.technologies.length === 0) continue; + try { + index.set(watchlist.organizationId, await scans.occurrences(watchlist.organizationId)); + } catch (error) { + logger.warn( + { err: error, organizationId: watchlist.organizationId }, + '[cve-feed] could not read the scans of an organization', + ); + } + } + return index; + } + + private async publish(planned: readonly PlannedEvent[]): Promise { + const { events, logger } = this.deps; + if (!events || planned.length === 0) return 0; + const slugs = new Map(); + let sent = 0; + for (const event of planned) { + if (!slugs.has(event.organizationId)) { + slugs.set( + event.organizationId, + (await this.deps.organizationSlug?.(event.organizationId).catch(() => null)) ?? null, + ); + } + const slug = slugs.get(event.organizationId); + const { advisory, technologyId } = event; + const affected = advisory.affected.find((item) => item.technologyId === technologyId); + const path = slug + ? `/org/${slug}/cves/${encodeURIComponent(advisory.id)}?tab=technology` + : `/cves/${encodeURIComponent(advisory.id)}`; + const payload: DomainEventMap['cve_feed.advisory.published'] = { + cveId: advisory.id, + aliases: advisory.aliases, + title: advisory.title, + severity: advisory.severity, + cvssScore: advisory.cvssScore, + epssScore: advisory.epssScore, + kev: advisory.kev, + technologyId, + ecosystem: affected?.ecosystem ?? null, + package: affected?.package ?? null, + fixedVersions: advisory.fixedVersions, + sources: advisory.sources, + url: this.deps.absoluteUrl?.(path) ?? path, + }; + if (event.kind === 'affects_project') { + await publishAfterWrite( + events, + logger, + 'cve_feed.advisory.affects_project', + { ...payload, projectId: event.projectId!, serviceIds: event.serviceIds ?? [] }, + { organizationId: event.organizationId, projectId: event.projectId! }, + ); + } else { + await publishAfterWrite(events, logger, `cve_feed.advisory.${event.kind}`, payload, { + organizationId: event.organizationId, + projectId: null, + }); + } + sent++; + } + return sent; + } +} diff --git a/src/modules/cve-feed/application/cve-watchlist.service.test.ts b/src/modules/cve-feed/application/cve-watchlist.service.test.ts new file mode 100644 index 0000000..9e47d6a --- /dev/null +++ b/src/modules/cve-feed/application/cve-watchlist.service.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest'; +import { CveWatchlistValidationError } from '../domain/watchlist'; +import type { CveWatchlist } from '../domain/types'; +import { CveWatchlistService, type WatchlistStore } from './cve-watchlist.service'; + +function setup() { + const rows = new Map(); + let saves = 0; + const changes: Array<{ organizationId: string; added: string[] }> = []; + const store: WatchlistStore = { + findByOrganization: async (id) => rows.get(id) ?? null, + save: async (organizationId, write, now) => { + saves++; + const saved: CveWatchlist = { + id: `wl-${organizationId}`, + organizationId, + ...write, + updatedAt: now, + }; + rows.set(organizationId, saved); + return saved; + }, + }; + let clock = Date.parse('2026-11-01T00:00:00Z'); + const service = new CveWatchlistService({ + store, + now: () => new Date((clock += 1000)), + onChanged: (organizationId, { addedTechnologies }) => + changes.push({ organizationId, added: addedTechnologies }), + }); + return { service, saves: () => saves, changes }; +} + +const input = (technologies: string[], extra = {}) => ({ + technologies: technologies.map((technologyId) => ({ technologyId })), + minSeverity: 'high', + includeKev: true, + ...extra, +}); + +describe('CveWatchlistService', () => { + it('returns an empty default without writing anything', async () => { + const { service, saves } = setup(); + expect(await service.get('org-1')).toMatchObject({ + id: null, + technologies: [], + minSeverity: 'high', + includeKev: true, + }); + expect(saves()).toBe(0); + }); + + it('saves, reports the added technologies and keeps addedAt of existing ones', async () => { + const { service, changes } = setup(); + const first = await service.update('org-1', input(['lodash']), 'user-1'); + const second = await service.update('org-1', input(['lodash', 'redis']), 'user-1'); + expect(second.technologies[0].addedAt).toBe(first.technologies[0].addedAt); + expect(second.technologies[1].addedAt > first.technologies[0].addedAt).toBe(true); + expect(changes).toEqual([ + { organizationId: 'org-1', added: ['lodash'] }, + { organizationId: 'org-1', added: ['redis'] }, + ]); + expect(second.updatedBy).toBe('user-1'); + }); + + it('does not write when nothing changed, nor for an empty first save', async () => { + const { service, saves, changes } = setup(); + await service.update('org-1', input([]), 'user-1'); + expect(saves()).toBe(0); + await service.update('org-1', input(['lodash']), 'user-1'); + await service.update('org-1', input(['lodash']), 'user-1'); + expect(saves()).toBe(1); + expect(changes).toHaveLength(1); + }); + + it('removing a technology saves but adds nothing to backfill', async () => { + const { service, changes } = setup(); + await service.update('org-1', input(['lodash', 'redis']), null); + await service.update('org-1', input(['redis']), null); + expect(changes.at(-1)).toEqual({ organizationId: 'org-1', added: [] }); + }); + + it('rejects invalid input', async () => { + const { service } = setup(); + await expect(service.update('org-1', input(['made-up']), null)).rejects.toBeInstanceOf( + CveWatchlistValidationError, + ); + await expect( + service.update('org-1', input(['lodash'], { minSeverity: 'nope' }), null), + ).rejects.toBeInstanceOf(CveWatchlistValidationError); + }); + + it('has no suggestions until the SBOM correlation is wired', async () => { + const { service } = setup(); + expect(await service.suggestions('org-1')).toEqual([]); + }); +}); diff --git a/src/modules/cve-feed/application/cve-watchlist.service.ts b/src/modules/cve-feed/application/cve-watchlist.service.ts new file mode 100644 index 0000000..65ffa95 --- /dev/null +++ b/src/modules/cve-feed/application/cve-watchlist.service.ts @@ -0,0 +1,82 @@ +import { emptyWatchlist, normalizeWatchlistInput, type WatchlistInput } from '../domain/watchlist'; +import type { WatchlistSuggestion } from '../domain/suggestions'; +import type { CveWatchlist, WatchlistEntry } from '../domain/types'; +import type { WatchlistWrite } from '../infrastructure/repositories/watchlist.repository'; + +export type WatchlistStore = { + findByOrganization(organizationId: string): Promise; + save(organizationId: string, write: WatchlistWrite, now: string): Promise; +}; + +export type { WatchlistSuggestion }; + +export type CveWatchlistServiceDeps = { + store: WatchlistStore; + now?: () => Date; + /** Called after a change that matters to the feed (cache, and a sync when technologies were added). */ + onChanged?: (organizationId: string, change: { addedTechnologies: string[] }) => void; + /** Suggestions from the SBOM/Trivy packages of the organization (`WatchlistSuggester`). */ + suggest?: ( + organizationId: string, + followed: ReadonlySet, + ) => Promise; +}; + +type Content = Pick; + +function sameContent(a: Content, b: Content): boolean { + return ( + a.minSeverity === b.minSeverity && + a.includeKev === b.includeKev && + JSON.stringify(a.technologies) === JSON.stringify(b.technologies) + ); +} + +export class CveWatchlistService { + constructor(private readonly deps: CveWatchlistServiceDeps) {} + + /** The organization's watchlist; an empty default (nothing stored) when it never set one. */ + async get(organizationId: string): Promise { + return ( + (await this.deps.store.findByOrganization(organizationId)) ?? emptyWatchlist(organizationId) + ); + } + + /** + * Replaces the watchlist. Throws `CveWatchlistValidationError` for invalid input. Nothing is + * written when the result equals what is stored. + */ + async update( + organizationId: string, + input: WatchlistInput, + userId: string | null, + ): Promise { + const current = await this.get(organizationId); + const now = (this.deps.now?.() ?? new Date()).toISOString(); + const normalized = normalizeWatchlistInput(input, current.technologies, now); + if (current.id && sameContent(current, normalized)) return current; + if (!current.id && normalized.technologies.length === 0) return current; + + const saved = await this.deps.store.save( + organizationId, + { ...normalized, updatedBy: userId }, + now, + ); + const before = new Set(current.technologies.map((entry: WatchlistEntry) => entry.technologyId)); + this.deps.onChanged?.(organizationId, { + addedTechnologies: saved.technologies + .map((entry) => entry.technologyId) + .filter((id) => !before.has(id)), + }); + return saved; + } + + async suggestions(organizationId: string): Promise { + if (!this.deps.suggest) return []; + const watchlist = await this.get(organizationId); + return this.deps.suggest( + organizationId, + new Set(watchlist.technologies.map((entry) => entry.technologyId)), + ); + } +} diff --git a/src/modules/cve-feed/application/ports.ts b/src/modules/cve-feed/application/ports.ts new file mode 100644 index 0000000..dbfbd64 --- /dev/null +++ b/src/modules/cve-feed/application/ports.ts @@ -0,0 +1,114 @@ +import type { + CveAdvisory, + CveSourceId, + CveWatchlist, + FeedSourceState, + LockState, + NormalizedAdvisory, + OrgMatch, + RunState, + WatchTarget, +} from '../domain/types'; + +/** An advisory a source fetched, with the source-native key used for its "rejected" bookkeeping. */ +export type SourceCandidate = { key: string; advisory: NormalizedAdvisory }; + +/** What the runtime already knows about an id or alias, so sources skip what has not changed. */ +export type KnownAdvisory = { + modifiedAt: string; + /** technologies the stored advisory is tied to; `null` for an advisory the filter rejected */ + technologyIds: readonly string[] | null; +}; + +export type SourceContext = { + targets: readonly WatchTarget[]; + now: Date; + /** Earliest `modifiedAt` worth keeping for a technology (retention, or the backfill window). */ + cutoffFor: (technologyId: string) => string; + known: ReadonlyMap; + /** Stored advisories, for sources that enrich them (EPSS). */ + stored: readonly CveAdvisory[]; + state: FeedSourceState; +}; + +export type SourceResult = { + candidates?: SourceCandidate[]; + /** The complete KEV set: CVE id -> date added. */ + kev?: ReadonlyMap; + epss?: ReadonlyMap; + /** Persisted on success only. */ + statePatch?: Partial>; + items: number; + /** The source got part of what it wanted: what it has is used and the error is recorded. */ + partialError?: string; +}; + +/** A public feed (OSV, CISA KEV, later NVD and EPSS). Sources never write: the runtime does. */ +export interface CveSource { + readonly id: CveSourceId; + /** Which watch targets this source can look up; none for pure enrichment sources. */ + readonly kinds: readonly WatchTarget['kind'][]; + sync(context: SourceContext): Promise; +} + +export type FeedStateRow = Partial> & + Partial & + Partial> & { + backfilledTechnologies?: Record | null; + }; + +export type AdvisoryWrite = { upsert: CveAdvisory[]; deleteIds: string[] }; +export type MatchWrite = { upsert: OrgMatch[]; deleteIds: string[] }; + +/** Storage of the feed tables (the dedicated GitDB repository when configured). */ +export interface CveFeedStore { + listAdvisories(): Promise; + /** At most one delete and one insert, whatever the number of rows. */ + applyAdvisories(write: AdvisoryWrite): Promise; + listMatches(): Promise; + applyMatches(write: MatchWrite): Promise; + listStates(): Promise>; + getState(id: string): Promise; + /** Merges `patch` into the row (creating it). */ + saveState(id: string, patch: FeedStateRow): Promise; +} + +/** Watchlists of every organization (main GitDB). */ +export interface WatchlistSource { + listAll(): Promise; +} + +export type ProjectRef = { id: string; slug: string; name: string }; + +/** A service whose latest completed scan reports a CVE. */ +export type ScanRef = { + projectId: string; + projectSlug: string; + projectName: string; + serviceId: string; + serviceSlug: string; + serviceName: string; +}; + +/** CVE id (upper-case) -> the services whose latest scans report it. */ +export type ScanOccurrences = Map; + +/** Scan data of one organization for the runtime: every active project, no user involved. */ +export interface OrganizationScans { + occurrences(organizationId: string): Promise; +} + +/** Scan data of the projects a user may see, for the pages. */ +export interface ProjectScans { + occurrences(projects: readonly ProjectRef[]): Promise; +} + +/** The distinct packages of the latest scans of each service of an organization (Trivy, SBOM). */ +export type ServicePackages = { + serviceId: string; + packages: Array<{ ecosystem: string; name: string }>; +}; + +export interface OrganizationPackages { + packages(organizationId: string): Promise; +} diff --git a/src/modules/cve-feed/application/testing.ts b/src/modules/cve-feed/application/testing.ts new file mode 100644 index 0000000..be751c0 --- /dev/null +++ b/src/modules/cve-feed/application/testing.ts @@ -0,0 +1,114 @@ +import type { Logger } from 'pino'; +import type { CveAdvisory, CveWatchlist, OrgMatch, WatchTarget } from '../domain/types'; +import type { + AdvisoryWrite, + CveFeedStore, + CveSource, + FeedStateRow, + MatchWrite, + SourceContext, + SourceResult, + WatchlistSource, +} from './ports'; +import type { CveFeedConfig } from './cve-feed-runtime'; +import type { WatchlistEntry } from '../domain/types'; + +export const silentLogger = { info() {}, warn() {}, error() {}, debug() {} } as unknown as Pick< + Logger, + 'info' | 'warn' | 'error' | 'debug' +>; + +/** In-memory feed store that counts the writes it receives, per table. */ +export class InMemoryCveFeedStore implements CveFeedStore { + advisories = new Map(); + matches = new Map(); + states = new Map(); + writes = { advisories: 0, matches: 0, state: 0, lock: 0 }; + + async listAdvisories() { + return [...this.advisories.values()].map((row) => structuredClone(row)); + } + async applyAdvisories({ upsert, deleteIds }: AdvisoryWrite) { + if (upsert.length === 0 && deleteIds.length === 0) return; + this.writes.advisories++; + for (const id of deleteIds) this.advisories.delete(id); + for (const row of upsert) this.advisories.set(row.id, structuredClone(row)); + } + async listMatches() { + return [...this.matches.values()].map((row) => structuredClone(row)); + } + async applyMatches({ upsert, deleteIds }: MatchWrite) { + if (upsert.length === 0 && deleteIds.length === 0) return; + this.writes.matches++; + for (const id of deleteIds) this.matches.delete(id); + for (const row of upsert) this.matches.set(row.id, structuredClone(row)); + } + async listStates() { + return new Map([...this.states].map(([id, row]) => [id, structuredClone(row)])); + } + async getState(id: string) { + const row = this.states.get(id); + return row ? structuredClone(row) : null; + } + async saveState(id: string, patch: FeedStateRow) { + this.writes[id === 'lock' ? 'lock' : 'state']++; + this.states.set(id, { ...this.states.get(id), ...structuredClone(patch) }); + } +} + +export class InMemoryWatchlists implements WatchlistSource { + rows: CveWatchlist[] = []; + async listAll() { + return structuredClone(this.rows); + } +} + +export function watchlist( + organizationId: string, + technologyIds: string[], + options: { + addedAt?: string; + minSeverity?: CveWatchlist['minSeverity']; + includeKev?: boolean; + } = {}, +): CveWatchlist { + const addedAt = options.addedAt ?? '2026-01-01T00:00:00.000Z'; + return { + id: `wl-${organizationId}`, + organizationId, + technologies: technologyIds.map((technologyId): WatchlistEntry => ({ technologyId, addedAt })), + minSeverity: options.minSeverity ?? 'high', + includeKev: options.includeKev ?? true, + updatedAt: addedAt, + updatedBy: null, + }; +} + +/** A source that returns what the test put in it, or throws. */ +export class FakeSource implements CveSource { + calls = 0; + contexts: SourceContext[] = []; + result: SourceResult = { items: 0 }; + error: Error | null = null; + + constructor( + readonly id: CveSource['id'], + readonly kinds: readonly WatchTarget['kind'][] = [], + ) {} + + async sync(context: SourceContext): Promise { + this.calls++; + this.contexts.push(context); + if (this.error) throw this.error; + return this.result; + } +} + +export const testConfig: CveFeedConfig = { + enabled: true, + intervalMs: 2 * 3_600_000, + minSeverity: 'high', + epssThreshold: 0.5, + retentionMs: 180 * 86_400_000, + backfillMs: 30 * 86_400_000, +}; diff --git a/src/modules/cve-feed/application/watchlist-suggester.test.ts b/src/modules/cve-feed/application/watchlist-suggester.test.ts new file mode 100644 index 0000000..0c7eb3e --- /dev/null +++ b/src/modules/cve-feed/application/watchlist-suggester.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, it } from 'vitest'; +import { WatchlistSuggester } from './watchlist-suggester'; +import { CveWatchlistService } from './cve-watchlist.service'; +import type { OrganizationPackages, ServicePackages } from './ports'; +import type { CveWatchlist } from '../domain/types'; + +function source(byOrganization: Record) { + const calls: string[] = []; + const port: OrganizationPackages = { + async packages(organizationId) { + calls.push(organizationId); + return byOrganization[organizationId] ?? []; + }, + }; + return { port, calls }; +} + +const express4 = Array.from({ length: 4 }, (_, i) => ({ + serviceId: `svc-${i}`, + packages: [ + { ecosystem: 'npm', name: 'express' }, + { ecosystem: 'npm', name: 'left-pad' }, + ], +})); + +describe('WatchlistSuggester', () => { + it('suggests the technologies of the scans, with the services that use them', async () => { + const { port } = source({ 'org-1': express4 }); + const suggestions = await new WatchlistSuggester({ packages: port }).suggest( + 'org-1', + new Set(), + ); + expect(suggestions).toEqual([ + { technologyId: 'express', name: 'Express', package: 'express', services: 4 }, + expect.objectContaining({ + technologyId: 'custom:osv:npm:left-pad', + custom: { kind: 'osv', ecosystem: 'npm', package: 'left-pad' }, + services: 4, + }), + ]); + }); + + it('memoizes the ranking per organization; excluding the followed runs every call', async () => { + const { port, calls } = source({ 'org-1': express4, 'org-2': [] }); + const suggester = new WatchlistSuggester({ packages: port }); + expect(await suggester.suggest('org-1', new Set())).toHaveLength(2); + expect(await suggester.suggest('org-1', new Set(['express']))).toHaveLength(1); + expect( + await suggester.suggest('org-1', new Set(['express', 'custom:osv:npm:left-pad'])), + ).toEqual([]); + await suggester.suggest('org-2', new Set()); + expect(calls).toEqual(['org-1', 'org-2']); + + suggester.invalidate('org-1'); // a new analysis arrived + await suggester.suggest('org-1', new Set()); + await suggester.suggest('org-2', new Set()); + expect(calls).toEqual(['org-1', 'org-2', 'org-1']); + }); + + it('does not remember a failure', async () => { + let fail = true; + const suggester = new WatchlistSuggester({ + packages: { + async packages() { + if (fail) throw new Error('GitDB down'); + return express4; + }, + }, + }); + await expect(suggester.suggest('org-1', new Set())).rejects.toThrow('GitDB down'); + fail = false; + expect(await suggester.suggest('org-1', new Set())).toHaveLength(2); + }); + + it('plugs into the watchlist service, which hides what the organization already follows', async () => { + const { port } = source({ 'org-1': express4 }); + const suggester = new WatchlistSuggester({ packages: port }); + const watchlist: CveWatchlist = { + id: 'w', + organizationId: 'org-1', + technologies: [{ technologyId: 'express', addedAt: '2026-01-01T00:00:00.000Z' }], + minSeverity: 'high', + includeKev: true, + updatedAt: null, + updatedBy: null, + }; + const service = new CveWatchlistService({ + store: { findByOrganization: async () => watchlist, save: async () => watchlist }, + suggest: (org, followed) => suggester.suggest(org, followed), + }); + expect((await service.suggestions('org-1')).map((item) => item.technologyId)).toEqual([ + 'custom:osv:npm:left-pad', + ]); + }); +}); diff --git a/src/modules/cve-feed/application/watchlist-suggester.ts b/src/modules/cve-feed/application/watchlist-suggester.ts new file mode 100644 index 0000000..0b06297 --- /dev/null +++ b/src/modules/cve-feed/application/watchlist-suggester.ts @@ -0,0 +1,53 @@ +import { + DEFAULT_CUSTOM_SUGGESTIONS, + rankSuggestions, + selectSuggestions, + type Suggestions, + type WatchlistSuggestion, +} from '../domain/suggestions'; +import type { OrganizationPackages } from './ports'; + +export type WatchlistSuggesterDeps = { + packages: OrganizationPackages; + /** Custom (not in the catalog) suggestions at most; default 10. */ + maxCustom?: number; +}; + +/** + * Suggestions for the watchlist from the packages of the organization's latest Trivy / SBOM + * analyses. The ranking (the expensive part: it reads every analysis) is memoized per + * organization and dropped when a new analysis arrives; excluding what is already followed is + * cheap and runs on every call. It only reads GitDB and never adds anything. + */ +export class WatchlistSuggester { + private readonly cache = new Map>(); + /** Rankings computed, to tell cache hits from misses in tests and metrics. */ + computations = 0; + + constructor(private readonly deps: WatchlistSuggesterDeps) {} + + invalidate(organizationId?: string): void { + if (organizationId) this.cache.delete(organizationId); + else this.cache.clear(); + } + + async suggest( + organizationId: string, + followed: ReadonlySet, + ): Promise { + let ranked = this.cache.get(organizationId); + if (!ranked) { + this.computations++; + ranked = this.deps.packages.packages(organizationId).then(rankSuggestions); + this.cache.set(organizationId, ranked); + ranked.catch(() => { + if (this.cache.get(organizationId) === ranked) this.cache.delete(organizationId); + }); + } + return selectSuggestions( + await ranked, + followed, + this.deps.maxCustom ?? DEFAULT_CUSTOM_SUGGESTIONS, + ); + } +} diff --git a/src/modules/cve-feed/domain/advisory.test.ts b/src/modules/cve-feed/domain/advisory.test.ts new file mode 100644 index 0000000..fa5f62e --- /dev/null +++ b/src/modules/cve-feed/domain/advisory.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from 'vitest'; +import { + buildAdvisory, + changesSinceNotified, + diffAdvisory, + fingerprintOf, + mergeAdvisories, + passesFilter, + withEnrichment, +} from './advisory'; +import { normalizeOsv } from './osv'; +import { LODASH, OSV_LODASH } from './fixtures'; +import type { CveAdvisory, NormalizedAdvisory } from './types'; + +const NOW = '2026-11-01T00:00:00.000Z'; +const filter = { minSeverity: 'high' as const, epssThreshold: 0.5 }; + +function advisory(overrides: Partial = {}): CveAdvisory { + return { ...buildAdvisory(normalizeOsv(OSV_LODASH, [LODASH])!, {}, NOW), ...overrides }; +} + +describe('mergeAdvisories', () => { + const osv = normalizeOsv(OSV_LODASH, [LODASH])!; + const nvd: NormalizedAdvisory = { + ...osv, + id: 'CVE-2021-23337', + aliases: ['GHSA-OTHER'], + title: 'NVD title', + severity: 'critical', + cvssScore: 9.1, + cvssVector: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H', + cwe: ['CWE-77', 'CWE-1'], + technologyIds: ['lodash', 'node'], + affected: [ + { + technologyId: 'node', + cpe: 'cpe:2.3:a:nodejs:node.js', + ranges: ['<20.0.0'], + fixedVersions: ['20.0.0'], + }, + ], + fixedVersions: ['20.0.0'], + references: ['https://nvd.nist.gov/vuln/detail/CVE-2021-23337', 'https://extra.example.com/a'], + sources: ['nvd'], + publishedAt: '2021-02-15T00:00:00Z', + modifiedAt: '2026-10-25T00:00:00Z', + }; + + it('unions aliases, sources, references, CWE, technologies and fixed versions', () => { + const merged = mergeAdvisories(osv, nvd); + expect(merged.aliases.sort()).toEqual(['GHSA-35jh-r3h4-6jhm', 'GHSA-OTHER']); + expect(merged.sources).toEqual(['nvd', 'osv']); + expect(merged.cwe).toEqual(['CWE-77', 'CWE-94', 'CWE-1']); + expect(merged.technologyIds).toEqual(['lodash', 'node']); + expect(merged.fixedVersions).toEqual(['4.17.21', '20.0.0']); + expect(merged.references).toContain('https://extra.example.com/a'); + expect(new Set(merged.references).size).toBe(merged.references.length); + expect(merged.affected).toHaveLength(2); + }); + + it('keeps the highest severity and CVSS, the earliest publication and the latest modification', () => { + const merged = mergeAdvisories(osv, nvd); + expect(merged.severity).toBe('critical'); + expect(merged.cvssScore).toBe(9.1); + expect(merged.cvssVector).toBe(nvd.cvssVector); + expect(merged.publishedAt).toBe('2021-02-15T00:00:00Z'); + expect(merged.modifiedAt).toBe('2026-10-25T00:00:00Z'); + expect(merged.title).toBe(osv.title); + }); +}); + +describe('passesFilter', () => { + it('accepts by severity, KEV or EPSS only', () => { + expect(passesFilter({ severity: 'high', kev: false, epssScore: null }, filter)).toBe(true); + expect(passesFilter({ severity: 'medium', kev: false, epssScore: null }, filter)).toBe(false); + expect(passesFilter({ severity: 'low', kev: true, epssScore: null }, filter)).toBe(true); + expect(passesFilter({ severity: 'low', kev: false, epssScore: 0.7 }, filter)).toBe(true); + expect(passesFilter({ severity: 'unknown', kev: false, epssScore: 0.1 }, filter)).toBe(false); + }); +}); + +describe('fingerprint', () => { + it('ignores bookkeeping dates and the EPSS refresh, not the content', () => { + const a = advisory(); + const b = buildAdvisory( + normalizeOsv(OSV_LODASH, [LODASH])!, + { epssUpdatedAt: NOW, epssPercentile: 0.3 }, + '2027-01-01T00:00:00.000Z', + ); + expect(b.fingerprint).toBe(a.fingerprint); + const changed = buildAdvisory( + { ...normalizeOsv(OSV_LODASH, [LODASH])!, fixedVersions: ['9.9.9'] }, + {}, + NOW, + ); + expect(changed.fingerprint).not.toBe(a.fingerprint); + }); + + it('is the same for tiny EPSS noise', () => { + const base = normalizeOsv(OSV_LODASH, [LODASH])!; + const withEpss = (score: number) => + fingerprintOf({ ...base, kev: false, kevAddedAt: null, epssScore: score }); + expect(withEpss(0.4501)).toBe(withEpss(0.4503)); + expect(withEpss(0.45)).not.toBe(withEpss(0.52)); + }); + + it('enrichment changes it only when KEV really changes', () => { + const a = advisory(); + expect(withEnrichment(a, { kev: false }, NOW).fingerprint).toBe(a.fingerprint); + expect(withEnrichment(a, { kev: true, kevAddedAt: '2026-10-30' }, NOW).fingerprint).not.toBe( + a.fingerprint, + ); + }); +}); + +describe('diffAdvisory / changesSinceNotified', () => { + it('flags a new advisory as published', () => { + expect(diffAdvisory(null, advisory(), 0.5)).toEqual({ published: true }); + }); + + it('flags escalations: higher severity, entering KEV, EPSS crossing the threshold', () => { + const before = advisory({ fixedVersions: ['1.0.0'] }); + expect(diffAdvisory(before, { ...before, severity: 'critical' }, 0.5).escalated?.severity).toBe( + 'critical', + ); + expect(diffAdvisory(before, { ...before, kev: true }, 0.5).escalated?.kev).toBe(true); + expect(diffAdvisory(before, { ...before, epssScore: 0.6 }, 0.5).escalated?.epssOver).toBe(true); + expect(diffAdvisory(before, { ...before, severity: 'medium' }, 0.5)).toEqual({}); + }); + + it('flags a fix that was not there before', () => { + const before = advisory({ fixedVersions: [] }); + expect(diffAdvisory(before, { ...before, fixedVersions: ['2.0.0'] }, 0.5)).toEqual({ + fixAvailable: true, + }); + }); + + it('works against the persisted state: nothing pending when it already says so', () => { + const notified = { + published: NOW, + escalated: { severity: 'critical' as const, kev: true, epssOver: true }, + fix_available: NOW, + }; + expect( + changesSinceNotified( + notified, + advisory({ severity: 'critical', kev: true, epssScore: 0.9, fixedVersions: ['1'] }), + 0.5, + ), + ).toEqual({}); + }); +}); diff --git a/src/modules/cve-feed/domain/advisory.ts b/src/modules/cve-feed/domain/advisory.ts new file mode 100644 index 0000000..db5b7b1 --- /dev/null +++ b/src/modules/cve-feed/domain/advisory.ts @@ -0,0 +1,293 @@ +import { createHash } from 'node:crypto'; +import { maxSeverity, severityRank } from './severity'; +import type { + AdvisoryAffected, + CveAdvisory, + FeedFilter, + NormalizedAdvisory, + NotifiedState, + Severity, +} from './types'; + +export const MAX_SUMMARY = 300; +export const MAX_DETAILS = 2000; +export const MAX_REFERENCES = 10; +const MAX_FIXED = 20; +const MAX_RANGES = 10; + +export function truncate(text: string | null | undefined, max: number): string { + const value = (text ?? '').trim(); + return value.length <= max ? value : `${value.slice(0, max - 1).trimEnd()}…`; +} + +function unique(values: Iterable): T[] { + return [...new Set(values)]; +} + +/** NVD / OSV / GHSA / vendor advisories first; at most MAX_REFERENCES. */ +export function pickReferences(urls: readonly string[]): string[] { + const score = (url: string) => { + if (url.includes('nvd.nist.gov')) return 0; + if (url.includes('osv.dev')) return 1; + if (url.includes('github.com/advisories') || url.includes('/security/advisories')) return 2; + if (/advisor|security|cve|bulletin/i.test(url)) return 3; + return 4; + }; + return unique(urls.filter((url) => /^https?:\/\//i.test(url))) + .map((url, index) => ({ url, index, rank: score(url) })) + .sort((a, b) => a.rank - b.rank || a.index - b.index) + .slice(0, MAX_REFERENCES) + .map((entry) => entry.url); +} + +function affectedKey(entry: AdvisoryAffected): string { + return `${entry.technologyId}|${entry.ecosystem ?? ''}|${(entry.package ?? entry.cpe ?? '').toLowerCase()}`; +} + +function mergeAffected(a: AdvisoryAffected[], b: AdvisoryAffected[]): AdvisoryAffected[] { + const merged = new Map(); + for (const entry of [...a, ...b]) { + const key = affectedKey(entry); + const current = merged.get(key); + merged.set( + key, + current + ? { + ...current, + ranges: unique([...current.ranges, ...entry.ranges]).slice(0, MAX_RANGES), + fixedVersions: unique([...current.fixedVersions, ...entry.fixedVersions]).slice( + 0, + MAX_FIXED, + ), + } + : { ...entry }, + ); + } + return [...merged.values()]; +} + +/** + * Merges two normalized versions of the same advisory (OSV + NVD, or a stored row + a fresh + * fetch): aliases, sources, references, technologies and fixed versions are unioned, the highest + * severity and CVSS win; `primary` wins for the free text and the canonical id. + */ +export function mergeAdvisories( + primary: NormalizedAdvisory, + other: NormalizedAdvisory, +): NormalizedAdvisory { + const id = primary.id; + const aliases = unique([...primary.aliases, other.id, ...other.aliases]).filter( + (alias) => alias !== id, + ); + const higherCvss = (other.cvssScore ?? -1) > (primary.cvssScore ?? -1) ? other : primary; + const published = [primary.publishedAt, other.publishedAt] + .filter((v): v is string => Boolean(v)) + .sort(); + return { + id, + aliases, + title: primary.title || other.title, + summary: primary.summary || other.summary, + details: primary.details || other.details, + severity: maxSeverity(primary.severity, other.severity), + cvssScore: higherCvss.cvssScore, + cvssVector: higherCvss.cvssVector, + cwe: unique([...primary.cwe, ...other.cwe]), + technologyIds: unique([...primary.technologyIds, ...other.technologyIds]), + affected: mergeAffected(primary.affected, other.affected), + fixedVersions: unique([...primary.fixedVersions, ...other.fixedVersions]).slice(0, MAX_FIXED), + references: pickReferences([...primary.references, ...other.references]), + sources: unique([...primary.sources, ...other.sources]).sort(), + publishedAt: published[0] ?? null, + modifiedAt: primary.modifiedAt >= other.modifiedAt ? primary.modifiedAt : other.modifiedAt, + }; +} + +/** Severity at or above the minimum, in CISA KEV, or EPSS at or above the threshold. */ +export function passesFilter( + advisory: Pick, + filter: FeedFilter, +): boolean { + return ( + severityRank(advisory.severity) >= severityRank(filter.minSeverity) || + advisory.kev || + (advisory.epssScore ?? 0) >= filter.epssThreshold + ); +} + +/** + * Hash of the normalized content. Bookkeeping dates and the daily EPSS refresh date are left out + * and the EPSS score is rounded, so an unchanged advisory is never rewritten. + */ +export function fingerprintOf( + advisory: NormalizedAdvisory & Pick, +): string { + const content = { + id: advisory.id, + aliases: [...advisory.aliases].sort(), + title: advisory.title, + summary: advisory.summary, + details: advisory.details, + severity: advisory.severity, + cvssScore: advisory.cvssScore, + cvssVector: advisory.cvssVector, + cwe: advisory.cwe, + technologyIds: [...advisory.technologyIds].sort(), + affected: advisory.affected, + fixedVersions: advisory.fixedVersions, + references: advisory.references, + sources: advisory.sources, + publishedAt: advisory.publishedAt, + modifiedAt: advisory.modifiedAt, + kev: advisory.kev, + kevAddedAt: advisory.kevAddedAt, + epssScore: advisory.epssScore === null ? null : Math.round(advisory.epssScore * 100) / 100, + }; + return createHash('sha256').update(JSON.stringify(content)).digest('hex').slice(0, 32); +} + +export function buildAdvisory( + normalized: NormalizedAdvisory, + extra: Partial< + Pick< + CveAdvisory, + 'kev' | 'kevAddedAt' | 'epssScore' | 'epssPercentile' | 'epssUpdatedAt' | 'firstSeenAt' + > + >, + now: string, +): CveAdvisory { + const base = { + ...normalized, + kev: extra.kev ?? false, + kevAddedAt: extra.kevAddedAt ?? null, + epssScore: extra.epssScore ?? null, + }; + return { + ...base, + epssPercentile: extra.epssPercentile ?? null, + epssUpdatedAt: extra.epssUpdatedAt ?? null, + fingerprint: fingerprintOf(base), + firstSeenAt: extra.firstSeenAt ?? now, + updatedAt: now, + }; +} + +/** Same advisory with new KEV / EPSS data applied and the fingerprint recomputed. */ +export function withEnrichment( + advisory: CveAdvisory, + enrichment: Partial< + Pick + >, + now: string, +): CveAdvisory { + const next = { ...advisory, ...enrichment }; + return { ...next, fingerprint: fingerprintOf(next), updatedAt: now }; +} + +export type AdvisoryChanges = { + published?: true; + escalated?: { severity: Severity; kev: boolean; epssOver: boolean }; + fixAvailable?: true; +}; + +export function epssOver(advisory: Pick, threshold: number): boolean { + return (advisory.epssScore ?? 0) >= threshold; +} + +/** The notified state that corresponds to an advisory as it is now (a baseline, nothing pending). */ +export function baselineNotified( + advisory: CveAdvisory, + threshold: number, + now: string, +): NotifiedState { + return { + published: now, + escalated: { + severity: advisory.severity, + kev: advisory.kev, + epssOver: epssOver(advisory, threshold), + }, + ...(advisory.fixedVersions.length > 0 ? { fix_available: now } : {}), + }; +} + +/** What changed since `notified` (the persisted dedup state), not since the previous fetch. */ +export function changesSinceNotified( + notified: NotifiedState, + advisory: CveAdvisory, + threshold: number, +): AdvisoryChanges { + const changes: AdvisoryChanges = {}; + if (!notified.published) changes.published = true; + const sent = notified.escalated; + const over = epssOver(advisory, threshold); + if (sent) { + if ( + severityRank(advisory.severity) > severityRank(sent.severity) || + (advisory.kev && !sent.kev) || + (over && !sent.epssOver) + ) { + changes.escalated = { severity: advisory.severity, kev: advisory.kev, epssOver: over }; + } + } + if (!notified.fix_available && advisory.fixedVersions.length > 0) changes.fixAvailable = true; + return changes; +} + +/** + * Change detection between two versions of an advisory: `prev` null means it is new. Built on the + * same rules as the persisted dedup, so the runtime and this function never disagree. + */ +export function diffAdvisory( + prev: CveAdvisory | null, + next: CveAdvisory, + threshold: number, +): AdvisoryChanges { + // a new advisory is `published`; a fix that was there from the start is part of that event + if (!prev) return { published: true }; + return changesSinceNotified(baselineNotified(prev, threshold, prev.updatedAt), next, threshold); +} + +/** Applies what was just notified to the persisted state. */ +export function applyChanges( + notified: NotifiedState, + changes: AdvisoryChanges, + now: string, +): NotifiedState { + return { + ...notified, + ...(changes.published ? { published: now } : {}), + ...(changes.escalated ? { escalated: changes.escalated } : {}), + ...(changes.fixAvailable ? { fix_available: now } : {}), + }; +} + +/** Union of several notified states (one organization, several technologies of the same CVE). */ +export function mergeNotified(states: readonly NotifiedState[]): NotifiedState { + const merged: NotifiedState = {}; + for (const state of states) { + if (state.published && (!merged.published || state.published < merged.published)) + merged.published = state.published; + if ( + state.fix_available && + (!merged.fix_available || state.fix_available < merged.fix_available) + ) + merged.fix_available = state.fix_available; + if (state.escalated) { + const current = merged.escalated; + merged.escalated = { + severity: current + ? maxSeverity(current.severity, state.escalated.severity) + : state.escalated.severity, + kev: (current?.kev ?? false) || state.escalated.kev, + epssOver: (current?.epssOver ?? false) || state.escalated.epssOver, + }; + } + if (state.affects_project) + merged.affects_project = unique([ + ...(merged.affects_project ?? []), + ...state.affects_project, + ]); + } + return merged; +} diff --git a/src/modules/cve-feed/domain/cvss.ts b/src/modules/cve-feed/domain/cvss.ts new file mode 100644 index 0000000..9e28edb --- /dev/null +++ b/src/modules/cve-feed/domain/cvss.ts @@ -0,0 +1,68 @@ +import { severityFromCvss } from './severity'; +import type { Severity } from './types'; + +const AV: Record = { N: 0.85, A: 0.62, L: 0.55, P: 0.2 }; +const AC: Record = { L: 0.77, H: 0.44 }; +const UI: Record = { N: 0.85, R: 0.62 }; +const CIA: Record = { H: 0.56, L: 0.22, N: 0 }; + +function roundUp(value: number): number { + const int = Math.round(value * 100_000); + return int % 10_000 === 0 ? int / 100_000 : (Math.floor(int / 10_000) + 1) / 10; +} + +/** Base score of a CVSS v3.x vector; `null` for other versions or malformed vectors. */ +export function cvss3BaseScore(vector: string): number | null { + if (!/^CVSS:3\.[01]\//.test(vector)) return null; + const metrics = new Map( + vector + .split('/') + .slice(1) + .map((part) => part.split(':') as [string, string]), + ); + const scopeChanged = metrics.get('S') === 'C'; + const pr = metrics.get('PR'); + const av = AV[metrics.get('AV') ?? '']; + const ac = AC[metrics.get('AC') ?? '']; + const ui = UI[metrics.get('UI') ?? '']; + const c = CIA[metrics.get('C') ?? '']; + const i = CIA[metrics.get('I') ?? '']; + const a = CIA[metrics.get('A') ?? '']; + const prValue = + pr === 'N' + ? 0.85 + : pr === 'L' + ? scopeChanged + ? 0.68 + : 0.62 + : pr === 'H' + ? scopeChanged + ? 0.5 + : 0.27 + : undefined; + if ([av, ac, ui, c, i, a, prValue].some((value) => value === undefined)) return null; + const iss = 1 - (1 - c) * (1 - i) * (1 - a); + const impact = scopeChanged ? 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 : 6.42 * iss; + if (impact <= 0) return 0; + const exploitability = 8.22 * av * ac * (prValue as number) * ui; + return roundUp(Math.min((scopeChanged ? 1.08 : 1) * (impact + exploitability), 10)); +} + +/** GitHub-style qualitative severities (`MODERATE`…). */ +export function severityFromLabel(label: unknown): Severity { + switch (typeof label === 'string' ? label.toUpperCase() : '') { + case 'CRITICAL': + return 'critical'; + case 'HIGH': + return 'high'; + case 'MODERATE': + case 'MEDIUM': + return 'medium'; + case 'LOW': + return 'low'; + default: + return 'unknown'; + } +} + +export { severityFromCvss }; diff --git a/src/modules/cve-feed/domain/duration.ts b/src/modules/cve-feed/domain/duration.ts new file mode 100644 index 0000000..53ac57b --- /dev/null +++ b/src/modules/cve-feed/domain/duration.ts @@ -0,0 +1,10 @@ +const UNITS: Record = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }; + +/** `30m`, `2h`, `1d`, `45s` (a bare number means seconds) to milliseconds; `null` if invalid. */ +export function parseDuration(raw: string): number | null { + const match = /^(\d+)\s*([smhd])?$/i.exec(raw.trim()); + if (!match) return null; + const amount = Number(match[1]); + const ms = amount * UNITS[(match[2] ?? 's').toLowerCase()]; + return Number.isSafeInteger(ms) && ms > 0 ? ms : null; +} diff --git a/src/modules/cve-feed/domain/fixtures.ts b/src/modules/cve-feed/domain/fixtures.ts new file mode 100644 index 0000000..6e1f9e9 --- /dev/null +++ b/src/modules/cve-feed/domain/fixtures.ts @@ -0,0 +1,47 @@ +import type { OsvVulnerability } from './osv'; +import type { WatchTarget } from './types'; + +export const LODASH: WatchTarget = { + technologyId: 'lodash', + kind: 'osv', + ecosystem: 'npm', + package: 'lodash', +}; +export const EXPRESS: WatchTarget = { + technologyId: 'express', + kind: 'osv', + ecosystem: 'npm', + package: 'express', +}; + +/** Shape of a real GitHub-reviewed OSV record (trimmed). */ +export const OSV_LODASH: OsvVulnerability = { + id: 'GHSA-35jh-r3h4-6jhm', + aliases: ['CVE-2021-23337'], + summary: 'Command Injection in lodash', + details: + 'lodash versions prior to 4.17.21 are vulnerable to Command Injection via the template function.', + published: '2021-05-06T16:05:51Z', + modified: '2026-10-20T10:00:00Z', + severity: [{ type: 'CVSS_V3', score: 'CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H' }], + database_specific: { severity: 'HIGH', cwe_ids: ['CWE-77', 'CWE-94'] }, + references: [ + { type: 'WEB', url: 'https://example.com/blog' }, + { type: 'ADVISORY', url: 'https://nvd.nist.gov/vuln/detail/CVE-2021-23337' }, + { type: 'WEB', url: 'https://github.com/advisories/GHSA-35jh-r3h4-6jhm' }, + ], + affected: [ + { + package: { ecosystem: 'npm', name: 'lodash' }, + ranges: [{ type: 'SEMVER', events: [{ introduced: '0' }, { fixed: '4.17.21' }] }], + }, + { + package: { ecosystem: 'npm', name: 'some-other-package' }, + ranges: [{ type: 'SEMVER', events: [{ introduced: '1.0.0' }, { fixed: '1.2.0' }] }], + }, + ], +}; + +export function osvVuln(overrides: Partial = {}): OsvVulnerability { + return { ...OSV_LODASH, ...overrides }; +} diff --git a/src/modules/cve-feed/domain/matching.ts b/src/modules/cve-feed/domain/matching.ts new file mode 100644 index 0000000..06ce490 --- /dev/null +++ b/src/modules/cve-feed/domain/matching.ts @@ -0,0 +1,188 @@ +import { applyChanges, baselineNotified, changesSinceNotified, mergeNotified } from './advisory'; +import { matchesEntry } from './watchlist'; +import type { CveAdvisory, CveWatchlist, NotifiedState, OrgMatch } from './types'; + +export type PlannedEvent = { + kind: 'published' | 'escalated' | 'fix_available' | 'affects_project'; + organizationId: string; + advisory: CveAdvisory; + technologyId: string; + /** `affects_project` only: the project whose scans report the advisory, and its services. */ + projectId?: string; + serviceIds?: string[]; +}; + +/** Where the latest scans of an organization report each CVE id (upper-case keys). */ +export type ScanIndex = ReadonlyMap; + +/** projectId -> serviceIds of the scans that report the advisory (by its id or any alias). */ +function affectedProjects(advisory: CveAdvisory, scans: ScanIndex): Map { + const projects = new Map>(); + for (const key of [advisory.id, ...advisory.aliases]) { + for (const { projectId, serviceId } of scans.get(key.toUpperCase()) ?? []) { + projects.set(projectId, (projects.get(projectId) ?? new Set()).add(serviceId)); + } + } + return new Map([...projects].map(([projectId, services]) => [projectId, [...services].sort()])); +} + +export type MatchPlan = { upsert: OrgMatch[]; deleteIds: string[]; events: PlannedEvent[] }; + +export function matchId(organizationId: string, cveId: string, technologyId: string): string { + return `${organizationId}:${cveId}:${technologyId}`; +} + +function stable(value: unknown): string { + return JSON.stringify(value, (_key, item) => + item && typeof item === 'object' && !Array.isArray(item) + ? Object.fromEntries( + Object.entries(item as Record).sort(([a], [b]) => a.localeCompare(b)), + ) + : item, + ); +} + +/** + * Decides, per organization, which advisories it follows, which match rows must be written and + * which events are due. Pure: the runtime writes `upsert`/`deleteIds` first and only then + * publishes `events`, so the persisted `notified` state is the dedup. + * + * - One event per organization × CVE × change type, whatever the number of matching technologies. + * - A match created by a backfill (`backfillTechs`) or for an advisory that is older than the + * moment the organization started following the technology is stored silently: no event. + * - `escalated` fires again only if the advisory escalates further than the stored state. + * - `affects_project`: once per organization × CVE × project whose scans report the advisory + * (`scans` per organization; an organization without an entry is skipped and its state left as + * it was). The projects already told live in `notified.affects_project`. A group created + * silently, and a group stored before this state existed, only record the projects they find. + */ +export function planMatches(input: { + watchlists: readonly CveWatchlist[]; + advisories: readonly CveAdvisory[]; + existing: readonly OrgMatch[]; + backfillTechs: ReadonlySet; + epssThreshold: number; + now: string; + scans?: ReadonlyMap; +}): MatchPlan { + const { watchlists, advisories, existing, backfillTechs, epssThreshold, now, scans } = input; + const byGroup = new Map(); + for (const row of existing) { + const key = `${row.organizationId}:${row.cveId}`; + byGroup.set(key, [...(byGroup.get(key) ?? []), row]); + } + + const upsert = new Map(); + const events: PlannedEvent[] = []; + + for (const watchlist of watchlists) { + const entries = new Map(watchlist.technologies.map((entry) => [entry.technologyId, entry])); + for (const advisory of advisories) { + const matched = advisory.technologyIds + .filter((tech) => { + const entry = entries.get(tech); + return entry !== undefined && matchesEntry(advisory, entry, watchlist, epssThreshold); + }) + .sort(); + if (matched.length === 0) continue; + + const group = byGroup.get(`${watchlist.organizationId}:${advisory.id}`) ?? []; + const rowOf = new Map(group.map((row) => [row.technologyId, row])); + const isNewGroup = group.length === 0; + const technologyId = matched[0]; + let notified: NotifiedState; + let silentNew: boolean; + let knownProjects: readonly string[] | undefined; + + if (isNewGroup) { + const followedSince = matched.map((tech) => entries.get(tech)!.addedAt).sort()[0]; + const seen = [advisory.firstSeenAt, advisory.publishedAt] + .filter((v): v is string => Boolean(v)) + .sort()[0]; + silentNew = matched.some((tech) => backfillTechs.has(tech)) || seen < followedSince; + notified = baselineNotified(advisory, epssThreshold, now); + knownProjects = silentNew ? undefined : []; + if (!silentNew) + events.push({ + kind: 'published', + organizationId: watchlist.organizationId, + advisory, + technologyId, + }); + } else { + const combined = mergeNotified(group.map((row) => row.notified)); + knownProjects = combined.affects_project; + const changes = changesSinceNotified(combined, advisory, epssThreshold); + notified = applyChanges(combined, changes, now); + silentNew = true; + if (changes.escalated) + events.push({ + kind: 'escalated', + organizationId: watchlist.organizationId, + advisory, + technologyId, + }); + if (changes.fixAvailable) + events.push({ + kind: 'fix_available', + organizationId: watchlist.organizationId, + advisory, + technologyId, + }); + } + + const scanIndex = scans?.get(watchlist.organizationId); + if (scanIndex) { + const found = affectedProjects(advisory, scanIndex); + const sent = new Set(knownProjects ?? []); + // `knownProjects` undefined: nothing to tell about the projects found now + for (const [projectId, serviceIds] of found) { + if (sent.has(projectId)) continue; + sent.add(projectId); + if (knownProjects !== undefined) + events.push({ + kind: 'affects_project', + organizationId: watchlist.organizationId, + advisory, + technologyId, + projectId, + serviceIds, + }); + } + notified = { ...notified, affects_project: [...sent].sort() }; + } + + for (const tech of matched) { + const id = matchId(watchlist.organizationId, advisory.id, tech); + const row = rowOf.get(tech); + if (!row) { + upsert.set(id, { + id, + organizationId: watchlist.organizationId, + cveId: advisory.id, + technologyId: tech, + firstSeenAt: now, + notified, + silent: silentNew, + }); + } else if (stable(row.notified) !== stable(notified)) { + upsert.set(id, { ...row, notified }); + } + } + } + } + + // rows of advisories that were purged, or of technologies an organization no longer follows + const followed = new Map( + watchlists.map((w) => [w.organizationId, new Set(w.technologies.map((e) => e.technologyId))]), + ); + const advisoryIds = new Set(advisories.map((advisory) => advisory.id)); + const deleteIds = existing + .filter( + (row) => + !advisoryIds.has(row.cveId) || !followed.get(row.organizationId)?.has(row.technologyId), + ) + .map((row) => row.id); + + return { upsert: [...upsert.values()], deleteIds, events }; +} diff --git a/src/modules/cve-feed/domain/nvd.test.ts b/src/modules/cve-feed/domain/nvd.test.ts new file mode 100644 index 0000000..b0d4461 --- /dev/null +++ b/src/modules/cve-feed/domain/nvd.test.ts @@ -0,0 +1,309 @@ +import { describe, expect, it } from 'vitest'; +import { cpeMatches, normalizeNvd, nvdDate, type NvdCve } from './nvd'; +import { mergeAdvisories } from './advisory'; +import { normalizeOsv } from './osv'; +import { OSV_LODASH } from './fixtures'; +import type { WatchTarget } from './types'; + +const MYSQL: WatchTarget = { + technologyId: 'mysql', + kind: 'cpe', + cpe: 'cpe:2.3:a:oracle:mysql', +}; +const NODE: WatchTarget = { + technologyId: 'nodejs', + kind: 'cpe', + cpe: 'cpe:2.3:a:nodejs:node.js', +}; + +/** Shape of a real NVD 2.0 record (trimmed). */ +const MYSQL_CVE: NvdCve = { + id: 'CVE-2026-20001', + vulnStatus: 'Analyzed', + published: '2026-10-20T14:15:10.123', + lastModified: '2026-10-25T09:30:00.456', + descriptions: [ + { lang: 'es', value: 'Vulnerabilidad en MySQL Server.' }, + { + lang: 'en', + value: + 'Vulnerability in the MySQL Server product of Oracle MySQL (component: Server: Optimizer).\nEasily exploitable vulnerability allows low privileged attacker to compromise MySQL Server.', + }, + ], + metrics: { + cvssMetricV2: [ + { + type: 'Primary', + baseSeverity: 'MEDIUM', + cvssData: { baseScore: 6.5, vectorString: 'AV:N/AC:L/Au:S/C:P/I:P/A:P' }, + }, + ], + cvssMetricV30: [ + { + type: 'Primary', + cvssData: { + baseScore: 7.5, + vectorString: 'CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H', + }, + }, + ], + cvssMetricV31: [ + { + type: 'Secondary', + cvssData: { + baseScore: 5.0, + vectorString: 'CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:L/I:L/A:L', + }, + }, + { + type: 'Primary', + cvssData: { + baseScore: 9.8, + vectorString: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H', + }, + }, + ], + }, + weaknesses: [ + { + description: [ + { lang: 'en', value: 'CWE-89' }, + { lang: 'en', value: 'NVD-CWE-Other' }, + ], + }, + { description: [{ lang: 'en', value: 'CWE-89' }] }, + ], + configurations: [ + { + nodes: [ + { + cpeMatch: [ + { + vulnerable: true, + criteria: 'cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*', + versionStartIncluding: '8.0.0', + versionEndExcluding: '8.0.35', + }, + { + vulnerable: true, + criteria: 'cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*', + versionStartIncluding: '8.1.0', + versionEndIncluding: '8.1.2', + }, + { + vulnerable: true, + criteria: 'cpe:2.3:a:oracle:mysql:5.7.1:*:*:*:*:*:*:*', + }, + // other products of the same node, and a platform entry that is not vulnerable + { vulnerable: true, criteria: 'cpe:2.3:a:oracle:mysql_cluster:*:*:*:*:*:*:*:*' }, + { vulnerable: false, criteria: 'cpe:2.3:o:linux:linux_kernel:*:*:*:*:*:*:*:*' }, + ], + }, + ], + }, + ], + references: [ + { url: 'https://example.com/blog' }, + { url: 'https://www.oracle.com/security-alerts/cpuoct2026.html' }, + { url: 'https://nvd.nist.gov/vuln/detail/CVE-2026-20001' }, + ], +}; + +describe('normalizeNvd', () => { + it('normalizes to a trimmed advisory for the watched CPE', () => { + const advisory = normalizeNvd(MYSQL_CVE, [MYSQL])!; + expect(advisory).toMatchObject({ + id: 'CVE-2026-20001', + aliases: [], + sources: ['nvd'], + technologyIds: ['mysql'], + publishedAt: '2026-10-20T14:15:10.123Z', + modifiedAt: '2026-10-25T09:30:00.456Z', + cwe: ['CWE-89'], + }); + expect(advisory.summary).toBe( + 'Vulnerability in the MySQL Server product of Oracle MySQL (component: Server: Optimizer).', + ); + expect(advisory.details).toContain('Easily exploitable'); + // NVD's own page first + expect(advisory.references[0]).toBe('https://nvd.nist.gov/vuln/detail/CVE-2026-20001'); + expect(advisory).not.toHaveProperty('metrics'); + }); + + it('prefers CVSS v3.1 (the primary entry) over v3.0 over v2', () => { + const v31 = normalizeNvd(MYSQL_CVE, [MYSQL])!; + expect(v31).toMatchObject({ cvssScore: 9.8, severity: 'critical' }); + expect(v31.cvssVector).toMatch(/^CVSS:3\.1\//); + + const v30 = normalizeNvd( + { ...MYSQL_CVE, metrics: { ...MYSQL_CVE.metrics, cvssMetricV31: undefined } }, + [MYSQL], + )!; + expect(v30).toMatchObject({ cvssScore: 7.5, severity: 'high' }); + + const v2 = normalizeNvd( + { ...MYSQL_CVE, metrics: { cvssMetricV2: MYSQL_CVE.metrics!.cvssMetricV2 } }, + [MYSQL], + )!; + expect(v2).toMatchObject({ + cvssScore: 6.5, + severity: 'medium', + cvssVector: expect.stringMatching(/^AV:N/), + }); + + const none = normalizeNvd({ ...MYSQL_CVE, metrics: {} }, [MYSQL])!; + expect(none).toMatchObject({ cvssScore: null, cvssVector: null, severity: 'unknown' }); + }); + + it('turns the configurations that match the CPE into ranges and fixed versions', () => { + const [affected] = normalizeNvd(MYSQL_CVE, [MYSQL])!.affected; + expect(affected).toEqual({ + technologyId: 'mysql', + cpe: 'cpe:2.3:a:oracle:mysql', + ranges: ['>=8.0.0 <8.0.35', '>=8.1.0 <=8.1.2', '=5.7.1'], + // only versionEndExcluding is a fix + fixedVersions: ['8.0.35'], + }); + expect(normalizeNvd(MYSQL_CVE, [MYSQL])!.fixedVersions).toEqual(['8.0.35']); + }); + + it('ignores other products of the vendor and entries that are not vulnerable', () => { + const advisory = normalizeNvd(MYSQL_CVE, [MYSQL])!; + expect(JSON.stringify(advisory.affected)).not.toContain('mysql_cluster'); + expect(JSON.stringify(advisory.affected)).not.toContain('linux'); + }); + + it('is null when no watched CPE matches, or the CVE is rejected', () => { + expect(normalizeNvd(MYSQL_CVE, [NODE])).toBeNull(); + expect(normalizeNvd(MYSQL_CVE, [])).toBeNull(); + expect(normalizeNvd({ ...MYSQL_CVE, vulnStatus: 'Rejected' }, [MYSQL])).toBeNull(); + expect( + normalizeNvd( + { + ...MYSQL_CVE, + configurations: [ + { + nodes: [{ cpeMatch: [{ vulnerable: false, criteria: 'cpe:2.3:a:oracle:mysql:*' }] }], + }, + ], + }, + [MYSQL], + ), + ).toBeNull(); + }); + + it('finds matches in nested nodes and keeps one entry per watched technology', () => { + const advisory = normalizeNvd( + { + ...MYSQL_CVE, + configurations: [ + { + nodes: [ + { + children: [ + { + cpeMatch: [ + { + vulnerable: true, + criteria: 'cpe:2.3:a:nodejs:node.js:*:*:*:*:*:*:*:*', + versionEndExcluding: '20.1.0', + }, + { + vulnerable: true, + criteria: 'cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*', + versionEndExcluding: '8.0.1', + }, + ], + }, + ], + }, + ], + }, + ], + }, + [MYSQL, NODE], + )!; + expect(advisory.technologyIds.sort()).toEqual(['mysql', 'nodejs']); + expect(advisory.affected.map((item) => item.ranges)).toEqual([['<8.0.1'], ['<20.1.0']]); + }); + + it('caps the text it keeps', () => { + const advisory = normalizeNvd( + { + ...MYSQL_CVE, + descriptions: [{ lang: 'en', value: 'x'.repeat(5000) }], + references: Array.from({ length: 30 }, (_, i) => ({ url: `https://example.com/${i}` })), + }, + [MYSQL], + )!; + expect(advisory.summary.length).toBeLessThanOrEqual(300); + expect(advisory.details.length).toBeLessThanOrEqual(2000); + expect(advisory.references).toHaveLength(10); + }); + + it('merges with the OSV record of the same CVE: ids, sources, severity and fixes are unioned', () => { + const osv = normalizeOsv(OSV_LODASH, [ + { technologyId: 'lodash', kind: 'osv', ecosystem: 'npm', package: 'lodash' }, + ])!; + const nvd = normalizeNvd( + { + ...MYSQL_CVE, + id: 'CVE-2021-23337', + configurations: [ + { + nodes: [ + { + cpeMatch: [ + { + vulnerable: true, + criteria: 'cpe:2.3:a:oracle:mysql:*:*:*:*:*:*:*:*', + versionEndExcluding: '9.0.0', + }, + ], + }, + ], + }, + ], + }, + [MYSQL], + )!; + expect(osv.id).toBe(nvd.id); + const merged = mergeAdvisories(osv, nvd); + expect(merged.id).toBe('CVE-2021-23337'); + expect(merged.aliases).toContain('GHSA-35jh-r3h4-6jhm'); + expect(merged.sources).toEqual(['nvd', 'osv']); + expect(merged.technologyIds.sort()).toEqual(['lodash', 'mysql']); + expect(merged.fixedVersions.sort()).toEqual(['4.17.21', '9.0.0']); + expect(merged.cvssScore).toBe(9.8); + expect(merged.title).toBe(osv.title); // the first one wins for the text + }); +}); + +describe('cpeMatches', () => { + it('compares part, vendor and product, and what the watched CPE pins after them', () => { + expect(cpeMatches('cpe:2.3:a:oracle:mysql', 'cpe:2.3:a:oracle:mysql:8.0:*:*:*:*:*:*:*')).toBe( + true, + ); + expect(cpeMatches('cpe:2.3:a:oracle:mysql', 'cpe:2.3:a:Oracle:MySQL:*:*:*:*:*:*:*:*')).toBe( + true, + ); + expect(cpeMatches('cpe:2.3:a:oracle:mysql', 'cpe:2.3:a:oracle:mysql_cluster:*')).toBe(false); + expect(cpeMatches('cpe:2.3:a:oracle:mysql', 'cpe:2.3:o:oracle:mysql:*')).toBe(false); + expect(cpeMatches('cpe:2.3:a:oracle:mysql:8.0.1', 'cpe:2.3:a:oracle:mysql:8.0.1:*')).toBe(true); + expect(cpeMatches('cpe:2.3:a:oracle:mysql:8.0.1', 'cpe:2.3:a:oracle:mysql:5.7.1:*')).toBe( + false, + ); + expect(cpeMatches('cpe:2.3:a:oracle:mysql:8.0.1', 'cpe:2.3:a:oracle:mysql:*:*')).toBe(true); + expect(cpeMatches('cpe:2.3:a:vendor:prod', 'cpe:2.3:a:vendor:pro\\:d:*')).toBe(false); + }); +}); + +describe('nvdDate', () => { + it('reads the zone-less NVD dates as UTC', () => { + expect(nvdDate('2026-01-01T10:15:00.123')).toBe('2026-01-01T10:15:00.123Z'); + expect(nvdDate('2026-01-01T10:15:00Z')).toBe('2026-01-01T10:15:00.000Z'); + expect(nvdDate('2026-01-01T11:15:00+01:00')).toBe('2026-01-01T10:15:00.000Z'); + expect(nvdDate('nonsense')).toBeNull(); + expect(nvdDate(undefined)).toBeNull(); + }); +}); diff --git a/src/modules/cve-feed/domain/nvd.ts b/src/modules/cve-feed/domain/nvd.ts new file mode 100644 index 0000000..f1558a5 --- /dev/null +++ b/src/modules/cve-feed/domain/nvd.ts @@ -0,0 +1,192 @@ +import { severityFromCvss, severityFromLabel } from './cvss'; +import { MAX_DETAILS, MAX_SUMMARY, pickReferences, truncate } from './advisory'; +import type { AdvisoryAffected, NormalizedAdvisory, Severity, WatchTarget } from './types'; + +type NvdMetric = { + type?: string; + baseSeverity?: string; + cvssData?: { baseScore?: number; vectorString?: string; baseSeverity?: string }; +}; + +type NvdCpeMatch = { + vulnerable?: boolean; + criteria: string; + versionStartIncluding?: string; + versionStartExcluding?: string; + versionEndIncluding?: string; + versionEndExcluding?: string; +}; + +type NvdNode = { cpeMatch?: NvdCpeMatch[]; children?: NvdNode[] }; + +/** The parts of an NVD 2.0 `cve` object this module reads (https://nvd.nist.gov/developers/vulnerabilities). */ +export type NvdCve = { + id: string; + vulnStatus?: string; + published?: string; + lastModified: string; + descriptions?: Array<{ lang: string; value: string }>; + metrics?: { + cvssMetricV31?: NvdMetric[]; + cvssMetricV30?: NvdMetric[]; + cvssMetricV2?: NvdMetric[]; + }; + weaknesses?: Array<{ description?: Array<{ lang: string; value: string }> }>; + configurations?: Array<{ nodes?: NvdNode[] }>; + references?: Array<{ url: string }>; +}; + +type CpeTarget = Extract; + +const MAX_FIXED = 20; +const MAX_RANGES = 10; + +/** NVD dates carry no zone (`2026-01-01T10:15:00.123`): they are UTC. */ +export function nvdDate(value: string | undefined): string | null { + if (!value) return null; + const date = new Date(/(Z|[+-]\d\d:\d\d)$/.test(value) ? value : `${value}Z`); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + +// CPE 2.3 names escape the colon inside a field as `\:` +function cpeFields(cpe: string): string[] { + return cpe.toLowerCase().split(/(? 4 && (found[index] === '*' || found[index] === undefined)) continue; + if (found[index] !== wanted[index]) return false; + } + return found.length > 4; +} + +function rangeOf(match: NvdCpeMatch): { range: string; fixed: string | null } { + const start = match.versionStartIncluding + ? `>=${match.versionStartIncluding}` + : match.versionStartExcluding + ? `>${match.versionStartExcluding}` + : ''; + const end = match.versionEndExcluding + ? `<${match.versionEndExcluding}` + : match.versionEndIncluding + ? `<=${match.versionEndIncluding}` + : ''; + if (start || end) { + return { + range: [start, end].filter(Boolean).join(' '), + fixed: match.versionEndExcluding ?? null, + }; + } + const version = cpeFields(match.criteria)[5]; + return { + range: version && version !== '*' && version !== '-' ? `=${version}` : '*', + fixed: null, + }; +} + +function vulnerableMatches(nodes: readonly NvdNode[] | undefined): NvdCpeMatch[] { + return (nodes ?? []).flatMap((node) => [ + ...(node.cpeMatch ?? []).filter((match) => match.vulnerable !== false), + ...vulnerableMatches(node.children), + ]); +} + +function pickMetric(metrics: NvdMetric[] | undefined): NvdMetric | undefined { + return metrics?.find((metric) => metric.type === 'Primary') ?? metrics?.[0]; +} + +/** CVSS v3.1 over v3.0 over v2 (v2 rates by its own scale, the label NVD gives it). */ +function cvssOf(cve: NvdCve): { score: number | null; vector: string | null; severity: Severity } { + const v3 = pickMetric(cve.metrics?.cvssMetricV31) ?? pickMetric(cve.metrics?.cvssMetricV30); + if (v3?.cvssData?.baseScore !== undefined) { + const score = v3.cvssData.baseScore; + return { + score, + vector: v3.cvssData.vectorString ?? null, + severity: severityFromCvss(score), + }; + } + const v2 = pickMetric(cve.metrics?.cvssMetricV2); + if (v2?.cvssData?.baseScore !== undefined) { + return { + score: v2.cvssData.baseScore, + vector: v2.cvssData.vectorString ?? null, + severity: severityFromLabel(v2.baseSeverity ?? v2.cvssData.baseSeverity), + }; + } + return { score: null, vector: null, severity: 'unknown' }; +} + +/** + * Normalizes an NVD CVE (trimmed: no raw payload) to an advisory for the watched CPEs. Only the + * vulnerable entries of the configurations that match a watched CPE are kept, as compact ranges; + * `versionEndExcluding` is the fixed version. `null` for a rejected CVE or one that no watched CPE + * matches. + */ +export function normalizeNvd( + cve: NvdCve, + watched: readonly WatchTarget[], +): NormalizedAdvisory | null { + if (cve.vulnStatus === 'Rejected') return null; + const targets = watched.filter((target): target is CpeTarget => target.kind === 'cpe'); + const matches = (cve.configurations ?? []).flatMap((config) => vulnerableMatches(config.nodes)); + + const affected: AdvisoryAffected[] = []; + for (const target of targets) { + const own = matches.filter((match) => cpeMatches(target.cpe, match.criteria)); + if (own.length === 0) continue; + const ranges = new Set(); + const fixed = new Set(); + for (const match of own) { + const { range, fixed: version } = rangeOf(match); + ranges.add(range); + if (version) fixed.add(version); + } + affected.push({ + technologyId: target.technologyId, + cpe: target.cpe, + ranges: [...ranges].slice(0, MAX_RANGES), + fixedVersions: [...fixed].slice(0, MAX_FIXED), + }); + } + if (affected.length === 0) return null; + + const description = + cve.descriptions?.find((item) => item.lang === 'en')?.value ?? cve.descriptions?.[0]?.value; + const summary = truncate(description?.split('\n')[0], MAX_SUMMARY); + const cvss = cvssOf(cve); + return { + id: cve.id, + aliases: [], + title: truncate(summary || cve.id, 200), + summary, + details: truncate(description, MAX_DETAILS), + severity: cvss.severity, + cvssScore: cvss.score, + cvssVector: cvss.vector, + cwe: [ + ...new Set( + (cve.weaknesses ?? []) + .flatMap((weakness) => weakness.description ?? []) + .map((item) => item.value) + .filter((value) => /^CWE-\d+$/.test(value)), + ), + ], + technologyIds: [...new Set(affected.map((item) => item.technologyId))], + affected, + fixedVersions: [...new Set(affected.flatMap((item) => item.fixedVersions))].slice(0, MAX_FIXED), + references: pickReferences((cve.references ?? []).map((reference) => reference.url)), + sources: ['nvd'], + publishedAt: nvdDate(cve.published), + modifiedAt: nvdDate(cve.lastModified) ?? new Date(0).toISOString(), + }; +} diff --git a/src/modules/cve-feed/domain/osv.test.ts b/src/modules/cve-feed/domain/osv.test.ts new file mode 100644 index 0000000..44534e9 --- /dev/null +++ b/src/modules/cve-feed/domain/osv.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it } from 'vitest'; +import { cvss3BaseScore } from './cvss'; +import { normalizeOsv } from './osv'; +import { EXPRESS, LODASH, OSV_LODASH, osvVuln } from './fixtures'; + +describe('cvss3BaseScore', () => { + it('computes known base scores', () => { + expect(cvss3BaseScore('CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H')).toBe(9.8); + expect(cvss3BaseScore('CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:U/C:H/I:H/A:H')).toBe(7.2); + expect(cvss3BaseScore('CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N')).toBe(6.1); + }); + + it('ignores other versions and malformed vectors', () => { + expect( + cvss3BaseScore('CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:N/VC:H/VI:H/VA:H/SC:N/SI:N/SA:N'), + ).toBeNull(); + expect(cvss3BaseScore('nonsense')).toBeNull(); + }); +}); + +describe('normalizeOsv', () => { + it('makes the CVE the canonical id and keeps the GHSA as an alias', () => { + const advisory = normalizeOsv(OSV_LODASH, [LODASH])!; + expect(advisory.id).toBe('CVE-2021-23337'); + expect(advisory.aliases).toEqual(['GHSA-35jh-r3h4-6jhm']); + expect(advisory.sources).toEqual(['osv']); + }); + + it('reads severity, CVSS and CWE', () => { + const advisory = normalizeOsv(OSV_LODASH, [LODASH])!; + expect(advisory.cvssScore).toBe(7.2); + expect(advisory.severity).toBe('high'); + expect(advisory.cwe).toEqual(['CWE-77', 'CWE-94']); + }); + + it('keeps only the watched packages, with compact ranges and fixed versions', () => { + const advisory = normalizeOsv(OSV_LODASH, [LODASH])!; + expect(advisory.technologyIds).toEqual(['lodash']); + expect(advisory.affected).toEqual([ + { + technologyId: 'lodash', + ecosystem: 'npm', + package: 'lodash', + ranges: ['<4.17.21'], + fixedVersions: ['4.17.21'], + }, + ]); + expect(advisory.fixedVersions).toEqual(['4.17.21']); + }); + + it('returns null when no watched package is affected', () => { + expect(normalizeOsv(OSV_LODASH, [EXPRESS])).toBeNull(); + }); + + it('writes lower bounds, last_affected and open ranges', () => { + const advisory = normalizeOsv( + osvVuln({ + affected: [ + { + package: { ecosystem: 'npm', name: 'lodash' }, + ranges: [ + { + type: 'SEMVER', + events: [ + { introduced: '1.0.0' }, + { fixed: '1.2.3' }, + { introduced: '2.0.0' }, + { last_affected: '2.5.0' }, + { introduced: '3.0.0' }, + ], + }, + { type: 'GIT', events: [{ introduced: '0' }, { fixed: 'deadbeef' }] }, + ], + }, + ], + }), + [LODASH], + )!; + expect(advisory.affected[0].ranges).toEqual(['>=1.0.0 <1.2.3', '>=2.0.0 <=2.5.0', '>=3.0.0']); + expect(advisory.affected[0].fixedVersions).toEqual(['1.2.3']); + }); + + it('trims the text and the references (no raw payload)', () => { + const advisory = normalizeOsv( + osvVuln({ + summary: 'x'.repeat(500), + details: 'y'.repeat(5000), + references: Array.from({ length: 30 }, (_, i) => ({ + url: `https://example.com/${i}`, + })).concat([{ url: 'https://osv.dev/vulnerability/GHSA-35jh-r3h4-6jhm' }]), + }), + [LODASH], + )!; + expect(advisory.summary.length).toBeLessThanOrEqual(300); + expect(advisory.details.length).toBeLessThanOrEqual(2000); + expect(advisory.references).toHaveLength(10); + expect(advisory.references[0]).toContain('osv.dev'); + }); + + it('prefers advisory sources in the references', () => { + const advisory = normalizeOsv(OSV_LODASH, [LODASH])!; + expect(advisory.references[0]).toContain('nvd.nist.gov'); + }); + + it('falls back to the GitHub label when there is no CVSS, and to the GHSA id without a CVE', () => { + const advisory = normalizeOsv( + osvVuln({ aliases: [], severity: undefined, database_specific: { severity: 'MODERATE' } }), + [LODASH], + )!; + expect(advisory.id).toBe('GHSA-35jh-r3h4-6jhm'); + expect(advisory.severity).toBe('medium'); + expect(advisory.cvssScore).toBeNull(); + }); +}); diff --git a/src/modules/cve-feed/domain/osv.ts b/src/modules/cve-feed/domain/osv.ts new file mode 100644 index 0000000..b1c0fc0 --- /dev/null +++ b/src/modules/cve-feed/domain/osv.ts @@ -0,0 +1,127 @@ +import { cvss3BaseScore, severityFromCvss, severityFromLabel } from './cvss'; +import { MAX_DETAILS, MAX_SUMMARY, pickReferences, truncate } from './advisory'; +import { maxSeverity } from './severity'; +import type { AdvisoryAffected, NormalizedAdvisory, Severity, WatchTarget } from './types'; + +/** The parts of an OSV vulnerability this module reads (https://ossf.github.io/osv-schema). */ +export type OsvVulnerability = { + id: string; + aliases?: string[]; + summary?: string; + details?: string; + published?: string; + modified: string; + severity?: Array<{ type: string; score: string }>; + database_specific?: { severity?: string; cwe_ids?: string[] }; + references?: Array<{ type?: string; url: string }>; + affected?: Array<{ + package?: { ecosystem: string; name: string }; + ranges?: Array<{ type: string; events?: Array> }>; + }>; +}; + +const MAX_FIXED = 20; + +function rangesOf( + ranges: NonNullable[number]['ranges']>, +) { + const compact: string[] = []; + const fixed: string[] = []; + for (const range of ranges) { + if (range.type === 'GIT') continue; // commit hashes, not versions + let introduced: string | null = null; + for (const event of range.events ?? []) { + if ('introduced' in event) introduced = event.introduced; + const lower = introduced && introduced !== '0' ? `>=${introduced} ` : ''; + if ('fixed' in event) { + compact.push(`${lower}<${event.fixed}`.trim()); + fixed.push(event.fixed); + introduced = null; + } else if ('last_affected' in event) { + compact.push(`${lower}<=${event.last_affected}`.trim()); + introduced = null; + } + } + if (introduced !== null) compact.push(introduced === '0' ? '*' : `>=${introduced}`); + } + return { compact, fixed }; +} + +function cvssOf(vuln: OsvVulnerability): { score: number | null; vector: string | null } { + for (const entry of vuln.severity ?? []) { + const score = cvss3BaseScore(entry.score); + if (score !== null) return { score, vector: entry.score }; + } + const vector = vuln.severity?.find((entry) => entry.type.startsWith('CVSS'))?.score ?? null; + return { score: null, vector }; +} + +/** + * Normalizes an OSV vulnerability to an advisory (trimmed: no raw payload), keeping only the + * affected packages that are watched. `null` when none of the watched packages is affected. + */ +export function normalizeOsv( + vuln: OsvVulnerability, + watched: readonly WatchTarget[], +): NormalizedAdvisory | null { + const bySource = new Map(); + for (const target of watched) { + if (target.kind === 'osv') + bySource.set(`${target.ecosystem}|${target.package.toLowerCase()}`, target.technologyId); + } + + const affected: AdvisoryAffected[] = []; + for (const entry of vuln.affected ?? []) { + if (!entry.package) continue; + const technologyId = bySource.get( + `${entry.package.ecosystem}|${entry.package.name.toLowerCase()}`, + ); + if (!technologyId) continue; + const { compact, fixed } = rangesOf(entry.ranges ?? []); + const existing = affected.find( + (item) => item.technologyId === technologyId && item.package === entry.package?.name, + ); + if (existing) { + existing.ranges = [...new Set([...existing.ranges, ...compact])].slice(0, 10); + existing.fixedVersions = [...new Set([...existing.fixedVersions, ...fixed])].slice( + 0, + MAX_FIXED, + ); + } else { + affected.push({ + technologyId, + ecosystem: entry.package.ecosystem, + package: entry.package.name, + ranges: [...new Set(compact)].slice(0, 10), + fixedVersions: [...new Set(fixed)].slice(0, MAX_FIXED), + }); + } + } + if (affected.length === 0) return null; + + const ids = [vuln.id, ...(vuln.aliases ?? [])]; + const id = ids.find((value) => /^CVE-\d{4}-\d+$/i.test(value)) ?? vuln.id; + const cvss = cvssOf(vuln); + let severity: Severity = severityFromLabel(vuln.database_specific?.severity); + if (cvss.score !== null) severity = maxSeverity(severity, severityFromCvss(cvss.score)); + + const summary = truncate(vuln.summary || vuln.details?.split('\n')[0], MAX_SUMMARY); + return { + id, + aliases: [...new Set(ids)].filter((value) => value !== id), + title: truncate(summary || id, 200), + summary, + details: truncate(vuln.details, MAX_DETAILS), + severity, + cvssScore: cvss.score, + cvssVector: cvss.vector, + cwe: (vuln.database_specific?.cwe_ids ?? []).filter((cwe) => /^CWE-\d+$/.test(cwe)), + technologyIds: [...new Set(affected.map((item) => item.technologyId))], + affected, + fixedVersions: [...new Set(affected.flatMap((item) => item.fixedVersions))].slice(0, MAX_FIXED), + references: pickReferences((vuln.references ?? []).map((reference) => reference.url)), + sources: ['osv'], + publishedAt: vuln.published ?? null, + modifiedAt: vuln.modified, + }; +} diff --git a/src/modules/cve-feed/domain/severity.ts b/src/modules/cve-feed/domain/severity.ts new file mode 100644 index 0000000..3c5242c --- /dev/null +++ b/src/modules/cve-feed/domain/severity.ts @@ -0,0 +1,27 @@ +import type { Severity } from './types'; + +export const SEVERITIES: readonly Severity[] = ['unknown', 'low', 'medium', 'high', 'critical']; + +const RANK: Record = { unknown: 0, low: 1, medium: 2, high: 3, critical: 4 }; + +export function severityRank(severity: Severity): number { + return RANK[severity]; +} + +export function isSeverity(value: unknown): value is Severity { + return typeof value === 'string' && Object.hasOwn(RANK, value); +} + +export function maxSeverity(a: Severity, b: Severity): Severity { + return RANK[a] >= RANK[b] ? a : b; +} + +/** CVSS v3/v4 qualitative rating. */ +export function severityFromCvss(score: number | null): Severity { + if (score === null || Number.isNaN(score)) return 'unknown'; + if (score >= 9) return 'critical'; + if (score >= 7) return 'high'; + if (score >= 4) return 'medium'; + if (score > 0) return 'low'; + return 'unknown'; +} diff --git a/src/modules/cve-feed/domain/suggestions.test.ts b/src/modules/cve-feed/domain/suggestions.test.ts new file mode 100644 index 0000000..4255573 --- /dev/null +++ b/src/modules/cve-feed/domain/suggestions.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it } from 'vitest'; +import { + MIN_CUSTOM_SERVICES, + rankSuggestions, + selectSuggestions, + type ServicePackageList, +} from './suggestions'; + +const svc = (serviceId: string, ...packages: Array<[string, string]>): ServicePackageList => ({ + serviceId, + packages: packages.map(([ecosystem, name]) => ({ ecosystem, name })), +}); + +describe('rankSuggestions', () => { + it('counts in how many services a catalog package is used, once per service', () => { + const ranked = rankSuggestions([ + svc('a', ['npm', 'express'], ['npm', 'express']), + svc('b', ['npm', 'express']), + svc('c', ['npm', 'express'], ['PyPI', 'django']), + svc('d', ['PyPI', 'django']), + ]); + expect(ranked.catalog).toEqual([ + { technologyId: 'express', name: 'Express', package: 'express', services: 3 }, + { technologyId: 'django', name: 'Django', package: 'django', services: 2 }, + ]); + }); + + it('matches the catalog by ecosystem + package, case-insensitively, and not across ecosystems', () => { + const ranked = rankSuggestions([ + svc('a', ['PyPI', 'Django'], ['PyPI', 'requests'], ['npm', 'requests']), + ]); + expect(ranked.catalog.map((item) => item.technologyId).sort()).toEqual(['django', 'requests']); + // npm "requests" is not the PyPI package of the catalog: it is an unlisted package (1 service) + expect(ranked.custom).toEqual([]); + }); + + it('joins several packages of one technology into one suggestion with the union of services', () => { + const ranked = rankSuggestions([ + svc('a', ['npm', 'react'], ['npm', 'react-dom']), + svc('b', ['npm', 'react']), + svc('c', ['npm', 'react-dom']), + svc('d', ['npm', 'react']), + ]); + expect(ranked.catalog).toEqual([ + { technologyId: 'react', name: 'React', package: 'react', services: 4 }, + ]); + }); + + it('proposes unlisted packages used in several services as custom OSV entries', () => { + const many = Array.from({ length: MIN_CUSTOM_SERVICES }, (_, i) => + svc(`s${i}`, ['npm', 'left-pad'], ['npm', 'only-here']), + ); + const ranked = rankSuggestions([...many, svc('x', ['npm', 'lonely'])]); + expect(ranked.custom.map((item) => item.package).sort()).toEqual(['left-pad', 'only-here']); + expect(ranked.custom[0]).toMatchObject({ + technologyId: expect.stringMatching(/^custom:osv:npm:/), + custom: { kind: 'osv', ecosystem: 'npm' }, + services: MIN_CUSTOM_SERVICES, + }); + expect(ranked.custom.map((item) => item.package)).not.toContain('lonely'); + }); + + it('ignores ecosystems OSV does not index in this feed', () => { + const ranked = rankSuggestions([ + svc('a', ['Debian', 'openssl'], ['npm', 'foo']), + svc('b', ['Debian', 'openssl'], ['npm', 'foo']), + ]); + expect(ranked.custom.map((item) => item.package)).toEqual(['foo']); + }); +}); + +describe('selectSuggestions', () => { + const services = [ + ...Array.from({ length: 4 }, (_, i) => svc(`s${i}`, ['npm', 'express'], ['npm', 'a-lib'])), + ...Array.from({ length: 3 }, (_, i) => svc(`t${i}`, ['npm', 'b-lib'], ['npm', 'express'])), + ]; + + it('leaves out what is already followed (catalog or custom)', () => { + const ranked = rankSuggestions(services); + expect(selectSuggestions(ranked, new Set()).map((item) => item.technologyId)).toEqual([ + 'express', + 'custom:osv:npm:a-lib', + 'custom:osv:npm:b-lib', + ]); + expect( + selectSuggestions(ranked, new Set(['express', 'custom:osv:npm:a-lib'])).map( + (item) => item.technologyId, + ), + ).toEqual(['custom:osv:npm:b-lib']); + }); + + it('keeps the top N custom ones after excluding the followed, never counting those', () => { + const many = Array.from({ length: 4 }, (_, s) => + svc( + `s${s}`, + ...Array.from({ length: 15 }, (_, i): [string, string] => [ + 'npm', + `pkg-${String(i).padStart(2, '0')}`, + ]), + ), + ); + const ranked = rankSuggestions(many); + expect(selectSuggestions(ranked, new Set(), 10)).toHaveLength(10); + const followed = new Set(['custom:osv:npm:pkg-00', 'custom:osv:npm:pkg-01']); + const picked = selectSuggestions(ranked, followed, 10).map((item) => item.package); + expect(picked).toHaveLength(10); + expect(picked).not.toContain('pkg-00'); + expect(picked[0]).toBe('pkg-02'); + }); +}); diff --git a/src/modules/cve-feed/domain/suggestions.ts b/src/modules/cve-feed/domain/suggestions.ts new file mode 100644 index 0000000..28ae253 --- /dev/null +++ b/src/modules/cve-feed/domain/suggestions.ts @@ -0,0 +1,114 @@ +import { CVE_TECHNOLOGIES, OSV_ECOSYSTEMS, type OsvEcosystem } from '#lib/cves/technologies.data'; +import { customTechnologyId } from './watchlist'; +import type { CustomTechnology } from './types'; + +/** A technology proposed from what the scans of an organization use. Never added on its own. */ +export type WatchlistSuggestion = { + /** catalog id, or the deterministic id of the custom entry */ + technologyId: string; + name: string; + /** set when the package is not in the catalog: the entry that would be added */ + custom?: CustomTechnology; + /** the package behind the suggestion (the most used one when a technology has several) */ + package: string; + /** in how many services of the organization it appears */ + services: number; +}; + +export type ServicePackageList = { + serviceId: string; + packages: ReadonlyArray<{ ecosystem: string; name: string }>; +}; + +export type Suggestions = { catalog: WatchlistSuggestion[]; custom: WatchlistSuggestion[] }; + +export const DEFAULT_CUSTOM_SUGGESTIONS = 10; +/** A package needs to be this widespread to be proposed when it is not in the catalog. */ +export const MIN_CUSTOM_SERVICES = 2; +const CUSTOM_POOL = 50; + +const key = (ecosystem: string, name: string) => `${ecosystem}|${name.toLowerCase()}`; + +const CATALOG_INDEX = new Map( + CVE_TECHNOLOGIES.flatMap((technology) => + technology.osv.map((ref) => [key(ref.ecosystem, ref.package), technology] as const), + ), +); + +/** + * Counts in how many services each package appears and ranks it: packages of the catalog become + * catalog suggestions (one per technology, however many of its packages are used); the most used + * ones that are not in the catalog become custom OSV entries. Pure; the followed technologies are + * excluded later, so the result can be memoized. + */ +export function rankSuggestions(services: readonly ServicePackageList[]): Suggestions { + const perPackage = new Map }>(); + for (const service of services) { + for (const pkg of service.packages) { + if (!(OSV_ECOSYSTEMS as readonly string[]).includes(pkg.ecosystem)) continue; + const id = key(pkg.ecosystem, pkg.name); + const entry = perPackage.get(id) ?? { ...pkg, services: new Set() }; + entry.services.add(service.serviceId); + perPackage.set(id, entry); + } + } + + const technologies = new Map< + string, + { name: string; services: Set; top: { name: string; services: number } } + >(); + const custom: WatchlistSuggestion[] = []; + for (const [id, entry] of perPackage) { + const technology = CATALOG_INDEX.get(id); + if (technology) { + const current = technologies.get(technology.id) ?? { + name: technology.name, + services: new Set(), + top: { name: entry.name, services: 0 }, + }; + for (const serviceId of entry.services) current.services.add(serviceId); + if (entry.services.size > current.top.services) + current.top = { name: entry.name, services: entry.services.size }; + technologies.set(technology.id, current); + } else if (entry.services.size >= MIN_CUSTOM_SERVICES) { + const definition: CustomTechnology = { + kind: 'osv', + ecosystem: entry.ecosystem as OsvEcosystem, + package: entry.name, + }; + custom.push({ + technologyId: customTechnologyId(definition), + name: entry.name, + custom: definition, + package: entry.name, + services: entry.services.size, + }); + } + } + + const byUse = (a: WatchlistSuggestion, b: WatchlistSuggestion) => + b.services - a.services || a.name.localeCompare(b.name); + return { + catalog: [...technologies] + .map(([technologyId, value]) => ({ + technologyId, + name: value.name, + package: value.top.name, + services: value.services.size, + })) + .sort(byUse), + custom: custom.sort(byUse).slice(0, CUSTOM_POOL), + }; +} + +/** What is left to propose once the followed technologies are out; at most `maxCustom` custom ones. */ +export function selectSuggestions( + ranked: Suggestions, + followed: ReadonlySet, + maxCustom = DEFAULT_CUSTOM_SUGGESTIONS, +): WatchlistSuggestion[] { + return [ + ...ranked.catalog.filter((item) => !followed.has(item.technologyId)), + ...ranked.custom.filter((item) => !followed.has(item.technologyId)).slice(0, maxCustom), + ]; +} diff --git a/src/modules/cve-feed/domain/types.ts b/src/modules/cve-feed/domain/types.ts new file mode 100644 index 0000000..d558b6c --- /dev/null +++ b/src/modules/cve-feed/domain/types.ts @@ -0,0 +1,132 @@ +import type { OsvEcosystem } from '#lib/cves/technologies.data'; + +export type Severity = 'critical' | 'high' | 'medium' | 'low' | 'unknown'; +export type CveSourceId = 'osv' | 'nvd' | 'kev' | 'epss'; + +export type CustomTechnology = + { kind: 'osv'; ecosystem: OsvEcosystem; package: string } | { kind: 'cpe'; cpe: string }; + +/** One followed technology of a watchlist. `technologyId` is always set (deterministic for custom ones). */ +export type WatchlistEntry = { + technologyId: string; + custom?: CustomTechnology; + label?: string; + minSeverity?: Severity; + /** Shown only: matching is by technology, never by version. */ + versions?: string[]; + addedAt: string; +}; + +export type CveWatchlist = { + id: string | null; + organizationId: string; + technologies: WatchlistEntry[]; + minSeverity: Severity; + includeKev: boolean; + updatedAt: string | null; + updatedBy: string | null; +}; + +/** What a source is asked to look up: one catalog or custom technology resolved to a lookup key. */ +export type WatchTarget = + | { technologyId: string; kind: 'osv'; ecosystem: OsvEcosystem; package: string } + | { technologyId: string; kind: 'cpe'; cpe: string }; + +export type AdvisoryAffected = { + technologyId: string; + ecosystem?: string; + package?: string; + cpe?: string; + /** compact ranges, `>=1.0.0 <1.2.3` */ + ranges: string[]; + fixedVersions: string[]; +}; + +export type CveAdvisory = { + /** canonical: the CVE id when any alias is one, else the source id (GHSA-…) */ + id: string; + aliases: string[]; + title: string; + summary: string; + details: string; + severity: Severity; + cvssScore: number | null; + cvssVector: string | null; + cwe: string[]; + technologyIds: string[]; + affected: AdvisoryAffected[]; + fixedVersions: string[]; + references: string[]; + sources: Array<'osv' | 'nvd'>; + publishedAt: string | null; + modifiedAt: string; + kev: boolean; + kevAddedAt: string | null; + epssScore: number | null; + epssPercentile: number | null; + epssUpdatedAt: string | null; + fingerprint: string; + firstSeenAt: string; + updatedAt: string; +}; + +/** What a normalizer produces: the row before it is stored (no bookkeeping dates, no fingerprint). */ +export type NormalizedAdvisory = Omit< + CveAdvisory, + | 'fingerprint' + | 'firstSeenAt' + | 'updatedAt' + | 'kev' + | 'kevAddedAt' + | 'epssScore' + | 'epssPercentile' + | 'epssUpdatedAt' +>; + +export type NotifiedState = { + published?: string; + escalated?: { severity: Severity; kev: boolean; epssOver: boolean }; + fix_available?: string; + affects_project?: string[]; +}; + +export type OrgMatch = { + id: string; + organizationId: string; + cveId: string; + technologyId: string; + firstSeenAt: string; + notified: NotifiedState; + silent: boolean; +}; + +export type FeedSourceState = { + id: string; + cursor: unknown; + etag: string | null; + lastModifiedHeader: string | null; + lastRunAt: string | null; + lastSuccessAt: string | null; + lastError: string | null; + lastErrorAt: string | null; + itemsLastRun: number | null; +}; + +export type LockState = { + holder: string | null; + acquiredAt: string | null; + expiresAt: string | null; +}; + +export type RunState = { + requestedAt: string | null; + handledRequestedAt: string | null; + lastRunAt: string | null; + lastDurationMs: number | null; + backfilledTechnologies: Record; +}; + +export type FeedFilter = { + minSeverity: Severity; + epssThreshold: number; +}; diff --git a/src/modules/cve-feed/domain/watchlist.test.ts b/src/modules/cve-feed/domain/watchlist.test.ts new file mode 100644 index 0000000..0bf4571 --- /dev/null +++ b/src/modules/cve-feed/domain/watchlist.test.ts @@ -0,0 +1,159 @@ +import { describe, expect, it } from 'vitest'; +import { + CveWatchlistValidationError, + customTechnologyId, + matchesEntry, + normalizeWatchlistInput, + targetsOfEntry, + unionTargets, + MAX_WATCHLIST_ENTRIES, +} from './watchlist'; +import { CVE_TECHNOLOGIES, OSV_ECOSYSTEMS } from '../../../lib/cves/technologies.data'; + +const NOW = '2026-11-01T00:00:00.000Z'; + +describe('technology catalog', () => { + it('has unique ids and exact OSV ecosystem names', () => { + expect(new Set(CVE_TECHNOLOGIES.map((t) => t.id)).size).toBe(CVE_TECHNOLOGIES.length); + for (const technology of CVE_TECHNOLOGIES) { + for (const ref of technology.osv) expect(OSV_ECOSYSTEMS).toContain(ref.ecosystem); + for (const cpe of technology.cpe) expect(cpe).toMatch(/^cpe:2\.3:[aoh]:/); + expect(technology.osv.length + technology.cpe.length).toBeGreaterThan(0); + } + }); +}); + +describe('normalizeWatchlistInput', () => { + it('accepts catalog and custom technologies with deterministic ids', () => { + const result = normalizeWatchlistInput( + { + minSeverity: 'high', + includeKev: true, + technologies: [ + { technologyId: 'lodash' }, + { custom: { kind: 'osv', ecosystem: 'npm', package: 'Left-Pad' } }, + { custom: { kind: 'cpe', cpe: 'cpe:2.3:a:vendor:product' } }, + ], + }, + [], + NOW, + ); + expect(result.technologies.map((t) => t.technologyId)).toEqual([ + 'lodash', + 'custom:osv:npm:left-pad', + 'custom:cpe:cpe:2.3:a:vendor:product', + ]); + expect(customTechnologyId({ kind: 'osv', ecosystem: 'PyPI', package: 'X' })).toBe( + 'custom:osv:PyPI:x', + ); + }); + + it('keeps addedAt of entries that were already followed and collapses duplicates', () => { + const previous = [{ technologyId: 'lodash', addedAt: '2026-01-01T00:00:00.000Z' }]; + const result = normalizeWatchlistInput( + { + minSeverity: 'medium', + includeKev: false, + technologies: [ + { technologyId: 'lodash' }, + { technologyId: 'lodash' }, + { technologyId: 'redis' }, + ], + }, + previous, + NOW, + ); + expect(result.technologies).toEqual([ + { technologyId: 'lodash', addedAt: '2026-01-01T00:00:00.000Z' }, + { technologyId: 'redis', addedAt: NOW }, + ]); + }); + + it.each([ + [{ technologies: [{ technologyId: 'nope' }], minSeverity: 'high', includeKev: true }], + [ + { + technologies: [{ custom: { kind: 'osv', ecosystem: 'Cargo', package: 'x' } }], + minSeverity: 'high', + includeKev: true, + }, + ], + [ + { + technologies: [{ custom: { kind: 'cpe', cpe: 'not-a-cpe' } }], + minSeverity: 'high', + includeKev: true, + }, + ], + [{ technologies: [], minSeverity: 'severe', includeKev: true }], + [ + { + technologies: [{ technologyId: 'lodash', minSeverity: 'huge' }], + minSeverity: 'high', + includeKev: true, + }, + ], + ])('rejects invalid input %#', (input) => { + expect(() => normalizeWatchlistInput(input as never, [], NOW)).toThrow( + CveWatchlistValidationError, + ); + }); + + it('rejects more than the maximum number of technologies', () => { + const technologies = Array.from({ length: MAX_WATCHLIST_ENTRIES + 1 }, (_, i) => ({ + custom: { kind: 'osv' as const, ecosystem: 'npm' as const, package: `pkg-${i}` }, + })); + expect(() => + normalizeWatchlistInput({ technologies, minSeverity: 'high', includeKev: true }, [], NOW), + ).toThrow(/at most/); + }); +}); + +describe('targets and matching', () => { + it('resolves catalog and custom entries and deduplicates across organizations', () => { + expect(targetsOfEntry({ technologyId: 'postgresql' })).toEqual([ + { technologyId: 'postgresql', kind: 'cpe', cpe: 'cpe:2.3:a:postgresql:postgresql' }, + ]); + const entry = { technologyId: 'lodash', addedAt: NOW }; + const base = { + id: null, + minSeverity: 'high' as const, + includeKev: true, + updatedAt: null, + updatedBy: null, + }; + const union = unionTargets([ + { ...base, organizationId: 'a', technologies: [entry] }, + { ...base, organizationId: 'b', technologies: [entry] }, + ]); + expect(union).toHaveLength(targetsOfEntry(entry).length); + }); + + it('matches by entry severity over the list one, KEV only with includeKev, EPSS always', () => { + const entry = { technologyId: 'lodash', addedAt: NOW }; + const low = { severity: 'low' as const, kev: false, epssScore: null }; + expect(matchesEntry(low, entry, { minSeverity: 'high', includeKev: true }, 0.5)).toBe(false); + expect( + matchesEntry( + low, + { ...entry, minSeverity: 'low' }, + { minSeverity: 'high', includeKev: true }, + 0.5, + ), + ).toBe(true); + expect( + matchesEntry({ ...low, kev: true }, entry, { minSeverity: 'high', includeKev: true }, 0.5), + ).toBe(true); + expect( + matchesEntry({ ...low, kev: true }, entry, { minSeverity: 'high', includeKev: false }, 0.5), + ).toBe(false); + expect( + matchesEntry( + { ...low, epssScore: 0.9 }, + entry, + { minSeverity: 'high', includeKev: false }, + 0.5, + ), + ).toBe(true); + }); +}); diff --git a/src/modules/cve-feed/domain/watchlist.ts b/src/modules/cve-feed/domain/watchlist.ts new file mode 100644 index 0000000..5c63fd9 --- /dev/null +++ b/src/modules/cve-feed/domain/watchlist.ts @@ -0,0 +1,205 @@ +import { OSV_ECOSYSTEMS, getTechnology, type OsvEcosystem } from '#lib/cves/technologies.data'; +import { isSeverity, severityRank } from './severity'; +import type { + CustomTechnology, + CveAdvisory, + CveWatchlist, + Severity, + WatchTarget, + WatchlistEntry, +} from './types'; + +export const MAX_WATCHLIST_ENTRIES = 200; +export const DEFAULT_MIN_SEVERITY: Severity = 'high'; + +export class CveWatchlistValidationError extends Error { + constructor( + message: string, + readonly code: + | 'too_many' + | 'unknown_technology' + | 'invalid_custom' + | 'invalid_severity' + | 'invalid_versions' = 'invalid_custom', + ) { + super(message); + this.name = 'CveWatchlistValidationError'; + } +} + +/** Deterministic id of a custom technology. */ +export function customTechnologyId(custom: CustomTechnology): string { + return custom.kind === 'osv' + ? `custom:osv:${custom.ecosystem}:${custom.package.toLowerCase()}` + : `custom:cpe:${custom.cpe.toLowerCase()}`; +} + +export function emptyWatchlist(organizationId: string): CveWatchlist { + return { + id: null, + organizationId, + technologies: [], + minSeverity: DEFAULT_MIN_SEVERITY, + includeKev: true, + updatedAt: null, + updatedBy: null, + }; +} + +const CPE_PATTERN = /^cpe:2\.3:[aoh]:[^:\s]+:[^:\s]+/i; +const PACKAGE_PATTERN = /^[^\s]{1,200}$/; + +export type WatchlistEntryInput = { + technologyId?: string; + custom?: CustomTechnology; + label?: string; + minSeverity?: string | null; + versions?: string[]; +}; + +export type WatchlistInput = { + technologies: WatchlistEntryInput[]; + minSeverity: string; + includeKev: boolean; +}; + +function validateCustom(raw: unknown): CustomTechnology { + const custom = raw as Partial | undefined; + if (custom?.kind === 'osv') { + const ecosystem = custom.ecosystem as OsvEcosystem; + const name = typeof custom.package === 'string' ? custom.package.trim() : ''; + if (!OSV_ECOSYSTEMS.includes(ecosystem)) { + throw new CveWatchlistValidationError(`Unknown ecosystem "${String(custom.ecosystem)}"`); + } + if (!PACKAGE_PATTERN.test(name)) throw new CveWatchlistValidationError('Invalid package name'); + return { kind: 'osv', ecosystem, package: name }; + } + if (custom?.kind === 'cpe') { + const cpe = typeof custom.cpe === 'string' ? custom.cpe.trim() : ''; + if (cpe.length > 200 || !CPE_PATTERN.test(cpe)) { + throw new CveWatchlistValidationError( + 'Invalid CPE (expected cpe:2.3:::)', + ); + } + return { kind: 'cpe', cpe }; + } + throw new CveWatchlistValidationError('Invalid custom technology'); +} + +/** + * Validates and normalizes a watchlist. Entries keep the `addedAt` they already had (`previous`), + * so editing the list never turns old technologies into "new" ones; duplicates are collapsed. + */ +export function normalizeWatchlistInput( + input: WatchlistInput, + previous: readonly WatchlistEntry[], + now: string, +): Pick { + if (!isSeverity(input.minSeverity)) { + throw new CveWatchlistValidationError('Invalid minimum severity', 'invalid_severity'); + } + if (input.technologies.length > MAX_WATCHLIST_ENTRIES) { + throw new CveWatchlistValidationError( + `A watchlist can follow at most ${MAX_WATCHLIST_ENTRIES} technologies`, + 'too_many', + ); + } + const before = new Map(previous.map((entry) => [entry.technologyId, entry])); + const entries = new Map(); + for (const raw of input.technologies) { + let technologyId: string; + let custom: CustomTechnology | undefined; + if (raw.custom) { + custom = validateCustom(raw.custom); + technologyId = customTechnologyId(custom); + } else if (raw.technologyId && getTechnology(raw.technologyId)) { + technologyId = raw.technologyId; + } else { + throw new CveWatchlistValidationError( + `Unknown technology "${raw.technologyId ?? ''}"`, + 'unknown_technology', + ); + } + const minSeverity = raw.minSeverity ?? undefined; + if (minSeverity !== undefined && !isSeverity(minSeverity)) { + throw new CveWatchlistValidationError('Invalid severity', 'invalid_severity'); + } + const versions = (raw.versions ?? []).map((version) => version.trim()).filter(Boolean); + if (versions.length > 20 || versions.some((version) => version.length > 50)) { + throw new CveWatchlistValidationError('Invalid versions', 'invalid_versions'); + } + const label = raw.label?.trim().slice(0, 100) || undefined; + entries.set(technologyId, { + technologyId, + ...(custom ? { custom } : {}), + ...(label ? { label } : {}), + ...(minSeverity ? { minSeverity } : {}), + ...(versions.length ? { versions } : {}), + addedAt: before.get(technologyId)?.addedAt ?? now, + }); + } + return { + technologies: [...entries.values()], + minSeverity: input.minSeverity as Severity, + includeKev: Boolean(input.includeKev), + }; +} + +/** The lookup keys of one entry, per source. */ +export function targetsOfEntry( + entry: Pick, +): WatchTarget[] { + if (entry.custom) { + return entry.custom.kind === 'osv' + ? [ + { + technologyId: entry.technologyId, + kind: 'osv', + ecosystem: entry.custom.ecosystem, + package: entry.custom.package, + }, + ] + : [{ technologyId: entry.technologyId, kind: 'cpe', cpe: entry.custom.cpe }]; + } + const technology = getTechnology(entry.technologyId); + if (!technology) return []; + return [ + ...technology.osv.map((ref) => ({ technologyId: technology.id, kind: 'osv' as const, ...ref })), + ...technology.cpe.map((cpe) => ({ technologyId: technology.id, kind: 'cpe' as const, cpe })), + ]; +} + +/** Union of the watchlists: what the sources are asked, deduplicated across organizations. */ +export function unionTargets(watchlists: readonly CveWatchlist[]): WatchTarget[] { + const seen = new Map(); + for (const watchlist of watchlists) { + for (const entry of watchlist.technologies) { + for (const target of targetsOfEntry(entry)) { + const key = + target.kind === 'osv' + ? `osv:${target.technologyId}:${target.ecosystem}:${target.package}` + : `cpe:${target.technologyId}:${target.cpe}`; + seen.set(key, target); + } + } + } + return [...seen.values()]; +} + +/** + * Does an advisory of a followed technology interest this organization? Entry severity wins over + * the watchlist one; KEV counts when `includeKev`; EPSS over the threshold always counts. + */ +export function matchesEntry( + advisory: Pick, + entry: WatchlistEntry, + watchlist: Pick, + epssThreshold: number, +): boolean { + const min = entry.minSeverity ?? watchlist.minSeverity; + return ( + severityRank(advisory.severity) >= severityRank(min) || + (watchlist.includeKev && advisory.kev) || + (advisory.epssScore ?? 0) >= epssThreshold + ); +} diff --git a/src/modules/cve-feed/index.ts b/src/modules/cve-feed/index.ts new file mode 100644 index 0000000..38d853f --- /dev/null +++ b/src/modules/cve-feed/index.ts @@ -0,0 +1,216 @@ +import { eventBus } from '#lib/server/events'; +import { getGitDb } from '#lib/server/gitdb'; +import type { CachedGitDb } from '#lib/server/gitdb/cached-client'; +import { startSecondaryGitDb } from '#lib/server/gitdb/secondary'; +import { absoluteUrl } from '#lib/server/infra/notifications/config'; +import { createLogger } from '#lib/server/logger'; +import { codeReportCveService } from '../code-report'; +import { organizationService } from '../organization'; +import { projectService } from '../projects'; +import { CveFeedQueryService } from './application/cve-feed-query.service'; +import { CveFeedRuntime } from './application/cve-feed-runtime'; +import { CveWatchlistService } from './application/cve-watchlist.service'; +import { WatchlistSuggester } from './application/watchlist-suggester'; +import { + DEFAULT_CVE_FEED_CONFIG, + readCveFeedConfig, + readCveFeedRepositoryConfig, + type CveFeedFullConfig, +} from './infrastructure/config'; +import { HttpClient } from './infrastructure/http'; +import { CodeReportScans } from './infrastructure/scan-correlation'; +import { CveFeedStoreRepository } from './infrastructure/repositories/cve-feed-store.repository'; +import { WatchlistRepository } from './infrastructure/repositories/watchlist.repository'; +import { EpssSource } from './infrastructure/sources/epss.source'; +import { KevSource } from './infrastructure/sources/kev.source'; +import { NvdSource } from './infrastructure/sources/nvd.source'; +import { OsvSource } from './infrastructure/sources/osv.source'; + +const log = createLogger('cve-feed'); + +type CveFeedSlot = { + runtime: CveFeedRuntime; + query: CveFeedQueryService; + watchlist: CveWatchlistService; + suggester: WatchlistSuggester; + feedDb: CachedGitDb | null; + usesDedicatedRepository: boolean; + startup: Promise | null; + shutdownHooked: boolean; +}; + +const SLOT_KEY = Symbol.for('gitops.cve-feed'); +type GlobalWithCveFeed = typeof globalThis & { [SLOT_KEY]?: CveFeedSlot }; + +// an invalid CVE_FEED_* value must not take the server down: log it, use the default +const config: CveFeedFullConfig = (() => { + try { + return readCveFeedConfig((message) => log.warn(`[cve-feed] ${message}`)); + } catch (error) { + log.error({ err: error }, '[cve-feed] invalid configuration, using defaults'); + return { ...DEFAULT_CVE_FEED_CONFIG }; + } +})(); + +function feedDb(): CachedGitDb { + // the dedicated repository once started; the main GitDB otherwise + return slot.feedDb ?? getGitDb(); +} + +// the scans of Code Report as the feed sees them (ids and names only, never the findings) +const scans = new CodeReportScans({ + listProjects: async (organizationId) => + (await projectService.listProjectsByOrganization(organizationId)) + .filter((project) => project.status === 'active' && project.modules?.codereport) + .map((project) => ({ id: project.id, slug: project.slug ?? '', name: project.name })), + occurrences: (projects) => codeReportCveService.getOrganizationCveOccurrences(projects), + packages: (projects) => codeReportCveService.getOrganizationPackages(projects), +}); + +const store = new CveFeedStoreRepository(() => feedDb()); +const watchlistRepository = new WatchlistRepository(); + +// one runtime per process: HMR re-evaluating this module must keep the timers and the KEV set +const slot: CveFeedSlot = ((globalThis as GlobalWithCveFeed)[SLOT_KEY] ??= (() => { + const http = new HttpClient(); + const runtime: CveFeedRuntime = new CveFeedRuntime({ + store, + watchlists: watchlistRepository, + // KEV first: its set decides what the advisories are worth keeping. EPSS last: it enriches + // what is stored. NVD (CPE targets) is the slowest because of its rate limit + sources: [ + new KevSource(http), + new OsvSource(http), + new NvdSource(http, { apiKey: config.nvdApiKey }), + new EpssSource(http), + ], + config, + logger: log, + events: eventBus, + organizationSlug: async (id) => (await organizationService.getOrganization(id)).slug, + absoluteUrl, + scans, + onChanged: () => query.invalidate(), + }); + const query: CveFeedQueryService = new CveFeedQueryService({ + store, + watchlists: watchlistRepository, + epssThreshold: config.epssThreshold, + enabled: config.enabled, + status: async () => ({ + sources: await runtime.sourceStatuses(), + lastRunAt: runtime.lastRunInfo().at, + }), + scans, + }); + const suggester = new WatchlistSuggester({ packages: scans }); + // a new analysis changes "Te afecta" and the suggestions of its organization + const invalidateScans = (event: { scope: { organizationId?: string | null } }) => { + query.invalidateScans(event.scope.organizationId ?? undefined); + suggester.invalidate(event.scope.organizationId ?? undefined); + }; + for (const type of [ + 'code_report.analysis.completed', + 'code_report.service.created', + 'code_report.service.deleted', + ] as const) { + eventBus.subscribe(type, invalidateScans); + } + const watchlist = new CveWatchlistService({ + store: watchlistRepository, + suggest: (organizationId, followed) => suggester.suggest(organizationId, followed), + onChanged: (organizationId, { addedTechnologies }) => { + query.invalidate(organizationId); + // new technologies are backfilled soon instead of at the next interval + if (addedTechnologies.length > 0) { + runtime + .requestSync() + .catch((error) => log.warn({ err: error }, '[cve-feed] could not request a sync')); + } + }, + }); + return { + runtime, + query, + watchlist, + suggester, + feedDb: null, + usesDedicatedRepository: false, + startup: null, + shutdownHooked: false, + }; +})()); + +export const cveFeedRuntime = slot.runtime; +export const cveFeedQueryService = slot.query; +export const cveWatchlistService = slot.watchlist; + +export function getCveFeedConfig() { + return { ...config, nvdApiKey: config.nvdApiKey ? '***' : null }; +} + +/** Whether the feed may talk to the public sources. With false nothing external is ever called. */ +export function isCveFeedEnabled(): boolean { + return config.enabled; +} + +export function cveFeedInfo() { + return { enabled: config.enabled, dedicatedRepository: slot.usesDedicatedRepository }; +} + +/** + * Starts the feed repository and the runtime, once per process. Called after GitDB is ready + * (`hooks.server.ts`). Without CVE_FEED_ENABLED=true no timer is started and no source is called. + */ +export function startCveFeed(): Promise { + slot.startup ??= (async () => { + const repository = readCveFeedRepositoryConfig(); + if (repository) { + slot.feedDb = await startSecondaryGitDb({ name: 'cve-feed', ...repository }); + slot.usesDedicatedRepository = true; + } + if (!slot.shutdownHooked) { + slot.shutdownHooked = true; + process.once('sveltekit:shutdown' as never, () => void stopCveFeed()); + } + if (!config.enabled) { + log.info('[cve-feed] disabled (CVE_FEED_ENABLED is not true)'); + return; + } + await slot.runtime.start(); + log.info( + { dedicatedRepository: slot.usesDedicatedRepository, intervalMs: config.intervalMs }, + '[cve-feed] started', + ); + })().catch((error) => { + slot.startup = null; + throw error; + }); + return slot.startup; +} + +export async function stopCveFeed(): Promise { + await slot.runtime.stop(); +} + +export { CveWatchlistValidationError } from './domain/watchlist'; +export type { WatchlistInput, WatchlistEntryInput } from './domain/watchlist'; +export type { + CveFeedDetail, + CveFeedFilters, + CveFeedItem, + FeedScope, + CveFeedPage, + FeedStatus, + FollowedTechnology, + OrgFeedView, +} from './application/cve-feed-query.service'; +export type { WatchlistSuggestion } from './application/cve-watchlist.service'; +export type { ProjectRef, ScanRef } from './application/ports'; +export type { + CveAdvisory, + CveWatchlist, + FeedSourceState, + Severity, + WatchlistEntry, +} from './domain/types'; diff --git a/src/modules/cve-feed/infrastructure/config.test.ts b/src/modules/cve-feed/infrastructure/config.test.ts new file mode 100644 index 0000000..448952f --- /dev/null +++ b/src/modules/cve-feed/infrastructure/config.test.ts @@ -0,0 +1,78 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { readCveFeedConfig, readCveFeedRepositoryConfig } from './config'; + +const NAMES = [ + 'CVE_FEED_ENABLED', + 'CVE_FEED_SYNC_INTERVAL', + 'CVE_FEED_MIN_SEVERITY', + 'CVE_FEED_EPSS_THRESHOLD', + 'CVE_FEED_RETENTION', + 'CVE_FEED_BACKFILL', + 'NVD_API_KEY', + 'CVE_FEED_GITDB_REPOSITORY_URL', +]; + +afterEach(() => { + for (const name of NAMES) delete process.env[name]; +}); + +describe('readCveFeedConfig', () => { + it('is disabled with sensible defaults', () => { + expect(readCveFeedConfig()).toEqual({ + enabled: false, + intervalMs: 7_200_000, + minSeverity: 'high', + epssThreshold: 0.5, + retentionMs: 180 * 86_400_000, + backfillMs: 30 * 86_400_000, + nvdApiKey: null, + }); + }); + + it('reads valid values', () => { + Object.assign(process.env, { + CVE_FEED_ENABLED: 'true', + CVE_FEED_SYNC_INTERVAL: '30m', + CVE_FEED_MIN_SEVERITY: 'medium', + CVE_FEED_EPSS_THRESHOLD: '0.2', + CVE_FEED_RETENTION: '90d', + CVE_FEED_BACKFILL: '7d', + NVD_API_KEY: 'k', + }); + expect(readCveFeedConfig()).toMatchObject({ + enabled: true, + intervalMs: 1_800_000, + minSeverity: 'medium', + epssThreshold: 0.2, + retentionMs: 90 * 86_400_000, + backfillMs: 7 * 86_400_000, + nvdApiKey: 'k', + }); + }); + + it('falls back to the default for invalid values, and says so, without throwing', () => { + Object.assign(process.env, { + CVE_FEED_SYNC_INTERVAL: '5m', + CVE_FEED_MIN_SEVERITY: 'extreme', + CVE_FEED_EPSS_THRESHOLD: '7', + CVE_FEED_RETENTION: 'forever', + }); + const warnings: string[] = []; + const config = readCveFeedConfig((message) => warnings.push(message)); + expect(config.intervalMs).toBe(7_200_000); + expect(config.minSeverity).toBe('high'); + expect(config.epssThreshold).toBe(0.5); + expect(config.retentionMs).toBe(180 * 86_400_000); + expect(warnings).toHaveLength(4); + }); + + it('reads the optional dedicated repository', () => { + expect(readCveFeedRepositoryConfig()).toBeNull(); + process.env.CVE_FEED_GITDB_REPOSITORY_URL = 'git@example.com:o/r.git'; + expect(readCveFeedRepositoryConfig()).toMatchObject({ + repositoryUrl: 'git@example.com:o/r.git', + branch: 'main', + dataPath: null, + }); + }); +}); diff --git a/src/modules/cve-feed/infrastructure/config.ts b/src/modules/cve-feed/infrastructure/config.ts new file mode 100644 index 0000000..68498a5 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/config.ts @@ -0,0 +1,92 @@ +import * as env from '$app/env/private'; +import { parseDuration } from '../domain/duration'; +import { isSeverity } from '../domain/severity'; +import type { CveFeedConfig } from '../application/cve-feed-runtime'; + +export type CveFeedRepositoryConfig = { + repositoryUrl: string; + branch: string; + dataPath: string | null; + token: string | null; +}; + +export type CveFeedFullConfig = CveFeedConfig & { nvdApiKey: string | null }; + +export const DEFAULT_CVE_FEED_CONFIG: CveFeedFullConfig = { + enabled: false, + intervalMs: 2 * 3_600_000, + minSeverity: 'high', + epssThreshold: 0.5, + retentionMs: 180 * 86_400_000, + backfillMs: 30 * 86_400_000, + nvdApiKey: null, +}; + +const MIN_INTERVAL_MS = 15 * 60_000; + +function value(name: keyof typeof env): string | null { + const raw = env[name]?.trim(); + if (!raw) return null; + const quote = raw[0]; + return (quote === '"' || quote === "'") && raw.endsWith(quote) + ? raw.slice(1, -1).trim() || null + : raw; +} + +/** + * Reads CVE_FEED_* from the environment. An invalid value logs (via `warn`) and falls back to its + * default: a typo here must never take the server down. + */ +export function readCveFeedConfig(warn: (message: string) => void = () => {}): CveFeedFullConfig { + const config = { ...DEFAULT_CVE_FEED_CONFIG }; + + const flag = value('CVE_FEED_ENABLED')?.toLowerCase(); + if (flag) config.enabled = flag === 'true' || flag === '1' || flag === 'yes'; + + const duration = (name: keyof typeof env, fallback: number, min = 0) => { + const raw = value(name); + if (!raw) return fallback; + const parsed = parseDuration(raw); + if (parsed === null || parsed < min) { + warn( + `${name}="${raw}" is invalid${min ? ` (minimum ${min / 60_000}m)` : ''}, using the default`, + ); + return fallback; + } + return parsed; + }; + config.intervalMs = duration('CVE_FEED_SYNC_INTERVAL', config.intervalMs, MIN_INTERVAL_MS); + config.retentionMs = duration('CVE_FEED_RETENTION', config.retentionMs); + config.backfillMs = duration('CVE_FEED_BACKFILL', config.backfillMs); + + const severity = value('CVE_FEED_MIN_SEVERITY')?.toLowerCase(); + if (severity) { + if (isSeverity(severity) && severity !== 'unknown') config.minSeverity = severity; + else warn(`CVE_FEED_MIN_SEVERITY="${severity}" is invalid, using "${config.minSeverity}"`); + } + + const epss = value('CVE_FEED_EPSS_THRESHOLD'); + if (epss) { + const parsed = Number(epss); + if (Number.isFinite(parsed) && parsed >= 0 && parsed <= 1) config.epssThreshold = parsed; + else + warn( + `CVE_FEED_EPSS_THRESHOLD="${epss}" must be between 0 and 1, using ${config.epssThreshold}`, + ); + } + + config.nvdApiKey = value('NVD_API_KEY'); + return config; +} + +/** The dedicated feed repository, or `null` to keep the feed tables in the main GitDB. */ +export function readCveFeedRepositoryConfig(): CveFeedRepositoryConfig | null { + const repositoryUrl = value('CVE_FEED_GITDB_REPOSITORY_URL'); + if (!repositoryUrl) return null; + return { + repositoryUrl, + branch: value('CVE_FEED_GITDB_BRANCH') ?? 'main', + dataPath: value('CVE_FEED_GITDB_DATA_PATH'), + token: value('CVE_FEED_GITDB_TOKEN'), + }; +} diff --git a/src/modules/cve-feed/infrastructure/http.test.ts b/src/modules/cve-feed/infrastructure/http.test.ts new file mode 100644 index 0000000..96ac074 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/http.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from 'vitest'; +import { HttpClient, HttpError, parseRetryAfter } from './http'; + +function client(responses: Array, sleeps: number[] = []) { + const calls: Array<{ url: string; headers: Record }> = []; + const http = new HttpClient({ + fetch: async (url, init) => { + calls.push({ url, headers: init?.headers as Record }); + const next = responses.shift()!; + if (next instanceof Error) throw next; + return next; + }, + sleep: async (ms) => void sleeps.push(ms), + random: () => 0, + baseDelayMs: 100, + maxDelayMs: 5_000, + }); + return { http, calls, sleeps }; +} + +const json = (body: unknown, init: ResponseInit = {}) => new Response(JSON.stringify(body), init); + +describe('HttpClient', () => { + it('sends the user agent and returns JSON', async () => { + const { http, calls } = client([json({ ok: true })]); + expect(await http.json('https://api.osv.dev/x')).toEqual({ ok: true }); + expect(calls[0].headers['user-agent']).toBe('GitOps-CVE-Feed'); + }); + + it('retries 5xx and network errors with exponential backoff, then succeeds', async () => { + const { http, calls, sleeps } = client([ + new Response('', { status: 503 }), + new Error('ECONNRESET'), + json({ ok: 1 }), + ]); + expect(await http.json('https://api.osv.dev/x')).toEqual({ ok: 1 }); + expect(calls).toHaveLength(3); + expect(sleeps).toEqual([100, 200]); + }); + + it('honours Retry-After on 429', async () => { + const { http, sleeps } = client([ + new Response('', { status: 429, headers: { 'retry-after': '3' } }), + json({}), + ]); + await http.json('https://api.osv.dev/x'); + expect(sleeps).toEqual([3000]); + }); + + it('gives up after 3 attempts, and at once when asked to wait too long', async () => { + const failing = client([ + new Response('', { status: 500 }), + new Response('', { status: 500 }), + new Response('', { status: 502 }), + ]); + await expect(failing.http.json('https://api.osv.dev/x')).rejects.toBeInstanceOf(HttpError); + expect(failing.calls).toHaveLength(3); + + const limited = client([ + new Response('', { status: 429, headers: { 'retry-after': '3600' } }), + json({}), + ]); + await expect(limited.http.json('https://api.osv.dev/x')).rejects.toThrow(/HTTP 429/); + expect(limited.calls).toHaveLength(1); + }); + + it('does not retry a 4xx, and passes a 304 through', async () => { + const notFound = client([new Response('', { status: 404 }), json({})]); + await expect(notFound.http.json('https://api.osv.dev/x')).rejects.toMatchObject({ + status: 404, + }); + expect(notFound.calls).toHaveLength(1); + const unchanged = client([new Response(null, { status: 304 })]); + expect((await unchanged.http.request('https://x.test')).status).toBe(304); + }); + + it('parses Retry-After as seconds or date', () => { + expect(parseRetryAfter('5')).toBe(5000); + expect(parseRetryAfter(new Date(10_000).toUTCString(), 4_000)).toBe(6_000); + expect(parseRetryAfter(null)).toBeNull(); + expect(parseRetryAfter('soon')).toBeNull(); + }); +}); diff --git a/src/modules/cve-feed/infrastructure/http.ts b/src/modules/cve-feed/infrastructure/http.ts new file mode 100644 index 0000000..1afbceb --- /dev/null +++ b/src/modules/cve-feed/infrastructure/http.ts @@ -0,0 +1,104 @@ +export type FetchFn = (url: string, init?: RequestInit) => Promise; + +export type HttpClientOptions = { + fetch?: FetchFn; + timeoutMs?: number; + maxAttempts?: number; + /** Base of the exponential backoff. */ + baseDelayMs?: number; + maxDelayMs?: number; + sleep?: (ms: number) => Promise; + random?: () => number; + userAgent?: string; +}; + +export class HttpError extends Error { + constructor( + readonly status: number, + readonly url: string, + ) { + super(`HTTP ${status} from ${new URL(url).host}`); + this.name = 'HttpError'; + } +} + +const RETRYABLE = new Set([408, 425, 429, 500, 502, 503, 504]); + +/** `Retry-After` in seconds or as an HTTP date, in milliseconds. */ +export function parseRetryAfter(value: string | null, now = Date.now()): number | null { + if (!value) return null; + const seconds = Number(value); + if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000); + const date = Date.parse(value); + return Number.isNaN(date) ? null : Math.max(0, date - now); +} + +/** + * `fetch` with a timeout, and retries with exponential backoff plus jitter on 429, 5xx and + * network errors (honouring `Retry-After`). Plain global `fetch`: the hosts are fixed public ones, + * not user input, so the SSRF guard of the notification channels does not apply. A 304 is a + * normal answer. Anything else that is not 2xx throws `HttpError`. + */ +export class HttpClient { + private readonly fetchFn: FetchFn; + private readonly timeoutMs: number; + private readonly maxAttempts: number; + private readonly baseDelayMs: number; + private readonly maxDelayMs: number; + private readonly sleep: (ms: number) => Promise; + private readonly random: () => number; + private readonly userAgent: string; + + constructor(options: HttpClientOptions = {}) { + this.fetchFn = options.fetch ?? ((url, init) => fetch(url, init)); + this.timeoutMs = options.timeoutMs ?? 20_000; + this.maxAttempts = options.maxAttempts ?? 3; + this.baseDelayMs = options.baseDelayMs ?? 1_000; + this.maxDelayMs = options.maxDelayMs ?? 60_000; + this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + this.random = options.random ?? Math.random; + this.userAgent = options.userAgent ?? 'GitOps-CVE-Feed'; + } + + async request(url: string, init: RequestInit = {}): Promise { + let lastError: unknown; + for (let attempt = 1; attempt <= this.maxAttempts; attempt++) { + let retryAfter: number | null = null; + try { + const response = await this.fetchFn(url, { + ...init, + headers: { 'user-agent': this.userAgent, accept: 'application/json', ...init.headers }, + redirect: 'follow', + signal: AbortSignal.timeout(this.timeoutMs), + }); + if (response.ok || response.status === 304) return response; + lastError = new HttpError(response.status, url); + if (!RETRYABLE.has(response.status)) throw lastError; + retryAfter = parseRetryAfter(response.headers.get('retry-after')); + // asked to wait longer than we are willing to: give up, the next sync tries again + if (retryAfter !== null && retryAfter > this.maxDelayMs) throw lastError; + await response.body?.cancel().catch(() => {}); + } catch (error) { + if ( + error instanceof HttpError && + (!RETRYABLE.has(error.status) || + attempt >= this.maxAttempts || + (retryAfter ?? 0) > this.maxDelayMs) + ) + throw error; + lastError = error; + } + if (attempt < this.maxAttempts) { + const backoff = Math.min(this.maxDelayMs, this.baseDelayMs * 2 ** (attempt - 1)); + const jitter = backoff * 0.25 * this.random(); + await this.sleep(Math.min(this.maxDelayMs, Math.max(retryAfter ?? 0, backoff + jitter))); + } + } + throw lastError; + } + + async json(url: string, init: RequestInit = {}): Promise { + const response = await this.request(url, init); + return (await response.json()) as T; + } +} diff --git a/src/modules/cve-feed/infrastructure/rate-limiter.test.ts b/src/modules/cve-feed/infrastructure/rate-limiter.test.ts new file mode 100644 index 0000000..958cbfa --- /dev/null +++ b/src/modules/cve-feed/infrastructure/rate-limiter.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest'; +import { SlidingWindowRateLimiter, nvdRateLimiter } from './rate-limiter'; + +function clock() { + const state = { now: 0, sleeps: [] as number[] }; + return { + state, + now: () => state.now, + sleep: async (ms: number) => { + state.sleeps.push(ms); + state.now += ms; + }, + }; +} + +describe('SlidingWindowRateLimiter', () => { + it('lets `limit` requests through at once and holds the next until the window moves', async () => { + const c = clock(); + const limiter = new SlidingWindowRateLimiter({ limit: 3, windowMs: 1000, ...c }); + for (let i = 0; i < 3; i++) await limiter.acquire(); + expect(c.state.sleeps).toEqual([]); + await limiter.acquire(); + expect(c.state.sleeps).toEqual([1000]); + expect(c.state.now).toBe(1000); + }); + + it('is a rolling window: spaced requests never wait', async () => { + const c = clock(); + const limiter = new SlidingWindowRateLimiter({ limit: 2, windowMs: 1000, ...c }); + for (let i = 0; i < 6; i++) { + await limiter.acquire(); + c.state.now += 600; + } + expect(c.state.sleeps).toEqual([]); + }); + + it('never has more than `limit` requests inside any window, whatever the burst', async () => { + const c = clock(); + const limiter = new SlidingWindowRateLimiter({ limit: 5, windowMs: 30_000, ...c }); + const times: number[] = []; + await Promise.all( + Array.from({ length: 23 }, async () => { + await limiter.acquire(); + times.push(c.now()); + }), + ); + for (const start of times) { + expect(times.filter((t) => t >= start && t < start + 30_000).length).toBeLessThanOrEqual(5); + } + expect(times).toHaveLength(23); + }); + + it('uses 5 requests per 30 s without an NVD key and 50 with one', async () => { + for (const [key, limit] of [ + [null, 5], + ['secret', 50], + ] as const) { + const c = clock(); + const limiter = nvdRateLimiter(key, c); + for (let i = 0; i < limit; i++) await limiter.acquire(); + expect(c.state.sleeps).toEqual([]); + await limiter.acquire(); + expect(c.state.sleeps).toEqual([30_000]); + } + }); +}); diff --git a/src/modules/cve-feed/infrastructure/rate-limiter.ts b/src/modules/cve-feed/infrastructure/rate-limiter.ts new file mode 100644 index 0000000..748d929 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/rate-limiter.ts @@ -0,0 +1,59 @@ +/** Waits until a request may go out. Injectable so tests never sleep. */ +export interface RateLimiter { + acquire(): Promise; +} + +export type SlidingWindowOptions = { + /** Requests allowed in any window of `windowMs`. */ + limit: number; + windowMs: number; + now?: () => number; + sleep?: (ms: number) => Promise; +}; + +/** + * At most `limit` requests in any rolling window of `windowMs`. A caller over the limit waits for + * the oldest request of the window to leave it. Calls are served in order. + */ +export class SlidingWindowRateLimiter implements RateLimiter { + private readonly sent: number[] = []; + private tail: Promise = Promise.resolve(); + private readonly now: () => number; + private readonly sleep: (ms: number) => Promise; + + constructor(private readonly options: SlidingWindowOptions) { + this.now = options.now ?? Date.now; + this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + } + + acquire(): Promise { + const turn = this.tail.then(() => this.take()); + this.tail = turn.catch(() => {}); + return turn; + } + + private async take(): Promise { + const { limit, windowMs } = this.options; + for (;;) { + const now = this.now(); + while (this.sent.length > 0 && this.sent[0] <= now - windowMs) this.sent.shift(); + if (this.sent.length < limit) { + this.sent.push(now); + return; + } + await this.sleep(Math.max(1, this.sent[0] + windowMs - now)); + } + } +} + +/** NVD: 5 requests per rolling 30 seconds without an API key, 50 with one. */ +export function nvdRateLimiter( + apiKey: string | null | undefined, + options: Pick = {}, +): SlidingWindowRateLimiter { + return new SlidingWindowRateLimiter({ + limit: apiKey ? 50 : 5, + windowMs: 30_000, + ...options, + }); +} diff --git a/src/modules/cve-feed/infrastructure/repositories/cve-feed-store.repository.ts b/src/modules/cve-feed/infrastructure/repositories/cve-feed-store.repository.ts new file mode 100644 index 0000000..952266e --- /dev/null +++ b/src/modules/cve-feed/infrastructure/repositories/cve-feed-store.repository.ts @@ -0,0 +1,129 @@ +import type { CachedGitDb } from '#lib/server/gitdb/cached-client'; +import { CveAdvisoryEntity, CveFeedStateEntity, CveOrgMatchEntity } from '#lib/database/schemas'; +import type { + AdvisoryWrite, + CveFeedStore, + FeedStateRow, + MatchWrite, +} from '../../application/ports'; +import type { CveAdvisory, NotifiedState, OrgMatch, Severity } from '../../domain/types'; + +type Row = Record; + +function inList(field: string, values: readonly string[]) { + const set = new Set(values); + return { + kind: 'predicate' as const, + test: (row: Row) => set.has(String(row[field])), + debug: `${field} in [${values.length}]`, + }; +} + +const str = (value: unknown): string | null => (typeof value === 'string' ? value : null); +const num = (value: unknown): number | null => (typeof value === 'number' ? value : null); +const list = (value: unknown): T[] => (Array.isArray(value) ? (value as T[]) : []); + +function toAdvisory(row: Row): CveAdvisory { + return { + id: String(row.id), + aliases: list(row.aliases), + title: String(row.title), + summary: String(row.summary ?? ''), + details: String(row.details ?? ''), + severity: (str(row.severity) ?? 'unknown') as Severity, + cvssScore: num(row.cvssScore), + cvssVector: str(row.cvssVector), + cwe: list(row.cwe), + technologyIds: list(row.technologyIds), + affected: list(row.affected), + fixedVersions: list(row.fixedVersions), + references: list(row.references), + sources: list(row.sources), + publishedAt: str(row.publishedAt), + modifiedAt: String(row.modifiedAt), + kev: row.kev === true, + kevAddedAt: str(row.kevAddedAt), + epssScore: num(row.epssScore), + epssPercentile: num(row.epssPercentile), + epssUpdatedAt: str(row.epssUpdatedAt), + fingerprint: String(row.fingerprint), + firstSeenAt: String(row.firstSeenAt), + updatedAt: String(row.updatedAt), + }; +} + +function toMatch(row: Row): OrgMatch { + return { + id: String(row.id), + organizationId: String(row.organizationId), + cveId: String(row.cveId), + technologyId: String(row.technologyId), + firstSeenAt: String(row.firstSeenAt), + notified: (row.notified && typeof row.notified === 'object' + ? row.notified + : {}) as NotifiedState, + silent: row.silent === true, + }; +} + +function toState(row: Row): FeedStateRow { + const { id: _id, ...rest } = row; + void _id; + return rest as FeedStateRow; +} + +/** + * Reads and writes the feed tables (`cve_advisories`, `cve_org_matches`, `cve_feed_state`) of the + * feed GitDB: the dedicated repository when CVE_FEED_GITDB_REPOSITORY_URL is set, the main one + * otherwise. Every write is one delete plus one insert per table at most, whatever the rows; + * GitDB folds the writes of a sync into one commit. + */ +export class CveFeedStoreRepository implements CveFeedStore { + constructor(private readonly db: () => CachedGitDb) {} + + async listAdvisories(): Promise { + const { rows } = await this.db().select().from(CveAdvisoryEntity); + return rows.map(toAdvisory); + } + + async applyAdvisories({ upsert, deleteIds }: AdvisoryWrite): Promise { + const db = this.db(); + const stale = [...new Set([...deleteIds, ...upsert.map((row) => row.id)])]; + if (stale.length > 0) await db.delete(CveAdvisoryEntity).where(inList('id', stale)); + if (upsert.length > 0) + await db.insert(CveAdvisoryEntity).values(upsert.map((row) => ({ ...row }))); + } + + async listMatches(): Promise { + const { rows } = await this.db().select().from(CveOrgMatchEntity); + return rows.map(toMatch); + } + + async applyMatches({ upsert, deleteIds }: MatchWrite): Promise { + const db = this.db(); + const stale = [...new Set([...deleteIds, ...upsert.map((row) => row.id)])]; + if (stale.length > 0) await db.delete(CveOrgMatchEntity).where(inList('id', stale)); + if (upsert.length > 0) + await db.insert(CveOrgMatchEntity).values(upsert.map((row) => ({ ...row }))); + } + + async listStates(): Promise> { + const { rows } = await this.db().select().from(CveFeedStateEntity); + return new Map(rows.map((row) => [String(row.id), toState(row)])); + } + + async getState(id: string): Promise { + const { rows } = await this.db().select().from(CveFeedStateEntity).where({ id }); + return rows[0] ? toState(rows[0]) : null; + } + + async saveState(id: string, patch: FeedStateRow): Promise { + const values = Object.fromEntries( + Object.entries(patch).filter(([, value]) => value !== undefined), + ); + const db = this.db(); + const { rows } = await db.select().from(CveFeedStateEntity).where({ id }); + if (rows.length > 0) await db.update(CveFeedStateEntity).set(values).where({ id }); + else await db.insert(CveFeedStateEntity).values({ id, ...values }); + } +} diff --git a/src/modules/cve-feed/infrastructure/repositories/watchlist.repository.ts b/src/modules/cve-feed/infrastructure/repositories/watchlist.repository.ts new file mode 100644 index 0000000..f357208 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/repositories/watchlist.repository.ts @@ -0,0 +1,48 @@ +import { CveWatchlistEntity } from '#lib/database/schemas'; +import { getGitDb } from '#lib/server/gitdb'; +import type { CveWatchlist, Severity, WatchlistEntry } from '../../domain/types'; + +type Row = Record; + +export type WatchlistWrite = Pick & { + updatedBy: string | null; +}; + +function toWatchlist(row: Row): CveWatchlist { + return { + id: String(row.id), + organizationId: String(row.organizationId), + technologies: (Array.isArray(row.technologies) ? row.technologies : []) as WatchlistEntry[], + minSeverity: (typeof row.minSeverity === 'string' ? row.minSeverity : 'high') as Severity, + includeKev: row.includeKev !== false, + updatedAt: typeof row.updatedAt === 'string' ? row.updatedAt : null, + updatedBy: typeof row.updatedBy === 'string' ? row.updatedBy : null, + }; +} + +/** Watchlists are organization configuration: always the main GitDB, audited like any entity. */ +export class WatchlistRepository { + async listAll(): Promise { + const { rows } = await getGitDb().select().from(CveWatchlistEntity); + return rows.map(toWatchlist); + } + + async findByOrganization(organizationId: string): Promise { + const { rows } = await getGitDb().select().from(CveWatchlistEntity).where({ organizationId }); + return rows[0] ? toWatchlist(rows[0]) : null; + } + + async save(organizationId: string, write: WatchlistWrite, now: string): Promise { + const db = getGitDb(); + const existing = await this.findByOrganization(organizationId); + const values = { ...write, updatedAt: now }; + if (existing?.id) { + await db.update(CveWatchlistEntity).set(values).where({ id: existing.id }); + } else { + await db + .insert(CveWatchlistEntity) + .values({ id: crypto.randomUUID(), organizationId, ...values }); + } + return (await this.findByOrganization(organizationId))!; + } +} diff --git a/src/modules/cve-feed/infrastructure/scan-correlation.test.ts b/src/modules/cve-feed/infrastructure/scan-correlation.test.ts new file mode 100644 index 0000000..773da81 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/scan-correlation.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { CodeReportScans } from './scan-correlation'; + +const occurrence = (cve: string, serviceId: string, projectId = 'p1') => ({ + projectId, + projectSlug: projectId, + projectName: projectId.toUpperCase(), + serviceId, + serviceSlug: `slug-${serviceId}`, + serviceName: `Service ${serviceId}`, + finding: { id: cve, description: 'big payload that must not travel' }, +}); + +describe('CodeReportScans', () => { + const deps = () => { + const asked: string[][] = []; + return { + asked, + deps: { + listProjects: async () => [ + { id: 'p1', slug: 'p1', name: 'P1' }, + { id: 'p2', slug: 'p2', name: 'P2' }, + ], + occurrences: async (projects: Array<{ id: string }>) => { + asked.push(projects.map((project) => project.id)); + return new Map([ + ['cve-2026-1', [occurrence('cve-2026-1', 's1'), occurrence('cve-2026-1', 's1')]], + ['GHSA-x', [occurrence('GHSA-x', 's2', 'p2')]], + ]); + }, + packages: async () => [ + { serviceId: 's1', packages: [{ ecosystem: 'npm', name: 'express' }] }, + ], + }, + }; + }; + + it('indexes by upper-cased id, one entry per service, without the findings', async () => { + const { deps: d } = deps(); + const index = await new CodeReportScans(d).occurrences('org-1'); + expect([...index.keys()]).toEqual(['CVE-2026-1', 'GHSA-X']); + expect(index.get('CVE-2026-1')).toEqual([ + { + projectId: 'p1', + projectSlug: 'p1', + projectName: 'P1', + serviceId: 's1', + serviceSlug: 'slug-s1', + serviceName: 'Service s1', + }, + ]); + }); + + it('for the runtime asks about every active project; for a page, only the ones it is given', async () => { + const { deps: d, asked } = deps(); + const scans = new CodeReportScans(d); + await scans.occurrences('org-1'); + await scans.occurrences([{ id: 'p2', slug: 'p2', name: 'P2' }]); + expect(asked).toEqual([['p1', 'p2'], ['p2']]); + expect((await scans.occurrences([])).size).toBe(0); + expect(asked).toHaveLength(2); + }); + + it('lists the packages of the organization projects', async () => { + expect(await new CodeReportScans(deps().deps).packages('org-1')).toEqual([ + { serviceId: 's1', packages: [{ ecosystem: 'npm', name: 'express' }] }, + ]); + }); +}); diff --git a/src/modules/cve-feed/infrastructure/scan-correlation.ts b/src/modules/cve-feed/infrastructure/scan-correlation.ts new file mode 100644 index 0000000..9ad1ac7 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/scan-correlation.ts @@ -0,0 +1,65 @@ +import type { + OrganizationPackages, + OrganizationScans, + ProjectRef, + ProjectScans, + ScanOccurrences, + ServicePackages, +} from '../application/ports'; + +type OccurrenceLike = { + projectId: string; + projectSlug: string; + projectName: string; + serviceId: string; + serviceSlug: string; + serviceName: string; +}; + +export type CodeReportScansDeps = { + /** Active projects with Code Report of the organization. */ + listProjects(organizationId: string): Promise; + /** CVE id as the scans report it -> occurrences (the code-report module's own view). */ + occurrences(projects: ProjectRef[]): Promise>; + packages(projects: ProjectRef[]): Promise>; +}; + +/** + * The CVE feed's view of the Code Report data: which services report a CVE, and which packages + * they use. Only what the feed needs is kept (ids and names, never the findings), keyed by the + * upper-cased CVE id. The class does not know about permissions: the pages hand it the projects + * the user can see, the runtime asks for every active project of the organization. + */ +export class CodeReportScans implements OrganizationScans, ProjectScans, OrganizationPackages { + constructor(private readonly deps: CodeReportScansDeps) {} + + async occurrences(target: string | readonly ProjectRef[]): Promise { + const projects = + typeof target === 'string' ? await this.deps.listProjects(target) : [...target]; + const index: ScanOccurrences = new Map(); + if (projects.length === 0) return index; + for (const [cveId, occurrences] of await this.deps.occurrences(projects)) { + const services = new Map(); + for (const occurrence of occurrences) services.set(occurrence.serviceId, occurrence); + index.set( + cveId.toUpperCase(), + [...services.values()].map( + ({ projectId, projectSlug, projectName, serviceId, serviceSlug, serviceName }) => ({ + projectId, + projectSlug, + projectName, + serviceId, + serviceSlug, + serviceName, + }), + ), + ); + } + return index; + } + + async packages(organizationId: string): Promise { + const projects = await this.deps.listProjects(organizationId); + return projects.length === 0 ? [] : this.deps.packages(projects); + } +} diff --git a/src/modules/cve-feed/infrastructure/sources/epss.source.test.ts b/src/modules/cve-feed/infrastructure/sources/epss.source.test.ts new file mode 100644 index 0000000..395f512 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/epss.source.test.ts @@ -0,0 +1,181 @@ +import { describe, expect, it } from 'vitest'; +import { HttpClient } from '../http'; +import { EpssSource } from './epss.source'; +import { buildAdvisory } from '../../domain/advisory'; +import { normalizeOsv } from '../../domain/osv'; +import { LODASH, osvVuln } from '../../domain/fixtures'; +import type { SourceContext } from '../../application/ports'; +import type { CveAdvisory, FeedSourceState } from '../../domain/types'; + +const NOW = new Date('2026-11-10T10:00:00.000Z'); +const HOUR = 3_600_000; +const DAY = 24 * HOUR; +const iso = (ms: number) => new Date(ms).toISOString(); + +const emptyState: FeedSourceState = { + id: 'epss', + cursor: null, + etag: null, + lastModifiedHeader: null, + lastRunAt: null, + lastSuccessAt: null, + lastError: null, + lastErrorAt: null, + itemsLastRun: null, +}; + +function advisory( + n: number, + extra: Partial> & { id?: string } = {}, +): CveAdvisory { + const normalized = normalizeOsv( + osvVuln({ id: `GHSA-aaaa-bbbb-${String(n).padStart(4, '0')}`, aliases: [`CVE-2026-${n}`] }), + [LODASH], + )!; + const built = buildAdvisory( + { ...normalized, ...(extra.id ? { id: extra.id, aliases: [] } : {}) }, + { epssUpdatedAt: extra.epssUpdatedAt ?? null, firstSeenAt: extra.firstSeenAt }, + iso(NOW.getTime() - 5 * DAY), + ); + return built; +} + +function context(stored: CveAdvisory[], overrides: Partial = {}): SourceContext { + return { + targets: [], + now: NOW, + cutoffFor: () => '', + known: new Map(), + stored, + state: emptyState, + ...overrides, + }; +} + +function fakeEpss(score = '0.25') { + const asked: string[][] = []; + const http = new HttpClient({ + maxAttempts: 1, + fetch: async (url) => { + const ids = new URL(url).searchParams.get('cve')!.split(','); + asked.push(ids); + expect(new URL(url).origin + new URL(url).pathname).toBe( + 'https://api.first.org/data/v1/epss', + ); + return new Response( + JSON.stringify({ + data: ids.map((cve) => ({ cve, epss: score, percentile: '0.9', date: '2026-11-10' })), + }), + ); + }, + }); + return { http, asked }; +} + +describe('EpssSource', () => { + it('asks in batches of at most 100 CVE ids', async () => { + const { http, asked } = fakeEpss(); + const stored = Array.from({ length: 230 }, (_, i) => + advisory(i + 1, { id: `CVE-2026-${i + 1}` }), + ); + const result = await new EpssSource(http).sync(context(stored)); + expect(asked.map((batch) => batch.length)).toEqual([100, 100, 30]); + expect(result.epss!.size).toBe(230); + expect(result.epss!.get('CVE-2026-7')).toEqual({ score: 0.25, percentile: 0.9 }); + }); + + it('only asks for advisories with a CVE id (a GHSA-only advisory has no EPSS)', async () => { + const { http, asked } = fakeEpss(); + const ghsaOnly = advisory(1); + expect(ghsaOnly.id).toBe('CVE-2026-1'); // CVE is canonical when an alias is one + const noCve = { ...advisory(2), id: 'GHSA-only-only-only1', aliases: [] }; + await new EpssSource(http).sync(context([ghsaOnly, noCve])); + expect(asked).toEqual([['CVE-2026-1']]); + }); + + it('only asks for scores older than 24 h', async () => { + const { http, asked } = fakeEpss(); + const stored = [ + advisory(1, { epssUpdatedAt: iso(NOW.getTime() - 2 * HOUR) }), // fresh + advisory(2, { epssUpdatedAt: iso(NOW.getTime() - 25 * HOUR) }), // stale + advisory(3, { epssUpdatedAt: null }), // never scored + ]; + await new EpssSource(http).sync(context(stored)); + expect(asked).toEqual([['CVE-2026-2', 'CVE-2026-3']]); + }); + + it('does not ask again within the day even when the stored date cannot move', async () => { + // refreshing changed nothing relevant, so the runtime does not rewrite `epssUpdatedAt` + const { http, asked } = fakeEpss(); + const source = new EpssSource(http); + const stored = [advisory(1, { epssUpdatedAt: iso(NOW.getTime() - 30 * HOUR) })]; + await source.sync(context(stored)); + await source.sync(context(stored, { now: new Date(NOW.getTime() + 2 * HOUR) })); + await source.sync(context(stored, { now: new Date(NOW.getTime() + 4 * HOUR) })); + expect(asked).toHaveLength(1); + // a day later it is due again + await source.sync(context(stored, { now: new Date(NOW.getTime() + 25 * HOUR) })); + expect(asked).toHaveLength(2); + }); + + it('remembers the daily refresh in its state cursor, written once a day (and after a restart)', async () => { + const { http, asked } = fakeEpss(); + const stored = [advisory(1, { epssUpdatedAt: iso(NOW.getTime() - 30 * HOUR) })]; + const first = await new EpssSource(http).sync(context(stored)); + expect(first.statePatch).toEqual({ cursor: { refreshedAt: NOW.toISOString() } }); + + // restart: a new instance, with the persisted cursor and the same (unwritten) advisory + const later = new Date(NOW.getTime() + 3 * HOUR); + const restarted = await new EpssSource(http).sync( + context(stored, { + now: later, + state: { ...emptyState, cursor: first.statePatch!.cursor }, + }), + ); + expect(asked).toHaveLength(1); + expect(restarted.statePatch).toBeUndefined(); + expect(restarted.items).toBe(0); + }); + + it('asks for an advisory stored after the last refresh, without touching the persisted date', async () => { + const { http, asked } = fakeEpss(); + const cursor = { refreshedAt: iso(NOW.getTime() - 3 * HOUR) }; + const stored = [ + advisory(1, { firstSeenAt: iso(NOW.getTime() - 10 * DAY) }), // covered by the refresh + advisory(2, { firstSeenAt: iso(NOW.getTime() - 1 * HOUR) }), // newer than it + ]; + const result = await new EpssSource(http).sync( + context(stored, { state: { ...emptyState, cursor } }), + ); + expect(asked).toEqual([['CVE-2026-2']]); + expect(result.statePatch).toBeUndefined(); + }); + + it('keeps going when a batch fails, reports it, and does not move the refresh date', async () => { + let calls = 0; + const http = new HttpClient({ + maxAttempts: 1, + fetch: async (url) => { + calls++; + if (calls === 1) return new Response('boom', { status: 500 }); + const ids = new URL(url).searchParams.get('cve')!.split(','); + return new Response( + JSON.stringify({ data: ids.map((cve) => ({ cve, epss: '0.4', percentile: '0.8' })) }), + ); + }, + }); + const stored = Array.from({ length: 150 }, (_, i) => + advisory(i + 1, { id: `CVE-2026-${i + 1}` }), + ); + const result = await new EpssSource(http).sync(context(stored)); + expect(result.epss!.size).toBe(50); + expect(result.partialError).toMatch(/1 EPSS batches failed/); + expect(result.statePatch).toBeUndefined(); + }); + + it('does nothing when there is nothing stored', async () => { + const { http, asked } = fakeEpss(); + expect(await new EpssSource(http).sync(context([]))).toEqual({ items: 0 }); + expect(asked).toHaveLength(0); + }); +}); diff --git a/src/modules/cve-feed/infrastructure/sources/epss.source.ts b/src/modules/cve-feed/infrastructure/sources/epss.source.ts new file mode 100644 index 0000000..14d92b8 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/epss.source.ts @@ -0,0 +1,106 @@ +import type { CveAdvisory } from '../../domain/types'; +import type { CveSource, SourceContext, SourceResult } from '../../application/ports'; +import type { HttpClient } from '../http'; + +type EpssResponse = { data?: Array<{ cve: string; epss: string; percentile: string }> }; + +export type EpssSourceOptions = { + baseUrl?: string; + /** api.first.org accepts long lists; the feed stays at 100 CVEs per request. */ + batchSize?: number; + /** EPSS is published once a day. */ + maxAgeMs?: number; +}; + +type Cursor = { refreshedAt?: string }; + +const CVE_ID = /^CVE-\d{4}-\d+$/i; +const DAY = 86_400_000; + +/** + * FIRST EPSS (`api.first.org/data/v1/epss?cve=A,B,…`) for the advisories already stored under a + * CVE id, in batches of at most 100, and only for those whose score is older than a day. + * + * "Older than a day" is not read from each advisory alone. The advisory's `epssUpdatedAt` and + * percentile are outside the fingerprint, so a refresh that changes nothing relevant is never + * written, and `epssUpdatedAt` stays old on disk. What would then make every sync ask again is + * remembered in two places: this instance (`fetched`, lost on restart) and the `epss` state row + * (`cursor.refreshedAt`, one small write a day), which says "every advisory stored before this + * moment was refreshed then". An advisory is due when none of its three dates is recent. + */ +export class EpssSource implements CveSource { + readonly id = 'epss' as const; + readonly kinds = [] as const; + private readonly baseUrl: string; + private readonly batchSize: number; + private readonly maxAgeMs: number; + private readonly fetched = new Map(); + + constructor( + private readonly http: Pick, + options: EpssSourceOptions = {}, + ) { + this.baseUrl = options.baseUrl ?? 'https://api.first.org'; + this.batchSize = Math.min(options.batchSize ?? 100, 100); + this.maxAgeMs = options.maxAgeMs ?? DAY; + } + + /** The stored advisories whose EPSS has to be fetched now. */ + due(stored: readonly CveAdvisory[], state: SourceContext['state'], nowMs: number): CveAdvisory[] { + const refreshedAt = (state.cursor as Cursor | null)?.refreshedAt; + const refreshed = refreshedAt ? Date.parse(refreshedAt) : 0; + const limit = nowMs - this.maxAgeMs; + return stored.filter((advisory) => { + if (!CVE_ID.test(advisory.id)) return false; + const recent = Math.max( + advisory.epssUpdatedAt ? Date.parse(advisory.epssUpdatedAt) : 0, + // advisories stored after the last refresh are not covered by it + Date.parse(advisory.firstSeenAt) < refreshed ? refreshed : 0, + this.fetched.get(advisory.id) ?? 0, + ); + return recent < limit; + }); + } + + async sync(context: SourceContext): Promise { + const nowMs = context.now.getTime(); + const due = this.due(context.stored, context.state, nowMs); + if (due.length === 0) return { items: 0 }; + + const epss = new Map(); + let failures = 0; + let lastError = ''; + for (let start = 0; start < due.length; start += this.batchSize) { + const batch = due.slice(start, start + this.batchSize); + try { + const response = await this.http.json( + `${this.baseUrl}/data/v1/epss?cve=${batch.map((advisory) => advisory.id.toUpperCase()).join(',')}`, + ); + for (const row of response.data ?? []) { + const score = Number(row.epss); + const percentile = Number(row.percentile); + if (Number.isFinite(score) && Number.isFinite(percentile)) { + epss.set(row.cve.toUpperCase(), { score, percentile }); + } + } + // asked, answered or not (a very new CVE has no score yet): not asked again today + for (const advisory of batch) this.fetched.set(advisory.id, nowMs); + } catch (error) { + failures++; + lastError = error instanceof Error ? error.message : String(error); + } + } + + // the daily pass: the persisted date is older than a day (or there is none) and every due + // advisory answered, so it can move; a run that only fetched new advisories writes nothing + const refreshedAt = (context.state.cursor as Cursor | null)?.refreshedAt; + const covered = + failures === 0 && (!refreshedAt || Date.parse(refreshedAt) < nowMs - this.maxAgeMs); + return { + epss, + items: epss.size, + ...(covered ? { statePatch: { cursor: { refreshedAt: context.now.toISOString() } } } : {}), + ...(failures > 0 ? { partialError: `${failures} EPSS batches failed: ${lastError}` } : {}), + }; + } +} diff --git a/src/modules/cve-feed/infrastructure/sources/kev.source.ts b/src/modules/cve-feed/infrastructure/sources/kev.source.ts new file mode 100644 index 0000000..3ca3ceb --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/kev.source.ts @@ -0,0 +1,50 @@ +import type { CveSource, SourceContext, SourceResult } from '../../application/ports'; +import type { HttpClient } from '../http'; + +type KevCatalog = { vulnerabilities?: Array<{ cveID: string; dateAdded?: string }> }; + +const KEV_URL = + 'https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json'; + +/** + * CISA Known Exploited Vulnerabilities. Conditional GET (`If-None-Match` / `If-Modified-Since` + * with what the runtime persisted); the parsed set stays in memory and a 304 reuses it. After a + * restart the set is empty, so the first GET is unconditional. + */ +export class KevSource implements CveSource { + readonly id = 'kev' as const; + readonly kinds = [] as const; + private set: ReadonlyMap | null = null; + + constructor( + private readonly http: Pick, + private readonly url = KEV_URL, + ) {} + + async sync(context: SourceContext): Promise { + const conditional: Record = {}; + if (this.set) { + if (context.state.etag) conditional['if-none-match'] = context.state.etag; + if (context.state.lastModifiedHeader) + conditional['if-modified-since'] = context.state.lastModifiedHeader; + } + const response = await this.http.request(this.url, { headers: conditional }); + if (response.status === 304 && this.set) return { kev: this.set, items: this.set.size }; + + const catalog = (await response.json()) as KevCatalog; + const set = new Map(); + for (const entry of catalog.vulnerabilities ?? []) { + if (/^CVE-\d{4}-\d+$/i.test(entry.cveID)) + set.set(entry.cveID.toUpperCase(), entry.dateAdded ?? ''); + } + this.set = set; + return { + kev: set, + items: set.size, + statePatch: { + etag: response.headers.get('etag'), + lastModifiedHeader: response.headers.get('last-modified'), + }, + }; + } +} diff --git a/src/modules/cve-feed/infrastructure/sources/nvd.source.test.ts b/src/modules/cve-feed/infrastructure/sources/nvd.source.test.ts new file mode 100644 index 0000000..64ef260 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/nvd.source.test.ts @@ -0,0 +1,310 @@ +import { describe, expect, it } from 'vitest'; +import { HttpClient } from '../http'; +import { NvdSource, nvdCursorKey } from './nvd.source'; +import type { RateLimiter } from '../rate-limiter'; +import type { KnownAdvisory, SourceContext } from '../../application/ports'; +import type { NvdCve } from '../../domain/nvd'; +import type { FeedSourceState, WatchTarget } from '../../domain/types'; + +const NOW = new Date('2026-11-01T10:00:00.000Z'); +const DAY = 86_400_000; +const MYSQL: Extract = { + technologyId: 'mysql', + kind: 'cpe', + cpe: 'cpe:2.3:a:oracle:mysql', +}; +const REDIS: Extract = { + technologyId: 'redis', + kind: 'cpe', + cpe: 'cpe:2.3:a:redis:redis', +}; + +const emptyState: FeedSourceState = { + id: 'nvd', + cursor: null, + etag: null, + lastModifiedHeader: null, + lastRunAt: null, + lastSuccessAt: null, + lastError: null, + lastErrorAt: null, + itemsLastRun: null, +}; + +function cve(id: string, cpe: string, modified = '2026-10-20T10:00:00.000'): NvdCve { + return { + id, + lastModified: modified, + published: '2026-10-01T10:00:00.000', + descriptions: [{ lang: 'en', value: `Problem ${id}` }], + metrics: { + cvssMetricV31: [ + { + type: 'Primary', + cvssData: { + baseScore: 8.1, + vectorString: 'CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N', + }, + }, + ], + }, + configurations: [ + { + nodes: [ + { + cpeMatch: [ + { + vulnerable: true, + criteria: `${cpe}:*:*:*:*:*:*:*:*`, + versionEndExcluding: '2.0.0', + }, + ], + }, + ], + }, + ], + }; +} + +function context(overrides: Partial = {}): SourceContext { + return { + targets: [MYSQL], + now: NOW, + cutoffFor: () => new Date(NOW.getTime() - 30 * DAY).toISOString(), + known: new Map(), + stored: [], + state: emptyState, + ...overrides, + }; +} + +type Request = { url: URL; headers: Record }; + +/** Fake of services.nvd.nist.gov: `answer` gets each request and returns the page. */ +function fakeNvd(answer: (request: Request) => { totalResults: number; items: NvdCve[] } | number) { + const requests: Request[] = []; + const http = new HttpClient({ + maxAttempts: 1, + fetch: async (url, init) => { + const request = { + url: new URL(url), + headers: (init?.headers ?? {}) as Record, + }; + requests.push(request); + const result = answer(request); + if (typeof result === 'number') return new Response('no', { status: result }); + return new Response( + JSON.stringify({ + totalResults: result.totalResults, + vulnerabilities: result.items.map((item) => ({ cve: item })), + }), + ); + }, + }); + return { http, requests }; +} + +const noLimit: RateLimiter = { acquire: async () => {} }; + +describe('NvdSource', () => { + it('queries the CPE with virtualMatchString and a window from the cutoff to now', async () => { + const { http, requests } = fakeNvd(() => ({ + totalResults: 1, + items: [cve('CVE-2026-1', MYSQL.cpe)], + })); + const source = new NvdSource(http, { limiter: noLimit }); + const result = await source.sync(context()); + + expect(requests).toHaveLength(1); + const { url } = requests[0]; + expect(url.origin + url.pathname).toBe('https://services.nvd.nist.gov/rest/json/cves/2.0'); + expect(url.searchParams.get('virtualMatchString')).toBe('cpe:2.3:a:oracle:mysql'); + expect(url.searchParams.get('lastModStartDate')).toBe('2026-10-02T10:00:00.000'); + expect(url.searchParams.get('lastModEndDate')).toBe('2026-11-01T10:00:00.000'); + expect(url.searchParams.get('startIndex')).toBe('0'); + expect(result.candidates).toHaveLength(1); + expect(result.candidates![0]).toMatchObject({ + key: 'nvd:CVE-2026-1', + advisory: { id: 'CVE-2026-1', sources: ['nvd'], technologyIds: ['mysql'] }, + }); + }); + + it('sends the API key in the apiKey header, and no header without one', async () => { + const answer = () => ({ totalResults: 0, items: [] }); + const keyed = fakeNvd(answer); + await new NvdSource(keyed.http, { limiter: noLimit, apiKey: 'k-123' }).sync(context()); + expect(keyed.requests[0].headers).toMatchObject({ apiKey: 'k-123' }); + + const anonymous = fakeNvd(answer); + await new NvdSource(anonymous.http, { limiter: noLimit }).sync(context()); + expect(JSON.stringify(anonymous.requests[0].headers)).not.toContain('apiKey'); + }); + + it('pages with startIndex until totalResults', async () => { + const { http, requests } = fakeNvd(({ url }) => { + const start = Number(url.searchParams.get('startIndex')); + return { + totalResults: 3, + items: + start === 0 + ? [cve('CVE-2026-1', MYSQL.cpe), cve('CVE-2026-2', MYSQL.cpe)] + : [cve('CVE-2026-3', MYSQL.cpe)], + }; + }); + const result = await new NvdSource(http, { limiter: noLimit, pageSize: 2 }).sync(context()); + expect(requests.map((r) => r.url.searchParams.get('startIndex'))).toEqual(['0', '2']); + expect(result.candidates!.map((c) => c.advisory.id)).toEqual([ + 'CVE-2026-1', + 'CVE-2026-2', + 'CVE-2026-3', + ]); + }); + + it('splits a range longer than 120 days into windows and calls the limiter before each request', async () => { + const { http, requests } = fakeNvd(() => ({ totalResults: 0, items: [] })); + let acquired = 0; + const limiter: RateLimiter = { + acquire: async () => { + // a request is only made after the limiter let it through + expect(requests).toHaveLength(acquired); + acquired++; + }, + }; + await new NvdSource(http, { limiter }).sync( + context({ cutoffFor: () => new Date(NOW.getTime() - 180 * DAY).toISOString() }), + ); + expect(requests).toHaveLength(2); + expect(acquired).toBe(2); + const spans = requests.map( + ({ url }) => + (Date.parse(`${url.searchParams.get('lastModEndDate')}Z`) - + Date.parse(`${url.searchParams.get('lastModStartDate')}Z`)) / + DAY, + ); + expect(Math.max(...spans)).toBeLessThanOrEqual(120); + // the second window starts where the first ended + expect(requests[1].url.searchParams.get('lastModStartDate')).toBe( + requests[0].url.searchParams.get('lastModEndDate'), + ); + expect(requests[1].url.searchParams.get('lastModEndDate')).toBe('2026-11-01T10:00:00.000'); + }); + + describe('cursor', () => { + it('resumes from the stored cursor of each CPE, never before the cutoff', async () => { + const { http, requests } = fakeNvd(() => ({ totalResults: 0, items: [] })); + const cursor = { + cpes: { + [nvdCursorKey(MYSQL)]: '2026-10-31T00:00:00.000Z', + [nvdCursorKey(REDIS)]: '2020-01-01T00:00:00.000Z', // older than the cutoff + }, + }; + await new NvdSource(http, { limiter: noLimit }).sync( + context({ targets: [MYSQL, REDIS], state: { ...emptyState, cursor } }), + ); + const starts = Object.fromEntries( + requests.map((r) => [ + r.url.searchParams.get('virtualMatchString'), + r.url.searchParams.get('lastModStartDate'), + ]), + ); + expect(starts['cpe:2.3:a:oracle:mysql']).toBe('2026-10-31T00:00:00.000'); + expect(starts['cpe:2.3:a:redis:redis']).toBe('2026-10-02T10:00:00.000'); + }); + + it('is persisted on the first run, so the next one resumes from it', async () => { + const { http } = fakeNvd(() => ({ totalResults: 0, items: [] })); + const result = await new NvdSource(http, { limiter: noLimit }).sync(context()); + expect(result.statePatch?.cursor).toEqual({ + cpes: { [nvdCursorKey(MYSQL)]: NOW.toISOString() }, + }); + }); + + it('is not rewritten for less than a day of progress (a quiet sync writes nothing)', async () => { + const { http } = fakeNvd(() => ({ totalResults: 0, items: [] })); + const cursor = { cpes: { [nvdCursorKey(MYSQL)]: '2026-11-01T08:00:00.000Z' } }; + const result = await new NvdSource(http, { limiter: noLimit }).sync( + context({ state: { ...emptyState, cursor } }), + ); + expect(result.statePatch).toBeUndefined(); + expect(result.partialError).toBeUndefined(); + + const later = await new NvdSource(http, { limiter: noLimit }).sync( + context({ + now: new Date(NOW.getTime() + DAY), + state: { ...emptyState, cursor }, + }), + ); + expect(later.statePatch?.cursor).toEqual({ + cpes: { [nvdCursorKey(MYSQL)]: new Date(NOW.getTime() + DAY).toISOString() }, + }); + }); + + it('keeps the cursor of a CPE whose request failed and reports the error; the others advance', async () => { + const { http } = fakeNvd(({ url }) => + url.searchParams.get('virtualMatchString')!.includes('redis') + ? 503 + : { totalResults: 0, items: [] }, + ); + const old = '2026-10-20T00:00:00.000Z'; + const cursor = { cpes: { [nvdCursorKey(MYSQL)]: old, [nvdCursorKey(REDIS)]: old } }; + const result = await new NvdSource(http, { limiter: noLimit }).sync( + context({ targets: [MYSQL, REDIS], state: { ...emptyState, cursor } }), + ); + expect(result.partialError).toMatch(/1 of 2 CPEs failed/); + expect(result.statePatch?.cursor).toEqual({ + cpes: { [nvdCursorKey(MYSQL)]: NOW.toISOString(), [nvdCursorKey(REDIS)]: old }, + }); + }); + }); + + it('skips advisories the runtime already has unchanged, or remembers as rejected', async () => { + const { http } = fakeNvd(() => ({ + totalResults: 4, + items: [ + cve('CVE-2026-1', MYSQL.cpe, '2026-10-20T10:00:00.000'), + cve('CVE-2026-2', MYSQL.cpe, '2026-10-20T10:00:00.000'), + cve('CVE-2026-3', MYSQL.cpe, '2026-10-20T10:00:00.000'), + cve('CVE-2026-4', MYSQL.cpe, '2026-10-30T10:00:00.000'), + ], + })); + const known = new Map([ + ['CVE-2026-1', { modifiedAt: '2026-10-20T10:00:00.000Z', technologyIds: ['mysql'] }], + ['nvd:CVE-2026-2', { modifiedAt: '2026-10-20T10:00:00.000Z', technologyIds: null }], + // known for another technology: it still has to be tied to this one + ['CVE-2026-3', { modifiedAt: '2026-10-20T10:00:00.000Z', technologyIds: ['redis'] }], + // edited since + ['CVE-2026-4', { modifiedAt: '2026-10-20T10:00:00.000Z', technologyIds: ['mysql'] }], + ]); + const result = await new NvdSource(http, { limiter: noLimit }).sync(context({ known })); + expect(result.candidates!.map((c) => c.advisory.id)).toEqual(['CVE-2026-3', 'CVE-2026-4']); + }); + + it('retries 429/5xx through the shared client and fails the CPE after the last attempt', async () => { + let calls = 0; + const http = new HttpClient({ + maxAttempts: 3, + sleep: async () => {}, + random: () => 0, + fetch: async () => { + calls++; + return calls < 3 + ? new Response('slow down', { status: 429, headers: { 'retry-after': '1' } }) + : new Response(JSON.stringify({ totalResults: 0, vulnerabilities: [] })); + }, + }); + const result = await new NvdSource(http, { limiter: noLimit }).sync(context()); + expect(calls).toBe(3); + expect(result.partialError).toBeUndefined(); + }); + + it('does nothing without CPE targets', async () => { + const { http, requests } = fakeNvd(() => ({ totalResults: 0, items: [] })); + const result = await new NvdSource(http, { limiter: noLimit }).sync( + context({ + targets: [{ technologyId: 'lodash', kind: 'osv', ecosystem: 'npm', package: 'lodash' }], + }), + ); + expect(result).toEqual({ items: 0 }); + expect(requests).toHaveLength(0); + }); +}); diff --git a/src/modules/cve-feed/infrastructure/sources/nvd.source.ts b/src/modules/cve-feed/infrastructure/sources/nvd.source.ts new file mode 100644 index 0000000..2123234 --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/nvd.source.ts @@ -0,0 +1,168 @@ +import { normalizeNvd, type NvdCve } from '../../domain/nvd'; +import type { WatchTarget } from '../../domain/types'; +import type { + CveSource, + SourceCandidate, + SourceContext, + SourceResult, +} from '../../application/ports'; +import type { HttpClient } from '../http'; +import { nvdRateLimiter, type RateLimiter } from '../rate-limiter'; + +type CpeTarget = Extract; + +type NvdPage = { + totalResults: number; + startIndex?: number; + vulnerabilities?: Array<{ cve: NvdCve }>; +}; + +export type NvdSourceOptions = { + baseUrl?: string; + apiKey?: string | null; + /** Defaults to 5 requests / 30 s, 50 with an API key. */ + limiter?: RateLimiter; + pageSize?: number; + /** NVD accepts date ranges of at most 120 days. */ + maxWindowMs?: number; + maxPagesPerWindow?: number; + /** A cursor is only persisted when it is this much ahead of the stored one. */ + cursorPersistMs?: number; +}; + +type Cursor = { cpes?: Record }; + +const DAY = 86_400_000; + +/** NVD wants `YYYY-MM-DDThh:mm:ss.sss` (UTC when no offset is given). */ +const nvdParam = (ms: number) => new Date(ms).toISOString().slice(0, -1); + +export const nvdCursorKey = (target: CpeTarget) => `${target.technologyId}|${target.cpe}`; + +/** + * NVD API 2.0 for the CPE targets: `virtualMatchString` plus `lastModStartDate`/`lastModEndDate` + * windows (at most 120 days each), paged with `startIndex`. The cursor of each target is the end + * of the last window that succeeded; a target never goes further back than its retention or + * backfill cutoff. Every request goes through the rate limiter. + * + * Writes: the cursor lives in the `nvd` state row and is only handed back to be persisted when it + * is at least `cursorPersistMs` (24 h) ahead of the stored one (or there is none), so a sync + * without news writes nothing. Re-reading a window after a restart is harmless: stored advisories + * that have not changed are skipped through `known`. + */ +export class NvdSource implements CveSource { + readonly id = 'nvd' as const; + readonly kinds = ['cpe'] as const; + private readonly baseUrl: string; + private readonly apiKey: string | null; + private readonly limiter: RateLimiter; + private readonly pageSize: number; + private readonly maxWindowMs: number; + private readonly maxPages: number; + private readonly cursorPersistMs: number; + + constructor( + private readonly http: Pick, + options: NvdSourceOptions = {}, + ) { + this.baseUrl = options.baseUrl ?? 'https://services.nvd.nist.gov'; + this.apiKey = options.apiKey ?? null; + this.limiter = options.limiter ?? nvdRateLimiter(this.apiKey); + this.pageSize = options.pageSize ?? 2000; + // a day of margin under the 120 days NVD allows + this.maxWindowMs = options.maxWindowMs ?? 119 * DAY; + this.maxPages = options.maxPagesPerWindow ?? 50; + this.cursorPersistMs = options.cursorPersistMs ?? DAY; + } + + async sync(context: SourceContext): Promise { + const targets = context.targets.filter((target): target is CpeTarget => target.kind === 'cpe'); + if (targets.length === 0) return { items: 0 }; + + const stored = (context.state.cursor as Cursor | null)?.cpes ?? {}; + const reached: Record = {}; + const candidates: SourceCandidate[] = []; + const nowMs = context.now.getTime(); + let failures = 0; + let lastError = ''; + + for (const target of targets) { + const key = nvdCursorKey(target); + const cutoffMs = Date.parse(context.cutoffFor(target.technologyId)); + let startMs = Math.max(cutoffMs, stored[key] ? Date.parse(stored[key]) : cutoffMs); + reached[key] = stored[key] ?? new Date(Math.min(startMs, nowMs)).toISOString(); + try { + while (startMs < nowMs) { + const endMs = Math.min(startMs + this.maxWindowMs, nowMs); + await this.fetchWindow(target, startMs, endMs, context, candidates); + startMs = endMs; + reached[key] = new Date(endMs).toISOString(); + } + } catch (error) { + failures++; + lastError = error instanceof Error ? error.message : String(error); + } + } + + // only worth a write when it moved a day or more, or there was none + const persisted: Record = {}; + for (const target of targets) { + const key = nvdCursorKey(target); + const before = stored[key]; + persisted[key] = + !before || Date.parse(reached[key]) - Date.parse(before) >= this.cursorPersistMs + ? reached[key] + : before; + } + const changed = JSON.stringify(persisted) !== JSON.stringify(stored); + + return { + candidates, + items: candidates.length, + ...(changed ? { statePatch: { cursor: { cpes: persisted } satisfies Cursor } } : {}), + ...(failures > 0 + ? { partialError: `${failures} of ${targets.length} CPEs failed: ${lastError}` } + : {}), + }; + } + + private async fetchWindow( + target: CpeTarget, + startMs: number, + endMs: number, + context: SourceContext, + out: SourceCandidate[], + ): Promise { + for (let page = 0, startIndex = 0; page < this.maxPages; page++) { + const query = new URLSearchParams({ + virtualMatchString: target.cpe, + lastModStartDate: nvdParam(startMs), + lastModEndDate: nvdParam(endMs), + resultsPerPage: String(this.pageSize), + startIndex: String(startIndex), + }); + await this.limiter.acquire(); + const response = await this.http.json( + `${this.baseUrl}/rest/json/cves/2.0?${query}&noRejected`, + this.apiKey ? { headers: { apiKey: this.apiKey } } : {}, + ); + const items = response.vulnerabilities ?? []; + for (const { cve } of items) { + const advisory = normalizeNvd(cve, [target]); + if (!advisory) continue; + const known = context.known.get(`nvd:${cve.id}`) ?? context.known.get(cve.id); + if ( + known && + known.modifiedAt >= advisory.modifiedAt && + (known.technologyIds === null || known.technologyIds.includes(target.technologyId)) + ) { + continue; + } + out.push({ key: `nvd:${cve.id}`, advisory }); + } + startIndex += items.length; + if (items.length === 0 || startIndex >= response.totalResults) return; + } + throw new Error(`NVD returned more than ${this.maxPages} pages for ${target.cpe}`); + } +} diff --git a/src/modules/cve-feed/infrastructure/sources/osv.source.ts b/src/modules/cve-feed/infrastructure/sources/osv.source.ts new file mode 100644 index 0000000..c47779e --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/osv.source.ts @@ -0,0 +1,151 @@ +import { normalizeOsv, type OsvVulnerability } from '../../domain/osv'; +import type { WatchTarget } from '../../domain/types'; +import type { + CveSource, + SourceCandidate, + SourceContext, + SourceResult, +} from '../../application/ports'; +import type { HttpClient } from '../http'; + +type OsvTarget = Extract; + +type QueryBatchResponse = { + results: Array<{ vulns?: Array<{ id: string; modified: string }>; next_page_token?: string }>; +}; + +export type OsvSourceOptions = { + baseUrl?: string; + /** OSV accepts up to 1000 queries per request. */ + batchSize?: number; + concurrency?: number; + maxPagesPerQuery?: number; +}; + +/** + * OSV.dev: `POST /v1/querybatch` for every watched `{ecosystem, package}` (it only returns + * `{id, modified}`), then `GET /v1/vulns/{id}` for the ids that are new or modified since what we + * already hold, inside the technology's window. Nothing else is downloaded. + */ +export class OsvSource implements CveSource { + readonly id = 'osv' as const; + readonly kinds = ['osv'] as const; + private readonly baseUrl: string; + private readonly batchSize: number; + private readonly concurrency: number; + private readonly maxPages: number; + + constructor( + private readonly http: Pick, + options: OsvSourceOptions = {}, + ) { + this.baseUrl = options.baseUrl ?? 'https://api.osv.dev'; + this.batchSize = options.batchSize ?? 1000; + this.concurrency = options.concurrency ?? 4; + this.maxPages = options.maxPagesPerQuery ?? 20; + } + + async sync(context: SourceContext): Promise { + const targets = context.targets.filter((target): target is OsvTarget => target.kind === 'osv'); + if (targets.length === 0) return { items: 0 }; + + const byPackage = new Map(); + for (const target of targets) { + const key = `${target.ecosystem}|${target.package}`; + byPackage.set(key, [...(byPackage.get(key) ?? []), target]); + } + + // id -> modified and the technologies it was returned for + const listed = new Map }>(); + const packages = [...byPackage.entries()]; + for (let start = 0; start < packages.length; start += this.batchSize) { + await this.queryChunk(packages.slice(start, start + this.batchSize), listed); + } + + const toFetch: string[] = []; + for (const [id, vuln] of listed) { + const technologyIds = [...vuln.technologyIds]; + const cutoff = technologyIds.map((tech) => context.cutoffFor(tech)).sort()[0]; + if (vuln.modified < cutoff) continue; + const known = context.known.get(id); + if ( + known && + known.modifiedAt >= vuln.modified && + (known.technologyIds === null || + technologyIds.every((tech) => known.technologyIds?.includes(tech))) + ) { + continue; + } + toFetch.push(id); + } + + const candidates: SourceCandidate[] = []; + let failures = 0; + let lastError = ''; + let next = 0; + const worker = async () => { + while (next < toFetch.length) { + const id = toFetch[next++]; + try { + const vuln = await this.http.json( + `${this.baseUrl}/v1/vulns/${encodeURIComponent(id)}`, + ); + const advisory = normalizeOsv(vuln, targets); + if (advisory) candidates.push({ key: id, advisory }); + } catch (error) { + failures++; + lastError = error instanceof Error ? error.message : String(error); + } + } + }; + await Promise.all(Array.from({ length: Math.min(this.concurrency, toFetch.length) }, worker)); + + return { + candidates, + items: candidates.length, + ...(failures > 0 + ? { partialError: `${failures} of ${toFetch.length} vulnerabilities failed: ${lastError}` } + : {}), + }; + } + + private async queryChunk( + chunk: Array<[string, OsvTarget[]]>, + listed: Map }>, + ): Promise { + let pending = chunk.map(([key, targets]) => ({ + key, + targets, + pageToken: undefined as string | undefined, + pages: 0, + })); + while (pending.length > 0) { + const response = await this.http.json(`${this.baseUrl}/v1/querybatch`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ + queries: pending.map((query) => ({ + package: { ecosystem: query.targets[0].ecosystem, name: query.targets[0].package }, + ...(query.pageToken ? { page_token: query.pageToken } : {}), + })), + }), + }); + const following: typeof pending = []; + pending.forEach((query, index) => { + const result = response.results[index]; + for (const vuln of result?.vulns ?? []) { + const entry = listed.get(vuln.id) ?? { + modified: vuln.modified, + technologyIds: new Set(), + }; + for (const target of query.targets) entry.technologyIds.add(target.technologyId); + listed.set(vuln.id, entry); + } + if (result?.next_page_token && query.pages + 1 < this.maxPages) { + following.push({ ...query, pageToken: result.next_page_token, pages: query.pages + 1 }); + } + }); + pending = following; + } + } +} diff --git a/src/modules/cve-feed/infrastructure/sources/sources.test.ts b/src/modules/cve-feed/infrastructure/sources/sources.test.ts new file mode 100644 index 0000000..accf4dc --- /dev/null +++ b/src/modules/cve-feed/infrastructure/sources/sources.test.ts @@ -0,0 +1,224 @@ +import { describe, expect, it } from 'vitest'; +import { HttpClient } from '../http'; +import { OsvSource } from './osv.source'; +import { KevSource } from './kev.source'; +import type { KnownAdvisory, SourceContext } from '../../application/ports'; +import { LODASH, OSV_LODASH, osvVuln } from '../../domain/fixtures'; +import type { FeedSourceState } from '../../domain/types'; + +const NOW = new Date('2026-11-01T00:00:00Z'); +const emptyState: FeedSourceState = { + id: 'osv', + cursor: null, + etag: null, + lastModifiedHeader: null, + lastRunAt: null, + lastSuccessAt: null, + lastError: null, + lastErrorAt: null, + itemsLastRun: null, +}; + +function context(overrides: Partial = {}): SourceContext { + return { + targets: [ + LODASH, + { technologyId: 'express', kind: 'osv', ecosystem: 'npm', package: 'express' }, + ], + now: NOW, + cutoffFor: () => '2026-10-01T00:00:00.000Z', + known: new Map(), + stored: [], + state: emptyState, + ...overrides, + }; +} + +/** Fake of api.osv.dev: `listing` is what querybatch answers per package, `vulns` the full records. */ +function fakeOsv( + listing: Record>, + vulns: Record, + pages: Record = {}, +) { + const log: string[] = []; + const http = new HttpClient({ + fetch: async (url, init) => { + if (url.endsWith('/v1/querybatch')) { + const { queries } = JSON.parse(String(init?.body)) as { + queries: Array<{ package: { name: string }; page_token?: string }>; + }; + log.push( + `batch:${queries.map((q) => q.package.name + (q.page_token ? `#${q.page_token}` : '')).join(',')}`, + ); + const results = queries.map((q) => { + const all = listing[q.package.name] ?? []; + if (q.page_token === 'p2') return { vulns: all.slice(1) }; + if (pages[q.package.name] && !q.page_token) + return { vulns: all.slice(0, 1), next_page_token: pages[q.package.name] }; + return { vulns: all }; + }); + return new Response(JSON.stringify({ results })); + } + const id = decodeURIComponent(url.split('/v1/vulns/')[1]); + log.push(`vuln:${id}`); + return vulns[id] + ? new Response(JSON.stringify(vulns[id])) + : new Response('', { status: 404 }); + }, + sleep: async () => {}, + }); + return { source: new OsvSource(http), log }; +} + +describe('OsvSource', () => { + it('lists with querybatch and downloads only the vulnerabilities it needs', async () => { + const { source, log } = fakeOsv( + { + lodash: [ + { id: 'GHSA-35jh-r3h4-6jhm', modified: '2026-10-20T10:00:00Z' }, + { id: 'GHSA-unchanged', modified: '2026-10-10T00:00:00Z' }, + { id: 'GHSA-ancient', modified: '2020-01-01T00:00:00Z' }, + { id: 'GHSA-rejected', modified: '2026-10-11T00:00:00Z' }, + ], + express: [], + }, + { 'GHSA-35jh-r3h4-6jhm': OSV_LODASH }, + ); + const known = new Map([ + ['GHSA-unchanged', { modifiedAt: '2026-10-10T00:00:00Z', technologyIds: ['lodash'] }], + ['GHSA-rejected', { modifiedAt: '2026-10-11T00:00:00Z', technologyIds: null }], + ]); + const result = await source.sync(context({ known })); + + expect(log).toEqual(['batch:lodash,express', 'vuln:GHSA-35jh-r3h4-6jhm']); + expect(result.candidates).toHaveLength(1); + expect(result.candidates![0].advisory.id).toBe('CVE-2021-23337'); + expect(result.partialError).toBeUndefined(); + }); + + it('downloads again what was modified after the stored copy, or is now returned for a new technology', async () => { + const { source, log } = fakeOsv( + { lodash: [{ id: 'GHSA-35jh-r3h4-6jhm', modified: '2026-10-20T10:00:00Z' }], express: [] }, + { 'GHSA-35jh-r3h4-6jhm': OSV_LODASH }, + ); + const stale = new Map([ + ['GHSA-35jh-r3h4-6jhm', { modifiedAt: '2026-10-01T00:00:00Z', technologyIds: ['lodash'] }], + ]); + await source.sync(context({ known: stale })); + const otherTech = new Map([ + ['GHSA-35jh-r3h4-6jhm', { modifiedAt: '2026-10-20T10:00:00Z', technologyIds: ['react'] }], + ]); + await source.sync(context({ known: otherTech })); + expect(log.filter((line) => line.startsWith('vuln:'))).toHaveLength(2); + }); + + it('follows next_page_token', async () => { + const { source, log } = fakeOsv( + { + lodash: [ + { id: 'A', modified: '2026-10-20T00:00:00Z' }, + { id: 'B', modified: '2026-10-21T00:00:00Z' }, + ], + express: [], + }, + { A: osvVuln({ id: 'A', aliases: [] }), B: osvVuln({ id: 'B', aliases: [] }) }, + { lodash: 'p2' }, + ); + const result = await source.sync(context()); + expect(log.filter((line) => line.startsWith('batch'))).toEqual([ + 'batch:lodash,express', + 'batch:lodash#p2', + ]); + expect(result.candidates!.map((c) => c.key).sort()).toEqual(['A', 'B']); + }); + + it('splits more than 1000 packages into several batches', async () => { + const http = new HttpClient({ + fetch: async (url, init) => { + const { queries } = JSON.parse(String(init?.body)) as { queries: unknown[] }; + expect(queries.length).toBeLessThanOrEqual(1000); + return new Response(JSON.stringify({ results: queries.map(() => ({})) })); + }, + }); + const targets = Array.from({ length: 2500 }, (_, i) => ({ + technologyId: `t${i}`, + kind: 'osv' as const, + ecosystem: 'npm' as const, + package: `p${i}`, + })); + const result = await new OsvSource(http).sync(context({ targets })); + expect(result.items).toBe(0); + }); + + it('reports a partial failure but keeps what it downloaded', async () => { + const { source } = fakeOsv( + { + lodash: [ + { id: 'GHSA-35jh-r3h4-6jhm', modified: '2026-10-20T10:00:00Z' }, + { id: 'GHSA-gone', modified: '2026-10-21T00:00:00Z' }, + ], + express: [], + }, + { 'GHSA-35jh-r3h4-6jhm': OSV_LODASH }, + ); + const result = await source.sync(context()); + expect(result.candidates).toHaveLength(1); + expect(result.partialError).toMatch(/1 of 2/); + }); + + it('makes no request without OSV targets', async () => { + const { source, log } = fakeOsv({}, {}); + expect((await source.sync(context({ targets: [] }))).items).toBe(0); + expect(log).toEqual([]); + }); +}); + +describe('KevSource', () => { + const catalog = { + vulnerabilities: [{ cveID: 'CVE-2021-44228', dateAdded: '2021-12-10' }, { cveID: 'bogus' }], + }; + + function fakeKev() { + const requests: Array> = []; + const http = new HttpClient({ + fetch: async (_url, init) => { + const headers = init?.headers as Record; + requests.push(headers); + return headers['if-none-match'] === '"v1"' + ? new Response(null, { status: 304 }) + : new Response(JSON.stringify(catalog), { + headers: { etag: '"v1"', 'last-modified': 'Mon, 01 Nov 2026 00:00:00 GMT' }, + }); + }, + }); + return { source: new KevSource(http), requests }; + } + + it('downloads once, then revalidates with the stored validators and reuses the set on a 304', async () => { + const { source, requests } = fakeKev(); + const first = await source.sync(context()); + expect(first.kev!.get('CVE-2021-44228')).toBe('2021-12-10'); + expect(first.kev!.size).toBe(1); + expect(first.statePatch).toEqual({ + etag: '"v1"', + lastModifiedHeader: 'Mon, 01 Nov 2026 00:00:00 GMT', + }); + + const second = await source.sync( + context({ + state: { ...emptyState, etag: '"v1"', lastModifiedHeader: 'Mon, 01 Nov 2026 00:00:00 GMT' }, + }), + ); + expect(requests[1]['if-none-match']).toBe('"v1"'); + expect(requests[1]['if-modified-since']).toBeDefined(); + expect(second.kev!.get('CVE-2021-44228')).toBe('2021-12-10'); + expect(second.statePatch).toBeUndefined(); + }); + + it('after a restart (empty memory) downloads in full even with a stored etag', async () => { + const { source, requests } = fakeKev(); + const result = await source.sync(context({ state: { ...emptyState, etag: '"v1"' } })); + expect(requests[0]['if-none-match']).toBeUndefined(); + expect(result.kev!.size).toBe(1); + }); +}); diff --git a/src/routes/org/[org]/cves/+page.server.ts b/src/routes/org/[org]/cves/+page.server.ts index b399dc8..565874c 100644 --- a/src/routes/org/[org]/cves/+page.server.ts +++ b/src/routes/org/[org]/cves/+page.server.ts @@ -1,18 +1,121 @@ +import { error, fail } from '@sveltejs/kit'; +import { + CveWatchlistValidationError, + cveFeedQueryService, + cveFeedRuntime, + cveWatchlistService, + getCveFeedConfig, + isCveFeedEnabled, +} from '#modules/cve-feed'; +import { organizationService } from '#modules/organization'; import { buildCveList, loadCveOccurrences, organizationCveProjects, } from '#lib/server/code-report/cves'; +import { + FEED_PAGE_SIZE, + parseCvesTab, + parseFeedFilters, + parseWatchlistForm, +} from '#lib/cves/feed-view'; +import { + canReadCveFeed, + canReadOrganizationProjects, + canUpdateCveFeed, +} from '#lib/server/cve-feed-access'; export async function load({ parent, locals, url }) { const { organization } = await parent(); + const [canFeed, canProjects] = await Promise.all([ + canReadCveFeed(locals.user, organization.id), + canReadOrganizationProjects(locals.user, organization.id), + ]); + const tab = parseCvesTab(url.searchParams, { feed: canFeed, projects: canProjects }); + const base = { orgSlug: organization.slug as string, tab, canFeed }; + + if (tab === 'technology') { + const { filters, values } = parseFeedFilters(url.searchParams); + const [canUpdate, view, status] = await Promise.all([ + canUpdateCveFeed(locals.user, organization.id), + cveFeedQueryService.getView(organization.id), + cveFeedQueryService.status(), + ]); + // "Te afecta" and the suggestions come from the scans: only the projects the user can see + const projects = canProjects ? await organizationCveProjects(organization.id, locals.user) : []; + const [page, suggestions] = await Promise.all([ + cveFeedQueryService.list( + organization.id, + { ...filters, limit: FEED_PAGE_SIZE, offset: (values.page - 1) * FEED_PAGE_SIZE }, + { projects }, + ), + canUpdate && canProjects ? cveWatchlistService.suggestions(organization.id) : [], + ]); + return { + ...base, + feed: { + enabled: isCveFeedEnabled(), + canUpdate, + severityFloor: getCveFeedConfig().minSeverity, + watchlist: view.watchlist, + technologies: view.technologies, + items: page.items, + total: page.total, + pageSize: FEED_PAGE_SIZE, + filters: values, + status, + suggestions, + manage: url.searchParams.get('manage') === '1', + }, + }; + } + + // "Mis CVEs": exactly the scan view; no feed data is loaded here const projects = await organizationCveProjects(organization.id, locals.user); const occurrences = await loadCveOccurrences(projects); - return { - orgSlug: organization.slug as string, + ...base, cves: buildCveList(occurrences), projects: projects.map(({ slug, name }) => ({ slug, name })), initialProject: url.searchParams.get('project') ?? 'all', }; } + +export const actions = { + /** Replaces the watchlist (technologies, minimum severity, KEV). Works without JavaScript. */ + async watchlist({ request, locals, params }) { + const organization = await organizationService.tryFindBySlug(params.org); + if (!organization) throw error(404, 'Organization not found'); + if (!locals.user || !(await canUpdateCveFeed(locals.user, organization.id))) { + return fail(403, { action: 'watchlist', error: 'forbidden' }); + } + + const current = await cveWatchlistService.get(organization.id); + const input = parseWatchlistForm( + await request.formData(), + current, + getCveFeedConfig().minSeverity, + ); + try { + await cveWatchlistService.update(organization.id, input, locals.user.id); + } catch (err) { + if (err instanceof CveWatchlistValidationError) { + return fail(400, { action: 'watchlist', error: err.code, message: err.message }); + } + throw err; + } + return { action: 'watchlist', success: true }; + }, + + /** Asks the worker for a sync soon. It never calls a source from the request. */ + async sync({ locals, params }) { + const organization = await organizationService.tryFindBySlug(params.org); + if (!organization) throw error(404, 'Organization not found'); + if (!locals.user || !(await canUpdateCveFeed(locals.user, organization.id))) { + return fail(403, { action: 'sync', error: 'forbidden' }); + } + if (!isCveFeedEnabled()) return fail(409, { action: 'sync', error: 'disabled' }); + await cveFeedRuntime.requestSync(); + return { action: 'sync', success: true }; + }, +}; diff --git a/src/routes/org/[org]/cves/+page.svelte b/src/routes/org/[org]/cves/+page.svelte index 7d909e8..3379f6e 100644 --- a/src/routes/org/[org]/cves/+page.svelte +++ b/src/routes/org/[org]/cves/+page.svelte @@ -1,17 +1,29 @@ @@ -21,14 +33,26 @@

{$_('org.cves.title')}

-

{$_('org.cves.infoMessage')}

+

+ {data.tab === 'technology' ? $_('org.cves.feed.infoMessage') : $_('org.cves.infoMessage')} +

- `/org/${data.orgSlug}/cves/${encodeURIComponent(id)}`} - projects={data.projects} - initialProject={data.initialProject} - emptyMessage={$_('org.cves.emptyMessage')} - /> + {#if data.canFeed} + + {/if} + +
+ {#if data.tab === 'technology' && data.feed} + + {:else} + `/org/${data.orgSlug}/cves/${encodeURIComponent(id)}`} + projects={data.projects ?? []} + initialProject={data.initialProject ?? 'all'} + emptyMessage={$_('org.cves.emptyMessage')} + /> + {/if} +
diff --git a/src/routes/org/[org]/cves/[cve]/+page.server.ts b/src/routes/org/[org]/cves/[cve]/+page.server.ts index eff52b4..31c3279 100644 --- a/src/routes/org/[org]/cves/[cve]/+page.server.ts +++ b/src/routes/org/[org]/cves/[cve]/+page.server.ts @@ -1,16 +1,67 @@ import { error } from '@sveltejs/kit'; +import { cveFeedQueryService } from '#modules/cve-feed'; import { buildCveDetail, loadCveOccurrences, organizationCveProjects, } from '#lib/server/code-report/cves'; +import { advisoryToCveDetail } from '#lib/cves/feed-view'; +import { canReadCveFeed, canReadOrganizationProjects } from '#lib/server/cve-feed-access'; +import { getTechnology } from '#lib/cves/technologies.data'; export async function load({ parent, locals, params }) { const { organization } = await parent(); - const projects = await organizationCveProjects(organization.id, locals.user); + const [canFeed, canProjects] = await Promise.all([ + canReadCveFeed(locals.user, organization.id), + canReadOrganizationProjects(locals.user, organization.id), + ]); - const occurrences = (await loadCveOccurrences(projects)).get(params.cve); - if (!occurrences?.length) throw error(404, 'CVE not found'); + // without the feed permission this page behaves as it always did (403 / 404) + const projects = + canProjects || !canFeed ? await organizationCveProjects(organization.id, locals.user) : []; + const advisory = canFeed + ? await cveFeedQueryService.getAdvisory(organization.id, params.cve, { + projects: canProjects ? projects : [], + }) + : null; - return { orgSlug: organization.slug as string, ...buildCveDetail(params.cve, occurrences) }; + // the scans know the CVE by the id they report; the feed matches by id or alias + const ids = [ + params.cve, + ...(advisory ? [advisory.advisory.id, ...advisory.advisory.aliases] : []), + ]; + const byId = projects.length > 0 ? await loadCveOccurrences(projects) : new Map(); + const occurrences = ids.map((id) => byId.get(id)).find((list) => list?.length); + + if (!occurrences?.length && !advisory) throw error(404, 'CVE not found'); + + const feed = advisory + ? { + advisory: advisory.advisory, + affectsMe: advisory.affectsMe, + occurrences: advisory.occurrences, + technologies: advisory.technologyIds.map((id) => ({ + id, + name: getTechnology(id)?.name ?? id, + })), + } + : null; + + if (occurrences?.length) { + const id = ids.find((candidate) => byId.get(candidate)?.length) ?? params.cve; + return { + orgSlug: organization.slug as string, + scans: true, + feed, + ...buildCveDetail(id, occurrences), + }; + } + return { + orgSlug: organization.slug as string, + scans: false, + feed, + cve: advisoryToCveDetail(advisory!.advisory), + remediations: [], + affected: [], + }; } diff --git a/src/routes/org/[org]/cves/[cve]/+page.svelte b/src/routes/org/[org]/cves/[cve]/+page.svelte index bf10e0a..c67ad34 100644 --- a/src/routes/org/[org]/cves/[cve]/+page.svelte +++ b/src/routes/org/[org]/cves/[cve]/+page.svelte @@ -4,15 +4,24 @@ type CveDetail, type CveRemediation, } from '#lib/components/code-report/CveDetailView.svelte'; + import FeedAdvisorySection from '#lib/components/cves/FeedAdvisorySection.svelte'; + import type { CveAdvisory, ScanRef } from '#modules/cve-feed'; let { data, }: { data: { orgSlug: string; + scans: boolean; cve: CveDetail; remediations: CveRemediation[]; affected: CveAffected[]; + feed: { + advisory: CveAdvisory; + affectsMe: boolean; + occurrences: ScanRef[]; + technologies: { id: string; name: string }[]; + } | null; }; } = $props(); @@ -21,11 +30,26 @@ {data.cve.id} - CVEs - GitOps
+{#snippet feedSection()} + {#if data.feed} + + `/org/${data.orgSlug}/projects/${service.projectSlug}/code-report/services/${service.serviceSlug}`} + /> + {/if} +{/snippet} + `/org/${data.orgSlug}/projects/${service.projectSlug}/code-report/services/${service.serviceSlug}`} diff --git a/src/routes/org/[org]/cves/feed-actions.test.ts b/src/routes/org/[org]/cves/feed-actions.test.ts new file mode 100644 index 0000000..1bca112 --- /dev/null +++ b/src/routes/org/[org]/cves/feed-actions.test.ts @@ -0,0 +1,118 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +class ValidationError extends Error { + constructor( + message: string, + readonly code: string, + ) { + super(message); + } +} + +const mocks = vi.hoisted(() => ({ + canUpdate: vi.fn(), + enabled: vi.fn(), + requestSync: vi.fn(), + update: vi.fn(), + get: vi.fn(), +})); + +vi.mock('#modules/cve-feed', () => ({ + CveWatchlistValidationError: ValidationError, + cveFeedQueryService: {}, + cveFeedRuntime: { requestSync: mocks.requestSync }, + cveWatchlistService: { get: mocks.get, update: mocks.update, suggestions: vi.fn() }, + getCveFeedConfig: () => ({ minSeverity: 'high' }), + isCveFeedEnabled: mocks.enabled, +})); +vi.mock('#modules/organization', () => ({ + organizationService: { tryFindBySlug: async () => ({ id: 'org-1', slug: 'acme' }) }, +})); +vi.mock('#lib/server/cve-feed-access', () => ({ + canReadCveFeed: vi.fn(), + canReadOrganizationProjects: vi.fn(), + canUpdateCveFeed: mocks.canUpdate, +})); +vi.mock('#lib/server/code-report/cves', () => ({ + buildCveList: vi.fn(), + loadCveOccurrences: vi.fn(), + organizationCveProjects: vi.fn(), +})); + +const { actions } = await import('./+page.server'); + +const user = { id: 'user-1' }; +function event(fields: Record = {}, signedIn = true) { + const body = new FormData(); + for (const [key, value] of Object.entries(fields)) body.append(key, value); + return { + params: { org: 'acme' }, + locals: { user: signedIn ? user : null }, + request: { formData: async () => body }, + } as never; +} + +beforeEach(() => { + vi.resetAllMocks(); + mocks.canUpdate.mockResolvedValue(true); + mocks.enabled.mockReturnValue(true); + mocks.get.mockResolvedValue({ technologies: [] }); +}); + +describe('watchlist action', () => { + it('rejects users without organization:cves:feed:update', async () => { + mocks.canUpdate.mockResolvedValue(false); + const result = await actions.watchlist(event({ technology: 'redis' })); + expect(result).toMatchObject({ status: 403, data: { error: 'forbidden' } }); + expect(mocks.update).not.toHaveBeenCalled(); + }); + + it('rejects anonymous requests', async () => { + const result = await actions.watchlist(event({}, false)); + expect(result).toMatchObject({ status: 403 }); + expect(mocks.update).not.toHaveBeenCalled(); + }); + + it('saves the parsed watchlist with the user and lifts the severity to the floor', async () => { + const result = await actions.watchlist( + event({ technology: 'redis', minSeverity: 'low', includeKev: 'on' }), + ); + expect(result).toEqual({ action: 'watchlist', success: true }); + expect(mocks.update).toHaveBeenCalledWith( + 'org-1', + { technologies: [{ technologyId: 'redis' }], minSeverity: 'high', includeKev: true }, + 'user-1', + ); + }); + + it('turns validation errors into a 400 with the error code', async () => { + mocks.update.mockRejectedValue(new ValidationError('Unknown technology', 'unknown_technology')); + const result = await actions.watchlist(event({ technology: 'nope' })); + expect(result).toMatchObject({ status: 400, data: { error: 'unknown_technology' } }); + }); + + it('lets unexpected errors through', async () => { + mocks.update.mockRejectedValue(new Error('disk full')); + await expect(actions.watchlist(event({ technology: 'redis' }))).rejects.toThrow('disk full'); + }); +}); + +describe('sync action', () => { + it('rejects users without organization:cves:feed:update', async () => { + mocks.canUpdate.mockResolvedValue(false); + expect(await actions.sync(event())).toMatchObject({ status: 403 }); + expect(mocks.requestSync).not.toHaveBeenCalled(); + }); + + it('is rejected on the server when the feed is disabled', async () => { + mocks.enabled.mockReturnValue(false); + expect(await actions.sync(event())).toMatchObject({ status: 409, data: { error: 'disabled' } }); + expect(mocks.requestSync).not.toHaveBeenCalled(); + }); + + it('queues a sync when allowed and enabled', async () => { + mocks.requestSync.mockResolvedValue(true); + expect(await actions.sync(event())).toEqual({ action: 'sync', success: true }); + expect(mocks.requestSync).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/routes/org/[org]/settings/events/event-view.ts b/src/routes/org/[org]/settings/events/event-view.ts index d6f22ae..8d0e3e9 100644 --- a/src/routes/org/[org]/settings/events/event-view.ts +++ b/src/routes/org/[org]/settings/events/event-view.ts @@ -15,6 +15,7 @@ export const EVENT_MODULES: readonly EventModule[] = [ 'access', 'notifications', 'state_iac', + 'cve_feed', ]; export type EventStatusFilter = 'all' | 'pending' | 'acked';