From 8a3b8bd05304c64e1676e9287c183394a4b48ee7 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:17:53 +0100 Subject: [PATCH 1/2] feat(api): Code Report read endpoints (#125) Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 9 +- e2e/fixtures/seed.ts | 2 + e2e/specs/code-report-api.spec.ts | 94 ++++ src/lib/server/code-report/api.ts | 393 +++++++++++++++ src/routes/api/code-report/server.test.ts | 456 ++++++++++++++++++ .../api/code-report/services/+server.ts | 4 + .../api/code-report/services/[id]/+server.ts | 4 + .../services/[id]/vulnerabilities/+server.ts | 4 + src/routes/api/projects/+server.ts | 4 + 9 files changed, 969 insertions(+), 1 deletion(-) create mode 100644 e2e/specs/code-report-api.spec.ts create mode 100644 src/lib/server/code-report/api.ts create mode 100644 src/routes/api/code-report/server.test.ts create mode 100644 src/routes/api/code-report/services/+server.ts create mode 100644 src/routes/api/code-report/services/[id]/+server.ts create mode 100644 src/routes/api/code-report/services/[id]/vulnerabilities/+server.ts create mode 100644 src/routes/api/projects/+server.ts diff --git a/CLAUDE.md b/CLAUDE.md index 0402366a..f11385f6 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, @@ -748,6 +749,12 @@ Unauthenticated public routes for external alert recipients: `/notifications/ver They are allowed without a session in `hooks.server.ts` and validate their tokens rather than checking permissions. +Read API for discovery and Code Report (`GET /api/projects`, `/api/code-report/services[/id[/vulnerabilities]]`, +logic in `#lib/server/code-report/api.ts`): permission-first through `callerCan` (sessions and keys). A project +or service the caller cannot read is a 404; 403 only when the project is readable (`project:project:read` or a +Code Report read) but the action (`reports:read`, `vulnerabilities:read`) is not. Lists use `limit`/`cursor`; +CVE titles are cut to 300 characters and the SBOM or raw scanner output is never returned. + `locals.user.role` is a session role object, not the string `admin`. Use `isAdmin()` or the `can*` helpers. Keep authorization tests beside changes to permission behavior. diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index 8313e908..fec48e2f 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -56,6 +56,7 @@ export type SeedOutput = { outsiderOrgSlug: string; outsiderProjectSlug: string; seededServiceSlug: string; + seededServiceId: string; apiKeys: { readOnly: string; write: string; @@ -562,6 +563,7 @@ export async function seedAll(): Promise { outsiderOrgSlug: requireSeedSlug(outsiderOrg.slug, 'outsider organization'), outsiderProjectSlug: requireSeedSlug(outsiderProject.slug, 'outsider project'), seededServiceSlug: seededService.slug, + seededServiceId: seededService.id, apiKeys: { readOnly: readOnlyApiKeyToken, write: writeApiKeyToken, diff --git a/e2e/specs/code-report-api.spec.ts b/e2e/specs/code-report-api.spec.ts new file mode 100644 index 00000000..199a5705 --- /dev/null +++ b/e2e/specs/code-report-api.spec.ts @@ -0,0 +1,94 @@ +import { test, expect, getSeed } from '../fixtures/auth'; + +// read-only Code Report API (#125): a user (cookie) or a project key sees its project; everyone +// else gets 404 (existence not revealed) or 403 when the project is readable but not the action +const seed = getSeed(); +const services = `/api/code-report/services?projectId=${seed.primaryProjectId}`; +const detail = `/api/code-report/services/${seed.seededServiceId}`; +const vulnerabilities = `${detail}/vulnerabilities`; +const bearer = (token: string) => ({ Authorization: `Bearer ${token}` }); + +test.describe('code report API — session', () => { + test('a project viewer reads projects, services, report and vulnerabilities', async ({ + page, + loginAs, + }) => { + await loginAs('projectViewer'); + + const projects = await page.request.get('/api/projects'); + expect(projects.status()).toBe(200); + const { items } = await projects.json(); + const mine = items.find((p: { id: string }) => p.id === seed.primaryProjectId); + expect(mine).toMatchObject({ + slug: seed.primaryProjectSlug, + organization: { id: seed.primaryOrgId, slug: seed.primaryOrgSlug }, + }); + expect(mine.modules).toContain('codereport'); + expect(items.some((p: { slug: string }) => p.slug === seed.outsiderProjectSlug)).toBe(false); + + const list = await page.request.get(services); + expect(list.status()).toBe(200); + const listed = await list.json(); + expect(listed.items.map((s: { id: string }) => s.id)).toContain(seed.seededServiceId); + + const report = await page.request.get(detail); + expect(report.status()).toBe(200); + expect(await report.json()).toMatchObject({ + id: seed.seededServiceId, + name: 'E2E Seeded Service', + lastAnalysisAt: null, + }); + + const cves = await page.request.get(vulnerabilities); + expect(cves.status()).toBe(200); + expect(await cves.json()).toEqual({ items: [], nextCursor: null }); + }); + + test('invalid parameters are 400 with a normalized error', async ({ page, loginAs }) => { + await loginAs('projectViewer'); + const response = await page.request.get(`${vulnerabilities}?severity=nasty`); + expect(response.status()).toBe(400); + expect(await response.json()).toMatchObject({ code: 'invalid_request' }); + expect((await page.request.get('/api/code-report/services')).status()).toBe(400); + }); + + test('a project:project:read-only user is forbidden, not 404', async ({ page, loginAs }) => { + await loginAs('projectReadOnly'); + expect((await page.request.get(services)).status()).toBe(403); + expect((await page.request.get(detail)).status()).toBe(403); + expect((await page.request.get(vulnerabilities)).status()).toBe(403); + }); + + test('a user of another organization gets 404 everywhere', async ({ page, loginAs }) => { + await loginAs('projectOutsider'); + expect((await page.request.get(services)).status()).toBe(404); + expect((await page.request.get(detail)).status()).toBe(404); + expect((await page.request.get(vulnerabilities)).status()).toBe(404); + expect( + (await page.request.get(`/api/projects?organizationId=${seed.primaryOrgId}`)).status(), + ).toBe(404); + const { items } = await (await page.request.get('/api/projects')).json(); + expect(items.some((p: { id: string }) => p.id === seed.primaryProjectId)).toBe(false); + }); + + test('without a session the API answers 401', async ({ request }) => { + expect((await request.get(services)).status()).toBe(401); + }); +}); + +test.describe('code report API — project keys', () => { + test('a key reads its own project', async ({ request }) => { + const headers = bearer(seed.apiKeys.readOnly); + expect((await request.get(services, { headers })).status()).toBe(200); + expect((await request.get(detail, { headers })).status()).toBe(200); + const { items } = await (await request.get('/api/projects', { headers })).json(); + expect(items.map((p: { id: string }) => p.id)).toEqual([seed.primaryProjectId]); + }); + + test('a key of another project gets 404', async ({ request }) => { + const headers = bearer(seed.apiKeys.outsiderProject); + expect((await request.get(services, { headers })).status()).toBe(404); + expect((await request.get(detail, { headers })).status()).toBe(404); + expect((await request.get(vulnerabilities, { headers })).status()).toBe(404); + }); +}); diff --git a/src/lib/server/code-report/api.ts b/src/lib/server/code-report/api.ts new file mode 100644 index 00000000..260c5d96 --- /dev/null +++ b/src/lib/server/code-report/api.ts @@ -0,0 +1,393 @@ +/** + * Read-only public API for discovery and Code Report (#125): projects the caller can read, + * services with the summary of their last analysis, the report of one service and its CVEs. + * Permission-first: what the caller cannot read answers 404 (its existence is not revealed), + * 403 only when the project is readable but the concrete action is not. Handlers stay thin. + */ +import { codeReportAnalysisService, codeReportService } from '#modules/code-report'; +import { cveFeedQueryService } from '#modules/cve-feed'; +import { monitorService, monitoringRuntime } from '#modules/monitoring'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { + badRequest, + callerCan, + forbidden, + list, + notFound, + ok, + paginate, + parsePagination, + type ApiLocals, +} from '#lib/server/api'; +import { + extractVulnerabilities, + summarizeAnalysisResult, + type AnalysisSummary, + type VulnerabilityFinding, +} from '#lib/code-report/analysis-summary'; +import type { PermissionGrant } from '#lib/permissions'; + +type Severity = VulnerabilityFinding['severity']; + +const SEVERITIES: Severity[] = ['critical', 'high', 'medium', 'low', 'unknown']; +const SEVERITY_RANK: Record = { + critical: 4, + high: 3, + medium: 2, + low: 1, + unknown: 0, +}; +const TITLE_MAX = 300; +const MAX_FAILED_RULES = 50; + +type ProjectRecord = Awaited>; +type AnalysisRecord = Awaited>; + +const trim = (value: string, max = TITLE_MAX) => + value.length > max ? `${value.slice(0, max - 1)}…` : value; + +const projectContext = (project: { id: string; organization?: { id: string } | null }) => ({ + scope: 'project' as const, + projectId: project.id, + organizationId: project.organization?.id, +}); + +const enabledModules = (modules: Record | null | undefined) => + Object.entries(modules ?? {}) + .filter(([, enabled]) => enabled) + .map(([name]) => name) + .sort(); + +// --------------------------------------------------------------------------------------------- +// GET /api/projects + +export async function listProjectsApi(locals: ApiLocals, url: URL): Promise { + const page = parsePagination(url); + if (!page.ok) return page.response; + + const organizationId = url.searchParams.get('organizationId')?.trim() || null; + let projects: ProjectRecord[]; + if (organizationId) { + const organization = await organizationService + .getOrganization(organizationId) + .catch(() => null); + if (!organization) return notFound('Organization not found'); + projects = await projectService.listProjectsByOrganization(organizationId); + } else { + projects = await projectService.listProjects(); + } + + const readable = ( + await Promise.all( + projects.map(async (project) => + (await callerCan(locals, 'project:project:read', projectContext(project))) ? project : null, + ), + ) + ).filter((project): project is ProjectRecord => project !== null); + + if (organizationId && readable.length === 0) { + // an organization with nothing readable in it is only visible to those who can list its projects + const canListProjects = await callerCan(locals, 'organization:projects:read', { + scope: 'organization', + organizationId, + }); + if (!canListProjects) return notFound('Organization not found'); + } + + const items = readable + .filter((project) => project.organization) + .map((project) => ({ + id: project.id, + slug: project.slug, + name: project.name, + organization: { + id: project.organization!.id, + slug: project.organization!.slug, + name: project.organization!.name, + }, + modules: enabledModules(project.modules as unknown as Record), + })) + .sort( + (a, b) => + a.organization.slug.localeCompare(b.organization.slug) || + (a.slug ?? '').localeCompare(b.slug ?? '') || + a.id.localeCompare(b.id), + ); + + const { items: pageItems, nextCursor } = paginate(items, page); + return list(pageItems, nextCursor); +} + +// --------------------------------------------------------------------------------------------- +// access helpers + +type Access = { ok: true; project: ProjectRecord } & T; +type Denied = { ok: false; response: Response }; + +/** + * The project, once the caller holds `permission` on it. Nonexistent or unreadable project: 404; + * readable project but not this action: 403. + */ +async function authorizeProject( + locals: ApiLocals, + projectId: string, + permission: PermissionGrant, +): Promise | Denied> { + const project = await projectService.getProject(projectId).catch(() => null); + if (!project) return { ok: false, response: notFound('Project not found') }; + const context = projectContext(project); + if (await callerCan(locals, permission, context)) return { ok: true, project }; + const visible = await Promise.all( + ( + [ + 'project:project:read', + 'project:codereport:reports:read', + 'project:codereport:vulnerabilities:read', + ] as const + ).map((candidate) => callerCan(locals, candidate, context)), + ); + return { + ok: false, + response: visible.some(Boolean) ? forbidden() : notFound('Project not found'), + }; +} + +type ServiceRecord = Awaited>; + +async function authorizeService( + locals: ApiLocals, + serviceId: string, + permission: PermissionGrant, +): Promise<(Access & { service: ServiceRecord }) | Denied> { + const service = await codeReportService.getById(serviceId).catch(() => null); + if (!service) return { ok: false, response: notFound('Service not found') }; + const access = await authorizeProject(locals, service.projectId, permission); + if (!access.ok) { + // keep the 404 wording of a service, not of its project + return access.response.status === 404 + ? { ok: false, response: notFound('Service not found') } + : access; + } + return { ...access, service }; +} + +// --------------------------------------------------------------------------------------------- +// analysis summary + +type Latest = { + analysis: AnalysisRecord; + summary: AnalysisSummary; +} | null; + +async function latestCompleted(serviceId: string): Promise { + const { trivy } = await codeReportAnalysisService.getLatestByTool(serviceId, ['trivy']); + if (!trivy || trivy.status !== 'completed') return null; + return { analysis: trivy as AnalysisRecord, summary: summarizeAnalysisResult(trivy.result) }; +} + +const dateOf = (value: unknown): string | null => + value ? new Date(value as string | number | Date).toISOString() : null; + +/** `true`/`false` when policies were evaluated, `null` when the analysis carries no evaluation. */ +function policyCompliant(analysis: AnalysisRecord): boolean | null { + const status = analysis.securityPolicies?.status; + if (!status) return null; + return status !== 'violated'; +} + +function summarizeService( + service: ServiceRecord, + latest: Latest, + riskWeights: Parameters[1], +) { + return { + id: service.id, + name: service.name, + slug: service.slug, + lastAnalysisAt: latest ? dateOf(latest.analysis.createdAt) : null, + score: latest + ? codeReportService.calculateRiskScore(latest.summary.vulnerabilities, riskWeights) + : null, + severityCounts: latest ? { ...latest.summary.vulnerabilities } : null, + policyCompliant: latest ? policyCompliant(latest.analysis) : null, + }; +} + +// --------------------------------------------------------------------------------------------- +// GET /api/code-report/services?projectId= + +export async function listServicesApi(locals: ApiLocals, url: URL): Promise { + const projectId = url.searchParams.get('projectId')?.trim(); + if (!projectId) return badRequest('projectId is required'); + const page = parsePagination(url); + if (!page.ok) return page.response; + + const access = await authorizeProject(locals, projectId, 'project:codereport:reports:read'); + if (!access.ok) return access.response; + + const services = (await codeReportService.listByProject(projectId)).sort( + (a, b) => a.name.localeCompare(b.name) || a.id.localeCompare(b.id), + ); + const { items: pageServices, nextCursor } = paginate(services, page); + const riskWeights = await codeReportService.getRiskWeightsByProjectId(projectId); + const items = await Promise.all( + pageServices.map(async (service) => + summarizeService(service, await latestCompleted(service.id), riskWeights), + ), + ); + return list(items, nextCursor); +} + +// --------------------------------------------------------------------------------------------- +// GET /api/code-report/services/[id] + +async function linkedMonitors(locals: ApiLocals, project: ProjectRecord, serviceId: string) { + if (!project.modules?.monitoring) return null; + if (!(await callerCan(locals, 'project:monitoring:monitors:read', projectContext(project)))) { + return null; + } + try { + const records = (await monitorService.listRecordsByProject(project.id)).filter( + (record) => record.serviceId === serviceId, + ); + const [monitors, stats] = await Promise.all([ + monitorService.listByService(project.id, serviceId), + monitoringRuntime.stats(records).catch(() => []), + ]); + const statusById = new Map(stats.map((entry) => [entry.monitorId, entry.status])); + return monitors.map((monitor) => ({ + id: monitor.id, + name: monitor.name, + status: statusById.get(monitor.id) ?? (monitor.enabled ? 'pending' : 'paused'), + })); + } catch { + return null; + } +} + +export async function getServiceApi(locals: ApiLocals, serviceId: string): Promise { + const access = await authorizeService(locals, serviceId, 'project:codereport:reports:read'); + if (!access.ok) return access.response; + const { project, service } = access; + + const [latest, riskWeights, monitors] = await Promise.all([ + latestCompleted(service.id), + codeReportService.getRiskWeightsByProjectId(project.id), + linkedMonitors(locals, project, service.id), + ]); + + const failedRules = (latest?.analysis.securityPolicies?.failed ?? []) + .flatMap((evaluation) => + evaluation.violations.map((violation) => ({ + policy: evaluation.policyName, + enforcement: evaluation.enforcement, + rule: violation.label, + actual: violation.actual, + limit: violation.limit, + message: trim(violation.message), + })), + ) + .slice(0, MAX_FAILED_RULES); + + const git = latest?.analysis.gitInfo; + return ok({ + ...summarizeService(service, latest, riskWeights), + projectId: project.id, + commit: git?.commit ?? null, + branch: git?.branch ?? null, + securityPolicy: latest + ? { + status: latest.analysis.securityPolicies?.status ?? null, + compliant: policyCompliant(latest.analysis), + failedRules, + } + : null, + ...(monitors ? { monitors } : {}), + }); +} + +// --------------------------------------------------------------------------------------------- +// GET /api/code-report/services/[id]/vulnerabilities + +/** CVE ids (and aliases) of the KEV catalog the feed knows for the organization; empty if unknown. */ +async function kevIds(organizationId: string | undefined): Promise> { + const ids = new Set(); + if (!organizationId) return ids; + try { + const { items } = await cveFeedQueryService.getView(organizationId); + for (const { advisory } of items) { + if (!advisory.kev) continue; + for (const id of [advisory.id, ...advisory.aliases]) ids.add(id.toUpperCase()); + } + } catch { + // the feed is optional: without it nothing is flagged as KEV + } + return ids; +} + +export async function listVulnerabilitiesApi( + locals: ApiLocals, + serviceId: string, + url: URL, +): Promise { + const page = parsePagination(url); + if (!page.ok) return page.response; + + const rawSeverity = url.searchParams.get('severity'); + let severities: Set | null = null; + if (rawSeverity !== null) { + const requested = rawSeverity + .split(',') + .map((value) => value.trim().toLowerCase()) + .filter(Boolean); + if ( + requested.length === 0 || + requested.some((value) => !SEVERITIES.includes(value as Severity)) + ) { + return badRequest(`severity must be a comma separated list of: ${SEVERITIES.join(', ')}`); + } + severities = new Set(requested as Severity[]); + } + + const rawFixable = url.searchParams.get('fixable'); + if (rawFixable !== null && rawFixable !== 'true' && rawFixable !== 'false') { + return badRequest('fixable must be true or false'); + } + + const access = await authorizeService( + locals, + serviceId, + 'project:codereport:vulnerabilities:read', + ); + if (!access.ok) return access.response; + + const latest = await latestCompleted(access.service.id); + const findings = latest ? extractVulnerabilities(latest.analysis.result) : []; + const kev = await kevIds(access.project.organization?.id); + + const items = findings + .filter((finding) => !severities || severities.has(finding.severity)) + .filter( + (finding) => rawFixable === null || Boolean(finding.fixedVersion) === (rawFixable === 'true'), + ) + .map((finding) => ({ + id: finding.id, + package: finding.packageName, + installedVersion: finding.installedVersion, + fixedVersion: finding.fixedVersion || null, + severity: finding.severity, + kev: kev.has(finding.id.toUpperCase()), + title: trim(finding.title), + })) + .sort( + (a, b) => + SEVERITY_RANK[b.severity] - SEVERITY_RANK[a.severity] || + Number(b.kev) - Number(a.kev) || + a.id.localeCompare(b.id) || + a.package.localeCompare(b.package), + ); + + const { items: pageItems, nextCursor } = paginate(items, page); + return list(pageItems, nextCursor); +} diff --git a/src/routes/api/code-report/server.test.ts b/src/routes/api/code-report/server.test.ts new file mode 100644 index 00000000..43177a3b --- /dev/null +++ b/src/routes/api/code-report/server.test.ts @@ -0,0 +1,456 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// grants per caller (`user:` / `key:`) and context key (`org:` / `project:`) +const grants: Record> = {}; +const keyProjects: Record = {}; + +const contextKey = (context: { scope: string; organizationId?: string; projectId?: string }) => + context.scope === 'project' ? `project:${context.projectId}` : `org:${context.organizationId}`; + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async (user: { id?: string } | null, permission: string, context: never) => + (grants[`user:${user?.id}`]?.[contextKey(context)] ?? []).includes(permission), + canApiKey: ( + key: { id: string }, + permission: string, + context: { scope: string; projectId?: string }, + ) => { + const own = keyProjects[key.id]; + if (own && (context.scope !== 'project' || context.projectId !== own)) return false; + return (grants[`key:${key.id}`]?.[contextKey(context as never)] ?? []).includes(permission); + }, + }, +})); + +const orgs: Record = { + 'org-1': { id: 'org-1', slug: 'acme', name: 'Acme' }, + 'org-2': { id: 'org-2', slug: 'other', name: 'Other' }, +}; +const projects = [ + { + id: 'p1', + slug: 'billing', + name: 'Billing', + organization: orgs['org-1'], + modules: { codereport: true, monitoring: true, vault: false, stateiac: false }, + }, + { + id: 'p2', + slug: 'web', + name: 'Web', + organization: orgs['org-1'], + modules: { codereport: true, monitoring: false, vault: false, stateiac: false }, + }, + { + id: 'p3', + slug: 'secret', + name: 'Secret', + organization: orgs['org-2'], + modules: { codereport: true, monitoring: false, vault: false, stateiac: false }, + }, +]; + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => { + if (!orgs[id]) throw new Error('Organization not found'); + return orgs[id]; + }, + }, +})); + +vi.mock('#modules/projects', () => ({ + projectService: { + listProjects: async () => projects, + listProjectsByOrganization: async (id: string) => + projects.filter((project) => project.organization.id === id), + getProject: async (id: string) => { + const project = projects.find((candidate) => candidate.id === id); + if (!project) throw new Error('Project not found'); + return project; + }, + }, +})); + +const trivy = (vulnerabilities: Record[]) => ({ + Results: [{ Target: 'package-lock.json', Vulnerabilities: vulnerabilities }], + Metadata: { huge: 'x'.repeat(5000) }, +}); +const vuln = ( + id: string, + severity: string, + fixed: string, + extra: Record = {}, +) => ({ + VulnerabilityID: id, + PkgName: `pkg-${id}`, + InstalledVersion: '1.0.0', + FixedVersion: fixed, + Severity: severity, + Title: `Title of ${id}`, + Description: 'long advisory text '.repeat(100), + ...extra, +}); + +const services = [ + { id: 's1', projectId: 'p1', slug: 'api', name: 'API' }, + { id: 's2', projectId: 'p1', slug: 'worker', name: 'Worker' }, + { id: 's3', projectId: 'p2', slug: 'site', name: 'Site' }, +]; +const analyses: Record> = {}; + +vi.mock('#modules/code-report', () => ({ + codeReportService: { + listByProject: async (projectId: string) => + services.filter((service) => service.projectId === projectId), + getById: async (id: string) => { + const service = services.find((candidate) => candidate.id === id); + if (!service) throw new Error('Service not found'); + return service; + }, + getRiskWeightsByProjectId: async () => ({ critical: 10, high: 5, medium: 2, low: 1 }), + calculateRiskScore: ( + v: { critical: number; high: number; medium: number; low: number }, + w: { critical: number; high: number; medium: number; low: number }, + ) => v.critical * w.critical + v.high * w.high + v.medium * w.medium + v.low * w.low, + }, + codeReportAnalysisService: { + getLatestByTool: async (serviceId: string) => ({ trivy: analyses[serviceId] ?? null }), + }, +})); + +let kev: string[] = []; +vi.mock('#modules/cve-feed', () => ({ + cveFeedQueryService: { + getView: async () => ({ + items: kev.map((id) => ({ advisory: { id, aliases: [], kev: true } })), + }), + }, +})); + +vi.mock('#modules/monitoring', () => ({ + monitorService: { + listRecordsByProject: async () => [ + { id: 'm1', serviceId: 's1' }, + { id: 'm2', serviceId: 's2' }, + ], + listByService: async (_project: string, serviceId: string) => + serviceId === 's1' + ? [{ id: 'm1', name: 'API health', enabled: true, url: 'https://x?token=secret' }] + : [], + }, + monitoringRuntime: { stats: async () => [{ monitorId: 'm1', status: 'up' }] }, +})); + +const root = await import('./services/+server'); +const detail = await import('./services/[id]/+server'); +const vulns = await import('./services/[id]/vulnerabilities/+server'); +const projectsRoute = await import('../projects/+server'); + +const user = (id: string) => ({ user: { id } }); + +function call( + handler: (event: never) => Response | Promise, + query: string, + locals: Record, + params: Record = {}, +) { + return Promise.resolve( + handler({ locals, params, url: new URL(`http://localhost/api/x?${query}`) } as never), + ); +} + +const READ = ['project:project:read', 'project:codereport:reports:read']; + +beforeEach(() => { + for (const key of Object.keys(grants)) delete grants[key]; + kev = []; + grants['user:viewer'] = { + 'project:p1': [ + ...READ, + 'project:codereport:vulnerabilities:read', + 'project:monitoring:monitors:read', + ], + 'project:p2': READ, + }; + grants['user:noVulns'] = { 'project:p1': READ }; + grants['user:nothing'] = {}; + grants['user:orgReader'] = { 'org:org-2': ['organization:projects:read'] }; + grants['user:reportsOnly'] = { 'project:p1': ['project:codereport:reports:read'] }; + grants['key:k1'] = { + 'project:p1': [...READ, 'project:codereport:vulnerabilities:read'], + }; + keyProjects.k1 = 'p1'; + + analyses.s1 = { + id: 'a1', + tool: 'trivy', + status: 'completed', + createdAt: '2026-03-01T10:00:00.000Z', + gitInfo: { commit: 'abc123', branch: 'main' }, + result: trivy([ + vuln('CVE-1', 'LOW', ''), + vuln('CVE-2', 'CRITICAL', '2.0.0'), + vuln('CVE-3', 'HIGH', '1.5.0', { Title: 'T'.repeat(500) }), + vuln('CVE-4', 'HIGH', ''), + vuln('CVE-5', 'MEDIUM', '1.1.0'), + ]), + securityPolicies: { + status: 'violated', + failed: [ + { + policyName: 'No criticals', + enforcement: 'blocking', + violations: [ + { + label: 'Critical vulnerabilities', + actual: 1, + limit: 0, + message: 'M'.repeat(400), + samples: ['x'], + }, + ], + }, + ], + }, + }; + analyses.s2 = { id: 'a2', tool: 'trivy', status: 'failed', createdAt: '2026-03-02T10:00:00Z' }; + delete analyses.s3; +}); + +describe('GET /api/projects', () => { + it('lists only readable projects with organization and enabled modules', async () => { + const response = await call(projectsRoute.GET, '', user('viewer')); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body.nextCursor).toBeNull(); + expect(body.items).toEqual([ + { + id: 'p1', + slug: 'billing', + name: 'Billing', + organization: { id: 'org-1', slug: 'acme', name: 'Acme' }, + modules: ['codereport', 'monitoring'], + }, + { + id: 'p2', + slug: 'web', + name: 'Web', + organization: { id: 'org-1', slug: 'acme', name: 'Acme' }, + modules: ['codereport'], + }, + ]); + }); + + it('filters by organization; missing or invisible organizations are 404', async () => { + const own = await ( + await call(projectsRoute.GET, 'organizationId=org-1', user('viewer')) + ).json(); + expect(own.items).toHaveLength(2); + expect((await call(projectsRoute.GET, 'organizationId=nope', user('viewer'))).status).toBe(404); + expect((await call(projectsRoute.GET, 'organizationId=org-2', user('viewer'))).status).toBe( + 404, + ); + // someone who can list the organization's projects sees it, even without readable projects + const empty = await call(projectsRoute.GET, 'organizationId=org-2', user('orgReader')); + expect(empty.status).toBe(200); + expect((await empty.json()).items).toEqual([]); + }); + + it('paginates with limit and cursor', async () => { + const first = await (await call(projectsRoute.GET, 'limit=1', user('viewer'))).json(); + expect(first.items.map((p: { id: string }) => p.id)).toEqual(['p1']); + expect(first.nextCursor).toEqual(expect.any(String)); + const second = await ( + await call(projectsRoute.GET, `limit=1&cursor=${first.nextCursor}`, user('viewer')) + ).json(); + expect(second.items.map((p: { id: string }) => p.id)).toEqual(['p2']); + expect(second.nextCursor).toBeNull(); + expect((await call(projectsRoute.GET, 'limit=0', user('viewer'))).status).toBe(400); + const bad = await call(projectsRoute.GET, 'cursor=%%%', user('viewer')); + expect(bad.status).toBe(400); + expect((await bad.json()).code).toBe('invalid_cursor'); + }); + + it('a project API key only sees its own project', async () => { + const body = await ( + await call(projectsRoute.GET, '', { apiKey: { id: 'k1', projectId: 'p1' } }) + ).json(); + expect(body.items.map((p: { id: string }) => p.id)).toEqual(['p1']); + }); +}); + +describe('GET /api/code-report/services', () => { + it('requires projectId', async () => { + const response = await call(root.GET, '', user('viewer')); + expect(response.status).toBe(400); + expect((await response.json()).code).toBe('invalid_request'); + }); + + it('summarizes the last analysis of each service', async () => { + const response = await call(root.GET, 'projectId=p1', user('viewer')); + expect(response.status).toBe(200); + const { items, nextCursor } = await response.json(); + expect(nextCursor).toBeNull(); + expect(items).toEqual([ + { + id: 's1', + name: 'API', + slug: 'api', + lastAnalysisAt: '2026-03-01T10:00:00.000Z', + score: 10 + 5 * 2 + 2 + 1, + severityCounts: { critical: 1, high: 2, medium: 1, low: 1, unknown: 0 }, + policyCompliant: false, + }, + // the latest analysis failed: no usable summary + { + id: 's2', + name: 'Worker', + slug: 'worker', + lastAnalysisAt: null, + score: null, + severityCounts: null, + policyCompliant: null, + }, + ]); + }); + + it('paginates', async () => { + const page = await (await call(root.GET, 'projectId=p1&limit=1', user('viewer'))).json(); + expect(page.items).toHaveLength(1); + expect(page.nextCursor).not.toBeNull(); + }); + + it('answers 404 for unknown or unreadable projects and 403 for a missing action', async () => { + expect((await call(root.GET, 'projectId=nope', user('viewer'))).status).toBe(404); + expect((await call(root.GET, 'projectId=p3', user('viewer'))).status).toBe(404); + expect((await call(root.GET, 'projectId=p1', user('nothing'))).status).toBe(404); + // can read the project but not the reports + grants['user:projectOnly'] = { 'project:p1': ['project:project:read'] }; + expect((await call(root.GET, 'projectId=p1', user('projectOnly'))).status).toBe(403); + }); + + it('a project key stays in its project', async () => { + const key = { apiKey: { id: 'k1', projectId: 'p1' } }; + expect((await call(root.GET, 'projectId=p1', key)).status).toBe(200); + expect((await call(root.GET, 'projectId=p2', key)).status).toBe(404); + }); +}); + +describe('GET /api/code-report/services/[id]', () => { + it('returns the report with the policy result and the linked monitors', async () => { + const response = await call(detail.GET, '', user('viewer'), { id: 's1' }); + expect(response.status).toBe(200); + const body = await response.json(); + expect(body).toMatchObject({ + id: 's1', + projectId: 'p1', + commit: 'abc123', + branch: 'main', + lastAnalysisAt: '2026-03-01T10:00:00.000Z', + score: 23, + policyCompliant: false, + securityPolicy: { status: 'violated', compliant: false }, + monitors: [{ id: 'm1', name: 'API health', status: 'up' }], + }); + expect(body.securityPolicy.failedRules).toHaveLength(1); + expect(body.securityPolicy.failedRules[0]).toMatchObject({ + policy: 'No criticals', + rule: 'Critical vulnerabilities', + actual: 1, + limit: 0, + }); + expect(body.securityPolicy.failedRules[0].message.length).toBeLessThanOrEqual(300); + expect(JSON.stringify(body)).not.toMatch(/token=secret|Metadata|samples/); + }); + + it('omits monitors without monitors:read', async () => { + const body = await (await call(detail.GET, '', user('noVulns'), { id: 's1' })).json(); + expect(body).not.toHaveProperty('monitors'); + }); + + it('service without analysis has null fields', async () => { + const body = await (await call(detail.GET, '', user('viewer'), { id: 's3' })).json(); + expect(body).toMatchObject({ lastAnalysisAt: null, score: null, securityPolicy: null }); + }); + + it('404 for unknown services and unreadable projects, 403 without the action', async () => { + expect((await call(detail.GET, '', user('viewer'), { id: 'nope' })).status).toBe(404); + expect((await call(detail.GET, '', user('nothing'), { id: 's1' })).status).toBe(404); + expect((await call(detail.GET, '', user('viewer'), { id: 'p3-service' })).status).toBe(404); + grants['user:projectOnly'] = { 'project:p1': ['project:project:read'] }; + expect((await call(detail.GET, '', user('projectOnly'), { id: 's1' })).status).toBe(403); + }); +}); + +describe('GET /api/code-report/services/[id]/vulnerabilities', () => { + const ids = (body: { items: { id: string }[] }) => body.items.map((item) => item.id); + + it('sorts by severity, then KEV, and trims the payload', async () => { + kev = ['CVE-4']; + const response = await call(vulns.GET, '', user('viewer'), { id: 's1' }); + expect(response.status).toBe(200); + const body = await response.json(); + expect(ids(body)).toEqual(['CVE-2', 'CVE-4', 'CVE-3', 'CVE-5', 'CVE-1']); + expect(body.items[1]).toEqual({ + id: 'CVE-4', + package: 'pkg-CVE-4', + installedVersion: '1.0.0', + fixedVersion: null, + severity: 'high', + kev: true, + title: 'Title of CVE-4', + }); + const long = body.items.find((item: { id: string }) => item.id === 'CVE-3'); + expect(long.title.length).toBeLessThanOrEqual(300); + expect(JSON.stringify(body)).not.toMatch(/long advisory text|Metadata/); + }); + + it('filters by severity list and fixable', async () => { + const severity = await ( + await call(vulns.GET, 'severity=critical,low', user('viewer'), { id: 's1' }) + ).json(); + expect(ids(severity)).toEqual(['CVE-2', 'CVE-1']); + const fixable = await ( + await call(vulns.GET, 'fixable=true', user('viewer'), { id: 's1' }) + ).json(); + expect(ids(fixable)).toEqual(['CVE-2', 'CVE-3', 'CVE-5']); + const notFixable = await ( + await call(vulns.GET, 'severity=high&fixable=false', user('viewer'), { id: 's1' }) + ).json(); + expect(ids(notFixable)).toEqual(['CVE-4']); + }); + + it('paginates', async () => { + const first = await (await call(vulns.GET, 'limit=2', user('viewer'), { id: 's1' })).json(); + expect(ids(first)).toEqual(['CVE-2', 'CVE-3']); + const next = await ( + await call(vulns.GET, `limit=2&cursor=${first.nextCursor}`, user('viewer'), { id: 's1' }) + ).json(); + expect(ids(next)).toEqual(['CVE-4', 'CVE-5']); + }); + + it('rejects invalid parameters', async () => { + for (const query of ['severity=nasty', 'severity=', 'fixable=maybe', 'limit=abc']) { + const response = await call(vulns.GET, query, user('viewer'), { id: 's1' }); + expect(response.status).toBe(400); + expect((await response.json()).code).toBe('invalid_request'); + } + }); + + it('needs vulnerabilities:read: 403 when the project is readable, 404 when it is not', async () => { + expect((await call(vulns.GET, '', user('noVulns'), { id: 's1' })).status).toBe(403); + expect((await call(vulns.GET, '', user('reportsOnly'), { id: 's1' })).status).toBe(403); + expect((await call(vulns.GET, '', user('nothing'), { id: 's1' })).status).toBe(404); + expect((await call(vulns.GET, '', user('viewer'), { id: 'nope' })).status).toBe(404); + }); + + it('empty when there is no completed analysis; keys work too', async () => { + const empty = await (await call(vulns.GET, '', user('viewer'), { id: 's2' })).json(); + expect(empty).toEqual({ items: [], nextCursor: null }); + const key = { apiKey: { id: 'k1', projectId: 'p1' } }; + expect((await call(vulns.GET, '', key, { id: 's1' })).status).toBe(200); + expect((await call(vulns.GET, '', key, { id: 's3' })).status).toBe(404); + }); +}); diff --git a/src/routes/api/code-report/services/+server.ts b/src/routes/api/code-report/services/+server.ts new file mode 100644 index 00000000..bd906970 --- /dev/null +++ b/src/routes/api/code-report/services/+server.ts @@ -0,0 +1,4 @@ +import { listServicesApi } from '#lib/server/code-report/api'; + +// GET /api/code-report/services?projectId=…&limit=&cursor=: services with their last analysis summary +export const GET = ({ url, locals }) => listServicesApi(locals, url); diff --git a/src/routes/api/code-report/services/[id]/+server.ts b/src/routes/api/code-report/services/[id]/+server.ts new file mode 100644 index 00000000..4fe4db75 --- /dev/null +++ b/src/routes/api/code-report/services/[id]/+server.ts @@ -0,0 +1,4 @@ +import { getServiceApi } from '#lib/server/code-report/api'; + +// GET /api/code-report/services/[id]: last analysis, policy result and linked monitors +export const GET = ({ params, locals }) => getServiceApi(locals, params.id); diff --git a/src/routes/api/code-report/services/[id]/vulnerabilities/+server.ts b/src/routes/api/code-report/services/[id]/vulnerabilities/+server.ts new file mode 100644 index 00000000..17b4dbb9 --- /dev/null +++ b/src/routes/api/code-report/services/[id]/vulnerabilities/+server.ts @@ -0,0 +1,4 @@ +import { listVulnerabilitiesApi } from '#lib/server/code-report/api'; + +// GET /api/code-report/services/[id]/vulnerabilities?severity=&fixable=&limit=&cursor= +export const GET = ({ params, url, locals }) => listVulnerabilitiesApi(locals, params.id, url); diff --git a/src/routes/api/projects/+server.ts b/src/routes/api/projects/+server.ts new file mode 100644 index 00000000..329abffd --- /dev/null +++ b/src/routes/api/projects/+server.ts @@ -0,0 +1,4 @@ +import { listProjectsApi } from '#lib/server/code-report/api'; + +// GET /api/projects?organizationId=…&limit=&cursor=: projects the caller can read, with their slugs +export const GET = ({ url, locals }) => listProjectsApi(locals, url); From de85df3e9bc1f40a07061c13af1400a9169c4774 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Mon, 30 Nov 2026 15:22:27 +0100 Subject: [PATCH 2/2] test(e2e): MCP key reads Code Report (#124) Co-Authored-By: Claude Opus 5.5 --- e2e/specs/mcp-api-key.spec.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/e2e/specs/mcp-api-key.spec.ts b/e2e/specs/mcp-api-key.spec.ts index bb7735ab..f7759b85 100644 --- a/e2e/specs/mcp-api-key.spec.ts +++ b/e2e/specs/mcp-api-key.spec.ts @@ -36,3 +36,23 @@ test('a personal api key (not mcp) still has no permissions', async ({ request } }); expect(response.status()).toBe(403); }); + +test('an mcp key reads Code Report services and vulnerabilities', async ({ request }) => { + const services = await request.get( + `/api/code-report/services?projectId=${seed.primaryProjectId}`, + { headers: mcp }, + ); + expect(services.status()).toBe(200); + const vulnerabilities = await request.get( + `/api/code-report/services/${seed.seededServiceId}/vulnerabilities`, + { headers: mcp }, + ); + expect(vulnerabilities.status()).toBe(200); +}); + +test('an mcp key lists the primary project in /api/projects', async ({ request }) => { + const response = await request.get('/api/projects', { headers: mcp }); + expect(response.status()).toBe(200); + const { items } = await response.json(); + expect(items.map((project: { id: string }) => project.id)).toContain(seed.primaryProjectId); +});