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
8 changes: 7 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
60 changes: 60 additions & 0 deletions e2e/specs/cves-api.spec.ts
Original file line number Diff line number Diff line change
@@ -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());
});
});
213 changes: 213 additions & 0 deletions src/lib/server/cve-feed/api.ts
Original file line number Diff line number Diff line change
@@ -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<Access> {
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<ProjectRef[]> {
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<Response> {
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<Response> {
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<Response> {
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,
})),
}
: {}),
});
}
4 changes: 4 additions & 0 deletions src/routes/api/cves/[cve]/+server.ts
Original file line number Diff line number Diff line change
@@ -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);
4 changes: 4 additions & 0 deletions src/routes/api/cves/feed/+server.ts
Original file line number Diff line number Diff line change
@@ -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);
Loading
Loading