diff --git a/.env.example b/.env.example index c5f21c21..914c354a 100644 --- a/.env.example +++ b/.env.example @@ -136,6 +136,11 @@ GITDB_ENCRYPTION_KEY="development" # Closed incidents older than this are deleted (default 365) # MONITORING_INCIDENT_RETENTION_DAYS=365 +# ─── MCP API keys (docs/adr/0005-mcp-server.md) ──────────────────────────────────────────────── +# Requests per minute allowed to each personal API key created for MCP / AI agents (429 with +# Retry-After beyond it). Per process. Default 120. +# MCP_RATE_LIMIT_PER_MINUTE=120 + # ─── CVE feed (/org//cves, "CVEs por tecnología" tab; docs/adr/0004-cve-feed.md) ───────── # Follows the CVEs published in public sources (OSV.dev, NVD, CISA KEV, FIRST EPSS) for the # technologies each organization chooses, and emits cve_feed.* events. OFF by default: with false diff --git a/CLAUDE.md b/CLAUDE.md index 0402366a..40f57990 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, @@ -628,6 +629,11 @@ Making an event alertable: 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`). +- Public API (`/api/monitoring/{monitors,monitors/[id],monitors/[id]/test,status}`, ADR 0005, logic in + `#lib/server/monitoring/api.ts`): permission-first (404 unreadable project/monitor, 403 no action, + 409 `module_disabled`). Responses only carry `headerNames`/`hasHeaders`/`hasBody`, never header + values or the body, and URLs are the display URL. An `mcp` key sending `headers` or `body` on create + gets 400 `mcp_monitor_secrets_not_allowed`; other keys and sessions are unchanged. ## CVE feed @@ -659,6 +665,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. @@ -739,6 +750,14 @@ Machine-to-machine requests authenticate with `Authorization: Bearer gvs_...`; ` resolves them into `locals.apiKey` and `cancanService.canApiKey()` confines a project key to its own project. +API keys have an `audience` (`api` by default, or `mcp`). An `mcp` key is always personal (project +keys are always `api`) and is meant for AI agents (ADR 0005): `canApiKey()` (async) resolves it with +the permissions of its user in every organization and project (`canForUser`, most-specific-wins, +cluster admin included). Personal `api` keys still have no role and no permissions. Vault is closed +to `mcp` keys twice: `hooks.server.ts` answers 403 on `/api/vault/**` and `canApiKey()` denies any +`*:vault:*` permission. Calls run as actor `mcp:` and are rate limited per key +(`MCP_RATE_LIMIT_PER_MINUTE`, default 120; 429 + `Retry-After`). Always `await canApiKey()`. + `organization:notifications:read` and `organization:notifications:update` gate external email recipients at the organization level; `project:notifications:update` lets project alerts add them. Existing roles are not migrated: enable them from the role editor. @@ -748,6 +767,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/docs/adr/0005-mcp-server.md b/docs/adr/0005-mcp-server.md new file mode 100644 index 00000000..b09fef3e --- /dev/null +++ b/docs/adr/0005-mcp-server.md @@ -0,0 +1,200 @@ +# ADR 0005: MCP server for AI agents, a stateless client of the public API + +- Status: Proposed +- Date: 2026-11-30 +- Issues: #122 (epic), #123 + +## Context + +Developers work more and more through AI agents (Claude Code in the terminal or in VS Code). We want +an agent to answer "is this service healthy and secure?" without leaving the conversation: the +Code Report of a service (last analysis, score, vulnerabilities, security policy), its monitoring +(up/degraded/down, uptime, open incidents), the CVEs that affect it and those published for the +technologies the organization follows. It must also be able to create a monitor. + +The [Model Context Protocol](https://modelcontextprotocol.io) (MCP) is the standard way to give an +agent tools. Constraints: + +- GitDB is the only persistence and holds secrets (vault, monitor headers). A new process must not + get another path to it. +- Permissions, audit and rate limits already live in GitOps. A second implementation would drift. +- Anything a tool returns enters the LLM context, may be logged by the client and may be sent to a + model provider. Secrets must never get there, and responses must be small. + +## Decision + +### A separate, stateless service that only talks to the public API + +A new service, **`gitops-mcp`** (repository `getgitops/gitops-mcp`, own release cycle), published +at `https://mcp.cloud.getgitops.com/mcp` (development: `mcp.cloud.dev.getgitops.com`). + +``` +Claude Code ──MCP (HTTP + Bearer gvs_…)──▶ gitops-mcp ──REST + same Bearer──▶ GitOps API ──▶ GitDB + (stateless) (permissions, audit, + vault blocked) +``` + +- **No GitDB access, no credentials of its own, no state.** Every tool call is one or more REST + calls to the GitOps API (`/api/...`) forwarding the caller's `Authorization` header unchanged. + The API is the only place where permissions, audit, rate limit and the vault block are applied: + the MCP server cannot do anything the user cannot do in the UI. +- **Transport: Streamable HTTP, stateless mode** (current MCP spec, no `Mcp-Session-Id`, no SSE + resumption). Any replica can answer any request, so it scales horizontally behind a plain load + balancer. +- It never logs the `Authorization` header, header values of monitors or response bodies; it logs + the tool name, the status of the API call and the duration. + +### Authentication: a personal API key with `audience: 'mcp'` + +- `ApiKeyEntity` gets `audience: 'api' | 'mcp'` (default `api`; existing keys are unchanged). +- An MCP key is always **personal** (`userId` set, `projectId = null`, no role): it acts **with the + permissions of its user** in every organization and project, with the most-specific-wins rule of + sessions (`canForUser`). A cluster admin's MCP key is a cluster admin, minus vault. +- Only `mcp` keys get this delegation in v1. Existing personal `api` keys have no role and + therefore no permission today; giving them the user's permissions would silently widen tokens + already handed out, so that change, if ever wanted, is a separate decision. +- The client is configured with a header, which Claude Code supports, so **OAuth 2.1 is not needed + in v1**: + + ```bash + claude mcp add --transport http gitops https://mcp.cloud.getgitops.com/mcp \ + --header "Authorization: Bearer gvs_…" + ``` + + OAuth is only required for the Claude.ai web/desktop connectors (future phase, #132). + +### Vault is out, with two independent barriers + +1. **The MCP server has no vault tool** and no generic "call any endpoint" tool. +2. **The API refuses vault to any `mcp` key**, whatever its user's role allows: + - `hooks.server.ts` answers **403** to an `mcp` key on `/api/vault/**`, before any handler; + - `cancanService.canApiKey()` denies every permission matching `*:vault:*` to an `mcp` key, so + a vault permission checked from any other route is denied too. + +Either barrier alone keeps vault out; the e2e suite tests the second one directly (a Project Admin's +`mcp` key gets 403 on `/api/vault/secret`). + +### Audit, usage and rate limit + +- Calls made with an `mcp` key run with the actor `mcp:` (`runWithActor`), so audit + entries show what an agent did. `api` keys keep `apikey:`. `lastUsedAt` is updated as for + any key. +- Rate limit per `mcp` key (`RateLimiter`, key = api key id): `MCP_RATE_LIMIT_PER_MINUTE` + (default 120). Over the limit: **429** with `Retry-After` (seconds) and code `rate_limited`. + Agents loop; this protects GitDB from a runaway one. It is per process, like every other limiter. + +### Monitor headers and body are blocked in v1 + +A header that a monitor needs is almost always a token. If an agent could set it, the token would +travel through the conversation (and the model provider). In v1: + +- an `mcp` key cannot send `headers` or `body` when creating a monitor: **400** with code + `mcp_monitor_secrets_not_allowed`. Other keys and sessions keep today's behaviour; +- no endpoint ever returns header values or the body, only `headerNames`, `hasHeaders`, `hasBody`. + +Editing and deleting monitors are out of scope in v1. + +## API contract + +New endpoints live under `/api/...` without a version (decided: the API is not versioned for now). +They are thin handlers over the existing module services, **permission-first**, and work for +sessions and for every API key (not only `mcp`). + +### Conventions + +- **Success**: a single resource is the JSON object itself; a list is + `{ "items": [...], "nextCursor": string | null }`. +- **Errors** (normalized, all new endpoints): + + ```json + { "error": "Human readable message", "code": "machine_code", "errors": { "field": "code" } } + ``` + + `errors` only on validation failures. Codes: `unauthorized` (401), `forbidden` (403), + `not_found` (404), `invalid_request` (400), `invalid_cursor` (400), `validation_failed` (400/422 + with `errors`), `mcp_monitor_secrets_not_allowed` (400), `module_disabled` (409), + `rate_limited` (429). + +- **Not found vs forbidden**: a project, service, monitor or organization the caller cannot read + is a **404** (its existence is not revealed). 403 only when the caller can read the resource but + not perform the action. +- **Pagination**: `limit` (default 25, max 100) and `cursor` (opaque base64url string returned as + `nextCursor`; a cursor that does not decode is `invalid_cursor`). +- **Trimming**: no SBOMs, raw scanner payloads or full advisory texts. Strings that can be long + (`summary`, `description`) are cut (300 characters) with the full text only on the detail + endpoint, if at all. +- IDs are the GitDB uuids. `GET /api/projects` returns slugs too, so an agent can map what the + user says ("the billing project") to ids. + +Shared helpers for these conventions live in `#lib/server/api/` (response helpers, pagination, +`isMcpCaller(locals)`), so every new handler uses the same ones. + +### Discovery and Code Report (#125) + +| Endpoint | Permission | Returns | +| -------------------------------------------------------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `GET /api/projects?organizationId=` | `project:project:read` per project | visible projects: `id`, `slug`, `name`, `organization {id, slug, name}`, enabled `modules`. Without `organizationId`, every organization the caller can see | +| `GET /api/code-report/services?projectId=` | `project:codereport:reports:read` | services with a summary of the last analysis: `id`, `name`, `lastAnalysisAt`, `score`, counts by severity, `policyCompliant` | +| `GET /api/code-report/services/[id]` | `project:codereport:reports:read` | last analysis: date, commit, branch, score, counts by severity, security policy result (`compliant`, failed rules), linked monitors (`id`, `name`, `status`) | +| `GET /api/code-report/services/[id]/vulnerabilities?severity=&fixable=&limit=&cursor=` | `project:codereport:vulnerabilities:read` | CVEs of the last analysis: `id`, `package`, `installedVersion`, `fixedVersion`, `severity`, `kev`, `title` (trimmed). Sorted by severity, then KEV | + +### Monitoring (#126) + +| Endpoint | Permission | Returns | +| ---------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET /api/monitoring/monitors?projectId=&serviceId=` | `project:monitoring:monitors:read` | monitors: `id`, `name`, `method`, display URL, `serviceId`, `status`, `uptime24h`, `hasHeaders`, `hasBody` | +| `GET /api/monitoring/monitors/[id]` | `project:monitoring:monitors:read` | the above plus uptime 24 h/7 d/30 d, open incident, last 10 incidents, `headerNames` | +| `GET /api/monitoring/status?projectId=` | `project:monitoring:monitors:read` | `{ up, degraded, down, paused, total, openIncidents: [{monitorId, name, status, since, cause}] }` | +| `POST /api/monitoring/monitors` | `project:monitoring:monitors:create` | 201 with the created monitor. Through `MonitorService`: same field codes (`monitoring.errors.`), `modules.monitoring` must be on (`module_disabled`), private targets blocked | +| `POST /api/monitoring/monitors/[id]/test` | `project:monitoring:monitors:test` | result of one check: `status`, `httpStatus`, `latencyMs`, `error` (no URL query, no header values) | + +### CVE feed by technology (#127) + +| Endpoint | Permission | Returns | +| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `GET /api/cves/watchlist?organizationId=` | `organization:cves:feed:read` | followed technologies (catalog and custom) and minimum severity | +| `GET /api/cves/feed?organizationId=&technology=&severity=&kev=&affectsMe=&limit=&cursor=` | `organization:cves:feed:read` (+ `organization:projects:read` for `affectsMe`) | advisories from `cveFeedQueryService` (**GitDB only, never an external source**): `id`, `aliases`, `severity`, `cvss`, `epss`, `kev`, `technologies`, `summary`, `publishedAt`, `affectsMe` | +| `GET /api/cves/[cve]?organizationId=` | `organization:cves:feed:read` | detail: CVSS, EPSS, KEV, fixed versions, references; affected projects/services only with `organization:projects:read` | + +With `CVE_FEED_ENABLED=false` the three answer an empty result with `feedEnabled: false`, not an +error. "Te afecta" requires `organization:projects:read`, as in the UI. + +## MCP tool catalog v1 + +Tools are read-only unless marked. Each returns **a short text summary first** (one or two lines an +agent can repeat to the user: "billing-api: score 72, 2 critical, policy failed") **followed by +compact JSON** (only the fields above, nulls dropped). Lists carry `nextCursor` and the tool +accepts `cursor`, so the agent pages instead of receiving everything. + +| Tool | API | +| ------------------------------ | ---------------------------------------------------- | +| `list_projects` | `GET /api/projects` | +| `list_services` | `GET /api/code-report/services` | +| `get_service_report` | `GET /api/code-report/services/[id]` | +| `list_service_vulnerabilities` | `GET /api/code-report/services/[id]/vulnerabilities` | +| `get_monitoring_status` | `GET /api/monitoring/status` | +| `list_monitors` | `GET /api/monitoring/monitors` | +| `get_monitor` | `GET /api/monitoring/monitors/[id]` | +| `create_monitor` (write) | `POST /api/monitoring/monitors` (no headers/body) | +| `test_monitor` (write) | `POST /api/monitoring/monitors/[id]/test` | +| `get_cve_watchlist` | `GET /api/cves/watchlist` | +| `list_cve_feed` | `GET /api/cves/feed` | +| `get_cve` | `GET /api/cves/[cve]` | + +Write tools are annotated (`readOnlyHint: false`) so clients ask the user before running them. API +errors become tool errors (`isError: true`) with the `code` and message, never a stack trace. + +## Consequences + +- One new deployable (`gitops-mcp`) with no secrets of its own; revoking the user's key cuts the + agent off at once. +- The public API grows by ~12 endpoints that the UI could later use instead of page loaders. +- The vault block depends on `audience`; a future key type must decide explicitly whether it gets + vault. +- The rate limit is per process: with several GitOps replicas the effective limit is multiplied. + Acceptable for v1, as for the other limiters. + +## Out of scope (v1) + +Vault and secrets in general; editing or deleting monitors; launching scans; alerts and channels; +State IaC (possible v2); OAuth 2.1 and Claude.ai connectors (#132). diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index 8313e908..e9bf8ed1 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -56,10 +56,15 @@ export type SeedOutput = { outsiderOrgSlug: string; outsiderProjectSlug: string; seededServiceSlug: string; + seededServiceId: string; apiKeys: { readOnly: string; write: string; outsiderProject: string; + /** Personal `mcp` key of the Project Admin persona (acts with the user's permissions, no vault). */ + mcpProjectAdmin: string; + /** Personal `api` key of the same user: has no role, so no permissions. */ + personalProjectAdmin: string; }; }; @@ -490,6 +495,18 @@ export async function seedAll(): Promise { createdByUserId: clusterAdmin.userId, }); + const { token: mcpProjectAdminToken } = await apiKeysService.createApiKey( + projectAdminUser.userId, + 'e2e-mcp-project-admin', + null, + 'mcp', + ); + const { token: personalProjectAdminToken } = await apiKeysService.createApiKey( + projectAdminUser.userId, + 'e2e-personal-project-admin', + null, + ); + return { personas: { clusterAdmin: { userId: clusterAdmin.userId, username: clusterAdmin.username }, @@ -562,10 +579,13 @@ 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, outsiderProject: outsiderApiKeyToken, + mcpProjectAdmin: mcpProjectAdminToken, + personalProjectAdmin: personalProjectAdminToken, }, }; } 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/e2e/specs/cves-api.spec.ts b/e2e/specs/cves-api.spec.ts new file mode 100644 index 00000000..462dce41 --- /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/e2e/specs/mcp-api-key.spec.ts b/e2e/specs/mcp-api-key.spec.ts new file mode 100644 index 00000000..f7759b85 --- /dev/null +++ b/e2e/specs/mcp-api-key.spec.ts @@ -0,0 +1,58 @@ +import { test, expect } from '@playwright/test'; +import { getSeed } from '../fixtures/auth'; + +const seed = getSeed(); +const mcp = { Authorization: `Bearer ${seed.apiKeys.mcpProjectAdmin}` }; +const stacksUrl = `/api/state-iac/stacks?projectId=${seed.primaryProjectId}`; + +test('an mcp key gets 403 on the vault, even for a Project Admin', async ({ request }) => { + const read = await request.get(`/api/vault/secret/any-key?projectId=${seed.primaryProjectId}`, { + headers: mcp, + }); + expect(read.status()).toBe(403); + expect((await read.json()).code).toBe('forbidden'); + + const create = await request.post('/api/vault/secret', { + headers: mcp, + data: { projectId: seed.primaryProjectId, key: 'nope', values: { dev: 'x' } }, + }); + expect(create.status()).toBe(403); + expect((await create.json()).code).toBe('forbidden'); + + const exported = await request.get(`/api/vault/export?projectId=${seed.primaryProjectId}`, { + headers: mcp, + }); + expect(exported.status()).toBe(403); +}); + +test('an mcp key reads with the permissions of its user', async ({ request }) => { + const response = await request.get(stacksUrl, { headers: mcp }); + expect(response.status()).toBe(200); +}); + +test('a personal api key (not mcp) still has no permissions', async ({ request }) => { + const response = await request.get(stacksUrl, { + headers: { Authorization: `Bearer ${seed.apiKeys.personalProjectAdmin}` }, + }); + 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); +}); diff --git a/e2e/specs/monitoring-api.spec.ts b/e2e/specs/monitoring-api.spec.ts new file mode 100644 index 00000000..1276bbb5 --- /dev/null +++ b/e2e/specs/monitoring-api.spec.ts @@ -0,0 +1,96 @@ +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { test, expect } from '@playwright/test'; +import { getSeed } from '../fixtures/auth'; + +const seed = getSeed(); +const bearer = (token: string) => ({ Authorization: `Bearer ${token}` }); + +// a local target (the e2e server runs with MONITORING_ALLOW_PRIVATE_TARGETS=true) +let target: http.Server; +let targetUrl = ''; + +test.beforeAll(async () => { + target = http.createServer((_req, res) => res.writeHead(200).end('ok')); + await new Promise((resolve) => target.listen(0, '127.0.0.1', resolve)); + targetUrl = `http://127.0.0.1:${(target.address() as AddressInfo).port}`; +}); + +test.afterAll(() => { + target.closeAllConnections(); + target.close(); +}); + +test.describe('monitoring API', () => { + test('a key with create permission adds a monitor that shows up in the list', async ({ + request, + }) => { + const name = `API monitor ${Date.now()}`; + const created = await request.post('/api/monitoring/monitors', { + headers: bearer(seed.apiKeys.write), + data: { + projectId: seed.primaryProjectId, + name, + url: `${targetUrl}/health?token=abc`, + headers: [{ name: 'Authorization', value: 'Bearer e2e-secret-value' }], + }, + }); + expect(created.status()).toBe(201); + const monitor = await created.json(); + expect(monitor).toMatchObject({ name, hasHeaders: true, headerNames: ['Authorization'] }); + expect(JSON.stringify(monitor)).not.toContain('e2e-secret-value'); + expect(monitor.url).toBe(`${targetUrl}/health`); + + const listed = await request.get( + `/api/monitoring/monitors?projectId=${seed.primaryProjectId}`, + { headers: bearer(seed.apiKeys.readOnly) }, + ); + expect(listed.status()).toBe(200); + const items = (await listed.json()).items as { id: string; name: string }[]; + expect(items.some((item) => item.id === monitor.id && item.name === name)).toBe(true); + + const detail = await request.get(`/api/monitoring/monitors/${monitor.id}`, { + headers: bearer(seed.apiKeys.readOnly), + }); + expect(detail.status()).toBe(200); + + const status = await request.get(`/api/monitoring/status?projectId=${seed.primaryProjectId}`, { + headers: bearer(seed.apiKeys.readOnly), + }); + expect((await status.json()).total).toBeGreaterThan(0); + }); + + test('validation errors come back per field', async ({ request }) => { + const response = await request.post('/api/monitoring/monitors', { + headers: bearer(seed.apiKeys.write), + data: { projectId: seed.primaryProjectId, name: '', url: 'nope' }, + }); + expect(response.status()).toBe(400); + expect(await response.json()).toMatchObject({ + code: 'validation_failed', + errors: { name: 'monitoring.errors.required', url: 'monitoring.errors.invalid_url' }, + }); + }); + + test('a read-only key cannot create (403) and a key of another project sees nothing (404)', async ({ + request, + }) => { + const data = { projectId: seed.primaryProjectId, name: 'Nope', url: targetUrl }; + const readOnly = await request.post('/api/monitoring/monitors', { + headers: bearer(seed.apiKeys.readOnly), + data, + }); + expect(readOnly.status()).toBe(403); + + const outsider = await request.get( + `/api/monitoring/monitors?projectId=${seed.primaryProjectId}`, + { headers: bearer(seed.apiKeys.outsiderProject) }, + ); + expect(outsider.status()).toBe(404); + + const anonymous = await request.get( + `/api/monitoring/monitors?projectId=${seed.primaryProjectId}`, + ); + expect(anonymous.status()).toBe(401); + }); +}); diff --git a/src/env.ts b/src/env.ts index 536d4684..dd2e2733 100644 --- a/src/env.ts +++ b/src/env.ts @@ -51,6 +51,7 @@ export const variables = defineEnvVars({ MONITORING_FLUSH_SECONDS: optional, MONITORING_HOURLY_RETENTION_DAYS: optional, MONITORING_INCIDENT_RETENTION_DAYS: optional, + MCP_RATE_LIMIT_PER_MINUTE: optional, CVE_FEED_ENABLED: optional, CVE_FEED_SYNC_INTERVAL: optional, CVE_FEED_MIN_SEVERITY: optional, diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 32b36e97..393b3ced 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -33,10 +33,18 @@ import { SLACK_LINK_PATH, } from '#modules/notifications'; import { rememberDevOrigin } from '#lib/server/infra/notifications'; +import { apiError } from '#lib/server/api'; +import { + consumeMcpRateLimit, + createMcpRateLimiter, + parseMcpRateLimit, +} from '#lib/server/infra/mcp-rate-limit'; import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger'; const startupLog = createLogger('startup'); +const mcpRateLimiter = createMcpRateLimiter(parseMcpRateLimit(env.MCP_RATE_LIMIT_PER_MINUTE)); + const appEnvironment = resolveAppEnvironment(env.GITOPS_ENVIRONMENT, import.meta.env.DEV, (value) => startupLog.warn({ value }, '[startup] invalid GITOPS_ENVIRONMENT, using the default'), ); @@ -215,9 +223,20 @@ const authGuard: Handle = async ({ event, resolve }) => { event.locals.apiKey = apiKey; + const isMcp = apiKey.audience === 'mcp'; + + if (isMcp) { + // vault never reaches an MCP key, whatever its user's role allows (ADR 0005) + if (pathname === '/api/vault' || pathname.startsWith('/api/vault/')) { + return apiError(403, 'forbidden', 'Vault is not available to MCP API keys'); + } + const limited = consumeMcpRateLimit(mcpRateLimiter, apiKey.id); + if (limited) return limited; + } + return runWithActor( { - name: `apikey:${apiKey.name}`, + name: `${isMcp ? 'mcp' : 'apikey'}:${apiKey.name}`, email: `apikey+${apiKey.id}@gitops.local`, apiKeyId: apiKey.id, apiKeyProjectId: apiKey.projectId, diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 52b70513..432e05dc 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -68,6 +68,8 @@ export const ApiKeyEntity = entity('api_keys', { revokedAt: timestamp(), /** Última vez que se regeneró el secreto de la clave; null si nunca se ha rotado. */ rotatedAt: timestamp(), + /** Para qué superficie es la clave: 'api' (por defecto) o 'mcp' (agentes IA, siempre personal, sin vault). Las filas antiguas sin el campo cuentan como 'api'. */ + audience: text().default('api'), createdAt: timestamp() .notNull() .$defaultFn(() => new Date().toISOString()), diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 369d7bb4..724bc1aa 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -91,6 +91,21 @@ "close": "Dismiss what's new" }, "profile": { + "mcpOption": "For MCP / AI agents", + "mcpOptionHelp": "The key acts with your permissions in every organization and project, except the vault. Use it to connect Claude Code or another agent.", + "mcpBadge": "MCP", + "mcpSnippetTitle": "Connect Claude Code", + "mcpSnippetOnce": "Copy this now: the token and these snippets will not be shown again.", + "mcpSnippetCli": "Command", + "mcpSnippetJson": ".mcp.json file", + "apiKeysNever": "Never", + "lastUsed": "Last used", + "token": "Token", + "apiKeyCreated": "API key created", + "apiKeyRegenerated": "API key regenerated", + "apiKeyRevoked": "API key revoked", + "keyFailed": "The key could not be saved", + "namePlaceholder": "Claude Code (laptop)", "title": "Profile", "subtitle": "Manage your identity, password and API access from one place.", "account": "Account", diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index b4244f20..103cdc2f 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -91,6 +91,21 @@ "close": "Cerrar novedades" }, "profile": { + "mcpOption": "Para MCP / agentes IA", + "mcpOptionHelp": "La clave actúa con tus permisos en todas tus organizaciones y proyectos, salvo el vault. Úsala para conectar Claude Code u otro agente.", + "mcpBadge": "MCP", + "mcpSnippetTitle": "Conecta Claude Code", + "mcpSnippetOnce": "Cópialo ahora: el token y estos fragmentos no se volverán a mostrar.", + "mcpSnippetCli": "Comando", + "mcpSnippetJson": "Fichero .mcp.json", + "apiKeysNever": "Nunca", + "lastUsed": "Último uso", + "token": "Token", + "apiKeyCreated": "Clave de API creada", + "apiKeyRegenerated": "Clave de API regenerada", + "apiKeyRevoked": "Clave de API revocada", + "keyFailed": "No se pudo guardar la clave", + "namePlaceholder": "Claude Code (portátil)", "title": "Perfil", "subtitle": "Gestiona tu identidad, contraseña y acceso API desde un solo lugar.", "account": "Cuenta", diff --git a/src/lib/server/alerts/access.ts b/src/lib/server/alerts/access.ts index 77e967b7..43641cb9 100644 --- a/src/lib/server/alerts/access.ts +++ b/src/lib/server/alerts/access.ts @@ -14,6 +14,8 @@ export type AlertLocals = { projectId: string | null; userId: string | null; role: unknown; + /** Which surface the key is for; absent means 'api'. */ + audience?: 'api' | 'mcp'; } | null; }; diff --git a/src/lib/server/api/index.test.ts b/src/lib/server/api/index.test.ts new file mode 100644 index 00000000..03c35b71 --- /dev/null +++ b/src/lib/server/api/index.test.ts @@ -0,0 +1,129 @@ +import { describe, expect, it } from 'vitest'; +import { + apiError, + badRequest, + encodeCursor, + forbidden, + isMcpCaller, + list, + notFound, + ok, + paginate, + parsePagination, +} from './index'; + +const url = (qs = '') => new URL(`http://x.test/api/things${qs}`); + +describe('errors', () => { + it('apiError builds the JSON body and headers', async () => { + const res = apiError(422, 'validation_failed', 'Bad', { name: 'required' }, { 'x-a': '1' }); + expect(res.status).toBe(422); + expect(res.headers.get('x-a')).toBe('1'); + expect(await res.json()).toEqual({ + error: 'Bad', + code: 'validation_failed', + errors: { name: 'required' }, + }); + }); + + it('omits errors when absent', async () => { + expect(await apiError(401, 'unauthorized', 'No').json()).toEqual({ + error: 'No', + code: 'unauthorized', + }); + }); + + it('shortcuts use defaults', async () => { + expect(notFound().status).toBe(404); + expect(await notFound().json()).toEqual({ error: 'Not found', code: 'not_found' }); + expect(await forbidden().json()).toEqual({ error: 'Forbidden', code: 'forbidden' }); + const bad = badRequest('x', 'invalid_cursor'); + expect(bad.status).toBe(400); + expect((await bad.json()).code).toBe('invalid_cursor'); + expect((await badRequest('x').json()).code).toBe('invalid_request'); + }); + + it('ok and list', async () => { + const created = ok({ a: 1 }, 201); + expect(created.status).toBe(201); + expect(await created.json()).toEqual({ a: 1 }); + expect(await ok({ a: 1 }).status).toBe(200); + expect(await list([1, 2], 'c').json()).toEqual({ items: [1, 2], nextCursor: 'c' }); + }); +}); + +describe('parsePagination', () => { + it('uses defaults', () => { + expect(parsePagination(url())).toEqual({ ok: true, limit: 25, offset: 0 }); + expect(parsePagination(url(), { defaultLimit: 10 })).toEqual({ + ok: true, + limit: 10, + offset: 0, + }); + }); + + it('clamps limit to the max', () => { + expect(parsePagination(url('?limit=500'))).toEqual({ ok: true, limit: 100, offset: 0 }); + expect(parsePagination(url('?limit=50'), { maxLimit: 20 })).toMatchObject({ limit: 20 }); + }); + + it.each(['abc', '0', '-1', '', '1.5'])('rejects limit=%s', async (v) => { + const r = parsePagination(url(`?limit=${v}`)); + expect(r.ok).toBe(false); + if (!r.ok) { + expect(r.response.status).toBe(400); + expect((await r.response.json()).code).toBe('invalid_request'); + } + }); + + it('round-trips a cursor', () => { + const r = parsePagination(url(`?cursor=${encodeCursor(40)}`)); + expect(r).toEqual({ ok: true, limit: 25, offset: 40 }); + }); + + it.each([ + '!!!', + Buffer.from('nope').toString('base64url'), + Buffer.from('{"o":-1}').toString('base64url'), + Buffer.from('{"o":1.5}').toString('base64url'), + Buffer.from('{"o":"1"}').toString('base64url'), + Buffer.from('null').toString('base64url'), + ])('rejects invalid cursor %s', async (c) => { + const r = parsePagination(url(`?cursor=${c}`)); + expect(r.ok).toBe(false); + if (!r.ok) expect((await r.response.json()).code).toBe('invalid_cursor'); + }); +}); + +describe('paginate', () => { + const all = [1, 2, 3, 4, 5]; + + it('walks pages until nextCursor is null', () => { + const first = paginate(all, { limit: 2, offset: 0 }); + expect(first.items).toEqual([1, 2]); + expect(first.nextCursor).not.toBeNull(); + + const p = parsePagination(url(`?limit=2&cursor=${first.nextCursor}`)); + if (!p.ok) throw new Error('unexpected'); + const second = paginate(all, p); + expect(second.items).toEqual([3, 4]); + + const last = paginate(all, { limit: 2, offset: 4 }); + expect(last).toEqual({ items: [5], nextCursor: null }); + }); + + it('returns null cursor when exactly at the end', () => { + expect(paginate(all, { limit: 5, offset: 0 }).nextCursor).toBeNull(); + expect(paginate(all, { limit: 2, offset: 10 })).toEqual({ items: [], nextCursor: null }); + }); +}); + +describe('isMcpCaller', () => { + it('detects the mcp audience only', () => { + expect(isMcpCaller({ apiKey: { audience: 'mcp' } })).toBe(true); + expect(isMcpCaller({ apiKey: { audience: 'api' } })).toBe(false); + expect(isMcpCaller({ apiKey: {} })).toBe(false); + expect(isMcpCaller({ apiKey: null })).toBe(false); + expect(isMcpCaller({})).toBe(false); + }); +}); diff --git a/src/lib/server/api/index.ts b/src/lib/server/api/index.ts new file mode 100644 index 00000000..a36594e6 --- /dev/null +++ b/src/lib/server/api/index.ts @@ -0,0 +1,110 @@ +import type { AlertLocals } from '#lib/server/alerts/access'; + +export { callerCan } from '#lib/server/alerts/access'; + +/** What a public API handler reads from `event.locals` (same shape the alerts access helpers use). */ +export type ApiLocals = AlertLocals; + +export type ApiErrorCode = + | 'unauthorized' + | 'forbidden' + | 'not_found' + | 'invalid_request' + | 'invalid_cursor' + | 'validation_failed' + | 'mcp_monitor_secrets_not_allowed' + | 'module_disabled' + | 'rate_limited'; + +/** Error response: `{ error, code, errors? }`. */ +export function apiError( + status: number, + code: ApiErrorCode, + message: string, + errors?: Record, + headers?: HeadersInit, +): Response { + const body: { error: string; code: ApiErrorCode; errors?: Record } = { + error: message, + code, + }; + if (errors) body.errors = errors; + return Response.json(body, { status, headers }); +} + +export const notFound = (message = 'Not found') => apiError(404, 'not_found', message); + +export const forbidden = (message = 'Forbidden') => apiError(403, 'forbidden', message); + +export const badRequest = ( + message: string, + code: 'invalid_request' | 'invalid_cursor' = 'invalid_request', +) => apiError(400, code, message); + +export function ok(data: T, status = 200): Response { + return Response.json(data, { status }); +} + +/** Paginated list response. */ +export function list(items: T[], nextCursor: string | null): Response { + return Response.json({ items, nextCursor }); +} + +export function encodeCursor(offset: number): string { + return Buffer.from(JSON.stringify({ o: offset })).toString('base64url'); +} + +function decodeCursor(cursor: string): number | null { + try { + const parsed: unknown = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')); + const o = (parsed as { o?: unknown } | null)?.o; + return typeof o === 'number' && Number.isInteger(o) && o >= 0 ? o : null; + } catch { + return null; + } +} + +export type Pagination = + { ok: true; limit: number; offset: number } | { ok: false; response: Response }; + +/** Reads `limit` (clamped to `maxLimit`) and the opaque `cursor` from the query string. */ +export function parsePagination( + url: URL, + { defaultLimit = 25, maxLimit = 100 }: { defaultLimit?: number; maxLimit?: number } = {}, +): Pagination { + let limit = defaultLimit; + const rawLimit = url.searchParams.get('limit'); + if (rawLimit !== null) { + const n = Number(rawLimit); + if (rawLimit.trim() === '' || !Number.isInteger(n) || n < 1) { + return { ok: false, response: badRequest('limit must be a positive integer') }; + } + limit = Math.min(n, maxLimit); + } + + let offset = 0; + const cursor = url.searchParams.get('cursor'); + if (cursor) { + const decoded = decodeCursor(cursor); + if (decoded === null) { + return { ok: false, response: badRequest('Invalid cursor', 'invalid_cursor') }; + } + offset = decoded; + } + return { ok: true, limit, offset }; +} + +/** Slices one page out of `all` and returns the cursor for the next one (null on the last page). */ +export function paginate( + all: T[], + { limit, offset }: { limit: number; offset: number }, +): { items: T[]; nextCursor: string | null } { + const items = all.slice(offset, offset + limit); + const next = offset + limit; + return { items, nextCursor: next < all.length ? encodeCursor(next) : null }; +} + +/** True when the request was authenticated with an MCP-audience API key. */ +export function isMcpCaller(locals: { apiKey?: { audience?: 'api' | 'mcp' } | null }): boolean { + return locals.apiKey?.audience === 'mcp'; +} 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/lib/server/cve-feed/api.ts b/src/lib/server/cve-feed/api.ts new file mode 100644 index 00000000..927dcca0 --- /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/lib/server/infra/mcp-rate-limit.test.ts b/src/lib/server/infra/mcp-rate-limit.test.ts new file mode 100644 index 00000000..0b3b5dbb --- /dev/null +++ b/src/lib/server/infra/mcp-rate-limit.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { RateLimiter } from './rate-limit'; +import { consumeMcpRateLimit, parseMcpRateLimit } from './mcp-rate-limit'; + +describe('consumeMcpRateLimit', () => { + it('answers 429 with Retry-After once the key is over its limit', async () => { + let now = 0; + const limiter = new RateLimiter({ limit: 2, windowMs: 60_000 }, () => now); + expect(consumeMcpRateLimit(limiter, 'k1')).toBeNull(); + expect(consumeMcpRateLimit(limiter, 'k1')).toBeNull(); + + now = 59_500; + const res = consumeMcpRateLimit(limiter, 'k1'); + expect(res?.status).toBe(429); + expect(res?.headers.get('retry-after')).toBe('1'); + expect((await res!.json()).code).toBe('rate_limited'); + + now = 1000; + expect(consumeMcpRateLimit(limiter, 'k1')?.headers.get('retry-after')).toBe('59'); + }); + + it('counts each key on its own and recovers after the window', () => { + let now = 0; + const limiter = new RateLimiter({ limit: 1, windowMs: 60_000 }, () => now); + expect(consumeMcpRateLimit(limiter, 'a')).toBeNull(); + expect(consumeMcpRateLimit(limiter, 'b')).toBeNull(); + expect(consumeMcpRateLimit(limiter, 'a')?.status).toBe(429); + now = 60_000; + expect(consumeMcpRateLimit(limiter, 'a')).toBeNull(); + }); +}); + +describe('parseMcpRateLimit', () => { + it('uses the default for missing or invalid values', () => { + expect(parseMcpRateLimit(undefined)).toBe(120); + expect(parseMcpRateLimit('abc')).toBe(120); + expect(parseMcpRateLimit('0')).toBe(120); + expect(parseMcpRateLimit('30')).toBe(30); + }); +}); diff --git a/src/lib/server/infra/mcp-rate-limit.ts b/src/lib/server/infra/mcp-rate-limit.ts new file mode 100644 index 00000000..0cbc05f7 --- /dev/null +++ b/src/lib/server/infra/mcp-rate-limit.ts @@ -0,0 +1,31 @@ +import { apiError } from '#lib/server/api'; +import { RateLimiter } from './rate-limit'; + +export const DEFAULT_MCP_RATE_LIMIT_PER_MINUTE = 120; + +/** Parses `MCP_RATE_LIMIT_PER_MINUTE`; anything that is not a positive integer falls back to the default. */ +export function parseMcpRateLimit(value: string | undefined | null): number { + const parsed = Number(value); + return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MCP_RATE_LIMIT_PER_MINUTE; +} + +/** + * Counts one request of an `mcp` key (key = api key id). Returns the 429 response when the key is + * over its limit, `null` otherwise. Per process, like every other limiter. + */ +export function consumeMcpRateLimit(limiter: RateLimiter, apiKeyId: string): Response | null { + const decision = limiter.consume(apiKeyId); + if (decision.allowed) return null; + const retryAfter = Math.max(1, Math.ceil(decision.retryAfterMs / 1000)); + return apiError( + 429, + 'rate_limited', + 'Too many requests for this MCP key. Try again later.', + undefined, + { 'retry-after': String(retryAfter) }, + ); +} + +export function createMcpRateLimiter(limitPerMinute: number): RateLimiter { + return new RateLimiter({ limit: limitPerMinute, windowMs: 60_000 }); +} diff --git a/src/lib/server/monitoring/api.ts b/src/lib/server/monitoring/api.ts new file mode 100644 index 00000000..28f8ee8b --- /dev/null +++ b/src/lib/server/monitoring/api.ts @@ -0,0 +1,284 @@ +import { + MonitorValidationError, + monitorService, + monitoringRuntime, + type MonitorHeaderInput, + type MonitorInput, + type MonitorRecord, + type MonitorStats, + type MonitorView, +} from '#modules/monitoring'; +import { projectService } from '#modules/projects'; +import { + apiError, + badRequest, + callerCan, + forbidden, + isMcpCaller, + list, + notFound, + ok, + paginate, + parsePagination, + type ApiLocals, +} from '#lib/server/api'; +import { loadMonitorsWithStats } from '#lib/server/monitoring/page'; +import type { PermissionGrant } from '#lib/permissions'; + +type Action = 'read' | 'create' | 'test'; + +type ApiProject = { + id: string; + modules?: { monitoring?: boolean } | null; + organization?: { id: string } | null; +}; + +type Guard = { ok: true; project: ApiProject } | { ok: false; response: Response }; + +/** + * Permission-first: a project the caller cannot read is a 404; one it can read but not act on + * is a 403; only then does the module flag matter (409). + */ +async function guardProject( + locals: ApiLocals, + projectId: string | null | undefined, + action: Action, +): Promise { + const id = projectId?.trim(); + if (!id) return { ok: false, response: badRequest('projectId is required') }; + const project = (await projectService.getProject(id).catch(() => null)) as ApiProject | null; + if (!project) return { ok: false, response: notFound('Project not found') }; + + const context = { + scope: 'project' as const, + projectId: project.id, + organizationId: project.organization?.id, + }; + const can = (name: Action) => + callerCan(locals, `project:monitoring:monitors:${name}` as PermissionGrant, context); + if (!(await can('read'))) return { ok: false, response: notFound('Project not found') }; + if (action !== 'read' && !(await can(action))) return { ok: false, response: forbidden() }; + if (!project.modules?.monitoring) { + return { + ok: false, + response: apiError(409, 'module_disabled', 'Monitoring is not enabled in this project'), + }; + } + return { ok: true, project }; +} + +/** The monitor behind `[id]` and its project, once the caller may act on it. */ +async function guardMonitor(locals: ApiLocals, monitorId: string, action: Action) { + const record = await monitorService.findRecordById(monitorId).catch(() => null); + if (!record) return { ok: false as const, response: notFound('Monitor not found') }; + const guard = await guardProject(locals, record.projectId, action); + if (!guard.ok) { + // a monitor of a project the caller cannot read looks like a missing one + return guard.response.status === 404 + ? { ok: false as const, response: notFound('Monitor not found') } + : guard; + } + return { ok: true as const, project: guard.project, record }; +} + +function summary(monitor: MonitorView, stats: MonitorStats | null) { + return { + id: monitor.id, + name: monitor.name, + method: monitor.method, + url: monitor.displayUrl, + serviceId: monitor.serviceId, + enabled: monitor.enabled, + status: stats?.status ?? (monitor.enabled ? 'pending' : 'paused'), + uptime24h: stats?.uptime.h24 ?? null, + hasHeaders: monitor.headerNames.length > 0, + hasBody: monitor.hasBody, + }; +} + +function incidentView(row: { + id: string; + status: string; + cause: string | null; + httpStatus: number | null; + error: string | null; + startedAt: string; + endedAt: string | null; + failedChecks: number; +}) { + return { + id: row.id, + status: row.status, + cause: row.cause, + httpStatus: row.httpStatus, + error: row.error, + startedAt: row.startedAt, + endedAt: row.endedAt, + failedChecks: row.failedChecks, + }; +} + +async function detail(monitor: MonitorView, record: MonitorRecord) { + const [stats, incidents] = await Promise.all([ + monitoringRuntime + .stats([record]) + .then((rows) => rows[0] ?? null) + .catch(() => null), + monitoringRuntime.incidents(monitor.id, 10).catch(() => []), + ]); + return { + ...summary(monitor, stats), + headerNames: monitor.headerNames, + intervalSeconds: monitor.intervalSeconds, + timeoutMs: monitor.timeoutMs, + expectedStatus: monitor.expectedStatus, + uptime: { + h24: stats?.uptime.h24 ?? null, + d7: stats?.uptime.d7 ?? null, + d30: stats?.uptime.d30 ?? null, + }, + openIncident: stats?.openIncident ? incidentView(stats.openIncident) : null, + incidents: incidents.map(incidentView), + }; +} + +/** GET /api/monitoring/monitors?projectId=&serviceId= */ +export async function listMonitors(locals: ApiLocals, url: URL): Promise { + const guard = await guardProject(locals, url.searchParams.get('projectId'), 'read'); + if (!guard.ok) return guard.response; + const page = parsePagination(url); + if (!page.ok) return page.response; + + const serviceId = url.searchParams.get('serviceId')?.trim(); + const { monitors } = await loadMonitorsWithStats(guard.project.id); + const rows = monitors + .filter(({ monitor }) => !serviceId || monitor.serviceId === serviceId) + .map(({ monitor, stats }) => summary(monitor, stats)); + const { items, nextCursor } = paginate(rows, page); + return list(items, nextCursor); +} + +/** GET /api/monitoring/monitors/[id] */ +export async function getMonitor(locals: ApiLocals, monitorId: string): Promise { + const guard = await guardMonitor(locals, monitorId, 'read'); + if (!guard.ok) return guard.response; + const monitor = await monitorService.get(guard.record.projectId, monitorId); + return ok(await detail(monitor, guard.record)); +} + +/** + * GET /api/monitoring/status?projectId=. States are the real ones of the runtime: `up`, + * `degraded`, `down`, `paused` (disabled) and `pending` (enabled, nothing checked yet). + */ +export async function getStatus(locals: ApiLocals, url: URL): Promise { + const guard = await guardProject(locals, url.searchParams.get('projectId'), 'read'); + if (!guard.ok) return guard.response; + + const { monitors } = await loadMonitorsWithStats(guard.project.id); + const counts = { up: 0, degraded: 0, down: 0, paused: 0, pending: 0 }; + const openIncidents: { + monitorId: string; + name: string; + status: string; + since: string; + cause: string | null; + }[] = []; + for (const { monitor, stats } of monitors) { + const view = summary(monitor, stats); + counts[view.status as keyof typeof counts]++; + if (stats?.openIncident) { + openIncidents.push({ + monitorId: monitor.id, + name: monitor.name, + status: stats.openIncident.status, + since: stats.openIncident.startedAt, + cause: stats.openIncident.cause, + }); + } + } + return ok({ ...counts, total: monitors.length, openIncidents }); +} + +function parseHeaders(value: unknown): { ok: true; headers: MonitorHeaderInput[] } | { ok: false } { + if (value === undefined || value === null) return { ok: true, headers: [] }; + if (!Array.isArray(value)) return { ok: false }; + const headers: MonitorHeaderInput[] = []; + for (const row of value) { + const entry = row as { name?: unknown; value?: unknown } | null; + if (!entry || typeof entry.name !== 'string' || typeof entry.value !== 'string') { + return { ok: false }; + } + headers.push({ name: entry.name, value: entry.value }); + } + return { ok: true, headers }; +} + +/** POST /api/monitoring/monitors: JSON body with `projectId` and the `MonitorInput` fields. */ +export async function createMonitor(locals: ApiLocals, request: Request): Promise { + const raw: unknown = await request.json().catch(() => null); + if (!raw || typeof raw !== 'object' || Array.isArray(raw)) { + return badRequest('A JSON object body is required'); + } + const body = raw as Record; + const guard = await guardProject( + locals, + typeof body.projectId === 'string' ? body.projectId : null, + 'create', + ); + if (!guard.ok) return guard.response; + + // v1: an MCP key never carries a monitor's secrets (ADR 0005) + const hasHeaders = Array.isArray(body.headers) ? body.headers.length > 0 : Boolean(body.headers); + if (isMcpCaller(locals) && (hasHeaders || (body.body !== undefined && body.body !== null))) { + return apiError( + 400, + 'mcp_monitor_secrets_not_allowed', + 'MCP keys cannot set monitor headers or body; create the monitor with a regular API key or the UI', + ); + } + + const headers = parseHeaders(body.headers); + const errors: Record = {}; + if (!headers.ok) errors.headers = 'invalid_header'; + if (body.body !== undefined && body.body !== null && typeof body.body !== 'string') { + errors.body = 'required'; + } + if (Object.keys(errors).length > 0) { + return apiError(400, 'validation_failed', 'Invalid monitor', prefixed(errors)); + } + + const { projectId: _projectId, ...fields } = body; + const input: MonitorInput = { + ...fields, + headers: headers.ok ? headers.headers : [], + body: typeof body.body === 'string' ? body.body : null, + }; + try { + const monitor = await monitorService.create(guard.project.id, input); + const record = await monitorService.getRecord(guard.project.id, monitor.id); + return ok(await detail(monitor, record), 201); + } catch (err) { + if (err instanceof MonitorValidationError) { + return apiError(400, 'validation_failed', 'Invalid monitor', prefixed(err.errors)); + } + throw err; + } +} + +const prefixed = (errors: Record) => + Object.fromEntries( + Object.entries(errors).map(([key, code]) => [key, `monitoring.errors.${code}`]), + ); + +/** POST /api/monitoring/monitors/[id]/test: one check of the stored monitor, nothing is saved. */ +export async function testMonitor(locals: ApiLocals, monitorId: string): Promise { + const guard = await guardMonitor(locals, monitorId, 'test'); + if (!guard.ok) return guard.response; + const { outcome } = await monitorService.test(guard.record.projectId, {}, monitorId); + return ok({ + status: outcome.status, + httpStatus: outcome.httpStatus, + latencyMs: outcome.latencyMs, + error: outcome.error, + }); +} diff --git a/src/modules/auth/application/apikeys.service.test.ts b/src/modules/auth/application/apikeys.service.test.ts index fefd3128..36a26316 100644 --- a/src/modules/auth/application/apikeys.service.test.ts +++ b/src/modules/auth/application/apikeys.service.test.ts @@ -15,6 +15,7 @@ function apiKey(overrides: Partial = {}): ApiKeyView { expiresAt: null, lastUsedAt: null, revokedAt: null, + audience: 'api', createdAt: '2026-08-18T00:00:00.000Z', ...overrides, }; @@ -125,6 +126,7 @@ describe('ApiKeysService', () => { keyPrefix: result.token.slice(0, 10), keyHash: expect.any(String), expiresAt: '2026-12-31T00:00:00.000Z', + audience: 'api', }); }); @@ -170,6 +172,95 @@ describe('ApiKeysService', () => { expect(repository.create).not.toHaveBeenCalled(); }); + it('creates an mcp key as a personal key and returns its audience', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository); + + const { key } = await service.createApiKey('user-1', 'Claude Code', null, 'mcp'); + + expect(repository.create).toHaveBeenCalledWith( + expect.objectContaining({ + userId: 'user-1', + projectId: null, + roleId: null, + audience: 'mcp', + }), + ); + expect(key.audience).toBe('mcp'); + }); + + it('never gives a project key the mcp audience', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository, createRoleRepositoryMock()); + + const { key } = await service.createProjectApiKey({ + projectId: 'project-1', + roleId: 'role-1', + name: 'CI', + expiresAt: null, + createdByUserId: 'user-1', + }); + + expect(key.audience).toBe('api'); + expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ audience: 'api' })); + }); + + it('authenticate returns the audience of the key', async () => { + const repository = createRepositoryMock(); + const service = new ApiKeysService(repository, undefined, undefined, undefined, { + findById: async () => ({ disabled: false, status: 'active' }), + }); + + repository.findValidByHash.mockImplementation(async () => apiKey({ audience: 'mcp' })); + await expect(service.authenticate('gvs_121212')).resolves.toMatchObject({ + userId: 'user-1', + projectId: null, + role: null, + audience: 'mcp', + }); + + repository.findValidByHash.mockImplementation(async () => apiKey()); + await expect(service.authenticate('gvs_121212')).resolves.toMatchObject({ audience: 'api' }); + }); + + it.each([ + ['disabled', { disabled: true, status: 'active' }], + ['invited', { disabled: false, status: 'invited' }], + ['missing', null], + ])('does not authenticate an mcp key of a %s user', async (_label, user) => { + const repository = createRepositoryMock(); + repository.findValidByHash.mockImplementation(async () => apiKey({ audience: 'mcp' })); + const service = new ApiKeysService(repository, undefined, undefined, undefined, { + findById: async () => user, + }); + + await expect(service.authenticate('gvs_121212')).resolves.toBeNull(); + }); + + it('authenticates an mcp key of an active user', async () => { + const repository = createRepositoryMock(); + repository.findValidByHash.mockImplementation(async () => apiKey({ audience: 'mcp' })); + const service = new ApiKeysService(repository, undefined, undefined, undefined, { + findById: async () => ({ disabled: false, status: 'active' }), + }); + + await expect(service.authenticate('gvs_121212')).resolves.toMatchObject({ audience: 'mcp' }); + }); + + it('keeps the audience when regenerating a key', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => apiKey({ audience: 'mcp' })); + const service = new ApiKeysService(repository); + + const { key } = await service.regenerateApiKey('user-1', 'key-1'); + + expect(key.audience).toBe('mcp'); + expect(repository.updateKeyMaterial).toHaveBeenCalledWith( + 'key-1', + expect.not.objectContaining({ audience: expect.anything() }), + ); + }); + it('authenticates a project key into a project + role identity', async () => { const repository = createRepositoryMock(); repository.findValidByHash.mockImplementation(async () => diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index fad92181..aff13939 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -28,12 +28,17 @@ type ProjectLookup = { getProject(id: string): Promise<{ id: string; organization?: { id: string } | null } | null>; }; +type UserLookup = { + findById(id: string): Promise<{ disabled?: boolean; status?: string } | null>; +}; + export class ApiKeysService { constructor( private readonly apiKeyRepository: ApiKeyRepository, private readonly roleRepository?: RoleLookup, private readonly projectLookup?: ProjectLookup, private readonly events?: EventPublisher, + private readonly userLookup?: UserLookup, ) {} async listActiveApiKeys(userId: string): Promise { @@ -76,6 +81,14 @@ export class ApiKeysService { return null; } + // an mcp key acts as its user: a missing, disabled or still invited user leaves it useless + if (key.audience === 'mcp') { + const user = key.userId ? await this.userLookup?.findById(key.userId) : null; + if (!user || user.disabled || user.status !== 'active') { + return null; + } + } + let organizationId: string | null = role?.project?.organization?.id ?? null; if (key.projectId && !organizationId && this.projectLookup) { const project = await this.projectLookup.getProject(key.projectId).catch(() => null); @@ -90,6 +103,7 @@ export class ApiKeysService { organizationId, userId: key.userId, role: role ? (role.toJson() as SessionRole) : null, + audience: key.audience, }; } @@ -97,8 +111,10 @@ export class ApiKeysService { userId: string, name: string, expiresAt: string | null, + audience: 'api' | 'mcp' = 'api', ): Promise<{ token: string; key: ApiKeyView }> { return this.persist({ + audience, userId, projectId: null, roleId: null, @@ -232,6 +248,7 @@ export class ApiKeysService { createdByUserId: string | null; name: string; expiresAt: string | null; + audience?: 'api' | 'mcp'; }): Promise<{ token: string; key: ApiKeyView }> { const name = input.name.trim(); if (!name) { @@ -255,6 +272,7 @@ export class ApiKeysService { keyPrefix, keyHash, expiresAt: input.expiresAt, + audience: input.audience ?? 'api', }); await this.publishKeyEvent('api_key.created', { @@ -278,6 +296,7 @@ export class ApiKeysService { expiresAt: input.expiresAt, lastUsedAt: null, revokedAt: null, + audience: input.audience ?? 'api', createdAt: new Date().toISOString(), }, }; diff --git a/src/modules/auth/application/cancan.service.test.ts b/src/modules/auth/application/cancan.service.test.ts index 619ca938..585caf8e 100644 --- a/src/modules/auth/application/cancan.service.test.ts +++ b/src/modules/auth/application/cancan.service.test.ts @@ -131,7 +131,7 @@ describe('CanCanService', () => { expect(legacy.permissions).toEqual(['project:vault:secrets:read', 'project:project:all']); }); - it('authorizes an api key only inside its own project', () => { + it('authorizes an api key only inside its own project', async () => { const apiKey = { projectId: 'kettu', role: role({ @@ -142,28 +142,30 @@ describe('CanCanService', () => { }), }; - expect( + await expect( service.canApiKey(apiKey, 'project:codereport:reports:create', { scope: 'project', projectId: 'kettu', }), - ).toBe(true); - expect( + ).resolves.toBe(true); + await expect( service.canApiKey(apiKey, 'project:codereport:reports:create', { scope: 'project', projectId: 'other', }), - ).toBe(false); - expect(service.canApiKey(apiKey, 'cluster:settings:read', { scope: 'cluster' })).toBe(false); - expect( + ).resolves.toBe(false); + await expect( + service.canApiKey(apiKey, 'cluster:settings:read', { scope: 'cluster' }), + ).resolves.toBe(false); + await expect( service.canApiKey(apiKey, 'project:roles:delete', { scope: 'project', projectId: 'kettu' }), - ).toBe(false); - expect( + ).resolves.toBe(false); + await expect( service.canApiKey(null, 'project:codereport:reports:create', { scope: 'project', projectId: 'kettu', }), - ).toBe(false); + ).resolves.toBe(false); }); it('matches an N-segment wildcard grant against a narrower same-resource check', () => { @@ -293,6 +295,195 @@ describe('CanCanService', () => { ); }); + describe('mcp api keys', () => { + const projectAdmin = () => + role({ + id: 'project-admin', + slug: 'project-admin', + scope: 'project', + permissions: ['project:project:all', 'project:vault:secrets:all'], + }); + const mcpKey = (userId: string | null = 'jose') => ({ + projectId: null, + userId, + role: null, + audience: 'mcp' as const, + }); + + it('resolves the permissions of its user per organization and project', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + projectLookup.organizationsByProjectId.set('kettu', 'gitops'); + userAccessRepository.rows.push( + access({ + id: 'a1', + userId: 'jose', + scope: 'organization', + organizationId: 'gitops', + role: role({ + id: 'viewer', + slug: 'viewer', + scope: 'organization', + permissions: ['organization:projects:read'], + }), + }), + access({ + id: 'a2', + userId: 'jose', + scope: 'project', + projectId: 'billing', + role: projectAdmin(), + }), + ); + + await expect( + service.canApiKey(mcpKey(), 'organization:projects:read', { + scope: 'organization', + organizationId: 'gitops', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'organization:projects:read', { + scope: 'organization', + organizationId: 'other', + }), + ).resolves.toBe(false); + // an organization role carries organization:projects:read into the project + await expect( + service.canApiKey(mcpKey(), 'project:project:read', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'project:project:delete', { + scope: 'project', + projectId: 'billing', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'project:project:delete', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(false); + }); + + it('lets a cluster admin key act everywhere except in the vault', async () => { + userRepository.rows.set( + 'root', + user({ id: 'root', role: role({ id: 'admin', slug: 'admin' }) }), + ); + await expect( + service.canApiKey(mcpKey('root'), 'project:project:delete', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey('root'), 'project:vault:secrets:read', { + scope: 'project', + projectId: 'kettu', + }), + ).resolves.toBe(false); + }); + + it('denies vault permissions even to a Project Admin', async () => { + userRepository.rows.set('jose', user({ id: 'jose', role: null })); + userAccessRepository.rows.push( + access({ + id: 'a1', + userId: 'jose', + scope: 'project', + projectId: 'kettu', + role: projectAdmin(), + }), + ); + const context = { scope: 'project' as const, projectId: 'kettu' }; + + await expect(service.can('jose', 'project:vault:secrets:read', context)).resolves.toBe(true); + await expect( + service.canApiKey(mcpKey(), 'project:vault:secrets:read', context), + ).resolves.toBe(false); + await expect( + service.canApiKey(mcpKey(), 'project:vault:environments:read', context), + ).resolves.toBe(false); + await expect( + service.canApiKey(mcpKey(), 'organization:vault:secrets:read', { + scope: 'organization', + organizationId: 'gitops', + }), + ).resolves.toBe(false); + }); + + it('denies a disabled or still invited user', async () => { + const context = { scope: 'project' as const, projectId: 'kettu' }; + const admin = role({ id: 'admin', slug: 'admin' }); + const disabled = user({ id: 'off', role: admin }); + disabled.disabled = true; + const invited = user({ id: 'inv', role: admin }); + invited.status = 'invited'; + userRepository.rows.set('off', disabled); + userRepository.rows.set('inv', invited); + + await expect(service.canApiKey(mcpKey('off'), 'project:project:read', context)).resolves.toBe( + false, + ); + await expect(service.canApiKey(mcpKey('inv'), 'project:project:read', context)).resolves.toBe( + false, + ); + }); + + it('denies an unknown user, a missing userId and a project-bound key', async () => { + const context = { scope: 'project' as const, projectId: 'kettu' }; + await expect( + service.canApiKey(mcpKey('ghost'), 'project:project:read', context), + ).resolves.toBe(false); + await expect(service.canApiKey(mcpKey(null), 'project:project:read', context)).resolves.toBe( + false, + ); + await expect( + service.canApiKey({ ...mcpKey(), projectId: 'kettu' }, 'project:project:read', context), + ).resolves.toBe(false); + }); + + it('leaves personal api keys without permissions and project keys unchanged', async () => { + userRepository.rows.set( + 'root', + user({ id: 'root', role: role({ id: 'admin', slug: 'admin' }) }), + ); + const context = { scope: 'project' as const, projectId: 'kettu' }; + await expect( + service.canApiKey( + { projectId: null, userId: 'root', role: null, audience: 'api' }, + 'project:project:read', + context, + ), + ).resolves.toBe(false); + await expect( + service.canApiKey( + { projectId: null, userId: 'root', role: null }, + 'project:project:read', + context, + ), + ).resolves.toBe(false); + + const projectKey = { + projectId: 'kettu', + userId: null, + audience: 'api' as const, + role: role({ + id: 'r', + slug: 'dev', + scope: 'project', + permissions: ['project:vault:secrets:read'], + }), + }; + await expect( + service.canApiKey(projectKey, 'project:vault:secrets:read', context), + ).resolves.toBe(true); + }); + }); + describe('organization role authority cascades into its projects', () => { it('lets organization:projects: satisfy the matching project:* check', async () => { userRepository.rows.set('jose', user({ id: 'jose', role: null })); diff --git a/src/modules/auth/application/cancan.service.ts b/src/modules/auth/application/cancan.service.ts index 59462f86..ed5a6165 100644 --- a/src/modules/auth/application/cancan.service.ts +++ b/src/modules/auth/application/cancan.service.ts @@ -36,6 +36,12 @@ type ProjectLookup = { getProject(id: string): Promise; }; +/** `:vault:<…>` (or the legacy flat `vault:<…>`). */ +function isVaultPermission(permission: string): boolean { + const parts = permission.split(':'); + return parts[0] === 'vault' || parts[1] === 'vault'; +} + export class CanCanService { constructor( private readonly userRepository: UserLookup, @@ -94,14 +100,34 @@ export class CanCanService { /** * Authorizes a machine identity. A project-scoped key can only ever act inside its own project, * so any cluster- or cross-project context is denied regardless of the role permissions. + * + * An `mcp` key is personal and acts with the permissions of its user (most-specific-wins, like + * a session), except for vault: every `*:vault:*` permission is denied to it. Personal `api` + * keys have no role and therefore no permissions. */ - canApiKey( - apiKey: { projectId: string | null; role: PermissionRole } | null | undefined, + async canApiKey( + apiKey: + | { + projectId: string | null; + role: PermissionRole; + userId?: string | null; + audience?: 'api' | 'mcp'; + } + | null + | undefined, permission: PermissionGrant, context: CanCanContext, - ): boolean { + ): Promise { if (!apiKey) return false; + if (apiKey.audience === 'mcp') { + if (apiKey.projectId || !apiKey.userId) return false; + if (isVaultPermission(permission)) return false; + const user = await this.userRepository.findById(apiKey.userId); + if (!user || user.disabled || user.status !== 'active') return false; + return this.canForUser(user, permission, context); + } + if (apiKey.projectId) { if (context.scope !== 'project' || context.projectId !== apiKey.projectId) return false; } diff --git a/src/modules/auth/domain/entities.ts b/src/modules/auth/domain/entities.ts index 149bcc86..23112ae5 100644 --- a/src/modules/auth/domain/entities.ts +++ b/src/modules/auth/domain/entities.ts @@ -76,6 +76,8 @@ export type ApiKeyView = { revokedAt: string | null; /** Última rotación del secreto (regenerar); null si nunca se ha rotado. */ rotatedAt?: string | null; + /** 'mcp' keys are personal, act with their user's permissions and never reach the vault. */ + audience: 'api' | 'mcp'; createdAt: string; }; @@ -88,4 +90,6 @@ export type AuthenticatedApiKey = { organizationId: string | null; userId: string | null; role: SessionRole | null; + /** Absent means 'api'. */ + audience?: 'api' | 'mcp'; }; diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index c978ab1c..21b7a778 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -37,6 +37,7 @@ export const apiKeysService = new ApiKeysService( roleRepository, projectService, eventBus, + userRepository, ); export const authService = new AuthService( diff --git a/src/modules/auth/infrastructure/repositories/apikey.repository.ts b/src/modules/auth/infrastructure/repositories/apikey.repository.ts index 6008cc7d..cca7dbd0 100644 --- a/src/modules/auth/infrastructure/repositories/apikey.repository.ts +++ b/src/modules/auth/infrastructure/repositories/apikey.repository.ts @@ -15,6 +15,7 @@ type ApiKeyRow = { lastUsedAt: string | null; revokedAt: string | null; rotatedAt?: string | null; + audience?: string | null; createdAt: string; }; @@ -88,6 +89,7 @@ export class ApiKeyRepository extends Repository { keyPrefix: string; keyHash: string; expiresAt: string | null; + audience?: 'api' | 'mcp'; }): Promise { await this.db.insert(ApiKeyEntity).values({ id: input.id, @@ -99,6 +101,7 @@ export class ApiKeyRepository extends Repository { keyPrefix: input.keyPrefix, keyHash: input.keyHash, expiresAt: input.expiresAt, + audience: input.audience ?? 'api', lastUsedAt: null, revokedAt: null, createdAt: new Date().toISOString(), @@ -160,6 +163,7 @@ export class ApiKeyRepository extends Repository { lastUsedAt: row.lastUsedAt, revokedAt: row.revokedAt, rotatedAt: row.rotatedAt ?? null, + audience: row.audience === 'mcp' ? 'mcp' : 'api', createdAt: row.createdAt, }; } diff --git a/src/modules/monitoring/application/monitor.service.ts b/src/modules/monitoring/application/monitor.service.ts index 4b4dbe0e..3340b264 100644 --- a/src/modules/monitoring/application/monitor.service.ts +++ b/src/modules/monitoring/application/monitor.service.ts @@ -109,6 +109,11 @@ export class MonitorService { return this.deps.store.listByProject(projectId); } + /** A record by id alone (API routes that only know the monitor), `null` when it doesn't exist. */ + findRecordById(id: string): Promise { + return this.deps.store.findById(id); + } + async getRecord(projectId: string, id: string): Promise { const record = await this.deps.store.findById(id); if (!record || record.projectId !== projectId) throw new MonitorNotFoundError(); diff --git a/src/modules/monitoring/index.ts b/src/modules/monitoring/index.ts index fc6a957f..89551912 100644 --- a/src/modules/monitoring/index.ts +++ b/src/modules/monitoring/index.ts @@ -177,7 +177,7 @@ export async function stopMonitoring(): Promise { export { MonitorNotFoundError, MonitorValidationError } from './application/monitor.service'; export type { MonitorHeaderInput, MonitorInput } from './application/monitor.service'; export type { MonitorStats, MonitorLiveStatus, WorkerInfo } from './application/monitoring-runtime'; -export type { MonitorView } from './domain/monitor.domain'; +export type { MonitorRecord, MonitorView } from './domain/monitor.domain'; export type { Bar, IncidentRow } from './domain/aggregates'; export { MONITOR_DEFAULTS, diff --git a/src/routes/api/code-report/scan/+server.ts b/src/routes/api/code-report/scan/+server.ts index 9f09bf3c..0e223084 100644 --- a/src/routes/api/code-report/scan/+server.ts +++ b/src/routes/api/code-report/scan/+server.ts @@ -131,10 +131,10 @@ export async function POST({ request, locals }) { } if ( - !cancanService.canApiKey(apiKey, 'project:codereport:reports:create', { + !(await cancanService.canApiKey(apiKey, 'project:codereport:reports:create', { scope: 'project', projectId: project.id, - }) + })) ) { return json({ error: 'Forbidden' }, { status: 403 }); } 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/cves/[cve]/+server.ts b/src/routes/api/cves/[cve]/+server.ts new file mode 100644 index 00000000..206e4529 --- /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 00000000..a706b844 --- /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 00000000..896245b4 --- /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 00000000..dcb8c6d7 --- /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); diff --git a/src/routes/api/monitoring/monitors/+server.ts b/src/routes/api/monitoring/monitors/+server.ts new file mode 100644 index 00000000..3a289822 --- /dev/null +++ b/src/routes/api/monitoring/monitors/+server.ts @@ -0,0 +1,7 @@ +import { createMonitor, listMonitors } from '#lib/server/monitoring/api'; + +// GET /api/monitoring/monitors?projectId=…[&serviceId=…] (`project:monitoring:monitors:read`) +export const GET = ({ url, locals }) => listMonitors(locals, url); + +// POST /api/monitoring/monitors (`project:monitoring:monitors:create`) +export const POST = ({ request, locals }) => createMonitor(locals, request); diff --git a/src/routes/api/monitoring/monitors/[id]/+server.ts b/src/routes/api/monitoring/monitors/[id]/+server.ts new file mode 100644 index 00000000..527c8c79 --- /dev/null +++ b/src/routes/api/monitoring/monitors/[id]/+server.ts @@ -0,0 +1,4 @@ +import { getMonitor } from '#lib/server/monitoring/api'; + +// GET /api/monitoring/monitors/[id] (`project:monitoring:monitors:read`) +export const GET = ({ params, locals }) => getMonitor(locals, params.id); diff --git a/src/routes/api/monitoring/monitors/[id]/test/+server.ts b/src/routes/api/monitoring/monitors/[id]/test/+server.ts new file mode 100644 index 00000000..53a71914 --- /dev/null +++ b/src/routes/api/monitoring/monitors/[id]/test/+server.ts @@ -0,0 +1,4 @@ +import { testMonitor } from '#lib/server/monitoring/api'; + +// POST /api/monitoring/monitors/[id]/test (`project:monitoring:monitors:test`) +export const POST = ({ params, locals }) => testMonitor(locals, params.id); diff --git a/src/routes/api/monitoring/server.test.ts b/src/routes/api/monitoring/server.test.ts new file mode 100644 index 00000000..a261d3f3 --- /dev/null +++ b/src/routes/api/monitoring/server.test.ts @@ -0,0 +1,346 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { CheckOutcome } from '#lib/monitoring/types'; +import type { IncidentRow } from '#modules/monitoring/domain/aggregates'; + +const SECRET = 'Bearer s3cr3t-token-value'; +const BODY_SECRET = 'body-secret-payload'; + +// grants per caller (`user:` / `key:`) and project id +const grants: Record> = {}; +const projects: Record = {}; +const incidents: IncidentRow[] = []; +let checkResult: CheckOutcome = { + status: 'up', + cause: null, + httpStatus: 200, + latencyMs: 12, + error: null, + startedAt: '', + endedAt: '', +}; + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async ( + user: { id?: string } | null, + permission: string, + context: { projectId?: string }, + ) => (grants[`user:${user?.id}`]?.[context.projectId ?? ''] ?? []).includes(permission), + canApiKey: (key: { id: string }, permission: string, context: { projectId?: string }) => + (grants[`key:${key.id}`]?.[context.projectId ?? ''] ?? []).includes(permission), + }, +})); + +vi.mock('#modules/organization', () => ({ organizationService: {} })); + +vi.mock('#modules/projects', () => ({ + projectService: { + getProject: async (id: string) => + projects[id] ? { ...projects[id], organization: { id: 'org-1' } } : null, + }, +})); + +vi.mock('#modules/code-report', () => ({ + codeReportService: { listByProject: async () => [] }, +})); + +vi.mock('#modules/monitoring', async () => { + const { MonitorService, MonitorValidationError, MonitorNotFoundError } = + await import('#modules/monitoring/application/monitor.service'); + const { InMemoryMonitorStore } = await import('#modules/monitoring/application/testing'); + const { MONITOR_DEFAULTS, MONITOR_LIMITS, MONITOR_INTERVAL_OPTIONS } = + await import('#modules/monitoring/domain/monitor-limits.data'); + const vault = new Map(); + const store = new InMemoryMonitorStore(); + const monitorService = new MonitorService({ + store, + services: { getProjectIdOf: async () => null }, + encrypt: (id, secrets) => { + vault.set(id, secrets); + return `enc:${id}`; + }, + decrypt: (id, stored) => (stored ? (vault.get(id) as never) : { headers: {}, body: null }), + runCheck: async () => ({ outcome: checkResult, preview: null }), + allowPrivateTargets: () => false, + }); + const monitoringRuntime = { + stats: async (records: { id: string }[]) => + records.map((record) => ({ + monitorId: record.id, + status: record.id === 'down-monitor' ? 'down' : 'up', + since: null, + incidentId: null, + lastCheck: null, + uptime: { h24: 1, d7: 0.99, d30: 0.98, d90: 0.97 }, + openIncident: incidents.find((row) => row.monitorId === record.id && !row.endedAt) ?? null, + })), + incidents: async (monitorId: string, limit: number) => + incidents.filter((row) => row.monitorId === monitorId).slice(0, limit), + }; + return { + monitorService, + monitoringRuntime, + monitoringInfo: () => ({}), + MonitorValidationError, + MonitorNotFoundError, + MONITOR_DEFAULTS, + MONITOR_LIMITS, + MONITOR_INTERVAL_OPTIONS, + store, + }; +}); + +const { store } = (await import('#modules/monitoring')) as unknown as { + store: import('#modules/monitoring/application/testing').InMemoryMonitorStore; +}; +const listRoute = await import('./monitors/+server'); +const itemRoute = await import('./monitors/[id]/+server'); +const testRoute = await import('./monitors/[id]/test/+server'); +const statusRoute = await import('./status/+server'); + +const READ = 'project:monitoring:monitors:read'; +const CREATE = 'project:monitoring:monitors:create'; +const TEST = 'project:monitoring:monitors:test'; + +const user = (id: string) => ({ user: { id } }); +const key = (id: string, audience?: 'mcp') => ({ apiKey: { id, audience } }); +const urlOf = (query = '') => new URL(`http://localhost/api/monitoring/monitors?${query}`); +const post = (locals: object, body: unknown) => + listRoute.POST({ + locals, + request: new Request('http://localhost/api/monitoring/monitors', { + method: 'POST', + body: JSON.stringify(body), + }), + } as never); +const valid = { projectId: 'p1', name: 'API', url: 'https://api.example.com/health?token=abc' }; + +async function seedMonitor(overrides: Record = {}) { + const response = await post(key('rw'), { + ...valid, + headers: [{ name: 'Authorization', value: SECRET }], + method: 'POST', + body: BODY_SECRET, + ...overrides, + }); + return (await response.json()) as { id: string }; +} + +describe('/api/monitoring', () => { + beforeEach(() => { + store.rows = []; + incidents.length = 0; + for (const k of Object.keys(grants)) delete grants[k]; + for (const k of Object.keys(projects)) delete projects[k]; + projects.p1 = { id: 'p1', modules: { monitoring: true } }; + projects.off = { id: 'off', modules: { monitoring: false } }; + grants['key:rw'] = { p1: [READ, CREATE, TEST], off: [READ, CREATE] }; + grants['key:ro'] = { p1: [READ] }; + grants['key:mcp'] = { p1: [READ, CREATE, TEST] }; + grants['user:u1'] = { p1: [READ, CREATE, TEST] }; + grants['user:nobody'] = {}; + }); + + it('creates a monitor and returns the detail shape without secrets', async () => { + const response = await post(key('rw'), { + ...valid, + headers: [{ name: 'Authorization', value: SECRET }], + method: 'POST', + body: BODY_SECRET, + }); + expect(response.status).toBe(201); + const json = await response.json(); + expect(json).toMatchObject({ + name: 'API', + method: 'POST', + url: 'https://api.example.com/health', + status: 'up', + hasHeaders: true, + hasBody: true, + headerNames: ['Authorization'], + uptime: { h24: 1, d7: 0.99, d30: 0.98 }, + openIncident: null, + incidents: [], + }); + }); + + it('never leaks header values or the body in any response', async () => { + const created = await post(key('rw'), { + ...valid, + headers: [{ name: 'Authorization', value: SECRET }], + method: 'POST', + body: BODY_SECRET, + }); + const { id } = (await created.clone().json()) as { id: string }; + const responses = [ + created, + await listRoute.GET({ locals: key('ro'), url: urlOf('projectId=p1') } as never), + await itemRoute.GET({ locals: key('ro'), params: { id } } as never), + await testRoute.POST({ locals: key('rw'), params: { id } } as never), + await statusRoute.GET({ + locals: key('ro'), + url: new URL('http://localhost/api/monitoring/status?projectId=p1'), + } as never), + ]; + for (const response of responses) { + const text = JSON.stringify(await response.json()); + expect(text).not.toContain('s3cr3t'); + expect(text).not.toContain(BODY_SECRET); + expect(text).not.toContain('token=abc'); + } + }); + + it('lists with pagination, filters and permissions (404 unreadable, no pagination leak)', async () => { + await seedMonitor(); + await seedMonitor({ name: 'Other' }); + const page = await listRoute.GET({ + locals: key('ro'), + url: urlOf('projectId=p1&limit=1'), + } as never); + const json = await page.json(); + expect(json.items).toHaveLength(1); + expect(json.nextCursor).toBeTruthy(); + expect(json.items[0]).toEqual({ + id: expect.any(String), + name: 'API', + method: 'POST', + url: 'https://api.example.com/health', + serviceId: null, + enabled: true, + status: 'up', + uptime24h: 1, + hasHeaders: true, + hasBody: true, + }); + const filtered = await listRoute.GET({ + locals: key('ro'), + url: urlOf('projectId=p1&serviceId=nope'), + } as never); + expect((await filtered.json()).items).toEqual([]); + + for (const query of ['projectId=missing', 'projectId=p1']) { + const response = await listRoute.GET({ locals: user('nobody'), url: urlOf(query) } as never); + expect(response.status).toBe(404); + } + expect((await listRoute.GET({ locals: key('ro'), url: urlOf('') } as never)).status).toBe(400); + }); + + it('detail includes uptime, open incident and the last incidents; unknown or unreadable is 404', async () => { + const { id } = await seedMonitor(); + incidents.push({ + id: 'i1', + monitorId: id, + projectId: 'p1', + status: 'down', + cause: 'timeout', + httpStatus: null, + error: 'timeout', + startedAt: '2026-01-01T00:00:00.000Z', + endedAt: null, + failedChecks: 3, + }); + const response = await itemRoute.GET({ locals: key('ro'), params: { id } } as never); + const json = await response.json(); + expect(json.openIncident).toMatchObject({ id: 'i1', status: 'down', cause: 'timeout' }); + expect(json.incidents).toHaveLength(1); + + expect( + (await itemRoute.GET({ locals: key('ro'), params: { id: 'nope' } } as never)).status, + ).toBe(404); + expect((await itemRoute.GET({ locals: user('nobody'), params: { id } } as never)).status).toBe( + 404, + ); + }); + + it('status counts the real states and lists open incidents', async () => { + const { id } = await seedMonitor(); + store.rows.push({ ...store.rows[0], id: 'down-monitor', name: 'Down one' }); + store.rows.push({ ...store.rows[0], id: 'off-monitor', name: 'Off', enabled: false }); + incidents.push({ + id: 'i2', + monitorId: 'down-monitor', + projectId: 'p1', + status: 'down', + cause: 'unexpected_status', + httpStatus: 503, + error: 'x', + startedAt: '2026-01-02T00:00:00.000Z', + endedAt: null, + failedChecks: 2, + }); + const response = await statusRoute.GET({ + locals: key('ro'), + url: new URL('http://localhost/api/monitoring/status?projectId=p1'), + } as never); + const json = await response.json(); + expect(id).toBeTruthy(); + expect(json).toMatchObject({ up: 2, degraded: 0, down: 1, pending: 0, total: 3 }); + expect(json.openIncidents).toEqual([ + { + monitorId: 'down-monitor', + name: 'Down one', + status: 'down', + since: '2026-01-02T00:00:00.000Z', + cause: 'unexpected_status', + }, + ]); + }); + + it('create: 403 without create, 404 without read, 409 module off, 400 validation', async () => { + expect((await post(key('ro'), valid)).status).toBe(403); + expect((await post(user('nobody'), valid)).status).toBe(404); + expect((await post(key('rw'), { ...valid, projectId: 'missing' })).status).toBe(404); + + const off = await post(key('rw'), { ...valid, projectId: 'off' }); + expect(off.status).toBe(409); + expect((await off.json()).code).toBe('module_disabled'); + + const invalid = await post(key('rw'), { projectId: 'p1', name: '', url: 'ftp://x' }); + expect(invalid.status).toBe(400); + expect(await invalid.json()).toMatchObject({ + code: 'validation_failed', + errors: { name: 'monitoring.errors.required', url: 'monitoring.errors.invalid_url' }, + }); + + const priv = await post(key('rw'), { ...valid, url: 'http://127.0.0.1:8080' }); + expect((await priv.json()).errors.url).toBe('monitoring.errors.private_target'); + + const badHeaders = await post(key('rw'), { ...valid, headers: 'nope' }); + expect((await badHeaders.json()).errors.headers).toBe('monitoring.errors.invalid_header'); + expect(store.rows).toHaveLength(0); + }); + + it('an MCP key cannot send headers or body; it can create without them', async () => { + const mcp = key('mcp', 'mcp'); + for (const extra of [{ headers: [{ name: 'X-Token', value: 'v' }] }, { body: 'payload' }]) { + const response = await post(mcp, { ...valid, method: 'POST', ...extra }); + expect(response.status).toBe(400); + expect((await response.json()).code).toBe('mcp_monitor_secrets_not_allowed'); + } + expect(store.rows).toHaveLength(0); + expect((await post(mcp, { ...valid, headers: [] })).status).toBe(201); + // sessions and regular keys keep today's behaviour + expect( + (await post(user('u1'), { ...valid, headers: [{ name: 'X-Token', value: 'v' }] })).status, + ).toBe(201); + }); + + it('test runs one check and returns only the outcome', async () => { + const { id } = await seedMonitor(); + checkResult = { ...checkResult, status: 'down', httpStatus: 503, error: 'got 503' }; + const response = await testRoute.POST({ locals: key('rw'), params: { id } } as never); + expect(await response.json()).toEqual({ + status: 'down', + httpStatus: 503, + latencyMs: 12, + error: 'got 503', + }); + expect((await testRoute.POST({ locals: key('ro'), params: { id } } as never)).status).toBe(403); + expect((await testRoute.POST({ locals: user('nobody'), params: { id } } as never)).status).toBe( + 404, + ); + expect( + (await testRoute.POST({ locals: key('rw'), params: { id: 'nope' } } as never)).status, + ).toBe(404); + }); +}); diff --git a/src/routes/api/monitoring/status/+server.ts b/src/routes/api/monitoring/status/+server.ts new file mode 100644 index 00000000..5796afa5 --- /dev/null +++ b/src/routes/api/monitoring/status/+server.ts @@ -0,0 +1,4 @@ +import { getStatus } from '#lib/server/monitoring/api'; + +// GET /api/monitoring/status?projectId=… (`project:monitoring:monitors:read`) +export const GET = ({ url, locals }) => getStatus(locals, 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); diff --git a/src/routes/api/vault/export/+server.ts b/src/routes/api/vault/export/+server.ts index fdd51c87..4d8971bd 100644 --- a/src/routes/api/vault/export/+server.ts +++ b/src/routes/api/vault/export/+server.ts @@ -51,7 +51,7 @@ export async function GET({ url, locals }) { if (apiKey.projectId !== project.id) { return json({ error: 'Project mismatch' }, { status: 403 }); } - if (!cancanService.canApiKey(apiKey, 'project:vault:secrets:export', context)) { + if (!(await cancanService.canApiKey(apiKey, 'project:vault:secrets:export', context))) { return json({ error: 'Permission denied' }, { status: 403 }); } } else if ( diff --git a/src/routes/api/vault/secret/+server.ts b/src/routes/api/vault/secret/+server.ts index 6493e225..dab01a80 100644 --- a/src/routes/api/vault/secret/+server.ts +++ b/src/routes/api/vault/secret/+server.ts @@ -51,7 +51,7 @@ export async function POST({ request, locals }) { if (apiKey.projectId !== project.id) { return json({ error: 'Forbidden' }, { status: 403 }); } - if (!cancanService.canApiKey(apiKey, 'project:vault:secrets:create', context)) { + if (!(await cancanService.canApiKey(apiKey, 'project:vault:secrets:create', context))) { return json({ error: 'Forbidden' }, { status: 403 }); } } else if ( @@ -77,4 +77,3 @@ export async function POST({ request, locals }) { ); } } - diff --git a/src/routes/api/vault/secret/[key]/+server.ts b/src/routes/api/vault/secret/[key]/+server.ts index dcb6701a..60e5681f 100644 --- a/src/routes/api/vault/secret/[key]/+server.ts +++ b/src/routes/api/vault/secret/[key]/+server.ts @@ -14,7 +14,8 @@ function errorMessage(err: unknown) { } function notFoundStatus(err: unknown) { - return err instanceof Error && (err.message === 'Secret not found' || err.message === 'Folder not found') + return err instanceof Error && + (err.message === 'Secret not found' || err.message === 'Folder not found') ? 404 : 400; } @@ -29,7 +30,8 @@ function normalizePath(path: string | null) { async function authorize( url: URL, locals: App.Locals, - permission: 'project:vault:secrets:read' | 'project:vault:secrets:update' | 'project:vault:secrets:delete', + permission: + 'project:vault:secrets:read' | 'project:vault:secrets:update' | 'project:vault:secrets:delete', ) { const projectId = url.searchParams.get('projectId')?.trim(); if (!projectId) { @@ -53,7 +55,7 @@ async function authorize( if (apiKey.projectId !== project.id) { return { error: json({ error: 'Forbidden' }, { status: 403 }) }; } - if (!cancanService.canApiKey(apiKey, permission, context)) { + if (!(await cancanService.canApiKey(apiKey, permission, context))) { return { error: json({ error: 'Forbidden' }, { status: 403 }) }; } } else if (!(await cancanService.canSessionUser(locals.user, permission, context))) { @@ -72,7 +74,11 @@ export async function GET({ params, url, locals }) { try { const folder = await vaultService.getFolderByPath(auth.project.id, path); - const secret = await vaultService.findSecretByKey(auth.project.id, folder?.id ?? null, params.key); + const secret = await vaultService.findSecretByKey( + auth.project.id, + folder?.id ?? null, + params.key, + ); if (!secret) return json({ error: 'Secret not found' }, { status: 404 }); return json({ secret }); } catch (err) { diff --git a/src/routes/profile/+page.server.ts b/src/routes/profile/+page.server.ts index 9358d4f1..45babd41 100644 --- a/src/routes/profile/+page.server.ts +++ b/src/routes/profile/+page.server.ts @@ -27,7 +27,7 @@ export async function load({ locals }) { throw redirect(302, '/auth/login'); } - const apiKeys = await apiKeysService.listActiveApiKeys(user.id); + const apiKeys = (await apiKeysService.listActiveApiKeys(user.id)).filter((key) => !key.revokedAt); return { user: { @@ -107,10 +107,16 @@ export const actions = { } const expiresAt = expiresAtFromDays(expiresInDays || null); + const audience = formData.get('mcp') ? 'mcp' : 'api'; - const { token } = await apiKeysService.createApiKey(locals.user.id, name, expiresAt); + const { token } = await apiKeysService.createApiKey(locals.user.id, name, expiresAt, audience); - return { section: 'apiKeys', message: 'API key created.', createdKey: token }; + return { + section: 'apiKeys', + message: 'API key created.', + createdKey: token, + createdAudience: audience, + }; }, regenerateApiKey: async ({ request, locals }) => { @@ -123,9 +129,14 @@ export const actions = { return fail(400, { section: 'apiKeys', message: 'Key id is required.' }); } - const { token } = await apiKeysService.regenerateApiKey(locals.user.id, keyId); + const { token, key } = await apiKeysService.regenerateApiKey(locals.user.id, keyId); - return { section: 'apiKeys', message: 'API key regenerated.', createdKey: token }; + return { + section: 'apiKeys', + message: 'API key regenerated.', + createdKey: token, + createdAudience: key.audience, + }; }, revokeApiKey: async ({ request, locals }) => { diff --git a/src/routes/profile/+page.svelte b/src/routes/profile/+page.svelte index d5cbabba..8cd5716c 100644 --- a/src/routes/profile/+page.svelte +++ b/src/routes/profile/+page.svelte @@ -1,6 +1,6 @@