diff --git a/CLAUDE.md b/CLAUDE.md index df58c825..7c702c3e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -183,6 +183,14 @@ in `docs/adr/0001-event-bus-and-alerts.md`. `GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test` (dry runs: never send, never touch the throttle). Project API keys only reach their project. +- UI: `/org//settings/alerts` and `/org//projects//settings/alerts` (list, `new`, + `[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`, + `test`, `toggle`, `delete`; everything works without JavaScript). Components live in + `#lib/components/alerts/`: `ConditionBuilder` renders fields, operators and inputs only from the + `CatalogEntry` it receives (tested with `svelte/server` in `ConditionBuilder.test.ts`; Vitest + compiles `.svelte` through `vitest.config.ts`). Project pages also list the inherited + organization alerts, read-only. Error codes map to `alerts.errors.`. + Making an event alertable: 1. Declare the payload in `DomainEventMap` and publish it with `publishAfterWrite` and the right @@ -190,7 +198,7 @@ Making an event alertable: 2. Add its `EventDefinition` with `alertable: true`, the correct `scope` and `readPermission`, and the fields people will filter on (`reference` fields need a case in `PlatformDirectory`). 3. Add the `events..*` translations in `es.json` and `en.json`. -4. Nothing else: the catalog endpoint, the validation and the engine pick it up. +4. Nothing else: the catalog endpoint, the validation, the engine and the UI pick it up. ## Authorization diff --git a/README.md b/README.md index 71f56bfd..0acde952 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ operational data versioned and auditable in Git. - Cluster-wide Google sign-in (OpenID Connect) alongside local email and password login. - Security reporting for vulnerabilities, SBOMs, secrets, licenses, and services. - Pulumi state, history, and lock visibility for S3 and Google Cloud Storage backends. +- Email alerts on platform events (security analyses, vault, projects, access), with filters + built from an event catalog. - Git-backed, auditable application data through GitDB. ## Get started @@ -119,6 +121,48 @@ automatically, because the domain is checked against the Workspace `hd` claim, n address. If the variables are inconsistent (only one credential set, an invalid domain, or automatic sign-up without domains), the Google button is hidden and the reason is logged. +### Alerts + +Organizations and projects can get an email when something happens. Alerts live in **Settings → +Alerts** of the organization (they cover all of its projects) or of a project. Each alert watches +one event, filters it on the event's fields and emails users or roles. Emails need the +`NOTIFICATION_SMTP_*` variables; without SMTP, alerts are kept but nothing is sent. + +Guided example: *tell the security team when an analysis of the `api-gateway` service has critical +vulnerabilities*. + +1. Open the project's **Settings → Alerts** and click **Create alert**. +2. Event: **Analysis completed** (`code_report.analysis.completed`). +3. Conditions, matching **all**: **Service** *is* `api-gateway`, and **Critical vulnerabilities** + *greater than* `0`. +4. Recipients: the **Project Admin** role. Throttle: one email every **30** minutes at most. +5. **Test alert** shows whether an example event matches and who would get the email, without + sending anything. Then **Create alert**. + +The same alert through the API (`gvs_` project keys only manage alerts of their own project): + +```bash +curl -X POST "$ORIGIN/api/alerts" \ + -H "Authorization: Bearer $GITOPS_API_KEY" -H "Content-Type: application/json" \ + -d '{ + "projectId": "", + "name": "Critical vulnerabilities in api-gateway", + "eventType": "code_report.analysis.completed", + "match": "all", + "conditions": [ + { "field": "serviceId", "operator": "eq", "value": "" }, + { "field": "summary.critical", "operator": "gt", "value": 0 } + ], + "recipients": { "roleIds": [""] }, + "throttleMinutes": 30 + }' +``` + +`GET /api/events/catalog?scope=project&projectId=` lists the events you may alert on and their +fields. Only recipients allowed to view the event get the email, and you can only create alerts on +events you can view yourself. Some notifications are always on: users are told when their access to +an organization or project changes and when a personal API key is created on their account. + ## Development ```bash diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts new file mode 100644 index 00000000..786ed957 --- /dev/null +++ b/e2e/specs/alerts.spec.ts @@ -0,0 +1,192 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { expectAllowed, expectDenied } from '../fixtures/expect-access'; +import { E2E_BASE_URL } from '../global-setup'; + +const seed = getSeed(); +const projectBase = `/org/${seed.primaryOrgSlug}/projects/${seed.primaryProjectSlug}`; +const alertsUrl = `${projectBase}/settings/alerts`; +const orgAlertsUrl = `/org/${seed.primaryOrgSlug}/settings/alerts`; + +const GUIDED_NAME = 'Críticas en el servicio sembrado'; + +// the editor is interactive only once hydrated: before that, a select change is reset by Svelte +async function openEditor(page: import('@playwright/test').Page, url: string) { + await page.goto(url); + await page.waitForLoadState('networkidle'); +} + +test.describe.configure({ mode: 'serial' }); + +test.describe('project alerts', () => { + test('a project admin creates the guided example and tests it first', async ({ + page, + loginAs, + }) => { + await loginAs('projectAdmin'); + await expectAllowed(page, alertsUrl); + await expect(page.getByText('Todavía no hay alertas')).toBeVisible(); + await expect(page.getByRole('link', { name: 'Crear alerta' }).first()).toHaveAttribute( + 'href', + `${alertsUrl}/new`, + ); + await openEditor(page, `${alertsUrl}/new`); + + // step 1: event + await page.getByLabel('Nombre', { exact: true }).fill(GUIDED_NAME); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' }); + + // step 2: Servicio es · Vulnerabilidades críticas mayor que 0 + const builder = page.getByTestId('condition-builder'); + await builder.getByRole('button', { name: 'Añadir condición' }).click(); + const first = builder.getByTestId('condition-row').nth(0); + await first.getByLabel('Campo').selectOption({ label: 'Servicio' }); + await first.getByLabel('Operador').selectOption({ label: 'es' }); + await first.getByRole('radio', { name: 'E2E Seeded Service' }).check(); + + await builder.getByRole('button', { name: 'Añadir condición' }).click(); + const second = builder.getByTestId('condition-row').nth(1); + await second.getByLabel('Campo').selectOption({ label: 'Vulnerabilidades críticas' }); + await second.getByLabel('Operador').selectOption({ label: 'mayor que' }); + await second.getByLabel('Valor').fill('0'); + + // step 3: recipients and throttle + await page.getByRole('checkbox', { name: 'Project Admin' }).check(); + await page.getByLabel('No enviar más de un email cada (minutos)').fill('30'); + + // step 4: dry run, nothing is sent + await page.getByRole('button', { name: 'Probar alerta' }).click(); + const result = page.getByTestId('alert-test-result'); + await expect(result).toContainText('El evento de ejemplo cumple las condiciones.'); + await expect(result).toContainText(seed.personas.projectAdmin.username); + await expect(result).toContainText('no se ha enviado ningún email'); + + await page.getByRole('button', { name: 'Crear alerta' }).click(); + await expect(page).toHaveURL(new RegExp(`${alertsUrl}\\?saved=`)); + + const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME }); + await expect(row).toBeVisible(); + await expect(row.getByTestId('alert-summary')).toHaveText( + 'Servicio es E2E Seeded Service y Vulnerabilidades críticas mayor que 0', + ); + await expect(row).toContainText('Project Admin'); + await expect(row).toContainText('Máx. un email cada 30 min'); + await expect(row.getByRole('switch')).toHaveAttribute('aria-checked', 'true'); + }); + + test('server validation errors show next to their field', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await openEditor(page, `${alertsUrl}/new`); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' }); + await page.getByRole('button', { name: 'Crear alerta' }).click(); + + await expect(page.getByText('Este campo es obligatorio.').first()).toBeVisible(); + await expect(page.getByLabel('Nombre', { exact: true })).toHaveAttribute( + 'aria-describedby', + 'alert-name-error', + ); + }); + + test('a project viewer sees the list without any management action', async ({ + page, + loginAs, + }) => { + await loginAs('projectViewer'); + await expectAllowed(page, alertsUrl); + const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME }); + await expect(row).toBeVisible(); + await expect(page.getByRole('link', { name: 'Crear alerta' })).toHaveCount(0); + await expect(row.getByRole('link', { name: 'Editar' })).toHaveCount(0); + await expect(row.getByRole('button', { name: 'Borrar' })).toHaveCount(0); + await expect(row.getByRole('switch')).toHaveCount(0); + + // the server refuses the same actions when they are posted directly + const headers = { origin: E2E_BASE_URL }; + const save = await page.request.post(`${alertsUrl}/new?/save`, { + headers, + form: { name: 'x', eventType: 'code_report.analysis.completed', roleIds: 'any' }, + }); + expect(save.status()).toBe(403); + + const api = await page.request.post('/api/alerts', { + data: { projectId: 'irrelevant', name: 'x' }, + }); + expect([403, 404]).toContain(api.status()); + await expectDenied(page, `${alertsUrl}/new`); + }); + + test('the sidebar only shows alerts to people who can read them', async ({ page, loginAs }) => { + await loginAs('projectViewer'); + await page.goto(`${projectBase}/settings/overview`); + await expect(page.locator(`a[href="${alertsUrl}"]`)).toHaveCount(1); + + await loginAs('vaultSecretsOnly'); + await page.goto(`${projectBase}/vault`); + await expect(page.locator(`a[href="${alertsUrl}"]`)).toHaveCount(0); + await expectDenied(page, alertsUrl); + }); + + test('people outside the project cannot reach its alerts', async ({ page, loginAs }) => { + await loginAs('projectOutsider'); + await expectDenied(page, alertsUrl); + await loginAs('orgOutsider'); + await expectDenied(page, orgAlertsUrl); + }); + + test('the API requires authentication', async ({ playwright }) => { + const anonymous = await playwright.request.newContext({ baseURL: E2E_BASE_URL }); + const response = await anonymous.get(`/api/alerts?organizationId=${seed.primaryOrgId}`); + expect(response.status()).toBe(401); + await anonymous.dispose(); + }); +}); + +test.describe('organization alerts', () => { + test('the project page lists organization alerts as read-only inherited ones', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + await expectAllowed(page, orgAlertsUrl); + await openEditor(page, `${orgAlertsUrl}/new`); + await page.getByLabel('Nombre', { exact: true }).fill('Todos los análisis fallidos'); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis fallido' }); + await page.getByRole('checkbox', { name: 'Org Admin' }).check(); + await page.getByRole('button', { name: 'Crear alerta' }).click(); + await expect( + page.getByTestId('alert-row').filter({ hasText: 'Todos los análisis fallidos' }), + ).toBeVisible(); + + await loginAs('projectAdmin'); + await page.goto(alertsUrl); + const inherited = page.getByTestId('inherited-alerts'); + await expect(inherited).toContainText('Todos los análisis fallidos'); + await expect(inherited.getByRole('link', { name: 'Editar' })).toHaveCount(0); + await expect(inherited.getByRole('switch')).toHaveCount(0); + }); +}); + +test.describe('without JavaScript', () => { + test.use({ javaScriptEnabled: false }); + + test('the editor still creates an alert through form actions', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await page.goto(`${alertsUrl}/new`); + + await page.getByLabel('Nombre', { exact: true }).fill('Sin JS'); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' }); + await page.getByRole('button', { name: 'Usar este evento' }).click(); + + // ?/draft re-renders the form with one condition row for the chosen event + await page.getByRole('button', { name: 'Añadir condición' }).click(); + const row = page.getByTestId('condition-row').first(); + await expect(row.getByLabel('Campo')).toHaveValue('serviceId'); + await row.getByRole('radio', { name: 'E2E Seeded Service' }).check(); + await page.getByRole('checkbox', { name: 'Project Admin' }).check(); + + await page.getByRole('button', { name: 'Crear alerta' }).click(); + await expect(page).toHaveURL(new RegExp(`${alertsUrl}\\?saved=`)); + await expect( + page.getByTestId('alert-row').filter({ hasText: 'Sin JS' }).getByTestId('alert-summary'), + ).toHaveText('Servicio es E2E Seeded Service'); + }); +}); diff --git a/e2e/specs/organization-settings.spec.ts b/e2e/specs/organization-settings.spec.ts index d1fcb516..03781643 100644 --- a/e2e/specs/organization-settings.spec.ts +++ b/e2e/specs/organization-settings.spec.ts @@ -13,6 +13,7 @@ const settingsRoutes = [ `/org/${org}/settings/server-access-keys`, `/org/${org}/settings/audit`, `/org/${org}/settings/events`, + `/org/${org}/settings/alerts`, ]; test.describe('organization settings — org admin', () => { diff --git a/e2e/specs/project-settings.spec.ts b/e2e/specs/project-settings.spec.ts index 03d3b4e3..aa514086 100644 --- a/e2e/specs/project-settings.spec.ts +++ b/e2e/specs/project-settings.spec.ts @@ -13,6 +13,7 @@ const settingsRoutes = [ `${base}/settings/roles-permissions`, `${base}/settings/server-access-keys`, `${base}/settings/audit`, + `${base}/settings/alerts`, ]; test('project admin sees every project settings resource', async ({ page, loginAs }) => { diff --git a/src/lib/alerts/summary.test.ts b/src/lib/alerts/summary.test.ts new file mode 100644 index 00000000..74722870 --- /dev/null +++ b/src/lib/alerts/summary.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest'; +import { summarizeConditions, summarizeRecipients } from './summary'; +import type { CatalogEntry } from './types'; + +const labels: Record = { + 'f.service': 'Servicio', + 'f.critical': 'Vulnerabilidades críticas', + 'f.tool': 'Herramienta', + 'f.flag': 'Hay vulnerabilidades', + 'o.trivy': 'Trivy', + 'alerts.operators.eq': 'es', + 'alerts.operators.gt': 'mayor que', + 'alerts.operators.in': 'es uno de', + 'alerts.operators.is_true': 'es sí', + 'alerts.summary.and': 'y', + 'alerts.summary.or': 'o', + 'alerts.summary.always': 'Siempre', + 'alerts.summary.noRecipients': 'Nadie', +}; +const t = (key: string) => labels[key] ?? key; + +const definition = { + type: 'code_report.analysis.completed', + fields: [ + { + key: 'serviceId', + label: 'f.service', + type: 'reference', + reference: 'code_report_service', + operators: ['eq', 'in'], + }, + { key: 'summary.critical', label: 'f.critical', type: 'number', operators: ['gt'] }, + { + key: 'tool', + label: 'f.tool', + type: 'enum', + options: [{ value: 'trivy', label: 'o.trivy' }], + operators: ['in'], + }, + { + key: 'hasVulnerabilities', + label: 'f.flag', + type: 'boolean', + operators: ['is_true'], + derived: true, + }, + ], +} as unknown as CatalogEntry; + +const references = { code_report_service: [{ id: 'svc-1', label: 'api-gateway' }] }; + +describe('summarizeConditions', () => { + it('reads like the guided example', () => { + expect( + summarizeConditions( + definition, + [ + { field: 'serviceId', operator: 'eq', value: 'svc-1' }, + { field: 'summary.critical', operator: 'gt', value: 0 }, + ], + 'all', + references, + t, + ), + ).toBe('Servicio es api-gateway y Vulnerabilidades críticas mayor que 0'); + }); + + it('joins with "or", lists values and skips valueless operators', () => { + expect( + summarizeConditions( + definition, + [ + { field: 'tool', operator: 'in', value: ['trivy', 'grype'] }, + { field: 'hasVulnerabilities', operator: 'is_true', value: '' }, + ], + 'any', + references, + t, + ), + ).toBe('Herramienta es uno de Trivy, grype o Hay vulnerabilidades es sí'); + }); + + it('says when an alert has no conditions and keeps unknown fields raw', () => { + expect(summarizeConditions(definition, [], 'all', references, t)).toBe('Siempre'); + expect( + summarizeConditions( + definition, + [{ field: 'gone', operator: 'eq', value: 'x' }], + 'all', + references, + t, + ), + ).toBe('gone es'); + }); +}); + +describe('summarizeRecipients', () => { + it('names roles and users', () => { + expect( + summarizeRecipients( + { userIds: ['u1', 'ghost'], roleIds: ['r1'] }, + [{ id: 'u1', label: 'ana' }], + [{ id: 'r1', label: 'Project Admin' }], + t, + ), + ).toBe('Project Admin, ana, ghost'); + expect(summarizeRecipients({ userIds: [], roleIds: [] }, [], [], t)).toBe('Nadie'); + }); +}); diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts new file mode 100644 index 00000000..c38c820c --- /dev/null +++ b/src/lib/alerts/summary.ts @@ -0,0 +1,76 @@ +import type { Operator } from '#lib/events/catalog'; +import type { AlertOption, CatalogEntry, CatalogField, DraftCondition } from './types'; + +export type Translate = (key: string, options?: { values?: Record }) => string; + +/** Operators that take no value, and those that take a list. */ +export const VALUELESS_OPERATORS: readonly Operator[] = ['is_true', 'is_false', 'exists']; +export const LIST_OPERATORS: readonly Operator[] = ['in', 'not_in']; + +export function operatorLabel(operator: Operator | '', t: Translate): string { + return operator ? t(`alerts.operators.${operator}`) : ''; +} + +/** Human value of a condition: option labels for enums, entity names for references. */ +export function conditionValueLabel( + field: CatalogField, + value: DraftCondition['value'] | undefined, + referenceOptions: Record, + t: Translate, +): string { + const items = Array.isArray(value) ? value : value === undefined || value === '' ? [] : [value]; + return items + .map((item) => { + const text = String(item); + if (field.type === 'enum') { + const option = field.options?.find((candidate) => candidate.value === text); + return option ? t(option.label) : text; + } + if (field.type === 'reference' && field.reference) { + return ( + referenceOptions[field.reference]?.find((option) => option.id === text)?.label ?? text + ); + } + if (field.type === 'date') return new Date(text).toLocaleDateString(); + return text; + }) + .join(', '); +} + +/** + * "Servicio es api-gateway y Vulnerabilidades críticas mayor que 0". Conditions on fields the + * catalog no longer has keep their raw key. + */ +export function summarizeConditions( + definition: CatalogEntry | undefined, + conditions: readonly DraftCondition[], + match: 'all' | 'any', + referenceOptions: Record, + t: Translate, +): string { + if (conditions.length === 0) return t('alerts.summary.always'); + const parts = conditions.map((condition) => { + const field = definition?.fields.find((candidate) => candidate.key === condition.field); + const label = field ? t(field.label) : condition.field; + const operator = operatorLabel(condition.operator, t); + if (!field || VALUELESS_OPERATORS.includes(condition.operator as Operator)) { + return `${label} ${operator}`.trim(); + } + return `${label} ${operator} ${conditionValueLabel(field, condition.value, referenceOptions, t)}`; + }); + return parts.join(` ${t(match === 'any' ? 'alerts.summary.or' : 'alerts.summary.and')} `); +} + +/** "2 usuarios · Project Admin" */ +export function summarizeRecipients( + recipients: { userIds: string[]; roleIds: string[] }, + users: AlertOption[], + roles: AlertOption[], + t: Translate, +): string { + const names = [ + ...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id), + ...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id), + ]; + return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients'); +} diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts new file mode 100644 index 00000000..ea6cdb62 --- /dev/null +++ b/src/lib/alerts/types.ts @@ -0,0 +1,76 @@ +/** + * Data shapes of the alert pages, shared by the loaders (`#lib/server/alerts/page`) and the + * components (`#lib/components/alerts`). Type-only: safe to import from the client. + */ +import type { EventDefinition, Operator } from '#lib/events/catalog'; +import type { AlertRow, AlertScope } from '#modules/alerts/domain/alert.domain'; + +/** An alertable event as plain data: `derive` functions are dropped, `derived` marks them. */ +export type CatalogField = Omit & { + derived?: boolean; +}; + +export type CatalogEntry = Omit & { fields: CatalogField[] }; + +export type AlertOption = { id: string; label: string }; + +export type DraftCondition = { + field: string; + operator: Operator | ''; + value: string | number | string[]; +}; + +/** The editor's form state; the server validates and normalizes it on save. */ +export type AlertDraft = { + name: string; + description: string; + enabled: boolean; + eventType: string; + match: 'all' | 'any'; + conditions: DraftCondition[]; + recipients: { userIds: string[]; roleIds: string[] }; + throttleMinutes: number; +}; + +type Shared = { + basePath: string; + scope: AlertScope; + catalog: CatalogEntry[]; + /** Entities a `reference` field can point at, per reference kind. */ + referenceOptions: Record; + users: AlertOption[]; + roles: AlertOption[]; +}; + +export type AlertListData = Shared & { + alerts: AlertRow[]; + /** Organization alerts that also fire for this project (project pages only). */ + inherited: AlertRow[]; + canCreate: boolean; + canUpdate: boolean; + canDelete: boolean; +}; + +export type AlertEditorData = Shared & { + alertId: string | null; + draft: AlertDraft; + canSave: boolean; + canDelete: boolean; +}; + +export type AlertTestView = { + matched: boolean; + recipients: Array<{ userId: string; username: string }>; + deniedCount: number; + event: { type: string; payload: Record; projectId: string | null }; +}; + +/** What the editor's form actions return. */ +export type AlertFormResult = { + draft?: AlertDraft; + error?: string; + errors?: Record; + test?: AlertTestView; +} | null; + +export type { AlertRow, AlertScope }; diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index a0a4b609..6296d268 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -2,6 +2,7 @@ import { createPageStore } from '#lib/page-store'; import { Activity, + BellRing, BarChart3, Building2, ChevronDown, @@ -48,11 +49,13 @@ export let canReadOrgServerKeys = false; export let canReadOrgAudit = false; export let canReadOrgEvents = false; + export let canReadOrganizationAlerts = false; export let canReadProjectInfo = false; export let canReadProjectUsers = false; export let canReadProjectRoles = false; export let canReadProjectServerKeys = false; export let canReadProjectAudit = false; + export let canReadProjectAlerts = false; export let canReadProjectVault = false; export let canReadProjectCodeReport = false; export let canReadProjectStateIac = false; @@ -229,6 +232,12 @@ icon: ScrollText, visible: canReadProjectAudit, }, + { + label: $_('sidebar.items.alerts'), + href: `${projectBase}/settings/alerts`, + icon: BellRing, + visible: canReadProjectAlerts, + }, { label: $_('sidebar.items.serverKeys'), href: `${projectBase}/settings/server-access-keys`, @@ -310,6 +319,12 @@ icon: Activity, visible: canReadOrgEvents, }, + { + label: $_('sidebar.items.alerts'), + href: `/org/${organizationSlug}/settings/alerts`, + icon: BellRing, + visible: canReadOrganizationAlerts, + }, ] .filter((item) => item.visible) .map(({ visible, ...item }) => item); diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte new file mode 100644 index 00000000..4ef199d1 --- /dev/null +++ b/src/lib/components/alerts/AlertEditor.svelte @@ -0,0 +1,433 @@ + + +
+ + + {#if data.canSave} + + {/if} + +
+ + + {$_('alerts.editor.back')} + + {#if message} + + {/if} +
+ + +
+

+ 1. {$_('alerts.editor.stepEvent')} +

+ +
+
+ + + {#if errors.name} + + {/if} +
+
+ + +

+ {definition ? $_(definition.description) : $_('alerts.editor.eventHelp')} +

+ {#if errors.eventType} + + {/if} + +
+
+ +
+ + +
+ + +
+ + +
+

+ 2. {$_('alerts.editor.stepConditions')} +

+ {#if droppedConditions > 0} +

+ {$_('alerts.editor.droppedConditions', { values: { count: droppedConditions } })} +

+ {/if} + {#if definition} + + {:else} +

{$_('alerts.editor.chooseEventFirst')}

+ + {/if} +
+ + +
+

+ 3. {$_('alerts.editor.stepRecipients')} +

+

+ + {$_('alerts.editor.recipientsNotice')} +

+
+
+ + {$_('alerts.editor.roles')} + + { + draft.recipients.roleIds = selected; + }} + /> +
+
+ {$_('alerts.editor.users')} + { + draft.recipients.userIds = selected; + }} + /> +
+
+ {#if errors.recipients || errors['recipients.userIds'] || errors['recipients.roleIds']} + + {/if} + +
+ {$_('alerts.editor.channels')} + + {#each ['in_app', 'slack'] as channel (channel)} + + {/each} +
+ +
+ + +

+ {$_('alerts.editor.throttleHelp')} +

+ {#if errors.throttleMinutes} + + {/if} +
+
+ + +
+

+ 4. {$_('alerts.editor.stepSave')} +

+ + {#if needsSampleProject && projects.length > 0} +
+ + +
+ {/if} + + {#if test} +
+

+ {test.matched ? $_('alerts.test.matched') : $_('alerts.test.notMatched')} +

+ {#if test.recipients.length > 0} +

+ {$_('alerts.test.recipients', { + values: { names: test.recipients.map((recipient) => recipient.username).join(', ') }, + })} +

+ {:else} +

{$_('alerts.test.noRecipients')}

+ {/if} + {#if test.deniedCount > 0} +

+ {$_('alerts.test.denied', { values: { count: test.deniedCount } })} +

+ {/if} +

{$_('alerts.test.nothingSent')}

+
+ {/if} + +
+ {#if data.canSave} + + + {/if} + {#if data.canDelete} + + {/if} +
+
+
diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte new file mode 100644 index 00000000..cfc44630 --- /dev/null +++ b/src/lib/components/alerts/AlertList.svelte @@ -0,0 +1,227 @@ + + +
+
+
+

{$_('alerts.list.title')}

+

+ {data.scope === 'project' + ? $_('alerts.list.descriptionProject') + : $_('alerts.list.descriptionOrganization')} +

+
+ {#if data.canCreate && data.alerts.length > 0} + + + {$_('alerts.list.create')} + + {/if} +
+ + {#if error} + + {/if} + + {#if data.alerts.length === 0} +
+ +

{$_('alerts.list.emptyTitle')}

+
    + {#each examples as example (example)} +
  • “{$_(example)}”
  • + {/each} +
+ {#if data.canCreate} + + + {$_('alerts.list.create')} + + {/if} +
+ {:else} + {@render table(data.alerts, false)} + {/if} + + {#if data.scope === 'project' && data.inherited.length > 0} +
+
+

{$_('alerts.list.inheritedTitle')}

+

{$_('alerts.list.inheritedDescription')}

+
+ {@render table(data.inherited, true)} +
+ {/if} +
+ +{#snippet table(alerts: AlertRow[], readonly: boolean)} +
+ + + + + + + + + {#if !readonly && (data.canUpdate || data.canDelete)} + + {/if} + + + + {#each alerts as alert (alert.id)} + + + + + + + {#if !readonly && (data.canUpdate || data.canDelete)} + + {/if} + + {/each} + +
{$_('alerts.list.name')}{$_('alerts.list.event')}{$_('alerts.list.conditions')}{$_('alerts.list.recipients')}{$_('alerts.list.status')}{$_('alerts.list.actions')}
+ {#if !readonly && data.canUpdate} + {alert.name} + {:else} + {alert.name} + {/if} + {#if alert.throttleMinutes > 0} +

+ {$_('alerts.list.throttle', { values: { minutes: alert.throttleMinutes } })} +

+ {/if} +
+

{eventLabel(alert)}

+

{moduleLabel(alert)}

+
{conditionsOf(alert)} + {summarizeRecipients(alert.recipients, data.users, data.roles, t)} + + {#if !readonly && data.canUpdate} +
+ + + +
+ {:else} + + {alert.enabled ? $_('alerts.list.enabled') : $_('alerts.list.disabled')} + + {/if} +
+
+ {#if data.canUpdate} + + + {$_('alerts.list.edit')} + + {/if} + {#if data.canDelete} +
{ + if (!confirm($_('alerts.list.confirmDelete'))) cancel(); + }} + > + + +
+ {/if} +
+
+
+{/snippet} diff --git a/src/lib/components/alerts/ConditionBuilder.svelte b/src/lib/components/alerts/ConditionBuilder.svelte new file mode 100644 index 00000000..1bc3d253 --- /dev/null +++ b/src/lib/components/alerts/ConditionBuilder.svelte @@ -0,0 +1,288 @@ + + +
+
+ {$_('alerts.editor.matchLabel')} + + +
+ + {#if conditions.length === 0} +

+ {$_('alerts.editor.noConditions')} +

+ {/if} + +
    + {#each conditions as condition, index (index)} + {@const field = fieldOf(condition.field)} +
  1. +
    + + + {#if errors[`conditions.${index}.field`]} + + {/if} +
    + +
    + + + {#if errors[`conditions.${index}.operator`]} + + {/if} +
    + +
    + + {$_('alerts.editor.value')} + + + {#if !field || !needsValue(condition.operator)} +

    —

    + {:else if field.type === 'enum' || field.type === 'reference'} + ({ + id: option.value, + label: $_(option.label), + })) + : (referenceOptions[field.reference ?? ''] ?? [])} + selected={valueList(condition.value)} + invalid={Boolean(errors[`conditions.${index}.value`])} + describedBy={errorId(index, 'value')} + onchange={(selected) => + setValue(index, isList(condition.operator) ? selected : (selected[0] ?? ''))} + /> + {:else if field.type === 'number'} + setValue(index, event.currentTarget.value)} + /> + {:else if field.type === 'date'} + setValue(index, event.currentTarget.value)} + /> + {:else} + setValue(index, event.currentTarget.value)} + /> + {/if} + {#if errors[`conditions.${index}.value`]} + + {/if} +
    + +
    + +
    +
  2. + {/each} +
+ + {#if errors.conditions} + + {/if} + + +
diff --git a/src/lib/components/alerts/ConditionBuilder.test.ts b/src/lib/components/alerts/ConditionBuilder.test.ts new file mode 100644 index 00000000..41a1e666 --- /dev/null +++ b/src/lib/components/alerts/ConditionBuilder.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render } from 'svelte/server'; +import type { CatalogEntry } from '#lib/alerts/types'; + +// `#lib/i18n` reads `$app/env`, which only exists inside SvelteKit +vi.mock('$app/env', () => ({ browser: false })); + +const { default: ConditionBuilder } = await import('./ConditionBuilder.svelte'); + +/** A made-up event: nothing in the component knows about it. */ +const definition: CatalogEntry = { + type: 'code_report.analysis.completed', + module: 'code_report', + scope: 'project', + label: 'events.code_report.analysis.completed.label', + description: 'events.code_report.analysis.completed.description', + readPermission: 'project:codereport:reports:read', + alertable: true, + fields: [ + { key: 'branch', label: 'test.fields.branch', type: 'string', operators: ['eq', 'contains'] }, + { key: 'count', label: 'test.fields.count', type: 'number', operators: ['gt', 'lte'] }, + { key: 'when', label: 'test.fields.when', type: 'date', operators: ['gt'] }, + { key: 'flag', label: 'test.fields.flag', type: 'boolean', operators: ['is_true', 'is_false'] }, + { + key: 'tool', + label: 'test.fields.tool', + type: 'enum', + operators: ['eq', 'in'], + options: [ + { value: 'trivy', label: 'test.options.trivy' }, + { value: 'grype', label: 'test.options.grype' }, + ], + }, + { + key: 'serviceId', + label: 'test.fields.service', + type: 'reference', + reference: 'code_report_service', + operators: ['eq', 'in'], + }, + ], +}; + +const referenceOptions = { + code_report_service: [ + { id: 'svc-1', label: 'api-gateway' }, + { id: 'svc-2', label: 'web' }, + ], +}; + +function html(conditions: Array<{ field: string; operator: string; value: string | string[] }>) { + return render(ConditionBuilder, { + props: { + definition, + conditions: conditions as never, + match: 'all', + referenceOptions, + errors: { 'conditions.1.value': 'invalid' }, + }, + }).body; +} + +describe('ConditionBuilder', () => { + it('offers every catalog field of the event, and only its operators', () => { + const body = html([{ field: 'branch', operator: 'eq', value: 'main' }]); + + for (const field of definition.fields) { + expect(body).toContain(`value="${field.key}"`); + } + expect(body).toContain('name="conditions.0.field"'); + // operators of `branch` only + expect(body).toContain('value="contains"'); + expect(body).not.toContain('value="gt"'); + }); + + it('renders the input that matches each field type', () => { + const body = html([ + { field: 'branch', operator: 'eq', value: 'main' }, + { field: 'count', operator: 'gt', value: '0' }, + { field: 'when', operator: 'gt', value: '2026-01-01T00:00:00.000Z' }, + { field: 'flag', operator: 'is_true', value: '' }, + { field: 'tool', operator: 'in', value: ['trivy'] }, + { field: 'serviceId', operator: 'eq', value: 'svc-2' }, + ]); + const rows = body.split('data-testid="condition-row"').slice(1); + + expect(rows[0]).toMatch(/type="text"[^>]*name="conditions\.0\.value"/); + expect(rows[1]).toMatch(/type="number"/); + expect(rows[2]).toMatch(/type="date"/); + expect(rows[2]).toContain('value="2026-01-01"'); + // booleans take no value + expect(rows[3]).toContain('data-input="none"'); + expect(rows[3]).not.toContain('name="conditions.3.value"'); + // enum + `in`: multiple choice with the catalog options + expect(rows[4]).toMatch(/type="checkbox"[^>]*name="conditions\.4\.value"[^>]*value="trivy"/); + expect(rows[4]).toContain('value="grype"'); + expect(rows[4]).toContain('name="conditions.4.multiple" value="true"'); + // reference + `eq`: single choice among the entities of the scope + expect(rows[5]).toMatch(/type="radio"[^>]*name="conditions\.5\.value"[^>]*value="svc-2"/); + expect(rows[5]).toContain('api-gateway'); + }); + + it('links server errors to their input', () => { + const body = html([ + { field: 'branch', operator: 'eq', value: 'main' }, + { field: 'count', operator: 'gt', value: 'x' }, + ]); + expect(body).toContain('id="condition-1-value-error"'); + expect(body).toMatch(/aria-describedby="condition-1-value-error"/); + }); + + it('shows a new catalog field without touching the component', () => { + const extended: CatalogEntry = { + ...definition, + fields: [ + ...definition.fields, + { + key: 'summary.secrets', + label: 'test.fields.secrets', + type: 'number', + operators: ['gte'], + }, + ], + }; + const body = render(ConditionBuilder, { + props: { + definition: extended, + conditions: [{ field: 'summary.secrets', operator: 'gte', value: '1' }], + match: 'any', + referenceOptions, + }, + }).body; + + expect(body).toContain('value="summary.secrets"'); + expect(body).toContain('value="gte"'); + expect(body).toMatch(/type="number"[^>]*name="conditions\.0\.value"/); + }); +}); diff --git a/src/lib/components/alerts/OptionPicker.svelte b/src/lib/components/alerts/OptionPicker.svelte new file mode 100644 index 00000000..2f6ac7d7 --- /dev/null +++ b/src/lib/components/alerts/OptionPicker.svelte @@ -0,0 +1,88 @@ + + +
+ {label} + {#if options.length > SEARCH_THRESHOLD} + + {/if} + {#if options.length === 0} +

{$_('alerts.editor.noOptions')}

+ {:else} +
+ {#each options as option (option.id)} + + {/each} +
+ {/if} +
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index eb91ab2b..3f1d5e15 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -56,7 +56,8 @@ "database": "Database", "auditLog": "Audit Log", "registration": "Registration", - "events": "Events" + "events": "Events", + "alerts": "Alerts" } }, "footer": { @@ -1304,6 +1305,126 @@ "body": "The personal API key “{name}” ({prefix}…) was created on your account. If it wasn’t you, revoke it from your profile." } } + }, + "operators": { + "eq": "is", + "neq": "is not", + "in": "is one of", + "not_in": "is none of", + "contains": "contains", + "starts_with": "starts with", + "gt": "greater than", + "gte": "greater than or equal to", + "lt": "less than", + "lte": "less than or equal to", + "is_true": "is yes", + "is_false": "is no", + "exists": "has a value" + }, + "summary": { + "and": "and", + "or": "or", + "always": "Always (no conditions)", + "noRecipients": "No recipients" + }, + "errors": { + "required": "This field is required.", + "too_long": "It is too long.", + "invalid": "The value is not valid.", + "unknown_event": "That event does not exist.", + "not_alertable": "That event does not support alerts.", + "scope_mismatch": "This event can only be watched from the organization.", + "forbidden": "You are not allowed to view this event, so you cannot create alerts on it.", + "unknown_field": "This field does not exist for the chosen event.", + "invalid_operator": "Operator not allowed for this field.", + "unknown_option": "Pick one of the options.", + "unknown_reference": "Pick an item from this scope.", + "too_many": "There are too many items.", + "unknown_user": "Some user does not belong to this scope.", + "unknown_role": "Some role does not belong to this scope.", + "invalid_channel": "Channel not available." + }, + "channels": { + "mail": "Email", + "in_app": "In-app notification", + "slack": "Slack", + "soon": "Coming soon" + }, + "list": { + "title": "Alerts", + "descriptionOrganization": "Get an email when an event happens in the organization or in any of its projects.", + "descriptionProject": "Get an email when an event happens in this project.", + "create": "Create alert", + "emptyTitle": "No alerts yet", + "example1": "Tell the security team when an analysis has critical vulnerabilities", + "example2": "Tell me when someone deletes a production secret", + "example3": "Tell me when a project API key is created", + "name": "Name", + "event": "Event", + "conditions": "Filters", + "recipients": "Recipients", + "status": "Status", + "actions": "Actions", + "enabled": "Active", + "disabled": "Inactive", + "toggle": "Turn “{name}” on or off", + "edit": "Edit", + "delete": "Delete", + "confirmDelete": "Delete this alert? This cannot be undone.", + "throttle": "At most one email every {minutes} min", + "inheritedTitle": "Organization alerts", + "inheritedDescription": "These alerts are defined in the organization and also fire for this project’s events. They can only be changed from the organization settings." + }, + "editor": { + "newTitle": "New alert", + "editTitle": "Edit alert", + "subtitle": "Pick an event, filter on its fields and choose who gets the email.", + "back": "Back to alerts", + "stepEvent": "Event", + "stepConditions": "Conditions", + "stepRecipients": "Recipients and delivery", + "stepSave": "Test and save", + "name": "Name", + "description": "Description (optional)", + "enabled": "Alert active", + "event": "Event", + "chooseEvent": "Pick an event…", + "eventHelp": "Only events you can view are listed.", + "applyEvent": "Use this event", + "chooseEventFirst": "Pick an event first to see its fields.", + "droppedConditions": "{count} conditions that do not exist in the new event were removed.", + "matchLabel": "Match", + "matchAll": "all conditions (AND)", + "matchAny": "any of them (OR)", + "noConditions": "No conditions: the alert fires on every event of this type.", + "field": "Field", + "operator": "Operator", + "value": "Value", + "addCondition": "Add condition", + "removeCondition": "Remove condition {index}", + "search": "Search…", + "searchIn": "Search in {label}", + "noOptions": "No items available.", + "roles": "Roles", + "users": "Users", + "recipientsNotice": "Only recipients allowed to view this event will get the email.", + "channels": "Channel", + "throttle": "Send at most one email every (minutes)", + "throttleHelp": "0 = no limit. Skipped events are summed up in the next email.", + "sampleProject": "Project of the example event", + "sampleProjectAny": "The one the conditions name", + "test": "Test alert", + "create": "Create alert", + "saveChanges": "Save changes", + "fixErrors": "Check the highlighted fields." + }, + "test": { + "matched": "The example event matches the conditions.", + "notMatched": "The example event does not match the conditions.", + "recipients": "It would be sent to: {names}", + "noRecipients": "It would not be sent to anyone.", + "denied": "{count} recipients would not get it because they cannot view this event.", + "nothingSent": "This is a test: no email was sent." } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index fbab6bbc..2add992c 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -56,7 +56,8 @@ "database": "Base de datos", "auditLog": "Registro de auditoría", "registration": "Registro", - "events": "Eventos" + "events": "Eventos", + "alerts": "Alertas" } }, "footer": { @@ -1304,6 +1305,126 @@ "body": "Se ha creado la API key personal «{name}» ({prefix}…) en tu cuenta. Si no has sido tú, revócala desde tu perfil." } } + }, + "operators": { + "eq": "es", + "neq": "no es", + "in": "es uno de", + "not_in": "no es ninguno de", + "contains": "contiene", + "starts_with": "empieza por", + "gt": "mayor que", + "gte": "mayor o igual que", + "lt": "menor que", + "lte": "menor o igual que", + "is_true": "es sí", + "is_false": "es no", + "exists": "tiene valor" + }, + "summary": { + "and": "y", + "or": "o", + "always": "Siempre (sin condiciones)", + "noRecipients": "Sin destinatarios" + }, + "errors": { + "required": "Este campo es obligatorio.", + "too_long": "Es demasiado largo.", + "invalid": "El valor no es válido.", + "unknown_event": "Ese evento no existe.", + "not_alertable": "Ese evento no admite alertas.", + "scope_mismatch": "Este evento solo se puede vigilar desde la organización.", + "forbidden": "No tienes permiso para ver este evento, así que no puedes crear alertas sobre él.", + "unknown_field": "Este campo no existe para el evento elegido.", + "invalid_operator": "Operador no permitido para este campo.", + "unknown_option": "Elige una de las opciones.", + "unknown_reference": "Elige un elemento de este ámbito.", + "too_many": "Hay demasiados elementos.", + "unknown_user": "Algún usuario no pertenece a este ámbito.", + "unknown_role": "Algún rol no pertenece a este ámbito.", + "invalid_channel": "Canal no disponible." + }, + "channels": { + "mail": "Email", + "in_app": "Notificación en la app", + "slack": "Slack", + "soon": "Próximamente" + }, + "list": { + "title": "Alertas", + "descriptionOrganization": "Recibe un email cuando ocurra un evento en la organización o en cualquiera de sus proyectos.", + "descriptionProject": "Recibe un email cuando ocurra un evento en este proyecto.", + "create": "Crear alerta", + "emptyTitle": "Todavía no hay alertas", + "example1": "Avisar al equipo de seguridad si un análisis tiene vulnerabilidades críticas", + "example2": "Avisar cuando alguien borre un secreto de producción", + "example3": "Avisar cuando se cree una API key del proyecto", + "name": "Nombre", + "event": "Evento", + "conditions": "Filtros", + "recipients": "Destinatarios", + "status": "Estado", + "actions": "Acciones", + "enabled": "Activa", + "disabled": "Inactiva", + "toggle": "Activar o desactivar «{name}»", + "edit": "Editar", + "delete": "Borrar", + "confirmDelete": "¿Borrar esta alerta? No se puede deshacer.", + "throttle": "Máx. un email cada {minutes} min", + "inheritedTitle": "Alertas de la organización", + "inheritedDescription": "Estas alertas se definen en la organización y también se disparan con los eventos de este proyecto. Solo se pueden cambiar desde los ajustes de la organización." + }, + "editor": { + "newTitle": "Nueva alerta", + "editTitle": "Editar alerta", + "subtitle": "Elige un evento, filtra por sus campos y decide quién recibe el email.", + "back": "Volver a las alertas", + "stepEvent": "Evento", + "stepConditions": "Condiciones", + "stepRecipients": "Destinatarios y envío", + "stepSave": "Probar y guardar", + "name": "Nombre", + "description": "Descripción (opcional)", + "enabled": "Alerta activa", + "event": "Evento", + "chooseEvent": "Elige un evento…", + "eventHelp": "Solo aparecen los eventos que puedes ver.", + "applyEvent": "Usar este evento", + "chooseEventFirst": "Elige primero un evento para ver sus campos.", + "droppedConditions": "Se han quitado {count} condiciones que no existen en el nuevo evento.", + "matchLabel": "Coincidir con", + "matchAll": "todas las condiciones (Y)", + "matchAny": "cualquiera de ellas (O)", + "noConditions": "Sin condiciones: la alerta salta con cada evento de este tipo.", + "field": "Campo", + "operator": "Operador", + "value": "Valor", + "addCondition": "Añadir condición", + "removeCondition": "Quitar la condición {index}", + "search": "Buscar…", + "searchIn": "Buscar en {label}", + "noOptions": "No hay elementos disponibles.", + "roles": "Roles", + "users": "Usuarios", + "recipientsNotice": "Solo recibirán el email los destinatarios con permiso para ver este evento.", + "channels": "Canal", + "throttle": "No enviar más de un email cada (minutos)", + "throttleHelp": "0 = sin límite. Los eventos que se salten se resumen en el siguiente email.", + "sampleProject": "Proyecto del evento de ejemplo", + "sampleProjectAny": "El que indiquen las condiciones", + "test": "Probar alerta", + "create": "Crear alerta", + "saveChanges": "Guardar cambios", + "fixErrors": "Revisa los campos marcados." + }, + "test": { + "matched": "El evento de ejemplo cumple las condiciones.", + "notMatched": "El evento de ejemplo no cumple las condiciones.", + "recipients": "Se enviaría a: {names}", + "noRecipients": "No se enviaría a nadie.", + "denied": "{count} destinatarios no lo recibirían porque no pueden ver este evento.", + "nothingSent": "Es una prueba: no se ha enviado ningún email." } } } diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts index 54aa5ae2..a39d9951 100644 --- a/src/lib/server/alerts/operations.ts +++ b/src/lib/server/alerts/operations.ts @@ -17,8 +17,11 @@ import { type AlertLocation, type AlertRow, } from '#modules/alerts'; +import type { CatalogEntry } from '#lib/alerts/types'; import { actorFor, callerCan, canManageAlerts, contextOf, type AlertLocals } from './access'; +export type { CatalogEntry }; + /** Outcome of an alert operation, mapped to JSON by the API and to `fail()` by form actions. */ export type AlertResult = | { ok: true; status: number; data: T } @@ -35,11 +38,6 @@ function failure(error: unknown): AlertResult { throw error; } -/** Alertable event definitions as plain data (no `derive` functions). */ -export type CatalogEntry = Omit & { - fields: Array & { derived?: boolean }>; -}; - function serializable(definition: EventDefinition, location: AlertLocation): CatalogEntry { return { ...definition, diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts new file mode 100644 index 00000000..441f71fc --- /dev/null +++ b/src/lib/server/alerts/page.ts @@ -0,0 +1,385 @@ +import { error, fail, redirect } from '@sveltejs/kit'; +import { alertDirectory, alertService, type AlertLocation, type AlertRow } from '#modules/alerts'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { + getEventDefinition, + isEventType, + listAlertFields, + type EventDefinition, + type FieldReference, +} from '#lib/events/catalog'; +import type { + AlertDraft, + AlertEditorData, + AlertListData, + AlertOption, + DraftCondition, +} from '#lib/alerts/types'; +import { canManageAlerts, type AlertLocals } from './access'; +import { + createAlert, + deleteAlert, + listAlerts, + listCatalog, + testDraftAlert, + updateAlert, + type CatalogEntry, +} from './operations'; + +/** Where the pages of a location live and how they link back. */ +export type AlertPageContext = { + location: AlertLocation; + /** `/org//settings/alerts` or `/org//projects//settings/alerts` */ + basePath: string; +}; + +async function permissions(locals: AlertLocals, location: AlertLocation) { + const [canRead, canCreate, canUpdate, canDelete] = await Promise.all([ + canManageAlerts(locals, location, 'read'), + canManageAlerts(locals, location, 'create'), + canManageAlerts(locals, location, 'update'), + canManageAlerts(locals, location, 'delete'), + ]); + return { canRead, canCreate, canUpdate, canDelete }; +} + +/** Options for every reference the catalog fields use, all inside the location. */ +async function referenceOptions( + catalog: CatalogEntry[], + location: AlertLocation, +): Promise> { + const references = new Set(); + for (const definition of catalog) { + for (const field of definition.fields) if (field.reference) references.add(field.reference); + } + const entries = await Promise.all( + [...references].map( + async (reference) => + [ + reference, + await alertDirectory.listReferences(reference, location).catch(() => []), + ] as const, + ), + ); + return Object.fromEntries( + entries.map(([reference, options]) => [ + reference, + options.map((option) => ({ id: option.id, label: option.label })), + ]), + ); +} + +async function recipientOptions(location: AlertLocation) { + const [members, roles] = await Promise.all([ + alertDirectory.listMembers(location).catch(() => []), + alertDirectory.listRoles(location).catch(() => []), + ]); + return { + users: members + .filter((member) => !member.disabled) + .map((member) => ({ id: member.userId, label: member.username })) + .sort((a, b) => a.label.localeCompare(b.label)), + roles: roles.map((role) => ({ id: role.id, label: role.name })), + }; +} + +export async function loadAlertList( + locals: AlertLocals, + context: AlertPageContext, +): Promise { + const { location } = context; + const allowed = await permissions(locals, location); + if (!allowed.canRead) throw error(403, 'Forbidden'); + + const listed = await listAlerts(locals, location); + if (!listed.ok) throw error(listed.status, listed.error); + + // the organization catalog knows every event the inherited alerts may watch + const catalog = await listCatalog(locals, location); + const inheritedCatalog = + location.scope === 'project' + ? await listCatalog(locals, { ...location, scope: 'organization', projectId: null }) + : []; + const organizationLocation: AlertLocation = { + ...location, + scope: 'organization', + projectId: null, + }; + const [references, own, organizationRecipients] = await Promise.all([ + referenceOptions([...catalog, ...inheritedCatalog], organizationLocation), + recipientOptions(location), + location.scope === 'project' ? recipientOptions(organizationLocation) : null, + ]); + // names for the recipients of the location's alerts and of the inherited organization ones + const merge = (a: AlertOption[], b: AlertOption[] = []) => [ + ...a, + ...b.filter((option) => !a.some((existing) => existing.id === option.id)), + ]; + const recipients = { + users: merge(own.users, organizationRecipients?.users), + roles: merge(own.roles, organizationRecipients?.roles), + }; + + return { + basePath: context.basePath, + scope: location.scope, + alerts: listed.data.alerts, + inherited: listed.data.inherited, + catalog: [ + ...catalog, + ...inheritedCatalog.filter((entry) => !catalog.some((c) => c.type === entry.type)), + ], + referenceOptions: references, + users: recipients.users, + roles: recipients.roles, + canCreate: allowed.canCreate, + canUpdate: allowed.canUpdate, + canDelete: allowed.canDelete, + }; +} + +function emptyDraft(eventType: string | null): AlertDraft { + return { + name: '', + description: '', + enabled: true, + eventType: eventType ?? '', + match: 'all', + conditions: [], + recipients: { userIds: [], roleIds: [] }, + throttleMinutes: 0, + }; +} + +function toDraft(alert: AlertRow): AlertDraft { + return { + name: alert.name, + description: alert.description ?? '', + enabled: alert.enabled, + eventType: alert.eventType, + match: alert.match, + conditions: alert.conditions.map((condition) => ({ + field: condition.field, + operator: condition.operator, + value: condition.value === undefined ? '' : condition.value, + })), + recipients: { ...alert.recipients }, + throttleMinutes: alert.throttleMinutes, + }; +} + +export async function loadAlertEditor( + locals: AlertLocals, + context: AlertPageContext, + options: { alertId?: string; eventType?: string | null }, +): Promise { + const { location } = context; + const allowed = await permissions(locals, location); + if (!allowed.canRead) throw error(403, 'Forbidden'); + + let alert: AlertRow | null = null; + if (options.alertId) { + alert = (await alertService.get(options.alertId).catch(() => null))?.toJson() ?? null; + const sameLocation = + alert && + alert.organizationId === location.organizationId && + alert.scope === location.scope && + (location.scope === 'organization' || alert.projectId === location.projectId); + if (!alert || !sameLocation) throw error(404, 'Alert not found'); + } else if (!allowed.canCreate) { + throw error(403, 'Forbidden'); + } + + const catalog = await listCatalog(locals, location); + const [references, recipients] = await Promise.all([ + referenceOptions(catalog, location), + recipientOptions(location), + ]); + + const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null); + if (!alert && options.eventType && !catalog.some((entry) => entry.type === options.eventType)) { + draft.eventType = ''; + } + + return { + basePath: context.basePath, + scope: location.scope, + alertId: alert?.id ?? null, + draft, + catalog, + referenceOptions: references, + users: recipients.users, + roles: recipients.roles, + canSave: alert ? allowed.canUpdate : allowed.canCreate, + canDelete: Boolean(alert) && allowed.canDelete, + }; +} + +/** `conditions..` names → condition list; rows without a field are dropped. */ +export function parseAlertForm(form: FormData): AlertDraft { + const indices = new Set(); + for (const key of form.keys()) { + const match = key.match(/^conditions\.(\d+)\.field$/); + if (match) indices.add(Number(match[1])); + } + + const conditions = [...indices] + .sort((a, b) => a - b) + .map((index) => { + const values = form + .getAll(`conditions.${index}.value`) + .map(String) + .filter((value) => value !== ''); + const multiple = form.get(`conditions.${index}.multiple`) === 'true'; + return { + field: String(form.get(`conditions.${index}.field`) ?? ''), + // validated by the service; the draft only echoes it back + operator: String( + form.get(`conditions.${index}.operator`) ?? '', + ) as DraftCondition['operator'], + value: multiple ? values : (values[0] ?? ''), + }; + }) + .filter((condition) => condition.field); + + return { + name: String(form.get('name') ?? ''), + description: String(form.get('description') ?? ''), + enabled: form.get('enabled') === 'on' || form.get('enabled') === 'true', + eventType: String(form.get('eventType') ?? ''), + match: form.get('match') === 'any' ? 'any' : 'all', + conditions, + recipients: { + userIds: form.getAll('userIds').map(String), + roleIds: form.getAll('roleIds').map(String), + }, + throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0, + }; +} + +/** The draft as service input: empty optional values become `undefined`. */ +function toInput(draft: AlertDraft) { + return { + ...draft, + conditions: draft.conditions.map((condition) => ({ + ...condition, + value: condition.value === '' ? undefined : condition.value, + })), + }; +} + +/** Form actions shared by the organization and project alert pages. */ +export function alertActions( + resolve: (event: { + params: Record; + locals: AlertLocals; + }) => Promise, +) { + return { + /** + * Without JavaScript the editor posts here to add/remove a condition row or to switch the + * event: nothing is saved, the page comes back with the updated draft. + */ + async draft(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const intent = String(form.get('intent') ?? ''); + if (intent === 'add_condition' && isEventType(draft.eventType)) { + const definition = getEventDefinition(draft.eventType) as EventDefinition; + const [first] = listAlertFields(definition, context.location.scope); + if (first) { + draft.conditions.push({ + field: first.key as string, + operator: first.operators[0], + value: '', + }); + } + } else if (intent.startsWith('remove_condition:')) { + const index = Number(intent.split(':')[1]); + draft.conditions.splice(index, 1); + } else if (intent === 'change_event') { + draft.conditions = []; + } + return { draft }; + }, + + async save(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const alertId = String(form.get('alertId') ?? '') || null; + const result = alertId + ? await updateAlert(event.locals, alertId, toInput(draft)) + : await createAlert(event.locals, context.location, toInput(draft)); + if (!result.ok) { + return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} }); + } + throw redirect(303, `${context.basePath}?saved=${result.data.id}`); + }, + + async test(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const sampleProjectId = String(form.get('sampleProjectId') ?? '') || undefined; + const result = await testDraftAlert(event.locals, context.location, { + ...toInput(draft), + sampleProjectId, + }); + if (!result.ok) { + return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} }); + } + return { draft, test: result.data }; + }, + + async toggle(event: { request: Request; params: Record; locals: AlertLocals }) { + await resolve(event); + const form = await event.request.formData(); + const alertId = String(form.get('alertId') ?? ''); + const result = await updateAlert(event.locals, alertId, { + enabled: form.get('enabled') === 'true', + }); + if (!result.ok) return fail(result.status, { error: result.error, alertId }); + return { toggled: alertId }; + }, + + async delete(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const alertId = String(form.get('alertId') ?? ''); + const result = await deleteAlert(event.locals, alertId); + if (!result.ok) return fail(result.status, { error: result.error, alertId }); + if (form.get('redirect') === 'list') throw redirect(303, context.basePath); + return { deleted: alertId }; + }, + }; +} + +/** `/org//settings/alerts/…` */ +export async function organizationAlertContext(event: { + params: Record; +}): Promise { + const organization = await organizationService.tryFindBySlug(event.params.org); + if (!organization) throw error(404, 'Organization not found'); + return { + location: { scope: 'organization', organizationId: organization.id, projectId: null }, + basePath: `/org/${organization.slug}/settings/alerts`, + }; +} + +/** `/org//projects//settings/alerts/…` */ +export async function projectAlertContext(event: { + params: Record; +}): Promise { + const project = await projectService.getProjectBySlug(event.params.slug).catch(() => null); + const organization = project?.organization; + if (!project || !organization || organization.slug !== event.params.org) { + throw error(404, 'Project not found'); + } + return { + location: { scope: 'project', organizationId: organization.id, projectId: project.id }, + basePath: `/org/${organization.slug}/projects/${project.slug}/settings/alerts`, + }; +} diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 2284ea09..f3f1e751 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -61,11 +61,13 @@ canReadOrgServerKeys={data.canReadOrgServerKeys} canReadOrgAudit={data.canReadOrgAudit} canReadOrgEvents={data.canReadOrgEvents} + canReadOrganizationAlerts={data.canReadOrganizationAlerts} canReadProjectInfo={data.canReadProjectInfo} canReadProjectUsers={data.canReadProjectUsers} canReadProjectRoles={data.canReadProjectRoles} canReadProjectServerKeys={data.canReadProjectServerKeys} canReadProjectAudit={data.canReadProjectAudit} + canReadProjectAlerts={data.canReadProjectAlerts} canReadProjectVault={data.canReadProjectVault} canReadProjectCodeReport={data.canReadProjectCodeReport} canReadProjectStateIac={data.canReadProjectStateIac} diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.server.ts new file mode 100644 index 00000000..453f6cc3 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.server.ts @@ -0,0 +1,7 @@ +import { alertActions, loadAlertList, projectAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertList(event.locals, await projectAlertContext(event)); +} + +export const actions = alertActions(projectAlertContext); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.svelte new file mode 100644 index 00000000..4fec48a2 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.svelte @@ -0,0 +1,13 @@ + + + + {$_('alerts.list.title')} - GitOps + + + diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.server.ts new file mode 100644 index 00000000..0e23a41f --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, projectAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await projectAlertContext(event), { + alertId: event.params.id, + }); +} + +export const actions = alertActions(projectAlertContext); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.server.ts new file mode 100644 index 00000000..40172dd7 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, projectAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await projectAlertContext(event), { + eventType: event.url.searchParams.get('event'), + }); +} + +export const actions = alertActions(projectAlertContext); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/settings/alerts/+page.server.ts b/src/routes/org/[org]/settings/alerts/+page.server.ts new file mode 100644 index 00000000..2416d6d0 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/+page.server.ts @@ -0,0 +1,7 @@ +import { alertActions, loadAlertList, organizationAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertList(event.locals, await organizationAlertContext(event)); +} + +export const actions = alertActions(organizationAlertContext); diff --git a/src/routes/org/[org]/settings/alerts/+page.svelte b/src/routes/org/[org]/settings/alerts/+page.svelte new file mode 100644 index 00000000..4fec48a2 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/+page.svelte @@ -0,0 +1,13 @@ + + + + {$_('alerts.list.title')} - GitOps + + + diff --git a/src/routes/org/[org]/settings/alerts/[id]/+page.server.ts b/src/routes/org/[org]/settings/alerts/[id]/+page.server.ts new file mode 100644 index 00000000..a15bbeb3 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/[id]/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, organizationAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await organizationAlertContext(event), { + alertId: event.params.id, + }); +} + +export const actions = alertActions(organizationAlertContext); diff --git a/src/routes/org/[org]/settings/alerts/[id]/+page.svelte b/src/routes/org/[org]/settings/alerts/[id]/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/[id]/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/settings/alerts/new/+page.server.ts b/src/routes/org/[org]/settings/alerts/new/+page.server.ts new file mode 100644 index 00000000..19e0d9ad --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/new/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, organizationAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await organizationAlertContext(event), { + eventType: event.url.searchParams.get('event'), + }); +} + +export const actions = alertActions(organizationAlertContext); diff --git a/src/routes/org/[org]/settings/alerts/new/+page.svelte b/src/routes/org/[org]/settings/alerts/new/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/new/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/vitest.config.ts b/vitest.config.ts index 1b12b932..ff235cf4 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,7 +1,10 @@ import path from 'path'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; import { defineConfig } from 'vitest/config'; export default defineConfig({ + // compiles `.svelte` files so components can be rendered in tests (`svelte/server`) + plugins: [svelte({ configFile: false })], resolve: { alias: { $lib: path.resolve(import.meta.dirname, 'src/lib'),