Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,14 +183,22 @@ 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/<org>/settings/alerts` and `/org/<org>/projects/<slug>/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.<code>`.

Making an event alertable:

1. Declare the payload in `DomainEventMap` and publish it with `publishAfterWrite` and the right
scope.
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.<type>.*` 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

Expand Down
44 changes: 44 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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": "<project id>",
"name": "Critical vulnerabilities in api-gateway",
"eventType": "code_report.analysis.completed",
"match": "all",
"conditions": [
{ "field": "serviceId", "operator": "eq", "value": "<service id>" },
{ "field": "summary.critical", "operator": "gt", "value": 0 }
],
"recipients": { "roleIds": ["<project-admin role id>"] },
"throttleMinutes": 30
}'
```

`GET /api/events/catalog?scope=project&projectId=<id>` 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
Expand Down
192 changes: 192 additions & 0 deletions e2e/specs/alerts.spec.ts
Original file line number Diff line number Diff line change
@@ -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 <seeded service> · 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');
});
});
1 change: 1 addition & 0 deletions e2e/specs/organization-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
1 change: 1 addition & 0 deletions e2e/specs/project-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => {
Expand Down
Loading
Loading