diff --git a/CLAUDE.md b/CLAUDE.md index 0402366..40c7b54 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 diff --git a/e2e/specs/monitoring-api.spec.ts b/e2e/specs/monitoring-api.spec.ts new file mode 100644 index 0000000..1276bbb --- /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/lib/server/monitoring/api.ts b/src/lib/server/monitoring/api.ts new file mode 100644 index 0000000..28f8ee8 --- /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/monitoring/application/monitor.service.ts b/src/modules/monitoring/application/monitor.service.ts index 4b4dbe0..3340b26 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 fc6a957..8955191 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/monitoring/monitors/+server.ts b/src/routes/api/monitoring/monitors/+server.ts new file mode 100644 index 0000000..3a28982 --- /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 0000000..527c8c7 --- /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 0000000..53a7191 --- /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 0000000..a261d3f --- /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 0000000..5796afa --- /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);