diff --git a/CLAUDE.md b/CLAUDE.md index 0402366..ffd39a8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -414,12 +414,13 @@ in `docs/adr/0001-event-bus-and-alerts.md`. - `integration_disabled`: its type is off in the environment (Slack without `SLACK_CLIENT_ID`/`SECRET`), or the organization disconnected it (e.g., last Slack workspace was removed) - `unavailable`: no transport registered - + It is computed, never stored. When an organization removes its last Slack workspace (`removeSlackWorkspace()`), `disableForIntegration()` disables all enabled Slack channels with `disabledReason: 'integration'`; when Slack is installed again, `restoreForIntegration()` enables only those back (ones manually disabled or failed stay as they are). `deliver()` only sends to `connected` channels, the views (`toView()`, alert channel options) carry it, and the settings list badges `integration_disabled`. + - Paused alerts and delivery status: `alertDelivery()` (`#lib/alerts/delivery.ts`, shared with the client) says whether an alert is `live`: it has email recipients or at least one connected channel. It computes `disconnectedTypes` (types of the alert's disconnected channels without repeats, @@ -659,6 +660,11 @@ monitors, monitors/new, monitors/[id], monitors/[id]/edit}`, thin routes over 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`. +- Public API (`/api/cves/{watchlist,feed,[cve]}`, logic in `$lib/server/cve-feed/api.ts`, ADR 0005): + reads only `cveFeedQueryService` (GitDB, never a source). No `organization:cves:feed:read` or an + unknown organization is a 404; `affectsMe` (filter and field) needs `organization:projects:read` + too (the filter is a 403 without it, the field is omitted). With the feed off the feed and the + detail answer empty with `feedEnabled: false`; the watchlist is still read from GitDB. - 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. diff --git a/e2e/specs/cves-api.spec.ts b/e2e/specs/cves-api.spec.ts new file mode 100644 index 0000000..462dce4 --- /dev/null +++ b/e2e/specs/cves-api.spec.ts @@ -0,0 +1,60 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { E2E_BASE_URL } from '../global-setup'; +import { E2E_FEED_CVE_ID } from '../fixtures/seed'; + +// the feed stays disabled in the suite: with permission the endpoints answer empty with +// `feedEnabled: false`, without it the organization looks like it has no feed (404) +const seed = getSeed(); +const base = `${E2E_BASE_URL}/api/cves`; +const query = `organizationId=${seed.primaryOrgId}`; + +test.describe('/api/cves', () => { + test('a caller with organization:cves:feed:read gets the feed answers', async ({ + page, + loginAs, + }) => { + await loginAs('orgCveFeedReader'); + const watchlist = await page.request.get(`${base}/watchlist?${query}`); + expect(watchlist.status()).toBe(200); + await expect(watchlist.json()).resolves.toMatchObject({ feedEnabled: false, technologies: [] }); + + const feed = await page.request.get(`${base}/feed?${query}`); + expect(feed.status()).toBe(200); + await expect(feed.json()).resolves.toEqual({ + feedEnabled: false, + items: [], + nextCursor: null, + total: 0, + }); + + const detail = await page.request.get(`${base}/${E2E_FEED_CVE_ID}?${query}`); + expect(detail.status()).toBe(200); + await expect(detail.json()).resolves.toEqual({ feedEnabled: false, cve: null }); + }); + + test('affectsMe needs organization:projects:read', async ({ page, loginAs }) => { + await loginAs('orgCveFeedReader'); + expect((await page.request.get(`${base}/feed?${query}&affectsMe=true`)).status()).toBe(403); + await loginAs('orgAdmin'); + expect((await page.request.get(`${base}/feed?${query}&affectsMe=true`)).status()).toBe(200); + }); + + test('invalid parameters are a 400', async ({ page, loginAs }) => { + await loginAs('orgCveFeedReader'); + const response = await page.request.get(`${base}/feed?${query}&severity=nope`); + expect(response.status()).toBe(400); + await expect(response.json()).resolves.toMatchObject({ code: 'invalid_request' }); + }); + + test('without the permission the organization is a 404', async ({ page, loginAs }) => { + await loginAs('orgNone'); + for (const path of ['watchlist', 'feed', E2E_FEED_CVE_ID]) { + expect((await page.request.get(`${base}/${path}?${query}`)).status()).toBe(404); + } + }); + + test('an anonymous caller is rejected', async ({ request }) => { + const response = await request.get(`${base}/feed?${query}`, { maxRedirects: 0 }); + expect([401, 404]).toContain(response.status()); + }); +}); diff --git a/src/lib/server/cve-feed/api.ts b/src/lib/server/cve-feed/api.ts new file mode 100644 index 0000000..927dcca --- /dev/null +++ b/src/lib/server/cve-feed/api.ts @@ -0,0 +1,213 @@ +import { getTechnology } from '#lib/cves/technologies.data'; +import { + apiError, + badRequest, + callerCan, + forbidden, + notFound, + ok, + paginate, + parsePagination, + type ApiLocals, +} from '#lib/server/api'; +import { + cveFeedQueryService, + isCveFeedEnabled, + type CveFeedFilters, + type CveFeedItem, + type ProjectRef, + type Severity, +} from '#modules/cve-feed'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; + +const FEED_READ = 'organization:cves:feed:read'; +const PROJECTS_READ = 'organization:projects:read'; +const SEVERITIES = ['low', 'medium', 'high', 'critical'] as const; +const SUMMARY_MAX = 300; +const DETAILS_MAX = 2000; + +const trim = (text: string, max: number) => + text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text; + +type Access = + { ok: true; organizationId: string; canProjects: boolean } | { ok: false; response: Response }; + +/** + * Permission-first. An organization that does not exist and a caller without + * `organization:cves:feed:read` are both a 404 (the feed of an organization is not revealed to + * who cannot read it, as in the UI). Whether the caller also has `organization:projects:read` is + * resolved lazily: only `affectsMe` and the affected projects need it. + */ +async function authorize(locals: ApiLocals, url: URL): Promise { + const organizationId = url.searchParams.get('organizationId')?.trim(); + if (!organizationId) return { ok: false, response: badRequest('organizationId is required') }; + const organization = await organizationService.getOrganization(organizationId).catch(() => null); + const context = { scope: 'organization', organizationId } as const; + if (!organization || !(await callerCan(locals, FEED_READ, context))) { + return { ok: false, response: notFound('Organization not found') }; + } + return { + ok: true, + organizationId, + canProjects: await callerCan(locals, PROJECTS_READ, context), + }; +} + +/** The projects whose scans "Te afecta" uses: the ones the caller can see (as the UI does). */ +async function visibleProjects(organizationId: string): Promise { + return (await projectService.listProjectsByOrganization(organizationId)) + .filter((project) => project.status === 'active' && project.modules?.codereport) + .map((project) => ({ id: project.id, slug: project.slug ?? '', name: project.name })); +} + +function parseBoolean(url: URL, name: string): boolean | undefined | 'invalid' { + const raw = url.searchParams.get(name); + if (raw === null) return undefined; + if (raw === 'true' || raw === '1') return true; + if (raw === 'false' || raw === '0') return false; + return 'invalid'; +} + +export async function getWatchlist(locals: ApiLocals, url: URL): Promise { + const access = await authorize(locals, url); + if (!access.ok) return access.response; + // the watchlist is read from GitDB even with the feed off: nothing external is involved + const view = await cveFeedQueryService.getView(access.organizationId); + const technologies = view.watchlist.technologies.map((entry, index) => { + const name = view.technologies[index]?.name ?? entry.technologyId; + const base = { + id: entry.technologyId, + name, + ...(entry.minSeverity ? { minSeverity: entry.minSeverity } : {}), + }; + if (entry.custom?.kind === 'osv') { + return { + ...base, + kind: 'osv' as const, + ecosystem: entry.custom.ecosystem, + package: entry.custom.package, + }; + } + if (entry.custom) return { ...base, kind: 'cpe' as const, cpe: entry.custom.cpe }; + const known = getTechnology(entry.technologyId); + return { + ...base, + kind: 'catalog' as const, + ...(known?.osv.length ? { packages: known.osv } : {}), + ...(known?.cpe.length ? { cpes: known.cpe } : {}), + }; + }); + return ok({ + feedEnabled: isCveFeedEnabled(), + technologies, + minSeverity: view.watchlist.minSeverity, + includeKev: view.watchlist.includeKev, + }); +} + +function toItem(item: CveFeedItem, withAffectsMe: boolean) { + const { advisory } = item; + return { + id: advisory.id, + aliases: advisory.aliases, + severity: advisory.severity, + cvss: advisory.cvssScore, + epss: advisory.epssScore, + kev: advisory.kev, + technologies: item.technologyIds, + summary: trim(advisory.summary || advisory.title, SUMMARY_MAX), + publishedAt: advisory.publishedAt, + modifiedAt: advisory.modifiedAt, + ...(withAffectsMe ? { affectsMe: item.affectsMe } : {}), + }; +} + +export async function listFeed(locals: ApiLocals, url: URL): Promise { + const access = await authorize(locals, url); + if (!access.ok) return access.response; + + const pagination = parsePagination(url); + if (!pagination.ok) return pagination.response; + + const filters: CveFeedFilters = {}; + const technology = url.searchParams.get('technology')?.trim(); + if (technology) filters.technologyId = technology.slice(0, 200); + const severity = url.searchParams.get('severity'); + if (severity) { + if (!(SEVERITIES as readonly string[]).includes(severity)) { + return badRequest(`severity must be one of ${SEVERITIES.join(', ')}`); + } + filters.minSeverity = severity as Severity; + } + const kev = parseBoolean(url, 'kev'); + const affectsMe = parseBoolean(url, 'affectsMe'); + if (kev === 'invalid' || affectsMe === 'invalid') { + return badRequest('kev and affectsMe must be true or false'); + } + if (kev !== undefined) filters.kev = kev; + if (affectsMe !== undefined) { + // "Te afecta" correlates with the projects: it needs `organization:projects:read` too + if (!access.canProjects) return forbidden('affectsMe requires organization:projects:read'); + filters.affectsMe = affectsMe; + } + + if (!isCveFeedEnabled()) return ok({ feedEnabled: false, items: [], nextCursor: null, total: 0 }); + + const projects = access.canProjects ? await visibleProjects(access.organizationId) : []; + const page = await cveFeedQueryService.list(access.organizationId, filters, { projects }); + const { items, nextCursor } = paginate(page.items, pagination); + return ok({ + feedEnabled: true, + items: items.map((item) => toItem(item, access.canProjects)), + nextCursor, + total: page.total, + }); +} + +export async function getCve(locals: ApiLocals, url: URL, cve: string): Promise { + const access = await authorize(locals, url); + if (!access.ok) return access.response; + if (!cve.trim() || cve.length > 200) return badRequest('Invalid CVE id'); + if (!isCveFeedEnabled()) return ok({ feedEnabled: false, cve: null }); + + const projects = access.canProjects ? await visibleProjects(access.organizationId) : []; + const detail = await cveFeedQueryService.getAdvisory(access.organizationId, cve.trim(), { + projects, + }); + if (!detail) return apiError(404, 'not_found', 'CVE not found in the feed of the organization'); + + const { advisory } = detail; + return ok({ + feedEnabled: true, + ...toItem(detail, access.canProjects), + title: advisory.title, + cvssVector: advisory.cvssVector, + epssPercentile: advisory.epssPercentile, + kevAddedAt: advisory.kevAddedAt, + cwe: advisory.cwe, + fixedVersions: advisory.fixedVersions, + affected: advisory.affected.map((a) => ({ + technology: a.technologyId, + ecosystem: a.ecosystem, + package: a.package, + cpe: a.cpe, + ranges: a.ranges, + fixedVersions: a.fixedVersions, + })), + references: advisory.references, + details: trim(advisory.details, DETAILS_MAX), + ...(access.canProjects + ? { + affectedServices: detail.occurrences.map((ref) => ({ + projectId: ref.projectId, + projectSlug: ref.projectSlug, + projectName: ref.projectName, + serviceId: ref.serviceId, + serviceSlug: ref.serviceSlug, + serviceName: ref.serviceName, + })), + } + : {}), + }); +} diff --git a/src/routes/api/cves/[cve]/+server.ts b/src/routes/api/cves/[cve]/+server.ts new file mode 100644 index 0000000..206e452 --- /dev/null +++ b/src/routes/api/cves/[cve]/+server.ts @@ -0,0 +1,4 @@ +import { getCve } from '#lib/server/cve-feed/api'; + +// GET /api/cves/[cve]?organizationId=…: a CVE of the organization's feed (by id or alias) +export const GET = ({ url, locals, params }) => getCve(locals, url, params.cve); diff --git a/src/routes/api/cves/feed/+server.ts b/src/routes/api/cves/feed/+server.ts new file mode 100644 index 0000000..a706b84 --- /dev/null +++ b/src/routes/api/cves/feed/+server.ts @@ -0,0 +1,4 @@ +import { listFeed } from '#lib/server/cve-feed/api'; + +// GET /api/cves/feed: see #lib/server/cve-feed/api (docs/adr/0005-mcp-server.md) +export const GET = ({ url, locals }) => listFeed(locals, url); diff --git a/src/routes/api/cves/server.test.ts b/src/routes/api/cves/server.test.ts new file mode 100644 index 0000000..896245b --- /dev/null +++ b/src/routes/api/cves/server.test.ts @@ -0,0 +1,251 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const state = vi.hoisted(() => ({ enabled: true })); +const grants: { users: Record; apiKeys: Record } = { + users: {}, + apiKeys: {}, +}; + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async (user: { id?: string } | null, permission: string) => + !!user?.id && (grants.users[user.id] ?? []).includes(permission), + canApiKey: async (apiKey: { id: string }, permission: string) => + (grants.apiKeys[apiKey.id] ?? []).includes(permission), + }, +})); + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => { + if (id !== 'org-1') throw new Error('not found'); + return { id, slug: 'kettu' }; + }, + }, +})); + +vi.mock('#modules/projects', () => ({ + projectService: { + listProjectsByOrganization: async () => [ + { + id: 'p1', + slug: 'billing', + name: 'Billing', + status: 'active', + modules: { codereport: true }, + }, + ], + }, +})); + +vi.mock('#modules/cve-feed', async () => { + const { buildAdvisory } = await import('#modules/cve-feed/domain/advisory'); + const { normalizeOsv } = await import('#modules/cve-feed/domain/osv'); + const { LODASH, OSV_LODASH, osvVuln } = await import('#modules/cve-feed/domain/fixtures'); + const { CveFeedQueryService } = + await import('#modules/cve-feed/application/cve-feed-query.service'); + const { InMemoryCveFeedStore, watchlist } = await import('#modules/cve-feed/application/testing'); + const store = new InMemoryCveFeedStore(); + const high = buildAdvisory(normalizeOsv(OSV_LODASH, [LODASH])!, {}, '2026-11-01T00:00:00.000Z'); + high.summary = 'x'.repeat(400); + const low = 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 [high, low]) store.advisories.set(advisory.id, advisory); + const query = new CveFeedQueryService({ + store, + watchlists: { + findByOrganization: async (id) => + id === 'org-1' ? watchlist('org-1', ['lodash'], { minSeverity: 'low' }) : null, + }, + epssThreshold: 0.5, + enabled: true, + status: async () => ({ sources: [], lastRunAt: null }), + scans: { + occurrences: async (projects: unknown[]) => + projects.length === 0 + ? new Map() + : new Map([ + [ + high.id.toUpperCase(), + [ + { + projectId: 'p1', + projectSlug: 'billing', + projectName: 'Billing', + serviceId: 's1', + serviceSlug: 'api', + serviceName: 'API', + }, + ], + ], + ]), + packages: async () => [], + } as never, + }); + return { + cveFeedQueryService: query, + isCveFeedEnabled: () => state.enabled, + highId: high.id, + }; +}); + +const feed = await import('./feed/+server'); +const watchlist = await import('./watchlist/+server'); +const detail = await import('./[cve]/+server'); +const { highId } = (await import('#modules/cve-feed')) as unknown as { highId: string }; + +const READ = 'organization:cves:feed:read'; +const PROJECTS = 'organization:projects:read'; + +function call( + handler: (event: never) => Promise | Response, + query: string, + locals: Record, + params: Record = {}, +) { + return handler({ + locals, + params, + url: new URL(`http://localhost/api/cves?${query}`), + } as never); +} + +const reader = { user: { id: 'reader' } }; +const full = { user: { id: 'full' } }; + +describe('/api/cves', () => { + beforeEach(() => { + state.enabled = true; + grants.users = { reader: [READ], full: [READ, PROJECTS], nobody: [PROJECTS] }; + grants.apiKeys = { key: [READ, PROJECTS] }; + }); + + it('answers 404 to unknown organizations and callers without the feed permission', async () => { + for (const handler of [feed.GET, watchlist.GET]) { + expect((await call(handler, 'organizationId=org-9', full)).status).toBe(404); + expect((await call(handler, 'organizationId=org-1', { user: { id: 'nobody' } })).status).toBe( + 404, + ); + expect((await call(handler, 'organizationId=org-1', {})).status).toBe(404); + } + const missing = await call(feed.GET, '', full); + expect(missing.status).toBe(400); + await expect(missing.json()).resolves.toMatchObject({ code: 'invalid_request' }); + }); + + it('returns the watchlist', async () => { + const response = await call(watchlist.GET, 'organizationId=org-1', reader); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toMatchObject({ + feedEnabled: true, + minSeverity: 'low', + technologies: [{ id: 'lodash', name: 'Lodash', kind: 'catalog' }], + }); + }); + + it('lists the feed without "affectsMe" when the caller cannot read projects', async () => { + const response = await call(feed.GET, 'organizationId=org-1', reader); + const body = await response.json(); + expect(body.feedEnabled).toBe(true); + expect(body.items.map((i: { id: string }) => i.id)).toEqual([highId, 'CVE-2026-9']); + expect(body.items[0]).not.toHaveProperty('affectsMe'); + expect(body.items[0].summary.length).toBeLessThanOrEqual(300); + expect(body.items[0]).toMatchObject({ technologies: ['lodash'], kev: false }); + }); + + it('forbids affectsMe without organization:projects:read', async () => { + const response = await call(feed.GET, 'organizationId=org-1&affectsMe=true', reader); + expect(response.status).toBe(403); + await expect(response.json()).resolves.toMatchObject({ code: 'forbidden' }); + }); + + it('computes affectsMe with projects:read, for sessions and API keys', async () => { + for (const locals of [full, { apiKey: { id: 'key' } }]) { + const all = await (await call(feed.GET, 'organizationId=org-1', locals)).json(); + expect(all.items.map((i: { affectsMe: boolean }) => i.affectsMe)).toEqual([true, false]); + const mine = await ( + await call(feed.GET, 'organizationId=org-1&affectsMe=true', locals) + ).json(); + expect(mine.items.map((i: { id: string }) => i.id)).toEqual([highId]); + } + }); + + it('filters by severity, kev and technology; rejects invalid parameters', async () => { + const kev = await (await call(feed.GET, 'organizationId=org-1&kev=true', full)).json(); + expect(kev.items.map((i: { id: string }) => i.id)).toEqual(['CVE-2026-9']); + const high = await (await call(feed.GET, 'organizationId=org-1&severity=high', full)).json(); + expect(high.items.map((i: { id: string }) => i.id)).toEqual([highId]); + const other = await ( + await call(feed.GET, 'organizationId=org-1&technology=redis', full) + ).json(); + expect(other.items).toEqual([]); + + for (const query of ['severity=bad', 'kev=maybe', 'limit=0', 'cursor=@@']) { + const response = await call(feed.GET, `organizationId=org-1&${query}`, full); + expect(response.status).toBe(400); + } + }); + + it('paginates with an opaque cursor', async () => { + const first = await (await call(feed.GET, 'organizationId=org-1&limit=1', full)).json(); + expect(first.items).toHaveLength(1); + expect(first.total).toBe(2); + const second = await ( + await call(feed.GET, `organizationId=org-1&limit=1&cursor=${first.nextCursor}`, full) + ).json(); + expect(second.items.map((i: { id: string }) => i.id)).toEqual(['CVE-2026-9']); + expect(second.nextCursor).toBeNull(); + }); + + it('returns the detail, with affected services only with projects:read', async () => { + const withProjects = await call(detail.GET, 'organizationId=org-1', full, { cve: highId }); + expect(withProjects.status).toBe(200); + const body = await withProjects.json(); + expect(body).toMatchObject({ id: highId, affectsMe: true, feedEnabled: true }); + expect(body.affectedServices).toEqual([expect.objectContaining({ serviceId: 's1' })]); + expect(body.fixedVersions).toContain('4.17.21'); + + const without = await ( + await call(detail.GET, 'organizationId=org-1', reader, { cve: highId }) + ).json(); + expect(without).not.toHaveProperty('affectedServices'); + expect(without).not.toHaveProperty('affectsMe'); + }); + + it('answers 404 for a CVE that is not in the feed or without permission', async () => { + expect( + (await call(detail.GET, 'organizationId=org-1', full, { cve: 'CVE-2099-1' })).status, + ).toBe(404); + expect( + (await call(detail.GET, 'organizationId=org-1', { user: { id: 'nobody' } }, { cve: highId })) + .status, + ).toBe(404); + }); + + it('answers empty with feedEnabled false when the feed is disabled', async () => { + state.enabled = false; + await expect((await call(feed.GET, 'organizationId=org-1', full)).json()).resolves.toEqual({ + feedEnabled: false, + items: [], + nextCursor: null, + total: 0, + }); + await expect( + (await call(detail.GET, 'organizationId=org-1', full, { cve: highId })).json(), + ).resolves.toEqual({ feedEnabled: false, cve: null }); + const wl = await (await call(watchlist.GET, 'organizationId=org-1', full)).json(); + expect(wl).toMatchObject({ feedEnabled: false, technologies: [{ id: 'lodash' }] }); + }); +}); diff --git a/src/routes/api/cves/watchlist/+server.ts b/src/routes/api/cves/watchlist/+server.ts new file mode 100644 index 0000000..dcb8c6d --- /dev/null +++ b/src/routes/api/cves/watchlist/+server.ts @@ -0,0 +1,4 @@ +import { getWatchlist } from '#lib/server/cve-feed/api'; + +// GET /api/cves/watchlist: see #lib/server/cve-feed/api (docs/adr/0005-mcp-server.md) +export const GET = ({ url, locals }) => getWatchlist(locals, url);