diff --git a/apps/web/e2e/QUARANTINE.md b/apps/web/e2e/QUARANTINE.md index 5b096dae16..639892006b 100644 --- a/apps/web/e2e/QUARANTINE.md +++ b/apps/web/e2e/QUARANTINE.md @@ -755,3 +755,37 @@ no such part beyond the wrong notification). `published`, `deleted_at IS NULL` and board-not-deleted filters the public profile uses (`user.public-profile.ts`). owner: unassigned, review by: 2026-12-03. +- `status/api.spec.ts` › STA-X-04 a service created with a non-operational + status records it. Same cause as STA-P-15 (`status.components.ts:176`): no + history row and no `status.component_changed` webhook. owner: unassigned, + review by: 2026-12-03. +- `status/api.spec.ts` › STA-X-06 incident list paging answers bad limits and + cursors cleanly. `GET /api/v1/status/incidents` parses `limit` with + `parseInt` itself (`apps/web/src/routes/api/v1/status/incidents/index.ts:64`) + instead of the shared pagination guard: `limit=0` answers an empty page with + `hasMore: true` and no cursor, and a negative or non-numeric limit or a + garbage cursor reaches the database. Fix: use `parsePaginationParams` and + refuse a cursor that is not a status incident id. owner: unassigned, review + by: 2026-12-03. +- `status/settings.isolated.spec.ts` › STA-S-08 subscribing honours the page + gate. `subscribeStatusFn` + (`apps/web/src/lib/server/functions/status-subscriptions.ts:40`) checks only + that the caller is not anonymous, so with the page unpublished (or the viewer + outside the audience) a subscription is stored and takes a plan slot. Fix: + run `resolveStatusPageGate` first and refuse when it is not available. + owner: unassigned, review by: 2026-12-03. +- `status/settings.isolated.spec.ts` › STA-S-25 subscribers are not emailed + while the page is unpublished. The status subscriber fan-out + (`apps/web/src/lib/server/events/targets.ts:2132`) checks the audience and + service visibility but never `isStatusPagePublished` or portal privacy, so + people an admin added before launch get "New incident reported" with a + "View live status" link that 404s. Fix: return no recipients when the page + is not published or the portal is private to them. owner: unassigned, review + by: 2026-12-03. +- `status/settings.isolated.spec.ts` › STA-A-62 clear history keeps the events + behind statuses still held. `clearStatusHistory` + (`apps/web/src/lib/server/domains/status/status.service.ts:792`) deletes every + `status_component_events` row, including those behind statuses an open + incident still holds, so those services' uptime reads operational while they + are down. Fix: keep (or re-write) the latest event of each service with a + live hold. owner: unassigned, review by: 2026-12-03. diff --git a/apps/web/e2e/tests/status/api.spec.ts b/apps/web/e2e/tests/status/api.spec.ts new file mode 100644 index 0000000000..d35c251623 --- /dev/null +++ b/apps/web/e2e/tests/status/api.spec.ts @@ -0,0 +1,628 @@ +/** + * The status REST API (/api/v1/status/*). + * + * Journeys: STA-X-01, STA-X-02, STA-X-03, STA-X-04, STA-X-05, STA-X-06, + * STA-X-07, STA-X-08, STA-X-09, STA-X-10. + * + * Keys are minted per test (personal keys of the seeded people, or a + * workspace key). Lists are workspace-wide: each test finds its own rows. + */ +import type { APIRequestContext } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { personApi } from '../../support/server-fns' +import { apiFor, createKey, expectJson, type Wire } from '../../support/api-client' +import { supportEnv } from '../../support/env' +import { + createService, + deleteMadeIncidents, + domainEvents, + incidentRow, + maintenanceJobs, + must, + serviceEvents, + serviceRow, +} from '../../product/status' + +let admin: APIRequestContext +const opened: APIRequestContext[] = [] + +test.beforeEach(async ({ playwright }) => { + admin = await personApi(playwright, 'admin') +}) +test.afterEach(async () => { + for (const c of opened.splice(0)) await c.dispose() + await deleteMadeIncidents(admin) + await admin.dispose() +}) + +type Person = 'admin' | 'contributor' | 'noAccess' + +/** The principal of the key keyApi made last (a key acts as its own principal). */ +let lastKeyPrincipal = '' + +async function keyApi( + playwright: Parameters[0], + people: { people: Record }, + who: Person | 'workspace' +): Promise { + const created = + who === 'workspace' + ? createKey({ creatorEmail: people.people.admin.email, kind: 'workspace' }) + : createKey({ creatorEmail: people.people[who].email, kind: 'personal' }) + lastKeyPrincipal = created.principalId + const api = await apiFor(playwright, supportEnv().baseUrl, created.key) + opened.push(api) + return api +} + +/** Incidents created over REST are deleted after the test too. */ +async function deleteRestIncident(id: string) { + await must(admin, 'deleteStatusIncidentFn', { id }).catch(() => {}) +} + +test('STA-X-01 the summary endpoint', { tag: '@core' }, async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'admin') + const svc = await createService(admin, `${marker} Summary`, { description: 'desc' }) + const res = await expectJson(await api.get('/api/v1/status/summary'), 200) + expect(typeof res.data.status).toBe('string') + const mine = res.data.components.find((c: Wire) => c.id === svc.id) + expect(mine).toEqual({ + id: svc.id, + name: `${marker} Summary`, + description: 'desc', + status: 'operational', + showUptime: true, + }) + expect(Array.isArray(res.data.activeIncidents)).toBe(true) + const anon = await apiFor(playwright, supportEnv().baseUrl, null) + opened.push(anon) + const none = await anon.get('/api/v1/status/summary') + expect(none.status()).toBe(401) + expect(none.headers()['www-authenticate']).toBeTruthy() +}) + +test('STA-X-02 list and get services', { tag: '@core' }, async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'noAccess') + const svc = await createService(admin, `${marker} Listed`) + const gone = await createService(admin, `${marker} Gone`) + await must(admin, 'deleteStatusComponentFn', { id: gone.id }) + for (const path of ['/api/v1/status/services', '/api/v1/status/components']) { + const list = await expectJson(await api.get(path), 200) + const row = list.data.find((c: Wire) => c.id === svc.id) + expect(row).toEqual({ + id: svc.id, + groupId: null, + name: `${marker} Listed`, + description: null, + status: 'operational', + position: expect.any(Number), + showUptime: true, + segmentIds: [], + }) + expect(list.data.map((c: Wire) => c.id)).not.toContain(gone.id) + } + const one = await expectJson(await api.get(`/api/v1/status/services/${svc.id}`), 200) + expect(one.data.id).toBe(svc.id) + const missing = await expectJson(await api.get(`/api/v1/status/services/${gone.id}`), 404) + expect(missing.error.message).toMatch(/Status service not found/) + const bad = await expectJson(await api.get('/api/v1/status/services/not-an-id'), 400) + expect(bad.error.code).toBe('VALIDATION_ERROR') +}) + +test( + 'STA-X-03 create a service over REST', + { tag: '@core' }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'admin') + const created = await expectJson( + await api.post('/api/v1/status/services', { + data: { name: `${marker} Rest`, description: 'from rest', showUptime: false }, + }), + 201 + ) + expect(created.data).toMatchObject({ + name: `${marker} Rest`, + description: 'from rest', + showUptime: false, + status: 'operational', + }) + expect((await serviceRow(created.data.id)).name).toBe(`${marker} Rest`) + + const badGroup = await expectJson( + await api.post('/api/v1/status/services', { data: { name: `${marker} x`, groupId: 'nope' } }), + 400 + ) + expect(badGroup.error.message).toMatch(/Invalid groupId format/) + const noName = await expectJson( + await api.post('/api/v1/status/services', { data: {} }), + 400 + ) + expect(noName.error.message).toBe('Invalid request body') + expect(noName.error.details.errors.name).toBeTruthy() + + const contributor = await keyApi(playwright, people, 'contributor') + const refused = await expectJson( + await contributor.post('/api/v1/status/services', { data: { name: `${marker} nope` } }), + 403 + ) + expect(refused.error.code).toBe('FORBIDDEN') + const list = await expectJson(await api.get('/api/v1/status/services'), 200) + expect(list.data.map((c: Wire) => c.name)).not.toContain(`${marker} nope`) + } +) + +test( + 'STA-X-04 a service created with a non-operational status records it', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'createStatusComponent (status.components.ts:176) writes no status_component_events row and no status.component_changed for an initial non-operational status; see QUARANTINE.md (STA-P-15)', + }, + }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'admin') + const created = await expectJson( + await api.post('/api/v1/status/services', { + data: { name: `${marker} Down`, status: 'major_outage' }, + }), + 201 + ) + expect(created.data.status).toBe('major_outage') + expect(await serviceEvents(created.data.id)).toEqual([ + expect.objectContaining({ status: 'major_outage' }), + ]) + expect((await domainEvents(created.data.id)).map((e) => e.type)).toEqual([ + 'status.component_changed', + ]) + } +) + +test( + 'STA-X-05 drive a service status from a monitor (PATCH)', + { tag: '@core' }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'admin') + const svc = await createService(admin, `${marker} Monitored`) + const path = `/api/v1/status/services/${svc.id}` + const first = await expectJson( + await api.patch(path, { data: { status: 'partial_outage' } }), + 200 + ) + expect(first.data.status).toBe('partial_outage') + expect(await serviceEvents(svc.id)).toEqual([ + expect.objectContaining({ status: 'partial_outage', source: 'api' }), + ]) + const events = await domainEvents(svc.id) + expect(events).toHaveLength(1) + expect(events[0]).toMatchObject({ type: 'status.component_changed', actor_type: 'service' }) + expect(events[0].payload).toMatchObject({ + componentId: svc.id, + componentName: `${marker} Monitored`, + previousStatus: 'operational', + status: 'partial_outage', + source: 'api', + }) + await expectJson(await api.patch(path, { data: { status: 'partial_outage' } }), 200) + expect(await serviceEvents(svc.id)).toHaveLength(1) + + const both = await expectJson( + await api.patch(path, { data: { name: `${marker} Renamed`, status: 'operational' } }), + 200 + ) + expect(both.data).toMatchObject({ name: `${marker} Renamed`, status: 'operational' }) + const empty = await expectJson(await api.patch(path, { data: {} }), 400) + expect(empty.error.message).toBe('At least one field is required') + + const contributor = await keyApi(playwright, people, 'contributor') + await expectJson(await contributor.patch(path, { data: { status: 'major_outage' } }), 403) + await must(admin, 'deleteStatusComponentFn', { id: svc.id }) + await expectJson(await api.patch(path, { data: { status: 'major_outage' } }), 404) + } +) + +test( + 'STA-X-06 incident list paging answers bad limits and cursors cleanly', + { + tag: ['@nightly', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'GET /api/v1/status/incidents parses limit itself (incidents/index.ts:64) without the shared pagination guard: limit=0 reports hasMore with no cursor and a negative or non-numeric limit, or a garbage cursor, fails with 500; see QUARANTINE.md', + }, + }, + async ({ playwright, people }) => { + const api = await keyApi(playwright, people, 'admin') + const zero = await api.get('/api/v1/status/incidents?limit=0') + if (zero.status() === 200) { + const body = (await zero.json()) as Wire + expect(body.meta?.pagination?.hasMore && !body.meta?.pagination?.cursor).toBeFalsy() + } + for (const q of ['limit=-1', 'limit=abc', 'cursor=garbage']) { + const res = await api.get(`/api/v1/status/incidents?${q}`) + expect(res.status(), q).toBeLessThan(500) + } + } +) + +test( + 'STA-X-06 list incidents over REST', + { tag: '@nightly' }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'admin') + const svc = await createService(admin, `${marker} Listed`) + const ids: string[] = [] + for (let i = 0; i < 3; i++) { + const res = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'maintenance', + title: `${marker} window ${i}`, + status: 'scheduled', + body: 'planned', + notifySubscribers: false, + scheduledStartAt: new Date(Date.now() + 3_600_000).toISOString(), + scheduledEndAt: new Date(Date.now() + 7_200_000).toISOString(), + affectedComponents: [{ componentId: svc.id, componentStatus: 'under_maintenance' }], + }, + }), + 201 + ) + ids.push(res.data.id) + } + try { + const page1 = await expectJson( + await api.get('/api/v1/status/incidents?kind=maintenance&state=active&limit=2'), + 200 + ) + expect(page1.data).toHaveLength(2) + expect(page1.data.every((i: Wire) => i.kind === 'maintenance')).toBe(true) + // Newest first: ours are the newest windows unless another test races. + expect(page1.meta.pagination.hasMore).toBe(true) + const page2 = await expectJson( + await api.get( + `/api/v1/status/incidents?kind=maintenance&state=active&limit=2&cursor=${page1.meta.pagination.cursor}` + ), + 200 + ) + const seen = [...page1.data, ...page2.data].map((i: Wire) => i.id) + expect(new Set(seen).size).toBe(seen.length) + const ignored = await expectJson( + await api.get('/api/v1/status/incidents?kind=bogus&state=bogus&limit=1'), + 200 + ) + expect(ignored.data).toHaveLength(1) + } finally { + for (const id of ids) await deleteRestIncident(id) + } + } +) + +test( + 'STA-X-07 create an incident or window over REST', + { tag: '@smoke' }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'admin') + const svc = await createService(admin, `${marker} Rest svc`) + const made: string[] = [] + try { + const inc = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title: `${marker} rest incident`, + status: 'investigating', + body: 'From a monitor', + notifySubscribers: false, + affectedComponents: [{ componentId: svc.id, componentStatus: 'major_outage' }], + }, + }), + 201 + ) + made.push(inc.data.id) + expect(inc.data).toMatchObject({ + kind: 'incident', + status: 'investigating', + impact: 'critical', + }) + // The key's own principal. + expect(inc.data.createdBy).toBe(lastKeyPrincipal) + expect(inc.data.notifiedAt).not.toBeNull() + expect(inc.data).not.toHaveProperty('notifySubscribers') + expect((await serviceRow(svc.id)).status).toBe('major_outage') + expect((await domainEvents(inc.data.id)).map((e) => e.type)).toEqual([ + 'status.incident_created', + ]) + + const win = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'maintenance', + title: `${marker} rest window`, + status: 'scheduled', + body: 'Planned', + notifySubscribers: false, + scheduledStartAt: new Date(Date.now() + 3_600_000).toISOString(), + scheduledEndAt: new Date(Date.now() + 7_200_000).toISOString(), + affectedComponents: [{ componentId: svc.id, componentStatus: 'under_maintenance' }], + }, + }), + 201 + ) + made.push(win.data.id) + expect((await maintenanceJobs(win.data.id)).map((j) => j.kind)).toEqual(['complete', 'start']) + + const past = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title: `${marker} rest past`, + status: 'resolved', + body: 'History', + backfill: { + startedAt: new Date(Date.now() - 2 * 86_400_000).toISOString(), + resolvedAt: new Date(Date.now() - 86_400_000).toISOString(), + }, + affectedComponents: [{ componentId: svc.id, componentStatus: 'major_outage' }], + }, + }), + 201 + ) + made.push(past.data.id) + expect(past.data.notifiedAt).toBeNull() + expect((await incidentRow(past.data.id)).backfilled).toBe(true) + + // Refusals. + const noDate = await api.post('/api/v1/status/incidents', { + data: { + kind: 'maintenance', + title: marker, + status: 'scheduled', + body: 'x', + scheduledStartAt: 'tomorrow', + affectedComponents: [{ componentId: svc.id, componentStatus: 'under_maintenance' }], + }, + }) + expect(noDate.status()).toBe(400) + const mismatch = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title: marker, + status: 'scheduled', + body: 'x', + affectedComponents: [{ componentId: svc.id, componentStatus: 'major_outage' }], + }, + }), + 400 + ) + expect(mismatch.error.code).toBe('VALIDATION_ERROR') + const badId = await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title: marker, + status: 'investigating', + body: 'x', + affectedComponents: [{ componentId: 'nope', componentStatus: 'major_outage' }], + }, + }) + expect(badId.status()).toBe(400) + const gone = await createService(admin, `${marker} Gone`) + await must(admin, 'deleteStatusComponentFn', { id: gone.id }) + const deleted = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title: marker, + status: 'investigating', + body: 'x', + affectedComponents: [{ componentId: gone.id, componentStatus: 'major_outage' }], + }, + }), + 400 + ) + expect(deleted.error.message).toBe( + 'An affected service has been deleted. Choose the services again.' + ) + } finally { + for (const id of made) await deleteRestIncident(id) + } + } +) + +test( + 'STA-X-08 get one incident over REST', + { tag: '@nightly' }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'noAccess') + const a = await createService(admin, `${marker} A`) + const b = await createService(admin, `${marker} B`) + const inc = await must<{ id: string }>(admin, 'createStatusIncidentFn', { + kind: 'incident', + title: marker, + status: 'investigating', + body: 'first', + notifySubscribers: false, + affectedComponents: [ + { componentId: a.id, componentStatus: 'major_outage' }, + { componentId: b.id, componentStatus: 'major_outage' }, + ], + }) + try { + await must(admin, 'postStatusIncidentUpdateFn', { + id: inc.id, + status: 'identified', + body: 'second', + }) + await must(admin, 'deleteStatusComponentFn', { id: b.id }) + const got = await expectJson(await api.get(`/api/v1/status/incidents/${inc.id}`), 200) + expect(got.data.updates.map((u: Wire) => u.body)).toEqual(['first', 'second']) + expect(got.data.affectedComponents.map((c: Wire) => c.componentId ?? c.id)).toEqual([a.id]) + await must(admin, 'deleteStatusIncidentFn', { id: inc.id }) + const missing = await expectJson( + await api.get(`/api/v1/status/incidents/${inc.id}`), + 404 + ) + expect(missing.error.message).toMatch(/Status incident not found/) + await expectJson(await api.get('/api/v1/status/incidents/garbage'), 400) + } finally { + await deleteRestIncident(inc.id) + } + } +) + +test( + 'STA-X-09 post an update over REST', + { tag: '@core' }, + async ({ playwright, people, marker }) => { + const api = await keyApi(playwright, people, 'contributor') + const one = await createService(admin, `${marker} One`) + const two = await createService(admin, `${marker} Two`) + const create = async (svc: string, title: string) => + ( + await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title, + status: 'investigating', + body: 'x', + notifySubscribers: false, + affectedComponents: [{ componentId: svc, componentStatus: 'major_outage' }], + }, + }), + 201 + ) + ).data.id as string + const a = await create(one.id, `${marker} a`) + const b = await create(two.id, `${marker} b`) + try { + await expectJson( + await api.post(`/api/v1/status/incidents/${a}/updates`, { + data: { status: 'resolved', body: 'fixed' }, + }), + 201 + ) + expect((await serviceRow(one.id)).status).toBe('operational') + await expectJson( + await api.post(`/api/v1/status/incidents/${b}/updates`, { + data: { status: 'resolved', body: 'partly', skipRestore: true }, + }), + 201 + ) + expect((await serviceRow(two.id)).status).toBe('major_outage') + const kind = await expectJson( + await api.post(`/api/v1/status/incidents/${a}/updates`, { + data: { status: 'completed', body: 'x' }, + }), + 400 + ) + expect(kind.error.message).toMatch(/"completed" is not an incident status/) + const past = await expectJson( + await api.post('/api/v1/status/incidents', { + data: { + kind: 'incident', + title: `${marker} past`, + status: 'resolved', + body: 'x', + backfill: { + startedAt: new Date(Date.now() - 86_400_000).toISOString(), + resolvedAt: new Date(Date.now() - 3_600_000).toISOString(), + }, + affectedComponents: [{ componentId: one.id, componentStatus: 'major_outage' }], + }, + }), + 201 + ) + const reopen = await expectJson( + await api.post(`/api/v1/status/incidents/${past.data.id}/updates`, { + data: { status: 'investigating', body: 'x' }, + }), + 400 + ) + expect(reopen.error.message).toBe( + "A logged past incident can't be reopened. Report a new incident instead." + ) + await deleteRestIncident(past.data.id) + await expectJson( + await api.post( + '/api/v1/status/incidents/status_incident_01m7v6aewge02vtv3kd36ggmcw/updates', + { data: { status: 'resolved', body: 'x' } } + ), + 404 + ) + for (const id of [a, b]) { + expect( + (await domainEvents(id)).filter((e) => e.type === 'status.incident_updated') + ).toHaveLength(1) + } + } finally { + for (const id of [a, b]) await deleteRestIncident(id) + } + } +) + +test( + 'STA-X-10 key permissions and scopes', + { tag: '@core' }, + async ({ playwright, people, marker }) => { + const svc = await createService(admin, `${marker} Keys`) + const incidentBody = { + kind: 'incident', + title: `${marker} keyed`, + status: 'investigating', + body: 'x', + notifySubscribers: false, + affectedComponents: [{ componentId: svc.id, componentStatus: 'degraded_performance' }], + } + const made: string[] = [] + try { + for (const who of ['noAccess', 'contributor', 'admin', 'workspace'] as const) { + const api = await keyApi(playwright, people, who) + for (const path of [ + '/api/v1/status/summary', + '/api/v1/status/services', + '/api/v1/status/incidents', + ]) { + expect((await api.get(path)).status(), `${who} ${path}`).toBe(200) + } + const inc = await api.post('/api/v1/status/incidents', { data: incidentBody }) + const svcPatch = await api.patch(`/api/v1/status/services/${svc.id}`, { + data: { description: who }, + }) + if (who === 'noAccess') { + expect(inc.status()).toBe(403) + expect(((await inc.json()) as Wire).error.message).toMatch( + /Requires the 'status_page.publish' permission/ + ) + expect(svcPatch.status()).toBe(403) + } else if (who === 'contributor') { + expect(inc.status()).toBe(201) + made.push(((await inc.json()) as Wire).data.id) + expect(svcPatch.status()).toBe(403) + expect(((await svcPatch.json()) as Wire).error.message).toMatch( + /Requires the 'status_page.manage' permission/ + ) + } else { + expect(inc.status(), who).toBe(201) + made.push(((await inc.json()) as Wire).data.id) + expect(svcPatch.status(), who).toBe(200) + } + } + // A key scoped to reading feedback cannot write status. + const scoped = createKey({ + creatorEmail: people.people.admin.email, + kind: 'personal', + scopes: ['read:feedback'], + }).key + const scopedApi = await apiFor(playwright, supportEnv().baseUrl, scoped) + opened.push(scopedApi) + expect( + (await scopedApi.post('/api/v1/status/incidents', { data: incidentBody })).status() + ).toBe(403) + } finally { + for (const id of made) await deleteRestIncident(id) + } + } +) diff --git a/apps/web/e2e/tests/status/public-page.serial.spec.ts b/apps/web/e2e/tests/status/public-page.serial.spec.ts new file mode 100644 index 0000000000..afe0901bec --- /dev/null +++ b/apps/web/e2e/tests/status/public-page.serial.spec.ts @@ -0,0 +1,64 @@ +/** + * The public page's headline status, which every service in the workspace + * feeds: runs in the product-serial project, with no other test running. + * + * Journeys: STA-P-18. + * + * Every live service is set operational for the test and put back after. + * The hero only renders with no active incident, which other specs' leftovers + * can break, so this reads the status behind it (`topLevel.status`) as an + * anonymous visitor gets it. + */ +import { test, expect } from '../../support/fixtures' +import { personApi } from '../../support/server-fns' +import { supportDb } from '../../support/db' +import { supportEnv } from '../../support/env' +import { + createSegment, + createService, + publicSnapshot, + setServiceStatus, + type ServiceStatus, +} from '../../product/status' + +test( + 'STA-P-18 the headline follows the worst visible status', + { tag: '@nightly' }, + async ({ playwright, marker }) => { + const sql = supportDb() + const saved = await sql<{ id: string; status: string }[]>` + SELECT id, status FROM status_components WHERE deleted_at IS NULL` + const admin = await personApi(playwright, 'admin') + const anon = await playwright.request.newContext({ baseURL: supportEnv().baseUrl }) + try { + await sql`UPDATE status_components SET status = 'operational' WHERE deleted_at IS NULL` + const visible = await createService(admin, `${marker} Visible`) + const segment = await createSegment(marker) + const gated = await createService(admin, `${marker} Gated`, { segmentIds: [segment.id] }) + const headline = async () => + ((await publicSnapshot(anon)) as unknown as { topLevel: { status: string } }).topLevel + .status + expect(await headline()).toBe('operational') + for (const status of [ + 'degraded_performance', + 'partial_outage', + 'major_outage', + 'under_maintenance', + ] as ServiceStatus[]) { + await setServiceStatus(admin, visible.id, status) + expect(await headline(), status).toBe(status) + } + await setServiceStatus(admin, visible.id, 'operational') + // A service the visitor cannot see never moves it. + await setServiceStatus(admin, gated.id, 'major_outage') + expect(await headline()).toBe('operational') + } finally { + for (const row of saved) { + await sql`UPDATE status_components SET status = ${row.status} WHERE id = ${row.id}` + } + await sql`UPDATE status_components SET deleted_at = now() WHERE name LIKE ${`${marker}%`}` + await admin.dispose() + await anon.dispose() + } + } +) diff --git a/apps/web/e2e/tests/status/settings.isolated.spec.ts b/apps/web/e2e/tests/status/settings.isolated.spec.ts new file mode 100644 index 0000000000..1f8acd1dd5 --- /dev/null +++ b/apps/web/e2e/tests/status/settings.isolated.spec.ts @@ -0,0 +1,327 @@ +/** + * Status settings that change what every other test sees: the product flag, + * publishing, the audience, the email switch and Clear history. These run + * only in the product-isolated job (E2E_SUPPORT_ISOLATED=1, one worker, own + * database) and put every setting back. + * + * Journeys: STA-A-04, STA-A-61, STA-A-62, STA-P-05, STA-P-06, STA-P-23, + * STA-P-27, STA-S-08, STA-S-17, STA-S-25. + */ +import type { APIRequestContext } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { callServerFn, personApi } from '../../support/server-fns' +import { ISOLATED, ISOLATED_SKIP } from '../../support/automation' +import { restoreSettings, snapshotSettings, withSettings } from '../../support/isolated-settings' +import { supportEnv } from '../../support/env' +import { pollFor, supportDb } from '../../support/db' +import { mailTo, waitForMail } from '../../support/mailpit' +import { waitForEventHandled } from '../../support/bells' +import { + createIncident, + createService, + deleteMadeIncidents, + mintPortalUser, + must, + postUpdate, + serviceEvents, + statusBells, + subscribeAs, + subscriptionRow, + unsubscribeAs, + type PortalUser, +} from '../../product/status' + +test.describe.configure({ timeout: 60_000 }) + +let admin: APIRequestContext +let anon: APIRequestContext +let users: PortalUser[] = [] + +test.beforeEach(async ({ playwright }) => { + test.skip(!ISOLATED, ISOLATED_SKIP) + admin = await personApi(playwright, 'admin') + anon = await playwright.request.newContext({ baseURL: supportEnv().baseUrl }) + users = [] +}) +test.afterEach(async () => { + if (!ISOLATED) return + for (const u of users) { + await unsubscribeAs(u) + await u.api.dispose() + } + await deleteMadeIncidents(admin) + await admin.dispose() + await anon.dispose() +}) + +const UNPUBLISHED = { metadata: { 'statusSettings.enabled': false } } +const SIGNED_IN_ONLY = { metadata: { 'statusSettings.audience': 'authenticated' } } + +async function user( + playwright: Parameters[0], + marker: string, + label: string +) { + const u = await mintPortalUser(playwright, marker, label) + users.push(u) + return u +} + +test( + 'STA-A-04 the status admin redirects when the status product is off', + { tag: ['@nightly', '@isolated'] }, + async ({ asPerson }) => { + await withSettings({ feature_flags: { statusPage: false } }, async () => { + const ui = await asPerson('admin') + await ui.goto('/admin/status') + await expect(ui).not.toHaveURL(/\/admin\/status/) + await ui.goto('/admin/settings/status') + await expect(ui).toHaveURL(/\/admin\/settings\/general/) + }) + } +) + +test( + 'STA-A-61 publish and unpublish from Settings → General', + { tag: ['@core', '@isolated'] }, + async () => { + const snapshot = await snapshotSettings(['feature_flags', 'metadata']) + try { + await must(admin, 'updateFeatureFlagsFn', { statusPage: false }) + expect((await callServerFn(anon, 'getStatusPageFn', undefined, { method: 'GET' })).code).toBe( + 'STATUS_PAGE_NOT_FOUND' + ) + // Turning it on also publishes a page that was left unpublished. + await supportDb()`UPDATE settings SET metadata = jsonb_set(metadata::jsonb, '{statusSettings,enabled}', 'false')::text` + await must(admin, 'updateFeatureFlagsFn', { statusPage: true }) + const [row] = await supportDb()`SELECT metadata FROM settings LIMIT 1` + expect(JSON.parse(String(row.metadata)).statusSettings.enabled).toBe(true) + expect((await callServerFn(anon, 'getStatusPageFn', undefined, { method: 'GET' })).ok).toBe( + true + ) + } finally { + await restoreSettings(snapshot) + } + } +) + +test( + 'STA-P-05 STA-P-27 an unpublished page is not available, and each public read says so its own way', + { tag: ['@core', '@isolated'] }, + async ({ page, marker }) => { + const svc = await createService(admin, `${marker} Hidden`) + const inc = await createIncident(admin, { title: marker, services: [[svc.id, 'major_outage']] }) + await withSettings(UNPUBLISHED, async () => { + await page.goto('/status') + await expect(page.getByText('Status page not available')).toBeVisible() + await expect( + page.getByText("This status page isn't published, or you don't have access to view it.") + ).toBeVisible() + await expect(page.getByRole('link', { name: 'Go home' })).toBeVisible() + await page.goto(`/status/${inc.id}`) + await expect(page.getByRole('heading', { name: 'Incident not found' })).toBeVisible() + const feed = await anon.get('/status/feed') + expect(feed.status()).toBe(200) + expect(await feed.text()).not.toContain('') + + const pageFn = await callServerFn(anon, 'getStatusPageFn', undefined, { method: 'GET' }) + expect(pageFn.code).toBe('STATUS_PAGE_NOT_FOUND') + const detail = await callServerFn( + anon, + 'getStatusIncidentPublicFn', + { id: inc.id }, + { method: 'GET' } + ) + expect(detail.code).toBe('STATUS_INCIDENT_NOT_FOUND') + expect( + await must(anon, 'getStatusUptimeFn', { componentIds: [svc.id] }, { method: 'GET' }) + ).toEqual([]) + expect(await must(anon, 'listStatusHistoryFn', {}, { method: 'GET' })).toEqual({ + items: [], + nextCursor: null, + hasMore: false, + }) + expect(await must(anon, 'listStatusFeedFn', {}, { method: 'GET' })).toEqual([]) + }) + } +) + +test( + 'STA-P-06 STA-P-23 a signed-in audience prompts sign-in and hides the feed', + { tag: ['@core', '@isolated'] }, + async ({ browser, page, playwright, marker }) => { + const svc = await createService(admin, `${marker} Members`) + await createIncident(admin, { + title: `${marker} for members`, + services: [[svc.id, 'degraded_performance']], + }) + const u = await user(playwright, marker, 'reader') + await withSettings(SIGNED_IN_ONLY, async () => { + await page.goto('/status') + await expect(page.getByText('Sign in to view status')).toBeVisible() + await expect(page.getByText('You need to sign in to see this status page.')).toBeVisible() + await expect(page.getByRole('button', { name: 'Sign in' }).first()).toBeVisible() + const feed = await anon.get('/status/feed') + expect(feed.status()).toBe(200) + expect(await feed.text()).not.toContain('') + + const { portalPage } = await import('../../support/widget-portal') + const signedIn = await portalPage(browser, u) + await signedIn.goto('/status') + await expect(signedIn.getByText(`${marker} for members`).first()).toBeVisible() + await expect(signedIn.getByRole('link', { name: /RSS Feed/ })).toHaveCount(0) + await signedIn.context().close() + }) + } +) + +test( + 'STA-S-17 the workspace email switch off keeps the bell', + { tag: ['@nightly', '@isolated'] }, + async ({ playwright, marker }) => { + const svc = await createService(admin, `${marker} Quiet`) + const u = await user(playwright, marker, 'quiet') + await subscribeAs(u) + await withSettings({ metadata: { 'statusSettings.emailsDisabled': true } }, async () => { + const inc = await createIncident(admin, { + title: `${marker} no mail`, + services: [[svc.id, 'major_outage']], + notifySubscribers: true, + }) + await waitForEventHandled(inc.id, { type: 'status.incident_created' }) + const bells = await pollFor('the bell', async () => { + const rows = await statusBells(u.principalUuid, inc.id) + return rows.length ? rows : null + }) + expect(bells).toHaveLength(1) + expect((await mailTo(u.email)).filter((m) => m.Subject.includes(marker))).toEqual([]) + }) + } +) + +test( + 'STA-S-08 subscribing honours the page gate', + { + tag: ['@nightly', '@isolated', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'subscribeStatusFn (functions/status-subscriptions.ts:40) checks only that the caller is not anonymous, never the status page gate, so a visitor who cannot see the page still takes a subscriber slot; see QUARANTINE.md', + }, + }, + async ({ playwright, marker }) => { + const u = await user(playwright, marker, 'gated') + await withSettings(UNPUBLISHED, async () => { + const res = await callServerFn(u.api, 'subscribeStatusFn', { scope: 'page' }) + expect(res.ok).toBe(false) + expect(await subscriptionRow(u.principalUuid)).toBeNull() + }) + } +) + +test( + 'STA-S-25 subscribers are not emailed while the page is unpublished', + { + tag: ['@nightly', '@isolated', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'The status subscriber fan-out (events/targets.ts:2132) never checks isStatusPagePublished or portal privacy, so subscribers are emailed links that 404; see QUARANTINE.md', + }, + }, + async ({ playwright, marker }) => { + const svc = await createService(admin, `${marker} Launch`) + const u = await user(playwright, marker, 'early') + await must(admin, 'addStatusSubscriberFn', { email: u.email }) + await withSettings(UNPUBLISHED, async () => { + const inc = await createIncident(admin, { + title: `${marker} prelaunch`, + services: [[svc.id, 'major_outage']], + notifySubscribers: true, + }) + await waitForEventHandled(inc.id, { type: 'status.incident_created' }) + }) + // Published again: a later publish reaches them, bounding the wait. + await createIncident(admin, { + title: `${marker} sentinel`, + services: [[svc.id, 'degraded_performance']], + notifySubscribers: true, + }) + await waitForMail({ to: u.email, subject: `${marker} sentinel` }) + expect( + (await mailTo(u.email)).filter((m) => m.Subject.includes(`${marker} prelaunch`)) + ).toEqual([]) + } +) + +test( + 'STA-A-62 clear history removes resolved incidents and keeps open ones', + { tag: ['@core', '@isolated'] }, + async ({ asPerson, marker }) => { + const held = await createService(admin, `${marker} Held`) + const done = await createService(admin, `${marker} Done`) + const open = await createIncident(admin, { + title: `${marker} open`, + services: [[held.id, 'major_outage']], + }) + const closed = await createIncident(admin, { + title: `${marker} closed`, + services: [[done.id, 'major_outage']], + }) + await postUpdate(admin, closed.id, 'resolved', 'fixed') + const ui = await asPerson('admin') + await ui.goto('/admin/settings/status') + await ui.waitForLoadState('networkidle') + await ui.getByRole('button', { name: 'Clear history' }).click() + const confirm = ui.getByRole('alertdialog').or(ui.getByRole('dialog')) + await expect(confirm.getByText('Delete incident history?')).toBeVisible() + await confirm.getByRole('button', { name: 'Delete incident history' }).click() + await pollFor('the history to clear', async () => + (await callServerFn(admin, 'getStatusIncidentAdminFn', { id: closed.id }, { method: 'GET' })) + .data === null + ? true + : null + ) + expect( + (await callServerFn(admin, 'getStatusIncidentAdminFn', { id: open.id }, { method: 'GET' })) + .data + ).not.toBeNull() + expect(await serviceEvents(done.id)).toEqual([]) + } +) + +test( + 'STA-A-62 clear history keeps the events behind statuses still held', + { + tag: ['@nightly', '@isolated', '@quarantine'], + annotation: { + type: 'quarantine', + description: + 'clearStatusHistory (status.service.ts:792) deletes every service event, including those behind statuses open incidents still hold, so uptime reads operational for services that are down; see QUARANTINE.md', + }, + }, + async ({ marker }) => { + const held = await createService(admin, `${marker} Held`) + const done = await createService(admin, `${marker} Done`) + const open = await createIncident(admin, { + title: `${marker} open`, + services: [[held.id, 'major_outage']], + }) + const closed = await createIncident(admin, { + title: `${marker} closed`, + services: [[done.id, 'major_outage']], + }) + await postUpdate(admin, closed.id, 'resolved', 'fixed') + await must(admin, 'clearStatusHistoryFn') + // The resolved incident is gone; the open one and its hold remain. + expect( + (await callServerFn(admin, 'getStatusIncidentAdminFn', { id: closed.id }, { method: 'GET' })) + .data + ).toBeNull() + expect( + (await callServerFn(admin, 'getStatusIncidentAdminFn', { id: open.id }, { method: 'GET' })) + .data + ).not.toBeNull() + expect((await serviceEvents(held.id)).at(-1)?.status).toBe('major_outage') + } +) diff --git a/apps/web/e2e/tests/status/webhooks.spec.ts b/apps/web/e2e/tests/status/webhooks.spec.ts new file mode 100644 index 0000000000..65f8f41818 --- /dev/null +++ b/apps/web/e2e/tests/status/webhooks.spec.ts @@ -0,0 +1,227 @@ +/** + * Status webhooks, delivered to the webhook sink. + * + * Journeys: STA-X-12, STA-X-13, STA-X-14, STA-X-15. + * + * A status webhook receives every test's status events, so each test reads + * only deliveries that name its own incident or service id. "No delivery" is + * proved against a later delivery on the same hook (the dispatch is in order + * per hook only loosely, so the sentinel's own event is waited for first). + */ +import type { APIRequestContext } from '@playwright/test' +import { test, expect } from '../../support/fixtures' +import { personApi } from '../../support/server-fns' +import { waitForEventHandled } from '../../support/bells' +import { runSweep } from '../../support/sweeps' +import { + bodyOf, + deliveriesOf, + expectSigned, + hooksApi, + subscribe, + unsubscribe, + type Hook, +} from '../../support/webhooks' +import { sink } from '../../support/webhook-sink-client' +import { supportEnv } from '../../support/env' +import { + backdateWindow, + createIncident, + createService, + deleteMadeIncidents, + domainEvents, + must, + postUpdate, + scheduleWindow, + setServiceStatus, +} from '../../product/status' + +test.describe.configure({ timeout: 60_000 }) + +const STATUS_EVENTS = [ + 'status.incident_created', + 'status.incident_updated', + 'status.maintenance_scheduled', + 'status.maintenance_started', + 'status.maintenance_completed', + 'status.component_changed', +] + +let admin: APIRequestContext +let rest: APIRequestContext +let hook: Hook | undefined + +test.beforeEach(async ({ playwright, people, marker }) => { + admin = await personApi(playwright, 'admin') + rest = await hooksApi(playwright, supportEnv().baseUrl, people, marker) + hook = await subscribe(rest, marker, STATUS_EVENTS) +}) +test.afterEach(async () => { + await unsubscribe(rest, hook) + await deleteMadeIncidents(admin) + await admin.dispose() + await rest.dispose() +}) + +const typesFor = async (channel: string, id: string) => + (await sink.deliveries(channel)) + .filter((d) => d.body.includes(id)) + .map((d) => d.headers['x-quackback-event']) + +test('STA-X-12 status.incident_created', { tag: '@core' }, async ({ marker }) => { + const svc = await createService(admin, `${marker} Hooked`) + const inc = await createIncident(admin, { + title: `${marker} hooked`, + services: [[svc.id, 'major_outage']], + }) + const [d] = await deliveriesOf(marker, 'status.incident_created', inc.id) + expectSigned(d, hook!.secret) + const body = bodyOf<{ incident: Record }>(d) + expect(body.type).toBe('status.incident_created') + expect(body.data.incident).toMatchObject({ + id: inc.id, + kind: 'incident', + title: `${marker} hooked`, + status: 'investigating', + impact: 'critical', + componentIds: [svc.id], + notifySubscribers: false, + scheduledStartAt: null, + scheduledEndAt: null, + }) + // A backfill sends nothing; the next publish bounds the wait. + const past = await createIncident(admin, { + title: `${marker} past`, + status: 'resolved', + services: [[svc.id, 'major_outage']], + backfill: { + startedAt: new Date(Date.now() - 86_400_000), + resolvedAt: new Date(Date.now() - 3_600_000), + }, + }) + const sentinel = await createIncident(admin, { + title: `${marker} sentinel`, + services: [[svc.id, 'degraded_performance']], + }) + await deliveriesOf(marker, 'status.incident_created', sentinel.id) + expect(await typesFor(marker, past.id)).toEqual([]) +}) + +test( + 'STA-X-13 status.incident_updated per posted update only', + { tag: '@core' }, + async ({ marker }) => { + const svc = await createService(admin, `${marker} Updates`) + const inc = await createIncident(admin, { + title: `${marker} updates`, + services: [[svc.id, 'major_outage']], + }) + await postUpdate(admin, inc.id, 'identified', 'found') + await postUpdate(admin, inc.id, 'resolved', 'fixed') + await postUpdate(admin, inc.id, 'investigating', 'back') + const ds = await deliveriesOf(marker, 'status.incident_updated', inc.id, { count: 3 }) + expect(ds.map((d) => bodyOf<{ status: string }>(d).data.status).sort()).toEqual([ + 'identified', + 'investigating', + 'resolved', + ]) + for (const d of ds) { + const data = bodyOf>(d).data + expect(data).toMatchObject({ incidentId: inc.id, kind: 'incident' }) + expect(data).toHaveProperty('body') + expect(data).not.toHaveProperty('title') + } + // A title edit sends nothing. + await must(admin, 'updateStatusIncidentFn', { id: inc.id, title: `${marker} renamed` }) + await postUpdate(admin, inc.id, 'identified', 'sentinel') + await deliveriesOf(marker, 'status.incident_updated', inc.id, { count: 4 }) + expect( + (await typesFor(marker, inc.id)).filter((t) => t === 'status.incident_updated') + ).toHaveLength(4) + } +) + +test( + 'STA-X-14 maintenance scheduled, started and completed, once per transition', + { tag: '@core' }, + async ({ request, marker }) => { + const svc = await createService(admin, `${marker} Window`) + // By the scheduler. + const auto = await scheduleWindow(admin, { + title: `${marker} auto`, + services: [[svc.id, 'under_maintenance']], + }) + await backdateWindow(auto.id, { start: new Date(Date.now() - 1_000) }) + await runSweep(request, 'status-maintenance') + await backdateWindow(auto.id, { end: new Date(Date.now() - 1_000) }) + await runSweep(request, 'status-maintenance') + // By hand. + const manual = await scheduleWindow(admin, { + title: `${marker} manual`, + services: [[svc.id, 'under_maintenance']], + }) + await postUpdate(admin, manual.id, 'in_progress', 'going') + await postUpdate(admin, manual.id, 'completed', 'done') + + for (const w of [auto, manual]) { + await deliveriesOf(marker, 'status.maintenance_completed', w.id) + const types = await typesFor(marker, w.id) + expect(types.filter((t) => t === 'status.maintenance_scheduled')).toHaveLength(1) + expect(types.filter((t) => t === 'status.maintenance_started')).toHaveLength(1) + expect(types.filter((t) => t === 'status.maintenance_completed')).toHaveLength(1) + const [started] = await deliveriesOf(marker, 'status.maintenance_started', w.id) + expect(bodyOf(started).data).toEqual({ + incidentId: w.id, + title: w.title, + componentIds: [svc.id], + }) + } + + // Created already running: scheduled, then started. + const running = await createIncident(admin, { + kind: 'maintenance', + status: 'in_progress', + title: `${marker} running`, + services: [[svc.id, 'under_maintenance']], + scheduledStartAt: new Date(Date.now() - 60_000), + scheduledEndAt: new Date(Date.now() + 3_600_000), + }) + await deliveriesOf(marker, 'status.maintenance_started', running.id) + await deliveriesOf(marker, 'status.maintenance_scheduled', running.id) + await waitForEventHandled(running.id, { type: 'status.maintenance_started' }) + } +) + +test( + 'STA-X-15 status.component_changed only for hand and API changes', + { tag: '@core' }, + async ({ marker }) => { + const svc = await createService(admin, `${marker} Changed`) + await setServiceStatus(admin, svc.id, 'degraded_performance') + const patched = await rest.patch(`/api/v1/status/services/${svc.id}`, { + data: { status: 'partial_outage' }, + }) + expect(patched.status()).toBe(200) + const ds = await deliveriesOf(marker, 'status.component_changed', svc.id, { count: 2 }) + const datas = ds.map( + (d) => bodyOf<{ source: string; previousStatus: string; status: string }>(d).data + ) + expect(datas.map((x) => `${x.source}:${x.previousStatus}->${x.status}`).sort()).toEqual([ + 'api:degraded_performance->partial_outage', + 'manual:operational->degraded_performance', + ]) + // An incident moving the service sends only the incident's own event. + const inc = await createIncident(admin, { title: marker, services: [[svc.id, 'major_outage']] }) + await deliveriesOf(marker, 'status.incident_created', inc.id) + await waitForEventHandled(inc.id, { type: 'status.incident_created' }) + await setServiceStatus(admin, svc.id, 'operational') + await deliveriesOf(marker, 'status.component_changed', svc.id, { count: 3 }) + expect( + (await typesFor(marker, svc.id)).filter((t) => t === 'status.component_changed') + ).toHaveLength(3) + // The written events, not only the deliveries: the incident added none. + expect( + (await domainEvents(svc.id)).filter((e) => e.type === 'status.component_changed') + ).toHaveLength(3) + } +)