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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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: <GITDB_DATA_PATH>-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/<org>/settings/state-iac; their
# credentials live encrypted in GitDB (GITDB_ENCRYPTION_KEY), not here. Ambient auth uses the
Expand Down
34 changes: 34 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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`
Expand Down
192 changes: 192 additions & 0 deletions docs/adr/0004-cve-feed.md
Original file line number Diff line number Diff line change
@@ -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/<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` | `<org>:<cve>:<technology>` → 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 (`<technologyId>|<cpe>`) 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.
Loading
Loading