diff --git a/CLAUDE.md b/CLAUDE.md index cb1948e2..df58c825 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -100,8 +100,8 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data `*.data.ts`) for configuration constants: role permissions, default project settings, risk weights, and tool policy mappings. -Current modules include `auth`, `config`, `organization`, `projects`, `storage`, and -`code-report`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from +Current modules include `auth`, `config`, `organization`, `projects`, `storage`, +`code-report`, `vault`, `audit`, and `alerts`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from their `index.ts`, not internal layers. GitDB is the single source of truth. Users, roles, API keys, organizations, projects, storage @@ -154,6 +154,44 @@ in `docs/adr/0001-event-bus-and-alerts.md`. it from the role editor). Retention: `GITOPS_EVENTS_EXPIRATION` (default `7d`). It is per process and cleared on restart. +## Alerts + +`$modules/alerts` turns domain events into emails. + +- `AlertEntity` (GitDB `alerts`): an alert watches one `eventType` from an organization + (`scope: 'organization'`, covers every project of it) or a project. `conditions` + (`{ field, operator, value }`) use the catalog fields, combined with `match: 'all' | 'any'`; an + empty list always matches. Organization alerts on project events also get a `projectId` field + (`listAlertFields`, value taken from the event scope). +- `AlertService` validates every write against the catalog and the location and throws + `AlertValidationError` with field-level codes (`conditions.0.operator: 'invalid_operator'`): + alertable event compatible with the scope, operators of the field, typed values, references and + recipients (users, roles) inside the location, and **anti-escalation** (the author must hold the + event's `readPermission`). +- `AlertEngine` subscribes to `'*'` once per process (`registerAlertEngine()` in `hooks.server.ts`, + HMR-safe). Per event: fixed system notifications first (`system-notifications.data.ts`: access + granted/updated/revoked to the affected user, new personal API keys to their owner, never to the + actor, invitations skipped), then the enabled alerts of that type (cached 60 s, invalidated by + the service) whose location covers the event and whose conditions match. A per-alert in-memory + throttle (`throttleMinutes`) suppresses repeats and the next email reports how many were skipped. +- Recipients = selected users ∪ members with the selected roles, minus disabled users and users + without an email, then **filtered with `cancanService.can(userId, readPermission, event scope)`** + (most-specific-wins applies). One email per recipient (`AlertMailNotifier`, texts under + `alerts.email.*`, base locale); a failed email only affects that recipient. +- HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by + the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`, + `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. + +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..*` translations in `es.json` and `en.json`. +4. Nothing else: the catalog endpoint, the validation and the engine pick it up. + ## Authorization Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts` @@ -193,8 +231,8 @@ return { roles, canCreate }; The root layout (`+layout.server.ts`) calculates granular read permissions for each settings section and passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions: -- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`) -- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read` +- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`) +- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read` This ensures the UI only displays navigation items for sections the user has permission to view. @@ -203,11 +241,11 @@ Permissions always include their scope as a prefix (e.g., `organization:projects `project:vault:secrets:all`) and are stored verbatim—there is no scope-stripping transformation: - **GitOps Admin** (`cluster-admin`) — grants vault, openreport, stateiac full access - **GitOps User** (`cluster-user`) — no inherent permissions; base role for system-level access -- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events +- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts - **Organization Developer** — read/create/update projects only -- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history -- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access -- **Project Viewer** — read-only: project metadata, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history +- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history +- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access; reads alerts +- **Project Viewer** — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history Module resources have granular sub-permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. These allow fine-grained access control within each module. diff --git a/src/hooks.server.ts b/src/hooks.server.ts index d7e9f2f9..05e54309 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -3,6 +3,7 @@ import { sequence } from '@sveltejs/kit/hooks'; import { apiKeysService, authService, cancanService, ensureAuthReady } from '#modules/auth'; import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; +import { registerAlertEngine } from '#modules/alerts'; import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstrap'; import { startGitDb } from '#lib/server/gitdb'; import { markServerFailed, markServerReady } from '#lib/server/server-ready'; @@ -15,6 +16,8 @@ const startupLog = createLogger('startup'); const serverReady = (async () => { await startGitDb(); await ensureAuthReady(); + // once per process (HMR-safe): system notifications and alerts on every published event + registerAlertEngine(); await refreshBootstrapState(); markServerReady(); })(); diff --git a/src/lib/config/permissions.ts b/src/lib/config/permissions.ts index 1478064e..9c2bba54 100644 --- a/src/lib/config/permissions.ts +++ b/src/lib/config/permissions.ts @@ -64,6 +64,11 @@ const permissions = { resource: 'events', permissions: grantsFor('organization', 'events'), }, + // alerts of the organization (/org//settings/alerts), they cover all its projects + alerts: { + resource: 'alerts', + permissions: grantsFor('organization', 'alerts'), + }, }, }, project: { @@ -86,6 +91,11 @@ const permissions = { resource: 'audit', permissions: grantsFor('project', 'audit'), }, + // alerts of one project (/org//projects//settings/alerts) + alerts: { + resource: 'alerts', + permissions: grantsFor('project', 'alerts'), + }, modules: { resource: 'modules', sections: { diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 9851e26b..61cfbfc8 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -1,4 +1,13 @@ -import { bool, defineRelations, entity, integer, json, text, timestamp, uuid } from '@getgitops/gitdb'; +import { + bool, + defineRelations, + entity, + integer, + json, + text, + timestamp, + uuid, +} from '@getgitops/gitdb'; export const UserEntity = entity('users', { id: uuid().primaryKey(), @@ -268,6 +277,35 @@ export const VaultSettingsEntity = entity('vault_settings', { .$defaultFn(() => new Date().toISOString()), }); +// alert on one event type (#79): `projectId` is null for organization alerts, which cover every +// project of the organization; `conditions` filter on catalog fields (`#lib/events/catalog`) +export const AlertEntity = entity('alerts', { + id: uuid().primaryKey(), + name: text().notNull(), + description: text(), + enabled: bool().notNull().default(true), + scope: text().notNull(), + organizationId: uuid().notNull(), + projectId: uuid().$defaultFn(() => null), + eventType: text().notNull(), + match: text().notNull().default('all'), + conditions: json() + .notNull() + .$defaultFn(() => []), + recipients: json().notNull(), + channels: json() + .notNull() + .$defaultFn(() => ['mail']), + throttleMinutes: integer().notNull().default(0), + createdByUserId: uuid().notNull(), + createdAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), +}); + relations.for(ProjectEntity, ({ one, many }) => ({ roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }), organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), diff --git a/src/lib/events/catalog/alert-fields.ts b/src/lib/events/catalog/alert-fields.ts new file mode 100644 index 00000000..5acd1396 --- /dev/null +++ b/src/lib/events/catalog/alert-fields.ts @@ -0,0 +1,44 @@ +import type { EventType } from '../domain-events'; +import { OPERATORS } from './fields'; +import type { EventDefinition, EventDefinitionScope, EventFieldDefinition } from './types'; + +/** + * Field an organization alert uses to narrow a project event to some projects. Its value comes + * from the event scope (`scope.projectId`), not from the payload. + */ +export const PROJECT_SCOPE_FIELD = { + key: 'projectId', + label: 'events.scopeFields.projectId', + type: 'reference', + reference: 'project', + operators: OPERATORS.reference, + // never called: the evaluator reads `scope.projectId` for this field (see `isScopeField`) + derive: () => undefined, +} as const satisfies EventFieldDefinition; + +/** + * Fields an alert of `alertScope` can filter `definition` by: the catalog fields plus, for an + * organization alert on a project event, the project the event happened in. + */ +export function listAlertFields( + definition: EventDefinition, + alertScope: EventDefinitionScope, +): readonly EventFieldDefinition[] { + const fields = definition.fields as readonly EventFieldDefinition[]; + const ownsProjectId = fields.some((field) => field.key === PROJECT_SCOPE_FIELD.key); + if (alertScope === 'organization' && definition.scope === 'project' && !ownsProjectId) { + return [...fields, PROJECT_SCOPE_FIELD as EventFieldDefinition]; + } + return fields; +} + +/** Whether `field` reads its value from the event scope rather than the payload. */ +export function isScopeField(field: EventFieldDefinition): boolean { + return field === (PROJECT_SCOPE_FIELD as EventFieldDefinition); +} + +export type AlertableEventInput = { + type: EventType; + payload: unknown; + scope?: { organizationId?: string | null; projectId?: string | null }; +}; diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts index d22ce290..4ee2d846 100644 --- a/src/lib/events/catalog/index.ts +++ b/src/lib/events/catalog/index.ts @@ -19,6 +19,12 @@ export { VAULT_SECRET_CHANGED_FIELDS } from './vault.events'; export { PROJECT_CHANGED_FIELDS } from './projects.events'; export { ORGANIZATION_CHANGED_FIELDS } from './organization.events'; export { ACCESS_SCOPES } from './access.events'; +export { + PROJECT_SCOPE_FIELD, + isScopeField, + listAlertFields, + type AlertableEventInput, +} from './alert-fields'; /** * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 1905380f..eb91ab2b 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1271,6 +1271,39 @@ "name": "Name" } } + }, + "scopeFields": { + "projectId": "Project" + } + }, + "alerts": { + "email": { + "alertSubject": "[GitOps] {alert}: {event}", + "alertIntro": "The alert “{alert}” was triggered by this event.", + "event": "Event", + "occurredAt": "Date", + "suppressed": "{count} more matching events were skipped during the previous window.", + "footer": "You receive this email because you are a recipient of this alert and can view this event.", + "systemFooter": "GitOps sends this notice automatically and it cannot be turned off.", + "system": { + "projectTarget": "the project {project} ({organization})", + "access_granted": { + "subject": "You now have access to {target}", + "body": "You have been given access to {target} with the role {role}." + }, + "access_updated": { + "subject": "Your role in {target} has changed", + "body": "Your role in {target} is now {role}." + }, + "access_revoked": { + "subject": "You no longer have access to {target}", + "body": "You no longer have access to {target}." + }, + "api_key_created": { + "subject": "A personal API key was created", + "body": "The personal API key “{name}” ({prefix}…) was created on your account. If it wasn’t you, revoke it from your profile." + } + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index f866f4e2..fbab6bbc 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1271,6 +1271,39 @@ "name": "Nombre" } } + }, + "scopeFields": { + "projectId": "Proyecto" + } + }, + "alerts": { + "email": { + "alertSubject": "[GitOps] {alert}: {event}", + "alertIntro": "La alerta «{alert}» se ha disparado con este evento.", + "event": "Evento", + "occurredAt": "Fecha", + "suppressed": "Además, se omitieron {count} eventos que coincidían con la alerta durante la ventana anterior.", + "footer": "Recibes este email porque eres destinatario de esta alerta y tienes permiso para ver este evento.", + "systemFooter": "Este aviso lo envía GitOps automáticamente y no se puede desactivar.", + "system": { + "projectTarget": "el proyecto {project} ({organization})", + "access_granted": { + "subject": "Tienes acceso a {target}", + "body": "Te han dado acceso a {target} con el rol {role}." + }, + "access_updated": { + "subject": "Tu rol en {target} ha cambiado", + "body": "Tu rol en {target} ha cambiado a {role}." + }, + "access_revoked": { + "subject": "Ya no tienes acceso a {target}", + "body": "Ya no tienes acceso a {target}." + }, + "api_key_created": { + "subject": "Se ha creado una API key personal", + "body": "Se ha creado la API key personal «{name}» ({prefix}…) en tu cuenta. Si no has sido tú, revócala desde tu perfil." + } + } } } } diff --git a/src/lib/server/alerts/access.ts b/src/lib/server/alerts/access.ts new file mode 100644 index 00000000..77e967b7 --- /dev/null +++ b/src/lib/server/alerts/access.ts @@ -0,0 +1,98 @@ +import { cancanService } from '#modules/auth'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import type { AlertActor, AlertLocation } from '#modules/alerts'; +import type { PermissionGrant } from '#lib/permissions'; + +export type AlertAction = 'read' | 'create' | 'update' | 'delete'; + +/** What a request carries about its caller (`event.locals`). */ +export type AlertLocals = { + user?: { id: string; role?: unknown } | null; + apiKey?: { + id: string; + projectId: string | null; + userId: string | null; + role: unknown; + } | null; +}; + +export type PermissionContext = + | { scope: 'organization'; organizationId: string } + | { scope: 'project'; projectId: string; organizationId?: string }; + +export function contextOf(location: AlertLocation): PermissionContext { + return location.scope === 'project' && location.projectId + ? { scope: 'project', projectId: location.projectId, organizationId: location.organizationId } + : { scope: 'organization', organizationId: location.organizationId }; +} + +/** + * Checks `permission` for the caller: a session user through the role cascade, an API key + * through `canApiKey` (a project key never leaves its project, so organization contexts fail). + */ +export async function callerCan( + locals: AlertLocals, + permission: PermissionGrant, + context: PermissionContext, +): Promise { + if (locals.apiKey) { + return cancanService.canApiKey(locals.apiKey as never, permission, context); + } + return cancanService.canSessionUser(locals.user as never, permission, context); +} + +export function canManageAlerts( + locals: AlertLocals, + location: AlertLocation, + action: AlertAction, +): Promise { + return callerCan(locals, `${location.scope}:alerts:${action}`, contextOf(location)); +} + +/** The caller as an alert author, for the anti-escalation check. */ +export function actorFor(locals: AlertLocals): AlertActor | null { + const userId = locals.apiKey ? (locals.apiKey.userId ?? locals.apiKey.id) : locals.user?.id; + if (!userId) return null; + return { + userId, + canRead: (permission, context) => callerCan(locals, permission, context), + }; +} + +export type LocationLookup = + { ok: true; location: AlertLocation } | { ok: false; status: 400 | 404; error: string }; + +/** + * Location from request ids: a `projectId` makes it a project location (its organization comes + * from the project and must match `organizationId` when both are given). + */ +export async function resolveLocation(ids: { + organizationId?: string | null; + projectId?: string | null; +}): Promise { + const projectId = ids.projectId?.trim() || null; + const organizationId = ids.organizationId?.trim() || null; + + if (projectId) { + const project = await projectService.getProject(projectId).catch(() => null); + const projectOrganizationId = project?.organization?.id ?? null; + if (!project || !projectOrganizationId) { + return { ok: false, status: 404, error: 'Project not found' }; + } + if (organizationId && organizationId !== projectOrganizationId) { + return { ok: false, status: 404, error: 'Project not found' }; + } + return { + ok: true, + location: { scope: 'project', organizationId: projectOrganizationId, projectId: project.id }, + }; + } + + if (!organizationId) { + return { ok: false, status: 400, error: 'organizationId or projectId is required' }; + } + const organization = await organizationService.getOrganization(organizationId).catch(() => null); + if (!organization) return { ok: false, status: 404, error: 'Organization not found' }; + return { ok: true, location: { scope: 'organization', organizationId, projectId: null } }; +} diff --git a/src/lib/server/alerts/http.ts b/src/lib/server/alerts/http.ts new file mode 100644 index 00000000..2dc8a621 --- /dev/null +++ b/src/lib/server/alerts/http.ts @@ -0,0 +1,18 @@ +import { json } from '@sveltejs/kit'; +import type { AlertResult } from './operations'; + +/** JSON response for an alert operation: `{ data }` on success, `{ error, errors? }` otherwise. */ +export function toResponse(result: AlertResult): Response { + if (result.ok) return json(result.data, { status: result.status }); + return json( + result.errors ? { error: result.error, errors: result.errors } : { error: result.error }, + { status: result.status }, + ); +} + +export async function readJson(request: Request): Promise> { + const body = await request.json().catch(() => null); + return body && typeof body === 'object' && !Array.isArray(body) + ? (body as Record) + : {}; +} diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts new file mode 100644 index 00000000..54aa5ae2 --- /dev/null +++ b/src/lib/server/alerts/operations.ts @@ -0,0 +1,262 @@ +import { + getEventDefinition, + isEventType, + listAlertFields, + listAlertableEvents, + type EventDefinition, +} from '#lib/events/catalog'; +import { + AlertDomain, + AlertNotFoundError, + AlertValidationError, + alertDirectory, + alertEngine, + alertService, + buildSampleEvent, + type AlertInput, + type AlertLocation, + type AlertRow, +} from '#modules/alerts'; +import { actorFor, callerCan, canManageAlerts, contextOf, type AlertLocals } from './access'; + +/** 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 } + | { ok: false; status: number; error: string; errors?: Record }; + +const forbidden = { ok: false as const, status: 403, error: 'Forbidden' }; +const notFound = { ok: false as const, status: 404, error: 'Alert not found' }; + +function failure(error: unknown): AlertResult { + if (error instanceof AlertValidationError) { + return { ok: false, status: 400, error: 'Invalid alert', errors: error.errors }; + } + if (error instanceof AlertNotFoundError) return notFound; + 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, + fields: listAlertFields(definition, location.scope).map((field) => { + const { derive, ...rest } = field; + return derive ? { ...rest, derived: true } : rest; + }), + }; +} + +/** + * Events an alert in `location` can watch and the caller is allowed to read: project events in a + * project, every alertable event in an organization (project events then cover all projects). + */ +export async function listCatalog( + locals: AlertLocals, + location: AlertLocation, +): Promise { + const context = contextOf(location); + const candidates = listAlertableEvents(location.scope === 'project' ? { scope: 'project' } : {}); + const visible: CatalogEntry[] = []; + for (const definition of candidates) { + const allowed = + (await callerCan(locals, definition.readPermission, context)) || + (location.scope === 'organization' && + definition.scope === 'project' && + (await callerCan(locals, 'organization:projects:read', context))); + if (allowed) visible.push(serializable(definition, location)); + } + return visible; +} + +async function loadAuthorized( + locals: AlertLocals, + id: string, + action: 'read' | 'update' | 'delete', +): Promise> { + const alert = await alertService.get(id).catch(() => null); + if (!alert) return notFound; + // an alert the caller can't read is indistinguishable from a missing one + if (!(await canManageAlerts(locals, alert.location, 'read'))) return notFound; + if (action !== 'read' && !(await canManageAlerts(locals, alert.location, action))) { + return forbidden; + } + return { ok: true, status: 200, data: alert }; +} + +export async function listAlerts( + locals: AlertLocals, + location: AlertLocation, +): Promise> { + if (!(await canManageAlerts(locals, location, 'read'))) return forbidden; + const alerts = await alertService.list(location); + const inherited = + location.scope === 'project' && location.projectId + ? await alertService.listInherited(location.organizationId, location.projectId) + : []; + return { + ok: true, + status: 200, + data: { + alerts: alerts.map((alert) => alert.toJson()), + inherited: inherited.map((alert) => alert.toJson()), + }, + }; +} + +export async function getAlert(locals: AlertLocals, id: string): Promise> { + const loaded = await loadAuthorized(locals, id, 'read'); + return loaded.ok ? { ...loaded, data: loaded.data.toJson() } : loaded; +} + +export async function createAlert( + locals: AlertLocals, + location: AlertLocation, + input: AlertInput, +): Promise> { + if (!(await canManageAlerts(locals, location, 'create'))) return forbidden; + const actor = actorFor(locals); + if (!actor) return forbidden; + try { + const alert = await alertService.create(location, input, actor); + return { ok: true, status: 201, data: alert.toJson() }; + } catch (error) { + return failure(error); + } +} + +export async function updateAlert( + locals: AlertLocals, + id: string, + input: AlertInput, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + const actor = actorFor(locals); + if (!actor) return forbidden; + try { + const alert = await alertService.update(id, input, actor); + return { ok: true, status: 200, data: alert.toJson() }; + } catch (error) { + return failure(error); + } +} + +export async function deleteAlert( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'delete'); + if (!loaded.ok) return loaded; + try { + await alertService.delete(id); + return { ok: true, status: 200, data: { id } }; + } catch (error) { + return failure(error); + } +} + +/** `payload` overrides the invented sample; `sampleProjectId` picks the project of a project event + * for an organization alert. */ +export type AlertTestInput = { payload?: unknown; sampleProjectId?: unknown }; + +export type AlertTestResult = { + matched: boolean; + recipients: Array<{ userId: string; username: string }>; + /** Selected users left out because they can't read the event. */ + deniedCount: number; + event: { type: string; payload: Record; projectId: string | null }; +}; + +/** + * Evaluates an alert against an example event and tells who would receive it. Nothing is sent and + * the throttle is not touched. + */ +async function dryRun( + alert: Pick< + AlertDomain, + 'eventType' | 'scope' | 'conditions' | 'match' | 'recipients' | 'location' | 'appliesTo' + >, + input: AlertTestInput, +): Promise> { + if (!isEventType(alert.eventType)) return { ok: false, status: 400, error: 'Unknown event type' }; + const definition = getEventDefinition(alert.eventType) as EventDefinition; + const location = alert.location; + + const requestedProjectId = + typeof input.sampleProjectId === 'string' ? input.sampleProjectId : null; + const payloadOverride = + input.payload && typeof input.payload === 'object' && !Array.isArray(input.payload) + ? (input.payload as Record) + : undefined; + const sample = buildSampleEvent(definition, alert, { + payload: payloadOverride, + projectId: requestedProjectId, + }); + + let projectId: string | null = null; + if (location.scope === 'project') projectId = location.projectId; + else if (definition.scope === 'project' && sample.projectId) { + const projects = await alertDirectory.listReferences('project', location); + if (!projects.some((project) => project.id === sample.projectId)) { + return { + ok: false, + status: 400, + error: 'Project not found', + errors: { sampleProjectId: 'unknown_reference' }, + }; + } + projectId = sample.projectId; + } + + const result = await alertEngine.dryRun(alert, { + type: alert.eventType, + payload: sample.payload as never, + scope: { organizationId: location.organizationId, projectId }, + }); + + return { + ok: true, + status: 200, + data: { + matched: result.matched, + recipients: result.recipients.map(({ userId, username }) => ({ userId, username })), + deniedCount: result.denied.length, + event: { type: alert.eventType, payload: sample.payload, projectId }, + }, + }; +} + +export async function testAlert( + locals: AlertLocals, + id: string, + input: AlertTestInput, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + return dryRun(loaded.data, input); +} + +/** "Test alert" before saving: validates the draft and dry-runs it. */ +export async function testDraftAlert( + locals: AlertLocals, + location: AlertLocation, + input: AlertInput & AlertTestInput, +): Promise> { + const canWrite = + (await canManageAlerts(locals, location, 'create')) || + (await canManageAlerts(locals, location, 'update')); + if (!canWrite) return forbidden; + const actor = actorFor(locals); + if (!actor) return forbidden; + try { + const fields = await alertService.validate(location, input, actor); + const draft = new AlertDomain({ id: 'draft', ...location, ...fields }); + return dryRun(draft, input); + } catch (error) { + return failure(error); + } +} diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts new file mode 100644 index 00000000..bacd0a72 --- /dev/null +++ b/src/modules/alerts/application/alert-engine.test.ts @@ -0,0 +1,491 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import type { AnyDomainEvent } from '#lib/server/events'; +import { InProcessEventBus } from '#lib/server/events'; +import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events'; +import { CanCanService } from '../../auth/application/cancan.service'; +import { RoleDomain } from '../../auth/domain/role.domain'; +import { UserDomain } from '../../auth/domain/user.domain'; +import { UserAccessDomain } from '../../auth/domain/user-access.domain'; +import type { AlertRow } from '../domain/alert.domain'; +import { InMemoryAlertRepository } from '../infrastructure/repositories/in-memory-alert.repository'; +import { + AlertEngine, + type AlertEmail, + type AlertNotifierPort, + type SystemEmail, +} from './alert-engine'; +import { AlertThrottle } from './alert-throttle'; +import { RecipientResolver } from './recipient-resolver'; +import { FakeAlertDirectory } from './testing'; + +const ORG = 'org-1'; +const TIMESTAMP = '2024-01-01T00:00:00.000Z'; + +function role(id: string, scope: 'organization' | 'project', permissions: string[]) { + return new RoleDomain({ + id, + slug: id, + name: id, + scope, + permissions, + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + }); +} + +const roles = { + orgViewer: role('org-viewer', 'organization', [ + 'organization:projects:read', + 'organization:users:read', + ]), + orgOutsider: role('org-nothing', 'organization', []), + projectReporter: role('project-reporter', 'project', ['project:codereport:reports:read']), + projectGuest: role('project-guest', 'project', ['project:project:read']), +}; + +function access( + id: string, + userId: string, + entry: { role: RoleDomain; organizationId?: string; projectId?: string }, +) { + return new UserAccessDomain({ + id, + userId, + roleId: entry.role.id, + role: entry.role, + scope: entry.projectId ? 'project' : 'organization', + organizationId: entry.organizationId ?? null, + projectId: entry.projectId ?? null, + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + }); +} + +function completed( + summary: Partial = {}, + scope = { organizationId: ORG, projectId: 'p1' }, + id = 'event-1', +): AnyDomainEvent { + return { + id, + type: 'code_report.analysis.completed', + occurredAt: TIMESTAMP, + actor: { kind: 'api_key', apiKeyId: 'key-1', projectId: 'p1' }, + scope, + payload: { + analysisId: 'analysis-1', + serviceId: 'svc-gateway', + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: null, version: null }, + summary: { + critical: 1, + high: 0, + medium: 0, + low: 0, + unknown: 0, + total: 1, + secrets: 0, + ...summary, + }, + policies: { + status: 'compliant', + totalViolations: 0, + blockingFailures: 0, + failedPolicyIds: [], + }, + }, + }; +} + +function alertRow(overrides: Partial = {}): AlertRow { + return { + id: 'alert-1', + name: 'Críticas', + description: null, + enabled: true, + scope: 'project', + organizationId: ORG, + projectId: 'p1', + eventType: 'code_report.analysis.completed', + match: 'all', + conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }], + recipients: { userIds: [], roleIds: ['project-reporter'] }, + channels: ['mail'], + throttleMinutes: 0, + createdByUserId: 'author', + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + ...overrides, + }; +} + +class RecordingNotifier implements AlertNotifierPort { + alerts: AlertEmail[] = []; + system: SystemEmail[] = []; + failFor = new Set(); + + async sendAlert(email: AlertEmail) { + if (this.failFor.has(email.recipient.userId)) throw new Error('SMTP down'); + this.alerts.push(email); + } + + async sendSystemNotification(email: SystemEmail) { + this.system.push(email); + } +} + +describe('AlertEngine', () => { + let repository: InMemoryAlertRepository; + let directory: FakeAlertDirectory; + let notifier: RecordingNotifier; + let clock: number; + let engine: AlertEngine; + let logger: { + info: ReturnType; + warn: ReturnType; + error: ReturnType; + debug: ReturnType; + }; + + const sentTo = () => notifier.alerts.map((email) => email.recipient.userId).sort(); + + beforeEach(() => { + repository = new InMemoryAlertRepository(); + directory = new FakeAlertDirectory(); + notifier = new RecordingNotifier(); + clock = Date.parse('2026-11-20T10:00:00.000Z'); + logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + + const member = ( + userId: string, + roleIds: string[], + extra: { projectId?: string; disabled?: boolean; email?: string | null } = {}, + ) => ({ + organizationId: ORG, + projectId: extra.projectId ?? null, + userId, + username: userId, + email: extra.email === undefined ? `${userId}@example.com` : extra.email, + disabled: extra.disabled ?? false, + roleIds, + }); + + directory.members = [ + member('ana', ['project-reporter'], { projectId: 'p1' }), + member('bea', ['project-reporter'], { projectId: 'p1' }), + member('carl', ['project-reporter'], { projectId: 'p1', disabled: true }), + member('nomail', ['project-reporter'], { projectId: 'p1', email: null }), + member('dora', ['org-viewer', 'project-guest']), + member('eli', ['org-viewer']), + member('fran', ['org-nothing']), + member('pia', ['project-reporter'], { projectId: 'p2' }), + ]; + + const accessByUser: Record = { + ana: [access('a1', 'ana', { role: roles.projectReporter, projectId: 'p1' })], + bea: [access('a2', 'bea', { role: roles.projectReporter, projectId: 'p1' })], + carl: [access('a3', 'carl', { role: roles.projectReporter, projectId: 'p1' })], + nomail: [access('a4', 'nomail', { role: roles.projectReporter, projectId: 'p1' })], + // org role that cascades into projects, but an explicit project role in p1 wins + dora: [ + access('a5', 'dora', { role: roles.orgViewer, organizationId: ORG }), + access('a6', 'dora', { role: roles.projectGuest, projectId: 'p1' }), + ], + eli: [access('a7', 'eli', { role: roles.orgViewer, organizationId: ORG })], + fran: [access('a8', 'fran', { role: roles.orgOutsider, organizationId: ORG })], + pia: [access('a9', 'pia', { role: roles.projectReporter, projectId: 'p2' })], + }; + const cancan = new CanCanService( + { + findById: async (id: string) => + new UserDomain({ + id, + username: id, + email: null, + password: 'x', + role: null, + createdAt: TIMESTAMP, + updatedAt: TIMESTAMP, + }), + }, + { findByUserId: async (userId: string) => accessByUser[userId] ?? [] }, + { getProject: async (id: string) => ({ id, organization: { id: ORG } }) }, + ); + + engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, (userId, permission, context) => + cancan.can(userId, permission, context), + ), + notifier, + throttle: new AlertThrottle(() => clock), + logger: logger as never, + now: () => clock, + }); + }); + + it('sends one email per recipient that can read the event', async () => { + repository.rows = [alertRow()]; + await engine.handle(completed()); + + expect(sentTo()).toEqual(['ana', 'bea']); + expect(notifier.alerts[0]).toMatchObject({ alert: { id: 'alert-1' }, suppressed: 0 }); + expect(logger.info).toHaveBeenCalledWith( + expect.objectContaining({ alertId: 'alert-1', recipients: 2, sent: 2 }), + '[alerts] alert fired', + ); + }); + + it('skips disabled users and users without an email', async () => { + repository.rows = [ + alertRow({ recipients: { userIds: ['carl', 'nomail', 'ana'], roleIds: [] } }), + ]; + await engine.handle(completed()); + expect(sentTo()).toEqual(['ana']); + }); + + it('does not email recipients without the read permission, most-specific-wins included', async () => { + repository.rows = [ + alertRow({ recipients: { userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [] } }), + ]; + await engine.handle(completed()); + + // eli reads p1 through the organization cascade; dora's explicit p1 role has no report access; + // fran's organization role can't read projects at all + expect(sentTo()).toEqual(['ana', 'eli']); + expect(logger.debug).toHaveBeenCalledWith( + expect.objectContaining({ deniedUserIds: expect.arrayContaining(['dora', 'fran']) }), + expect.any(String), + ); + }); + + it('only fires alerts whose scope covers the event', async () => { + repository.rows = [ + alertRow({ id: 'p1-alert' }), + alertRow({ id: 'p2-alert', projectId: 'p2', recipients: { userIds: ['pia'], roleIds: [] } }), + alertRow({ + id: 'org-alert', + scope: 'organization', + projectId: null, + recipients: { userIds: ['eli'], roleIds: [] }, + }), + alertRow({ + id: 'other-org', + organizationId: 'org-2', + scope: 'organization', + projectId: null, + }), + alertRow({ id: 'disabled', enabled: false }), + ]; + await engine.handle(completed()); + + expect(notifier.alerts.map((email) => email.alert.id).sort()).toEqual([ + 'org-alert', + 'p1-alert', + 'p1-alert', + ]); + }); + + it('ignores events that do not match the conditions', async () => { + repository.rows = [alertRow()]; + await engine.handle(completed({ critical: 0 })); + expect(notifier.alerts).toHaveLength(0); + }); + + it('throttles an alert and reports the suppressed events in the next email', async () => { + repository.rows = [ + alertRow({ throttleMinutes: 30, recipients: { userIds: ['ana'], roleIds: [] } }), + ]; + + await engine.handle(completed({}, undefined, 'e1')); + clock += 10 * 60_000; + await engine.handle(completed({}, undefined, 'e2')); + await engine.handle(completed({}, undefined, 'e3')); + expect(notifier.alerts).toHaveLength(1); + + clock += 25 * 60_000; + await engine.handle(completed({}, undefined, 'e4')); + expect(notifier.alerts.map((email) => [email.event.id, email.suppressed])).toEqual([ + ['e1', 0], + ['e4', 2], + ]); + }); + + it('keeps sending to the other recipients when one email fails', async () => { + repository.rows = [alertRow()]; + notifier.failFor.add('ana'); + await engine.handle(completed()); + + expect(sentTo()).toEqual(['bea']); + expect(logger.warn).toHaveBeenCalledWith( + expect.objectContaining({ userId: 'ana' }), + '[alerts] email to recipient failed', + ); + }); + + it('caches alerts per event type until invalidated or expired', async () => { + const list = vi.spyOn(repository, 'listEnabledByEventType'); + repository.rows = [alertRow()]; + + await engine.handle(completed()); + await engine.handle(completed()); + expect(list).toHaveBeenCalledTimes(1); + + engine.invalidate(); + await engine.handle(completed()); + expect(list).toHaveBeenCalledTimes(2); + + clock += 61_000; + await engine.handle(completed()); + expect(list).toHaveBeenCalledTimes(3); + }); + + it('does nothing while email delivery is disabled', async () => { + let enabled = false; + engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, async () => true), + notifier, + logger: logger as never, + deliveryEnabled: () => enabled, + }); + const list = vi.spyOn(repository, 'listEnabledByEventType'); + repository.rows = [alertRow()]; + + await engine.handle(completed()); + expect(list).not.toHaveBeenCalled(); + expect(notifier.alerts).toHaveLength(0); + + enabled = true; + await engine.handle(completed()); + expect(notifier.alerts.length).toBeGreaterThan(0); + }); + + it('runs from the bus without failing the publisher', async () => { + const bus = new InProcessEventBus({ logger: { error: vi.fn() }, resolveActor: () => null }); + repository.rows = [alertRow()]; + engine.attach(bus); + + bus.publish('code_report.analysis.completed', completed().payload as never, { + scope: { organizationId: ORG, projectId: 'p1' }, + }); + await bus.drain(); + + expect(sentTo()).toEqual(['ana', 'bea']); + }); + + describe('dry run', () => { + it('tells who would receive the alert without sending or throttling', async () => { + const alert = new (await import('../domain/alert.domain')).AlertDomain( + alertRow({ throttleMinutes: 60 }), + ); + const result = await engine.dryRun(alert, completed()); + + expect(result.matched).toBe(true); + expect(result.recipients.map((recipient) => recipient.userId).sort()).toEqual(['ana', 'bea']); + expect(notifier.alerts).toHaveLength(0); + + repository.rows = [alertRow({ throttleMinutes: 60 })]; + await engine.handle(completed()); + expect(notifier.alerts).toHaveLength(2); + }); + }); + + describe('system notifications', () => { + function accessEvent( + type: 'access.granted' | 'access.updated' | 'access.revoked', + overrides: Record = {}, + actor: AnyDomainEvent['actor'] = { kind: 'user', userId: 'admin' }, + ): AnyDomainEvent { + return { + id: 'event-access', + type, + occurredAt: TIMESTAMP, + actor, + scope: { organizationId: ORG, projectId: 'p1' }, + payload: { + accessId: 'a1', + userId: 'ana', + roleId: 'project-reporter', + scope: 'project', + status: 'active', + previousRoleId: 'project-guest', + previousStatus: 'active', + ...overrides, + }, + } as AnyDomainEvent; + } + + beforeEach(() => { + directory.users = [ + { userId: 'ana', username: 'ana', email: 'ana@example.com', disabled: false }, + { userId: 'carl', username: 'carl', email: 'carl@example.com', disabled: true }, + ]; + directory.names = { [ORG]: 'Kettu', p1: 'Web', 'project-reporter': 'Reporter' }; + }); + + it.each(['access.granted', 'access.updated', 'access.revoked'] as const)( + 'tells the affected user about %s', + async (type) => { + await engine.handle(accessEvent(type)); + expect(notifier.system).toHaveLength(1); + expect(notifier.system[0]).toMatchObject({ + recipient: { userId: 'ana', email: 'ana@example.com' }, + kind: type.replace('.', '_'), + names: { organization: 'Kettu', project: 'Web', role: 'Reporter' }, + }); + }, + ); + + it('does not notify the user who made the change', async () => { + await engine.handle(accessEvent('access.granted', {}, { kind: 'user', userId: 'ana' })); + expect(notifier.system).toHaveLength(0); + }); + + it('skips invitations, unchanged roles and disabled users', async () => { + await engine.handle(accessEvent('access.granted', { status: 'invited' })); + await engine.handle(accessEvent('access.updated', { previousRoleId: 'project-reporter' })); + await engine.handle(accessEvent('access.revoked', { userId: 'carl' })); + expect(notifier.system).toHaveLength(0); + }); + + it('warns the owner of a new personal API key, not of project keys', async () => { + const apiKeyEvent = (projectId: string | null): AnyDomainEvent => ({ + id: 'event-key', + type: 'api_key.created', + occurredAt: TIMESTAMP, + actor: { kind: 'system' }, + scope: { organizationId: null, projectId }, + payload: { apiKeyId: 'k1', name: 'laptop', keyPrefix: 'gvs_abc', projectId, userId: 'ana' }, + }); + + await engine.handle(apiKeyEvent('p1')); + expect(notifier.system).toHaveLength(0); + + await engine.handle(apiKeyEvent(null)); + expect(notifier.system).toMatchObject([ + { kind: 'api_key_created', recipient: { userId: 'ana' } }, + ]); + }); + + it('runs before the alerts of the same event', async () => { + const order: string[] = []; + notifier.sendSystemNotification = async () => void order.push('system'); + notifier.sendAlert = async () => void order.push('alert'); + repository.rows = [ + alertRow({ + eventType: 'access.granted', + scope: 'organization', + projectId: null, + conditions: [], + recipients: { userIds: ['eli'], roleIds: [] }, + }), + ]; + + await engine.handle(accessEvent('access.granted')); + expect(order).toEqual(['system', 'alert']); + }); + }); +}); diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts new file mode 100644 index 00000000..13cce3ed --- /dev/null +++ b/src/modules/alerts/application/alert-engine.ts @@ -0,0 +1,258 @@ +import type { Logger } from 'pino'; +import { getEventDefinition, isEventType, type EventDefinition } from '#lib/events/catalog'; +import type { AnyDomainEvent, EventBus, Unsubscribe } from '#lib/server/events'; +import type { AlertDomain } from '../domain/alert.domain'; +import { matches } from '../domain/condition-evaluator'; +import { + getSystemNotification, + type SystemNotificationKind, +} from '../domain/system-notifications.data'; +import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository'; +import { AlertThrottle } from './alert-throttle'; +import { RecipientResolver, type Recipient } from './recipient-resolver'; +import { eventContext, type AlertDirectory, type ResolvedNames } from './types'; + +export type AlertEmail = { + recipient: Recipient; + alert: Pick; + event: AnyDomainEvent; + definition: EventDefinition; + /** Matching events skipped by the throttle since the previous email. */ + suppressed: number; + /** Display names of the ids the event references (services, projects, users…). */ + names: ReadonlyMap; +}; + +export type SystemEmail = { + recipient: Recipient; + kind: SystemNotificationKind; + event: AnyDomainEvent; + names: ResolvedNames; +}; + +export interface AlertNotifierPort { + sendAlert(email: AlertEmail): Promise; + sendSystemNotification(email: SystemEmail): Promise; +} + +export type AlertEngineOptions = { + repository: Pick; + directory: AlertDirectory; + recipients: RecipientResolver; + notifier: AlertNotifierPort; + throttle?: AlertThrottle; + logger: Pick; + /** How long alerts of one event type stay cached; GitDB sync changes show up after this. */ + cacheTtlMs?: number; + now?: () => number; + /** `false` when no email can be sent (SMTP not configured): events are then ignored. */ + deliveryEnabled?: () => boolean; +}; + +export type AlertDryRun = { + matched: boolean; + recipients: Recipient[]; + /** Selected users that would not get it because they can't read the event. */ + denied: string[]; +}; + +const DEFAULT_CACHE_TTL_MS = 60_000; + +/** + * Bus subscriber (`'*'`) that sends the fixed system notifications and evaluates configured + * alerts. Nothing here throws back to the bus: a failure is logged and, for one recipient, never + * stops the others. + */ +export class AlertEngine { + private readonly cache = new Map(); + private readonly throttle: AlertThrottle; + private readonly cacheTtlMs: number; + private readonly now: () => number; + + constructor(private readonly options: AlertEngineOptions) { + this.throttle = options.throttle ?? new AlertThrottle(); + this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS; + this.now = options.now ?? (() => Date.now()); + } + + attach(bus: Pick): Unsubscribe { + return bus.subscribe('*', (event) => this.handle(event)); + } + + /** Drops cached alerts; called by the alert service after every write. */ + invalidate(): void { + this.cache.clear(); + } + + async handle(event: AnyDomainEvent): Promise { + if (!isEventType(event.type)) return; + if (this.options.deliveryEnabled && !this.options.deliveryEnabled()) return; + const definition = getEventDefinition(event.type) as EventDefinition; + + // system notifications first: they don't depend on anyone configuring an alert + await this.sendSystemNotification(event).catch((error) => + this.options.logger.error( + { err: error, eventType: event.type, eventId: event.id }, + '[alerts] system notification failed', + ), + ); + + if (!definition.alertable) return; + + const alerts = await this.alertsFor(event.type); + for (const alert of alerts) { + if (!alert.appliesTo(event.scope) || !matches(event, alert, definition)) continue; + await this.fire(alert, event, definition).catch((error) => + this.options.logger.error( + { err: error, alertId: alert.id, eventType: event.type, eventId: event.id }, + '[alerts] alert failed', + ), + ); + } + } + + /** + * Evaluates `alert` against `event` and tells who would get it, without sending anything or + * touching the throttle (`POST /api/alerts/[id]/test`). + */ + async dryRun( + alert: Pick & { + appliesTo: AlertDomain['appliesTo']; + }, + event: Pick, + ): Promise { + const definition = getEventDefinition(event.type) as EventDefinition; + const matched = alert.appliesTo(event.scope) && matches(event, alert, definition); + const context = eventContext(event.scope); + if (!context) return { matched, recipients: [], denied: [] }; + const resolved = await this.options.recipients.resolve( + alert.location, + alert.recipients, + definition.readPermission, + context, + ); + return { matched, ...resolved }; + } + + private async alertsFor(eventType: string): Promise { + const cached = this.cache.get(eventType); + if (cached && cached.expiresAt > this.now()) return cached.alerts; + const alerts = await this.options.repository.listEnabledByEventType(eventType); + this.cache.set(eventType, { alerts, expiresAt: this.now() + this.cacheTtlMs }); + return alerts; + } + + private async fire( + alert: AlertDomain, + event: AnyDomainEvent, + definition: EventDefinition, + ): Promise { + const log = this.options.logger; + const context = eventContext(event.scope); + if (!context) return; + + const decision = this.throttle.acquire(alert.id, alert.throttleMinutes); + if (!decision.send) { + log.info( + { alertId: alert.id, eventType: event.type, eventId: event.id, suppressed: true }, + '[alerts] alert suppressed by throttle', + ); + return; + } + + const { recipients, denied } = await this.options.recipients.resolve( + alert.location, + alert.recipients, + definition.readPermission, + context, + ); + if (denied.length > 0) { + log.debug( + { alertId: alert.id, eventId: event.id, deniedUserIds: denied }, + '[alerts] recipients without read permission skipped', + ); + } + + const names = await this.referenceNames(alert, definition).catch( + () => new Map(), + ); + + let sent = 0; + // one email per recipient: addresses are never shared, and a failure only affects one person + for (const recipient of recipients) { + try { + await this.options.notifier.sendAlert({ + recipient, + alert, + event, + definition, + suppressed: decision.suppressed, + names, + }); + sent += 1; + } catch (error) { + log.warn( + { err: error, alertId: alert.id, eventId: event.id, userId: recipient.userId }, + '[alerts] email to recipient failed', + ); + } + } + + log.info( + { + alertId: alert.id, + eventType: event.type, + eventId: event.id, + recipients: recipients.length, + sent, + previouslySuppressed: decision.suppressed, + }, + '[alerts] alert fired', + ); + } + + private async referenceNames( + alert: AlertDomain, + definition: EventDefinition, + ): Promise> { + const references = new Set( + definition.fields.map((field) => field.reference).filter((reference) => !!reference), + ); + const names = new Map(); + for (const reference of references) { + const options = await this.options.directory.listReferences(reference!, alert.location); + for (const option of options) names.set(option.id, option.label); + } + return names; + } + + private async sendSystemNotification(event: AnyDomainEvent): Promise { + const rule = getSystemNotification(event.type); + if (!rule) return; + const userId = (rule.recipient as (payload: unknown) => string | null)(event.payload); + if (!userId) return; + // the actor already knows what they just did + if (event.actor.kind === 'user' && event.actor.userId === userId) return; + + const user = await this.options.directory.findUser(userId); + if (!user || user.disabled || !user.email) return; + + const payload = event.payload as { roleId?: string | null }; + const names = await this.options.directory.resolveNames({ + organizationId: event.scope.organizationId, + projectId: event.scope.projectId, + roleId: payload.roleId ?? null, + }); + + await this.options.notifier.sendSystemNotification({ + recipient: { userId: user.userId, username: user.username, email: user.email }, + kind: rule.kind, + event, + names, + }); + this.options.logger.info( + { eventType: event.type, eventId: event.id, kind: rule.kind }, + '[alerts] system notification sent', + ); + } +} diff --git a/src/modules/alerts/application/alert-throttle.ts b/src/modules/alerts/application/alert-throttle.ts new file mode 100644 index 00000000..489d91d4 --- /dev/null +++ b/src/modules/alerts/application/alert-throttle.ts @@ -0,0 +1,44 @@ +export type ThrottleDecision = + | { + send: true; + /** Events suppressed in the previous window, to mention in this email. */ + suppressed: number; + } + | { send: false }; + +type Window = { endsAt: number; suppressed: number }; + +/** + * Per-alert anti-spam window, in memory (per process, cleared on restart). After an alert fires, + * it stays quiet for `throttleMinutes`: matching events in that window are only counted, and the + * next email after the window mentions how many were skipped. + */ +export class AlertThrottle { + private readonly windows = new Map(); + + constructor(private readonly now: () => number = () => Date.now()) {} + + acquire(alertId: string, throttleMinutes: number): ThrottleDecision { + const now = this.now(); + const current = this.windows.get(alertId); + + if (current && now < current.endsAt) { + current.suppressed += 1; + return { send: false }; + } + + const suppressed = current?.suppressed ?? 0; + if (throttleMinutes > 0) { + this.windows.set(alertId, { endsAt: now + throttleMinutes * 60_000, suppressed: 0 }); + } else { + this.windows.delete(alertId); + } + return { send: true, suppressed }; + } + + /** Forgets an alert's window (the alert was edited or deleted). */ + reset(alertId?: string): void { + if (alertId) this.windows.delete(alertId); + else this.windows.clear(); + } +} diff --git a/src/modules/alerts/application/alert.service.test.ts b/src/modules/alerts/application/alert.service.test.ts new file mode 100644 index 00000000..4c716667 --- /dev/null +++ b/src/modules/alerts/application/alert.service.test.ts @@ -0,0 +1,358 @@ +import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest'; +import { AlertValidationError, type AlertInput, type AlertLocation } from '../domain/alert.domain'; +import { InMemoryAlertRepository } from '../infrastructure/repositories/in-memory-alert.repository'; +import { AlertService } from './alert.service'; +import { FakeAlertDirectory, actor } from './testing'; + +const ORG = 'org-1'; +const orgLocation: AlertLocation = { scope: 'organization', organizationId: ORG, projectId: null }; +const projectLocation: AlertLocation = { scope: 'project', organizationId: ORG, projectId: 'p1' }; + +function guidedExample(overrides: AlertInput = {}): AlertInput { + return { + name: 'Críticas en api-gateway', + eventType: 'code_report.analysis.completed', + match: 'all', + conditions: [ + { field: 'serviceId', operator: 'eq', value: 'svc-gateway' }, + { field: 'summary.critical', operator: 'gt', value: '0' }, + ], + recipients: { userIds: [], roleIds: ['role-project-admin'] }, + throttleMinutes: 30, + ...overrides, + }; +} + +async function validationErrors(promise: Promise) { + const error = await promise.catch((caught) => caught); + expect(error).toBeInstanceOf(AlertValidationError); + return (error as AlertValidationError).errors; +} + +describe('AlertService', () => { + let repository: InMemoryAlertRepository; + let directory: FakeAlertDirectory; + let onChange: Mock<() => void>; + let service: AlertService; + + beforeEach(() => { + repository = new InMemoryAlertRepository(); + directory = new FakeAlertDirectory(); + directory.members = [ + { + organizationId: ORG, + projectId: 'p1', + userId: 'u1', + username: 'ana', + email: 'ana@x.io', + disabled: false, + roleIds: [], + }, + ]; + directory.roles = [ + { organizationId: ORG, projectId: 'p1', id: 'role-project-admin', name: 'Project Admin' }, + { organizationId: ORG, projectId: 'p2', id: 'role-other-project', name: 'Project Admin' }, + { organizationId: ORG, id: 'role-org-admin', name: 'Org Admin' }, + ]; + directory.references = [ + { + organizationId: ORG, + projectId: 'p1', + reference: 'code_report_service', + id: 'svc-gateway', + label: 'api-gateway', + }, + { + organizationId: ORG, + projectId: 'p2', + reference: 'code_report_service', + id: 'svc-other', + label: 'web', + }, + { organizationId: ORG, projectId: 'p1', reference: 'project', id: 'p1', label: 'Kettu' }, + { organizationId: ORG, projectId: 'p2', reference: 'project', id: 'p2', label: 'Other' }, + ]; + onChange = vi.fn(); + service = new AlertService(repository, directory, { + generateId: () => 'alert-1', + now: () => new Date('2026-11-20T10:00:00.000Z'), + onChange, + }); + }); + + it('creates the guided example with normalized values', async () => { + const alert = await service.create(projectLocation, guidedExample(), actor('u1')); + + expect(alert.toJson()).toMatchObject({ + id: 'alert-1', + scope: 'project', + organizationId: ORG, + projectId: 'p1', + enabled: true, + channels: ['mail'], + throttleMinutes: 30, + createdByUserId: 'u1', + conditions: [ + { field: 'serviceId', operator: 'eq', value: 'svc-gateway' }, + { field: 'summary.critical', operator: 'gt', value: 0 }, + ], + }); + expect(repository.rows).toHaveLength(1); + expect(onChange).toHaveBeenCalledTimes(1); + }); + + it('reports every invalid field at once', async () => { + const errors = await validationErrors( + service.create( + projectLocation, + { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['slack'] }, + actor(), + ), + ); + expect(errors).toEqual({ + name: 'required', + match: 'invalid', + eventType: 'required', + recipients: 'required', + throttleMinutes: 'invalid', + channels: 'invalid_channel', + }); + expect(repository.rows).toHaveLength(0); + expect(onChange).not.toHaveBeenCalled(); + }); + + describe('event type', () => { + it('rejects unknown and non-alertable events', async () => { + expect( + await validationErrors( + service.create(orgLocation, guidedExample({ eventType: 'nope' }), actor()), + ), + ).toEqual({ + eventType: 'unknown_event', + }); + }); + + it('rejects organization events on a project alert', async () => { + const errors = await validationErrors( + service.create( + projectLocation, + guidedExample({ eventType: 'organization.updated', conditions: [] }), + actor(), + ), + ); + expect(errors.eventType).toBe('scope_mismatch'); + }); + + it('accepts a project event on an organization alert', async () => { + await expect( + service.create( + orgLocation, + guidedExample({ recipients: { roleIds: ['role-org-admin'] } }), + actor(), + ), + ).resolves.toBeDefined(); + }); + + it('refuses an author who cannot read the event (anti-escalation)', async () => { + const errors = await validationErrors( + service.create( + projectLocation, + guidedExample(), + actor('u1', ['project:vault:secrets:read']), + ), + ); + expect(errors.eventType).toBe('forbidden'); + }); + + it('accepts organization:projects:read for project events of an organization alert', async () => { + await expect( + service.create( + orgLocation, + guidedExample({ recipients: { roleIds: ['role-org-admin'] } }), + actor('u1', ['organization:projects:read']), + ), + ).resolves.toBeDefined(); + }); + }); + + describe('conditions', () => { + async function conditionErrors(conditions: unknown, location = projectLocation) { + return validationErrors(service.create(location, guidedExample({ conditions }), actor())); + } + + it('rejects unknown fields', async () => { + expect( + await conditionErrors([{ field: 'summary.secrets', operator: 'gt', value: 0 }]), + ).toEqual({ + 'conditions.0.field': 'unknown_field', + }); + }); + + it('rejects operators the field does not allow', async () => { + expect( + await conditionErrors([{ field: 'summary.critical', operator: 'contains', value: '1' }]), + ).toEqual({ + 'conditions.0.operator': 'invalid_operator', + }); + }); + + it('rejects values of the wrong type', async () => { + expect( + await conditionErrors([ + { field: 'summary.critical', operator: 'gt', value: 'many' }, + { field: 'tool', operator: 'eq', value: 'unknown-scanner' }, + { field: 'gitInfo.branch', operator: 'eq', value: '' }, + { field: 'tool', operator: 'in', value: [] }, + ]), + ).toEqual({ + 'conditions.0.value': 'invalid', + 'conditions.1.value': 'unknown_option', + 'conditions.2.value': 'required', + 'conditions.3.value': 'required', + }); + }); + + it('drops the value of valueless operators', async () => { + const alert = await service.create( + projectLocation, + guidedExample({ + conditions: [{ field: 'hasVulnerabilities', operator: 'is_true', value: 'x' }], + }), + actor(), + ); + expect(alert.conditions).toEqual([{ field: 'hasVulnerabilities', operator: 'is_true' }]); + }); + + it('rejects a reference from another project', async () => { + expect( + await conditionErrors([{ field: 'serviceId', operator: 'eq', value: 'svc-other' }]), + ).toEqual({ + 'conditions.0.value': 'unknown_reference', + }); + }); + + it('accepts references of any project of the organization on an organization alert', async () => { + const alert = await service.create( + orgLocation, + guidedExample({ + conditions: [ + { field: 'serviceId', operator: 'in', value: ['svc-gateway', 'svc-other'] }, + { field: 'projectId', operator: 'eq', value: 'p2' }, + ], + recipients: { roleIds: ['role-org-admin'] }, + }), + actor(), + ); + expect(alert.conditions).toHaveLength(2); + }); + + it('only offers the project field to organization alerts', async () => { + expect(await conditionErrors([{ field: 'projectId', operator: 'eq', value: 'p1' }])).toEqual({ + 'conditions.0.field': 'unknown_field', + }); + }); + + it('limits the number of conditions', async () => { + const many = Array.from({ length: 21 }, () => ({ + field: 'summary.critical', + operator: 'gt', + value: 0, + })); + expect(await conditionErrors(many)).toEqual({ conditions: 'too_many' }); + }); + }); + + describe('recipients', () => { + it('rejects users and roles outside the location', async () => { + const errors = await validationErrors( + service.create( + projectLocation, + guidedExample({ recipients: { userIds: ['stranger'], roleIds: ['role-other-project'] } }), + actor(), + ), + ); + expect(errors).toEqual({ + 'recipients.userIds': 'unknown_user', + 'recipients.roleIds': 'unknown_role', + }); + }); + + it('accepts organization roles on a project alert', async () => { + await expect( + service.create( + projectLocation, + guidedExample({ recipients: { roleIds: ['role-org-admin'] } }), + actor(), + ), + ).resolves.toBeDefined(); + }); + }); + + describe('update and delete', () => { + it('merges a partial update and validates the result', async () => { + await service.create(projectLocation, guidedExample(), actor()); + + const updated = await service.update('alert-1', { enabled: false, name: 'Renamed' }, actor()); + expect(updated).toMatchObject({ enabled: false, name: 'Renamed', throttleMinutes: 30 }); + expect(repository.rows[0]).toMatchObject({ enabled: false, name: 'Renamed' }); + + const errors = await validationErrors( + service.update('alert-1', { throttleMinutes: 99999 }, actor()), + ); + expect(errors).toEqual({ throttleMinutes: 'invalid' }); + expect(onChange).toHaveBeenCalledTimes(2); + }); + + it('deletes alerts and fails on unknown ids', async () => { + await service.create(projectLocation, guidedExample(), actor()); + await service.delete('alert-1'); + expect(repository.rows).toHaveLength(0); + await expect(service.delete('alert-1')).rejects.toThrow(/not found/); + }); + }); + + describe('listing', () => { + it('separates organization alerts from project alerts and finds inherited ones', async () => { + let id = 0; + service = new AlertService(repository, directory, { generateId: () => `a${++id}` }); + const orgActor = actor(); + await service.create(projectLocation, guidedExample({ name: 'project' }), orgActor); + await service.create( + orgLocation, + guidedExample({ name: 'all projects', recipients: { roleIds: ['role-org-admin'] } }), + orgActor, + ); + await service.create( + orgLocation, + guidedExample({ + name: 'only p2', + conditions: [{ field: 'projectId', operator: 'eq', value: 'p2' }], + recipients: { roleIds: ['role-org-admin'] }, + }), + orgActor, + ); + await service.create( + orgLocation, + guidedExample({ + name: 'org event', + eventType: 'organization.updated', + conditions: [], + recipients: { roleIds: ['role-org-admin'] }, + }), + orgActor, + ); + + expect( + (await service.list({ organizationId: ORG, projectId: 'p1' })).map((a) => a.name), + ).toEqual(['project']); + expect( + (await service.list({ organizationId: ORG, projectId: null })).map((a) => a.name), + ).toEqual(['all projects', 'only p2', 'org event']); + expect((await service.listInherited(ORG, 'p1')).map((a) => a.name)).toEqual(['all projects']); + expect((await service.listInherited(ORG, 'p2')).map((a) => a.name)).toEqual([ + 'all projects', + 'only p2', + ]); + }); + }); +}); diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts new file mode 100644 index 00000000..00e5e973 --- /dev/null +++ b/src/modules/alerts/application/alert.service.ts @@ -0,0 +1,435 @@ +import { + getEventDefinition, + isEventType, + listAlertFields, + type EventDefinition, + type EventFieldDefinition, +} from '#lib/events/catalog'; +import type { EventType } from '#lib/events/domain-events'; +import { + ALERT_CHANNELS, + ALERT_MATCHES, + AlertDomain, + AlertNotFoundError, + AlertValidationError, + MAX_THROTTLE_MINUTES, + type AlertChannel, + type AlertCondition, + type AlertFields, + type AlertInput, + type AlertLocation, + type AlertMatch, + type AlertRecipients, + type AlertValidationErrors, +} from '../domain/alert.domain'; +import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository'; +import { + locationContext, + type AlertActor, + type AlertDirectory, + type ReferenceOption, +} from './types'; + +const MAX_NAME_LENGTH = 120; +const MAX_DESCRIPTION_LENGTH = 1000; +const MAX_CONDITIONS = 20; +const MAX_LIST_VALUES = 100; + +const VALUELESS_OPERATORS = new Set(['is_true', 'is_false', 'exists']); +const LIST_OPERATORS = new Set(['in', 'not_in']); + +export type AlertServiceOptions = { + now?: () => Date; + generateId?: () => string; + /** Called after every successful write, so the engine drops its cached alerts. */ + onChange?: () => void; +}; + +/** Ids the location's reference lists contain, loaded once per validation. */ +type ReferenceCache = Map>; + +/** + * CRUD of alerts. Every write is validated against the event catalog and the location: the event + * must be alertable from that scope, conditions must use the event's fields with valid operators + * and values, references and recipients must belong to the location, and the actor must be able + * to read the event themselves (anti-escalation). + */ +export class AlertService { + private readonly now: () => Date; + private readonly generateId: () => string; + private readonly onChange: () => void; + + constructor( + private readonly repository: AlertRepositoryPort, + private readonly directory: AlertDirectory, + options: AlertServiceOptions = {}, + ) { + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + this.onChange = options.onChange ?? (() => {}); + } + + async get(id: string): Promise { + const alert = await this.repository.findById(id); + if (!alert) throw new AlertNotFoundError(id); + return alert; + } + + /** The location's own alerts: organization-level ones, or one project's. */ + async list( + location: Pick, + ): Promise { + if (location.projectId) return this.repository.listByProject(location.projectId); + const alerts = await this.repository.listByOrganization(location.organizationId); + return alerts.filter((alert) => alert.scope === 'organization'); + } + + /** + * Organization alerts that can fire for events of `projectId`: those on project events whose + * `projectId` conditions don't rule the project out. + */ + async listInherited(organizationId: string, projectId: string): Promise { + const alerts = await this.list({ organizationId, projectId: null }); + return alerts.filter((alert) => { + if (!isEventType(alert.eventType)) return false; + if (getEventDefinition(alert.eventType).scope !== 'project') return false; + const projectConditions = alert.conditions.filter( + (condition) => condition.field === 'projectId', + ); + if (projectConditions.length === 0 || alert.match === 'any') return true; + return projectConditions.every((condition) => { + const values = Array.isArray(condition.value) ? condition.value : [condition.value]; + if (condition.operator === 'eq' || condition.operator === 'in') + return values.includes(projectId); + if (condition.operator === 'neq' || condition.operator === 'not_in') { + return !values.includes(projectId); + } + return true; + }); + }); + } + + /** Validates `input` for `location` and returns the normalized fields, without saving. */ + async validate( + location: AlertLocation, + input: AlertInput, + actor: AlertActor, + ): Promise { + const errors: AlertValidationErrors = {}; + const references: ReferenceCache = new Map(); + + const name = typeof input.name === 'string' ? input.name.trim() : ''; + if (!name) errors.name = 'required'; + else if (name.length > MAX_NAME_LENGTH) errors.name = 'too_long'; + + const description = + typeof input.description === 'string' && input.description.trim() + ? input.description.trim() + : null; + if (description && description.length > MAX_DESCRIPTION_LENGTH) errors.description = 'too_long'; + + const enabled = + input.enabled === undefined ? true : input.enabled === true || input.enabled === 'true'; + + const match = (ALERT_MATCHES as readonly unknown[]).includes(input.match ?? 'all') + ? ((input.match ?? 'all') as AlertMatch) + : null; + if (!match) errors.match = 'invalid'; + + const definition = await this.validateEventType(location, input.eventType, actor, errors); + + const conditions = definition + ? await this.validateConditions(location, definition, input.conditions, errors, references) + : []; + + const recipients = await this.validateRecipients(location, input.recipients, errors); + + const channels = this.validateChannels(input.channels, errors); + + const throttleMinutes = Number(input.throttleMinutes ?? 0); + if ( + !Number.isInteger(throttleMinutes) || + throttleMinutes < 0 || + throttleMinutes > MAX_THROTTLE_MINUTES + ) { + errors.throttleMinutes = 'invalid'; + } + + if (Object.keys(errors).length > 0 || !definition || !match) { + throw new AlertValidationError(errors); + } + + return { + name, + description, + enabled, + eventType: definition.type, + match, + conditions, + recipients, + channels, + throttleMinutes, + }; + } + + async create( + location: AlertLocation, + input: AlertInput, + actor: AlertActor, + ): Promise { + const fields = await this.validate(location, input, actor); + const timestamp = this.now().toISOString(); + const row = { + id: this.generateId(), + ...location, + projectId: location.scope === 'project' ? location.projectId : null, + ...fields, + createdByUserId: actor.userId, + createdAt: timestamp, + updatedAt: timestamp, + }; + await this.repository.create(row); + this.onChange(); + return new AlertDomain(row); + } + + /** Partial update: missing fields keep their stored value; the result is validated as a whole. */ + async update(id: string, input: AlertInput, actor: AlertActor): Promise { + const current = await this.get(id); + const merged: AlertInput = { + name: current.name, + description: current.description, + enabled: current.enabled, + eventType: current.eventType, + match: current.match, + conditions: current.conditions, + recipients: current.recipients, + channels: current.channels, + throttleMinutes: current.throttleMinutes, + ...Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)), + }; + const fields = await this.validate(current.location, merged, actor); + await this.repository.update(id, fields); + this.onChange(); + return new AlertDomain({ ...current.toJson(), ...fields, updatedAt: this.now().toISOString() }); + } + + async delete(id: string): Promise { + await this.get(id); + await this.repository.delete(id); + this.onChange(); + } + + private async validateEventType( + location: AlertLocation, + value: unknown, + actor: AlertActor, + errors: AlertValidationErrors, + ): Promise { + if (typeof value !== 'string' || !value) { + errors.eventType = 'required'; + return null; + } + if (!isEventType(value)) { + errors.eventType = 'unknown_event'; + return null; + } + const definition = getEventDefinition(value as EventType) as EventDefinition; + if (!definition.alertable) { + errors.eventType = 'not_alertable'; + return null; + } + // project events can be watched from the project or its organization; organization events + // only from the organization + if (location.scope === 'project' && definition.scope === 'organization') { + errors.eventType = 'scope_mismatch'; + return null; + } + if (!(await this.canReadEvent(location, definition, actor))) { + errors.eventType = 'forbidden'; + return null; + } + return definition; + } + + /** + * Anti-escalation: an alert must not tell its author about events they can't see. In an + * organization, a project permission is also satisfied by `organization:projects:read`, the + * same grant that cascades into every project. + */ + private async canReadEvent( + location: AlertLocation, + definition: EventDefinition, + actor: AlertActor, + ): Promise { + const context = locationContext(location); + if (await actor.canRead(definition.readPermission, context)) return true; + return ( + context.scope === 'organization' && + definition.scope === 'project' && + definition.readPermission.startsWith('project:') && + actor.canRead('organization:projects:read', context) + ); + } + + private async validateConditions( + location: AlertLocation, + definition: EventDefinition, + value: unknown, + errors: AlertValidationErrors, + references: ReferenceCache, + ): Promise { + if (value === undefined || value === null) return []; + if (!Array.isArray(value)) { + errors.conditions = 'invalid'; + return []; + } + if (value.length > MAX_CONDITIONS) { + errors.conditions = 'too_many'; + return []; + } + + const fields = listAlertFields(definition, location.scope); + const conditions: AlertCondition[] = []; + + for (const [index, raw] of value.entries()) { + const prefix = `conditions.${index}`; + const candidate = (raw ?? {}) as Record; + const field = fields.find((item) => item.key === candidate.field); + if (!field) { + errors[`${prefix}.field`] = 'unknown_field'; + continue; + } + const operator = candidate.operator; + if ( + typeof operator !== 'string' || + !(field.operators as readonly string[]).includes(operator) + ) { + errors[`${prefix}.operator`] = 'invalid_operator'; + continue; + } + const condition = { field: field.key as string, operator } as AlertCondition; + const result = await this.normalizeValue( + location, + field, + condition, + candidate.value, + references, + ); + if (typeof result === 'string') { + errors[`${prefix}.value`] = result; + continue; + } + if (result.value !== undefined) condition.value = result.value; + conditions.push(condition); + } + + return conditions; + } + + /** The stored value for a condition, or the error code. */ + private async normalizeValue( + location: AlertLocation, + field: EventFieldDefinition, + condition: AlertCondition, + raw: unknown, + references: ReferenceCache, + ): Promise<{ value: AlertCondition['value'] } | string> { + if (VALUELESS_OPERATORS.has(condition.operator)) return { value: undefined }; + + if (LIST_OPERATORS.has(condition.operator)) { + const items = Array.isArray(raw) ? raw : typeof raw === 'string' && raw ? [raw] : []; + if (items.length === 0) return 'required'; + if (items.length > MAX_LIST_VALUES) return 'too_many'; + const normalized: string[] = []; + for (const item of items) { + const result = await this.normalizeScalar(location, field, item, references); + if (typeof result === 'string') return result; + normalized.push(String(result.value)); + } + return { value: [...new Set(normalized)] }; + } + + return this.normalizeScalar(location, field, raw, references); + } + + private async normalizeScalar( + location: AlertLocation, + field: EventFieldDefinition, + raw: unknown, + references: ReferenceCache, + ): Promise<{ value: string | number } | string> { + if (raw === undefined || raw === null || raw === '') return 'required'; + + switch (field.type) { + case 'number': { + const parsed = typeof raw === 'number' ? raw : typeof raw === 'string' ? Number(raw) : NaN; + return Number.isFinite(parsed) ? { value: parsed } : 'invalid'; + } + case 'date': { + const parsed = typeof raw === 'string' ? Date.parse(raw) : NaN; + return Number.isNaN(parsed) ? 'invalid' : { value: new Date(parsed).toISOString() }; + } + case 'enum': { + const allowed = (field.options ?? []).map((option) => option.value); + return typeof raw === 'string' && allowed.includes(raw) ? { value: raw } : 'unknown_option'; + } + case 'reference': { + if (typeof raw !== 'string' || !field.reference) return 'invalid'; + const key = field.reference; + if (!references.has(key)) { + references.set(key, this.directory.listReferences(field.reference, location)); + } + const options = await references.get(key)!; + return options.some((option) => option.id === raw) ? { value: raw } : 'unknown_reference'; + } + case 'string': { + if (typeof raw !== 'string' || !raw.trim()) return 'required'; + return { value: raw.trim() }; + } + default: + return 'invalid'; + } + } + + private async validateRecipients( + location: AlertLocation, + value: unknown, + errors: AlertValidationErrors, + ): Promise { + const raw = (value ?? {}) as Record; + const ids = (list: unknown) => + Array.isArray(list) + ? [...new Set(list.filter((id): id is string => typeof id === 'string' && !!id))] + : []; + const userIds = ids(raw.userIds); + const roleIds = ids(raw.roleIds); + + if (userIds.length === 0 && roleIds.length === 0) { + errors.recipients = 'required'; + return { userIds, roleIds }; + } + + if (userIds.length > 0) { + const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId)); + if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user'; + } + if (roleIds.length > 0) { + const roles = new Set((await this.directory.listRoles(location)).map((role) => role.id)); + if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role'; + } + + return { userIds, roleIds }; + } + + private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] { + if (value === undefined || value === null) return ['mail']; + const list = Array.isArray(value) ? value : [value]; + const valid = list.every((channel) => (ALERT_CHANNELS as readonly unknown[]).includes(channel)); + if (!valid || list.length === 0) { + errors.channels = 'invalid_channel'; + return ['mail']; + } + return [...new Set(list as AlertChannel[])]; + } +} diff --git a/src/modules/alerts/application/recipient-resolver.ts b/src/modules/alerts/application/recipient-resolver.ts new file mode 100644 index 00000000..39ad363e --- /dev/null +++ b/src/modules/alerts/application/recipient-resolver.ts @@ -0,0 +1,57 @@ +import type { PermissionGrant } from '#lib/permissions'; +import type { AlertLocation, AlertRecipients } from '../domain/alert.domain'; +import type { AlertDirectory, PermissionContext, ScopeMember, UserPermissionCheck } from './types'; + +export type Recipient = Pick & { email: string }; + +export type ResolvedRecipients = { + recipients: Recipient[]; + /** Selected users dropped because they can't read the event. */ + denied: string[]; +}; + +/** + * Turns an alert's users and roles into the people that get the email: the selected users plus + * every member holding one of the roles, restricted to current members of the alert's location + * that are enabled and have an email, and finally to those allowed to read the event + * (`readPermission` checked where the event happened, most-specific-wins included). + */ +export class RecipientResolver { + constructor( + private readonly directory: Pick, + private readonly can: UserPermissionCheck, + ) {} + + async resolve( + location: AlertLocation, + selection: AlertRecipients, + readPermission: PermissionGrant, + context: PermissionContext, + ): Promise { + const members = await this.directory.listMembers(location); + const userIds = new Set(selection.userIds); + const roleIds = new Set(selection.roleIds); + + const candidates = new Map(); + for (const member of members) { + const selected = + userIds.has(member.userId) || member.roleIds.some((roleId) => roleIds.has(roleId)); + if (!selected || member.disabled || !member.email) continue; + candidates.set(member.userId, { + userId: member.userId, + username: member.username, + email: member.email, + }); + } + + const recipients: Recipient[] = []; + const denied: string[] = []; + for (const candidate of candidates.values()) { + const allowed = await this.can(candidate.userId, readPermission, context).catch(() => false); + if (allowed) recipients.push(candidate); + else denied.push(candidate.userId); + } + + return { recipients, denied }; + } +} diff --git a/src/modules/alerts/application/testing.ts b/src/modules/alerts/application/testing.ts new file mode 100644 index 00000000..fc248971 --- /dev/null +++ b/src/modules/alerts/application/testing.ts @@ -0,0 +1,76 @@ +import type { FieldReference } from '#lib/events/catalog'; +import type { AlertLocation } from '../domain/alert.domain'; +import type { + AlertActor, + AlertDirectory, + NameIds, + ReferenceOption, + ResolvedNames, + ScopeMember, + ScopeRole, +} from './types'; + +type Scoped = T & { organizationId: string; projectId?: string | null }; + +/** + * In-memory `AlertDirectory` for unit tests. Entries carry the organization (and project) they + * belong to; a location sees its organization's entries and, for a project, only that project's. + */ +export class FakeAlertDirectory implements AlertDirectory { + members: Scoped[] = []; + roles: Scoped[] = []; + references: Array> = []; + users: Omit[] = []; + names: Record = {}; + + private within( + entry: { organizationId: string; projectId?: string | null }, + location: AlertLocation, + ) { + if (entry.organizationId !== location.organizationId) return false; + if (location.scope === 'organization') return true; + return !entry.projectId || entry.projectId === location.projectId; + } + + async listMembers(location: AlertLocation): Promise { + return this.members + .filter((member) => this.within(member, location)) + .map(({ organizationId: _o, projectId: _p, ...member }) => member); + } + + async listRoles(location: AlertLocation): Promise { + return this.roles + .filter((role) => this.within(role, location)) + .map((role) => ({ id: role.id, name: role.name })); + } + + async listReferences( + reference: FieldReference, + location: AlertLocation, + ): Promise { + return this.references + .filter((entry) => entry.reference === reference && this.within(entry, location)) + .map((entry) => ({ id: entry.id, label: entry.label })); + } + + async findUser(userId: string) { + return this.users.find((user) => user.userId === userId) ?? null; + } + + async resolveNames(ids: NameIds): Promise { + const names: ResolvedNames = {}; + if (ids.organizationId && this.names[ids.organizationId]) + names.organization = this.names[ids.organizationId]; + if (ids.projectId && this.names[ids.projectId]) names.project = this.names[ids.projectId]; + if (ids.roleId && this.names[ids.roleId]) names.role = this.names[ids.roleId]; + return names; + } +} + +/** An actor allowed to read everything, or only the grants listed. */ +export function actor(userId = 'author', allowed: string[] | 'all' = 'all'): AlertActor { + return { + userId, + canRead: async (permission) => allowed === 'all' || allowed.includes(permission), + }; +} diff --git a/src/modules/alerts/application/types.ts b/src/modules/alerts/application/types.ts new file mode 100644 index 00000000..a384859b --- /dev/null +++ b/src/modules/alerts/application/types.ts @@ -0,0 +1,81 @@ +import type { FieldReference } from '#lib/events/catalog'; +import type { PermissionGrant } from '#lib/permissions'; +import type { AlertLocation } from '../domain/alert.domain'; + +/** Same shape as `CanCanContext` in `#modules/auth`, without importing it. */ +export type PermissionContext = + | { scope: 'organization'; organizationId: string } + | { scope: 'project'; projectId: string; organizationId?: string }; + +/** Permission check for an arbitrary user (`cancanService.can`). */ +export type UserPermissionCheck = ( + userId: string, + permission: PermissionGrant, + context: PermissionContext, +) => Promise; + +/** Someone with access to the alert's organization or project. */ +export type ScopeMember = { + userId: string; + username: string; + email: string | null; + disabled: boolean; + /** Roles held in the alert's scope (and, for a project, in its organization). */ + roleIds: string[]; +}; + +export type ScopeRole = { id: string; name: string }; + +/** Entity selectable in a `reference` condition. */ +export type ReferenceOption = { id: string; label: string }; + +/** Read-only view of the platform the alerts module needs; wired in `index.ts`. */ +export interface AlertDirectory { + /** Active members: organization members and members of its projects, or a project's members + * and the members of its organization. */ + listMembers(location: AlertLocation): Promise; + /** Roles a recipient can be picked by: the organization's roles, plus the project's roles for a + * project alert. */ + listRoles(location: AlertLocation): Promise; + /** Entities of `reference` inside the location: a condition can only point at these. */ + listReferences(reference: FieldReference, location: AlertLocation): Promise; + /** Any user, member or not (system notifications reach users who just lost their access). */ + findUser(userId: string): Promise | null>; + /** Display names for a system notification; unknown ids are left out. */ + resolveNames(ids: NameIds): Promise; +} + +export type NameIds = { + organizationId?: string | null; + projectId?: string | null; + roleId?: string | null; +}; + +export type ResolvedNames = { organization?: string; project?: string; role?: string }; + +/** Who creates or edits an alert; `canRead` checks a grant in a context for that actor. */ +export type AlertActor = { + userId: string; + canRead(permission: PermissionGrant, context: PermissionContext): Promise; +}; + +export function locationContext(location: AlertLocation): PermissionContext { + return location.scope === 'project' && location.projectId + ? { scope: 'project', projectId: location.projectId, organizationId: location.organizationId } + : { scope: 'organization', organizationId: location.organizationId }; +} + +export function eventContext(scope: { + organizationId?: string | null; + projectId?: string | null; +}): PermissionContext | null { + if (scope.projectId) { + return { + scope: 'project', + projectId: scope.projectId, + organizationId: scope.organizationId ?? undefined, + }; + } + if (scope.organizationId) return { scope: 'organization', organizationId: scope.organizationId }; + return null; +} diff --git a/src/modules/alerts/domain/alert.domain.ts b/src/modules/alerts/domain/alert.domain.ts new file mode 100644 index 00000000..4095ce55 --- /dev/null +++ b/src/modules/alerts/domain/alert.domain.ts @@ -0,0 +1,181 @@ +import type { EventType } from '#lib/events/domain-events'; +import type { Operator } from '#lib/events/catalog'; + +export type AlertScope = 'organization' | 'project'; +export type AlertMatch = 'all' | 'any'; + +/** v1 only sends emails; the field is ready for in-app and Slack (#82). */ +export const ALERT_CHANNELS = ['mail'] as const; +export type AlertChannel = (typeof ALERT_CHANNELS)[number]; + +export const ALERT_MATCHES = ['all', 'any'] as const; + +/** Upper bound of the anti-spam window: one day. */ +export const MAX_THROTTLE_MINUTES = 24 * 60; + +export type AlertCondition = { + /** Catalog field key (`summary.critical`, `serviceId`, `projectId`…). */ + field: string; + operator: Operator; + /** Absent for `is_true`, `is_false` and `exists`; an array for `in` / `not_in`. */ + value?: string | number | string[]; +}; + +export type AlertRecipients = { + userIds: string[]; + roleIds: string[]; +}; + +/** Where an alert lives: an organization alert has no project. */ +export type AlertLocation = { + scope: AlertScope; + organizationId: string; + projectId: string | null; +}; + +/** What a client sends to create or replace an alert. Unknown values are validated by the service. */ +export type AlertInput = { + name?: unknown; + description?: unknown; + enabled?: unknown; + eventType?: unknown; + match?: unknown; + conditions?: unknown; + recipients?: unknown; + channels?: unknown; + throttleMinutes?: unknown; +}; + +/** Validated, normalized alert fields. */ +export type AlertFields = { + name: string; + description: string | null; + enabled: boolean; + eventType: EventType; + match: AlertMatch; + conditions: AlertCondition[]; + recipients: AlertRecipients; + channels: AlertChannel[]; + throttleMinutes: number; +}; + +export type AlertRow = AlertLocation & + AlertFields & { + id: string; + createdByUserId: string; + createdAt: string; + updatedAt: string; + }; + +function stringArray(value: unknown): string[] { + return Array.isArray(value) + ? value.filter((item): item is string => typeof item === 'string') + : []; +} + +function toIso(value: unknown): string { + if (value instanceof Date) return value.toISOString(); + return typeof value === 'string' ? value : new Date(0).toISOString(); +} + +export class AlertDomain implements AlertRow { + id: string; + name: string; + description: string | null; + enabled: boolean; + scope: AlertScope; + organizationId: string; + projectId: string | null; + eventType: EventType; + match: AlertMatch; + conditions: AlertCondition[]; + recipients: AlertRecipients; + channels: AlertChannel[]; + throttleMinutes: number; + createdByUserId: string; + createdAt: string; + updatedAt: string; + + constructor(row: Record) { + this.id = row.id; + this.name = row.name ?? ''; + this.description = row.description ?? null; + this.enabled = row.enabled !== false; + this.scope = row.scope === 'project' ? 'project' : 'organization'; + this.organizationId = row.organizationId; + this.projectId = this.scope === 'project' ? (row.projectId ?? null) : null; + this.eventType = row.eventType; + this.match = row.match === 'any' ? 'any' : 'all'; + this.conditions = Array.isArray(row.conditions) ? row.conditions : []; + this.recipients = { + userIds: stringArray(row.recipients?.userIds), + roleIds: stringArray(row.recipients?.roleIds), + }; + const channels = stringArray(row.channels).filter((channel): channel is AlertChannel => + (ALERT_CHANNELS as readonly string[]).includes(channel), + ); + this.channels = channels.length > 0 ? channels : ['mail']; + this.throttleMinutes = Number.isFinite(Number(row.throttleMinutes)) + ? Number(row.throttleMinutes) + : 0; + this.createdByUserId = row.createdByUserId; + this.createdAt = toIso(row.createdAt); + this.updatedAt = toIso(row.updatedAt); + } + + get location(): AlertLocation { + return { scope: this.scope, organizationId: this.organizationId, projectId: this.projectId }; + } + + /** + * Whether an event that happened in `eventScope` concerns this alert: an organization alert + * covers the organization and all its projects, a project alert only its project. + */ + appliesTo(eventScope: { organizationId?: string | null; projectId?: string | null }): boolean { + if (!eventScope.organizationId || eventScope.organizationId !== this.organizationId) { + return false; + } + return this.scope === 'organization' || eventScope.projectId === this.projectId; + } + + toJson(): AlertRow { + return { + id: this.id, + name: this.name, + description: this.description, + enabled: this.enabled, + scope: this.scope, + organizationId: this.organizationId, + projectId: this.projectId, + eventType: this.eventType, + match: this.match, + conditions: this.conditions.map((condition) => ({ ...condition })), + recipients: { + userIds: [...this.recipients.userIds], + roleIds: [...this.recipients.roleIds], + }, + channels: [...this.channels], + throttleMinutes: this.throttleMinutes, + createdByUserId: this.createdByUserId, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + }; + } +} + +/** Field-level validation errors: key → error code (`required`, `invalid_operator`…). */ +export type AlertValidationErrors = Record; + +export class AlertValidationError extends Error { + constructor(readonly errors: AlertValidationErrors) { + super(`Invalid alert: ${Object.keys(errors).join(', ')}`); + this.name = 'AlertValidationError'; + } +} + +export class AlertNotFoundError extends Error { + constructor(id: string) { + super(`Alert not found: ${id}`); + this.name = 'AlertNotFoundError'; + } +} diff --git a/src/modules/alerts/domain/condition-evaluator.test.ts b/src/modules/alerts/domain/condition-evaluator.test.ts new file mode 100644 index 00000000..802a2be3 --- /dev/null +++ b/src/modules/alerts/domain/condition-evaluator.test.ts @@ -0,0 +1,265 @@ +import { describe, expect, it } from 'vitest'; +import { getEventDefinition, type EventDefinition, type FieldType } from '#lib/events/catalog'; +import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events'; +import type { AlertCondition } from './alert.domain'; +import { evaluateCondition, matches } from './condition-evaluator'; + +type Case = [ + operator: AlertCondition['operator'], + value: AlertCondition['value'], + actual: unknown, + expected: boolean, +]; + +function run(type: FieldType, cases: Case[]) { + it.each(cases)('%s %j against %j → %s', (operator, value, actual, expected) => { + expect(evaluateCondition({ type }, { operator, value }, actual)).toBe(expected); + }); +} + +describe('evaluateCondition', () => { + describe('string', () => { + run('string', [ + ['eq', 'main', 'main', true], + ['eq', 'main', 'Main', false], + ['eq', 'main', 'develop', false], + ['neq', 'main', 'develop', true], + ['neq', 'main', 'main', false], + ['contains', 'FEAT', 'release/feature-x', true], + ['contains', 'hotfix', 'release/feature-x', false], + ['starts_with', 'Release/', 'release/feature-x', true], + ['starts_with', 'feature', 'release/feature-x', false], + ['in', ['main', 'develop'], 'develop', true], + ['in', ['main', 'develop'], 'staging', false], + ['not_in', ['main', 'develop'], 'staging', true], + ['not_in', ['main', 'develop'], 'main', false], + ['contains', 'a', 42, false], + ]); + }); + + describe('number', () => { + run('number', [ + ['eq', 3, 3, true], + ['eq', 3, 4, false], + ['gt', 0, 1, true], + ['gt', 0, 0, false], + ['gte', 0, 0, true], + ['gte', 1, 0, false], + ['lt', 5, 4, true], + ['lt', 5, 5, false], + ['lte', 5, 5, true], + ['lte', 5, 6, false], + // values coming from a form are numeric strings + ['gt', '2', 3, true], + ['gt', 'abc', 3, false], + ['gt', 0, 'not a number', false], + ]); + }); + + describe('date', () => { + run('date', [ + ['gt', '2026-01-01T00:00:00.000Z', '2026-02-01T00:00:00.000Z', true], + ['gt', '2026-01-01T00:00:00.000Z', '2025-12-31T23:59:59.000Z', false], + ['gte', '2026-01-01', '2026-01-01T00:00:00.000Z', true], + ['lt', '2026-01-01', '2025-06-01', true], + ['lte', '2026-01-01', '2026-01-02', false], + ['lt', 'not a date', '2025-06-01', false], + ]); + }); + + describe('boolean', () => { + run('boolean', [ + ['is_true', undefined, true, true], + ['is_true', undefined, false, false], + ['is_false', undefined, false, true], + ['is_false', undefined, true, false], + ['is_true', undefined, 'true', false], + ]); + }); + + describe('enum and reference', () => { + run('enum', [ + ['eq', 'trivy', 'trivy', true], + ['neq', 'trivy', 'grype', true], + ['in', ['trivy', 'grype'], 'grype', true], + ['not_in', ['trivy', 'grype'], 'semgrep', true], + ]); + run('reference', [ + ['eq', 'svc-1', 'svc-1', true], + ['eq', 'svc-1', 'svc-2', false], + ['in', ['svc-1', 'svc-2'], 'svc-2', true], + ['not_in', ['svc-1'], 'svc-1', false], + ]); + }); + + describe('list values', () => { + run('enum', [ + ['in', ['values'], ['key', 'values'], true], + ['in', ['folder'], ['key', 'values'], false], + ['not_in', ['folder'], ['key', 'values'], true], + ['not_in', ['key'], ['key', 'values'], false], + ['eq', 'key', ['key', 'values'], true], + ['neq', 'key', ['key', 'values'], false], + ]); + }); + + describe('absent values', () => { + const operators: AlertCondition['operator'][] = [ + 'eq', + 'neq', + 'in', + 'not_in', + 'contains', + 'starts_with', + 'gt', + 'gte', + 'lt', + 'lte', + 'is_true', + 'is_false', + ]; + + it.each(operators)('%s fails on a missing value', (operator) => { + expect(evaluateCondition({ type: 'string' }, { operator, value: 'x' }, undefined)).toBe( + false, + ); + expect(evaluateCondition({ type: 'string' }, { operator, value: 'x' }, null)).toBe(false); + }); + + it('exists only checks presence', () => { + expect(evaluateCondition({ type: 'string' }, { operator: 'exists' }, 'x')).toBe(true); + expect(evaluateCondition({ type: 'number' }, { operator: 'exists' }, 0)).toBe(true); + expect(evaluateCondition({ type: 'string' }, { operator: 'exists' }, undefined)).toBe(false); + expect(evaluateCondition({ type: 'string' }, { operator: 'exists' }, null)).toBe(false); + }); + }); +}); + +describe('matches', () => { + const definition = getEventDefinition('code_report.analysis.completed') as EventDefinition; + + function completed(overrides: Partial = {}) { + const payload: CodeReportAnalysisCompletedPayload = { + analysisId: 'analysis-1', + serviceId: 'svc-gateway', + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc', version: null }, + summary: { critical: 2, high: 1, medium: 0, low: 0, unknown: 0, total: 3, secrets: 0 }, + policies: { + status: 'compliant', + totalViolations: 0, + blockingFailures: 0, + failedPolicyIds: [], + }, + ...overrides, + }; + return { + type: 'code_report.analysis.completed' as const, + payload, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + }; + } + + const critical: AlertCondition = { field: 'summary.critical', operator: 'gt', value: 0 }; + const gateway: AlertCondition = { field: 'serviceId', operator: 'eq', value: 'svc-gateway' }; + const otherService: AlertCondition = { field: 'serviceId', operator: 'eq', value: 'svc-web' }; + + it('always matches without conditions', () => { + expect( + matches(completed(), { scope: 'project', match: 'all', conditions: [] }, definition), + ).toBe(true); + expect( + matches(completed(), { scope: 'project', match: 'any', conditions: [] }, definition), + ).toBe(true); + }); + + it('requires every condition with match all', () => { + const alert = { + scope: 'project' as const, + match: 'all' as const, + conditions: [gateway, critical], + }; + expect(matches(completed(), alert, definition)).toBe(true); + expect( + matches( + completed({ summary: { ...completed().payload.summary, critical: 0 } }), + alert, + definition, + ), + ).toBe(false); + }); + + it('requires any condition with match any', () => { + const alert = { + scope: 'project' as const, + match: 'any' as const, + conditions: [otherService, critical], + }; + expect(matches(completed(), alert, definition)).toBe(true); + expect(matches(completed(), { ...alert, conditions: [otherService] }, definition)).toBe(false); + }); + + it('reads nested paths', () => { + const alert = { + scope: 'project' as const, + match: 'all' as const, + conditions: [ + { field: 'gitInfo.branch', operator: 'starts_with', value: 'ma' } as AlertCondition, + ], + }; + expect(matches(completed(), alert, definition)).toBe(true); + expect( + matches( + completed({ gitInfo: { repositoryUrl: null, branch: null, commit: null, version: null } }), + alert, + definition, + ), + ).toBe(false); + }); + + it('evaluates derived fields', () => { + const alert = { + scope: 'project' as const, + match: 'all' as const, + conditions: [{ field: 'policiesViolated', operator: 'is_true' } as AlertCondition], + }; + expect(matches(completed(), alert, definition)).toBe(false); + expect( + matches( + completed({ + policies: { + status: 'violated', + totalViolations: 1, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }), + alert, + definition, + ), + ).toBe(true); + }); + + it('never matches a condition on an unknown field', () => { + const alert = { + scope: 'project' as const, + match: 'any' as const, + conditions: [{ field: 'nope', operator: 'exists' } as AlertCondition], + }; + expect(matches(completed(), alert, definition)).toBe(false); + }); + + it('lets an organization alert filter a project event by project', () => { + const byProject = (value: string[]) => ({ + scope: 'organization' as const, + match: 'all' as const, + conditions: [{ field: 'projectId', operator: 'in', value } as AlertCondition], + }); + expect(matches(completed(), byProject(['project-1']), definition)).toBe(true); + expect(matches(completed(), byProject(['project-2']), definition)).toBe(false); + // a project alert has no projectId field to filter by + expect( + matches(completed(), { ...byProject(['project-1']), scope: 'project' }, definition), + ).toBe(false); + }); +}); diff --git a/src/modules/alerts/domain/condition-evaluator.ts b/src/modules/alerts/domain/condition-evaluator.ts new file mode 100644 index 00000000..76527b8d --- /dev/null +++ b/src/modules/alerts/domain/condition-evaluator.ts @@ -0,0 +1,156 @@ +import { + getFieldValue, + isScopeField, + listAlertFields, + type AlertableEventInput, + type EventDefinition, + type EventFieldDefinition, + type FieldType, +} from '#lib/events/catalog'; +import type { AlertCondition, AlertMatch, AlertScope } from './alert.domain'; + +/** The part of an alert the evaluator needs. */ +export type EvaluableAlert = { + scope: AlertScope; + match: AlertMatch; + conditions: readonly AlertCondition[]; +}; + +function isAbsent(value: unknown): boolean { + return value === undefined || value === null; +} + +function toNumber(value: unknown): number | null { + if (typeof value === 'number') return Number.isFinite(value) ? value : null; + if (typeof value === 'string' && value.trim() !== '') { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : null; + } + return null; +} + +function toTime(value: unknown): number | null { + if (value instanceof Date) return value.getTime(); + if (typeof value !== 'string') return null; + const parsed = Date.parse(value); + return Number.isNaN(parsed) ? null : parsed; +} + +/** Comparable value of `raw` for a field of `type`; `null` when it can't be compared. */ +function comparable(type: FieldType, raw: unknown): number | string | null { + if (type === 'number') return toNumber(raw); + if (type === 'date') return toTime(raw); + if (typeof raw === 'string') return raw; + if (typeof raw === 'number' || typeof raw === 'boolean') return String(raw); + return null; +} + +function compare(type: FieldType, actual: unknown, expected: unknown): number | null { + const left = comparable(type, actual); + const right = comparable(type, expected); + if (left === null || right === null || typeof left !== typeof right) return null; + if (left === right) return 0; + return left < right ? -1 : 1; +} + +function equals(type: FieldType, actual: unknown, expected: unknown): boolean { + return compare(type, actual, expected) === 0; +} + +function asList(value: unknown): unknown[] { + return Array.isArray(value) ? value : [value]; +} + +/** + * Evaluates one condition against the field value of an event. + * + * - An absent value (`undefined` / `null`) fails every operator except `exists`. + * - A list value (e.g. `changedFields`) matches `in` when it shares any item with the condition + * value and `not_in` when it shares none; `eq` / `neq` test whether it contains the value. + * - `contains` and `starts_with` ignore case; `gt`… compare numbers for `number` fields and + * instants for `date` fields (ISO 8601). + */ +export function evaluateCondition( + field: Pick, + condition: Pick, + actual: unknown, +): boolean { + if (condition.operator === 'exists') return !isAbsent(actual); + if (isAbsent(actual)) return false; + + const type = field.type; + const expected = condition.value; + + switch (condition.operator) { + case 'is_true': + return actual === true; + case 'is_false': + return actual === false; + case 'eq': + return asList(actual).some((item) => equals(type, item, expected)); + case 'neq': + return !asList(actual).some((item) => equals(type, item, expected)); + case 'in': { + const options = asList(expected); + return asList(actual).some((item) => options.some((option) => equals(type, item, option))); + } + case 'not_in': { + const options = asList(expected); + return !asList(actual).some((item) => options.some((option) => equals(type, item, option))); + } + case 'contains': + case 'starts_with': { + if (typeof actual !== 'string' || typeof expected !== 'string') return false; + const haystack = actual.toLocaleLowerCase(); + const needle = expected.toLocaleLowerCase(); + return condition.operator === 'contains' + ? haystack.includes(needle) + : haystack.startsWith(needle); + } + case 'gt': + case 'gte': + case 'lt': + case 'lte': { + const order = compare(type, actual, expected); + if (order === null) return false; + if (condition.operator === 'gt') return order > 0; + if (condition.operator === 'gte') return order >= 0; + if (condition.operator === 'lt') return order < 0; + return order <= 0; + } + default: + return false; + } +} + +/** Value of `field` for `event`: the event scope for scope fields, the catalog otherwise. */ +export function readAlertField(event: AlertableEventInput, field: EventFieldDefinition): unknown { + if (isScopeField(field)) return event.scope?.projectId ?? undefined; + try { + return getFieldValue(event, field.key as string); + } catch { + // a `derive` on an incomplete payload (sample events, older payload shapes) counts as absent + return undefined; + } +} + +/** + * Whether `event` satisfies the alert's conditions: `all` is AND, `any` is OR, and no conditions + * always match. A condition on a field the event definition doesn't have never matches. + */ +export function matches( + event: AlertableEventInput, + alert: EvaluableAlert, + definition: EventDefinition, +): boolean { + if (alert.conditions.length === 0) return true; + + const fields = listAlertFields(definition, alert.scope); + const results = alert.conditions.map((condition) => { + const field = fields.find((candidate) => candidate.key === condition.field); + if (!field) return false; + return evaluateCondition(field, condition, readAlertField(event, field)); + }); + + return alert.match === 'any' ? results.some(Boolean) : results.every(Boolean); +} diff --git a/src/modules/alerts/domain/sample-event.ts b/src/modules/alerts/domain/sample-event.ts new file mode 100644 index 00000000..a942d545 --- /dev/null +++ b/src/modules/alerts/domain/sample-event.ts @@ -0,0 +1,76 @@ +import { + isScopeField, + listAlertFields, + type EventDefinition, + type EventFieldDefinition, +} from '#lib/events/catalog'; +import type { AlertCondition, AlertScope } from './alert.domain'; + +/** A value that satisfies `condition` for `field`, or `undefined` when none can be made up. */ +function satisfying(field: EventFieldDefinition, condition: AlertCondition): unknown { + const value = condition.value; + const first = Array.isArray(value) ? value[0] : value; + switch (condition.operator) { + case 'eq': + case 'contains': + case 'starts_with': + return field.type === 'number' ? Number(value) : value; + case 'in': + return Array.isArray(value) ? first : value; + case 'gt': + case 'gte': + if (field.type === 'date') return new Date(Date.parse(String(value)) + 60_000).toISOString(); + return Number(value) + 1; + case 'lt': + case 'lte': + if (field.type === 'date') return new Date(Date.parse(String(value)) - 60_000).toISOString(); + return Number(value) - 1; + case 'is_true': + return true; + case 'is_false': + return false; + case 'exists': + return field.type === 'number' ? 1 : 'sample'; + default: + // neq / not_in: anything else works, but there is nothing sensible to invent + return undefined; + } +} + +function setPath(target: Record, path: string, value: unknown) { + const segments = path.split('.'); + let node = target; + for (const segment of segments.slice(0, -1)) { + if (typeof node[segment] !== 'object' || node[segment] === null) node[segment] = {}; + node = node[segment] as Record; + } + node[segments[segments.length - 1]] = value; +} + +/** + * Example event for "Test alert": a payload built so that, where possible, every condition holds + * (derived fields can't be forced). Values the caller passes win over the invented ones. + */ +export function buildSampleEvent( + definition: EventDefinition, + alert: { scope: AlertScope; conditions: readonly AlertCondition[] }, + overrides: { payload?: Record; projectId?: string | null } = {}, +): { payload: Record; projectId: string | null } { + const fields = listAlertFields(definition, alert.scope); + const payload: Record = {}; + let projectId: string | null = null; + + for (const condition of alert.conditions) { + const field = fields.find((candidate) => candidate.key === condition.field); + if (!field) continue; + const value = satisfying(field, condition); + if (value === undefined) continue; + if (isScopeField(field)) projectId = typeof value === 'string' ? value : null; + else if (!field.derive) setPath(payload, field.key as string, value); + } + + return { + payload: { ...payload, ...(overrides.payload ?? {}) }, + projectId: overrides.projectId ?? projectId, + }; +} diff --git a/src/modules/alerts/domain/system-notifications.data.ts b/src/modules/alerts/domain/system-notifications.data.ts new file mode 100644 index 00000000..42fa6705 --- /dev/null +++ b/src/modules/alerts/domain/system-notifications.data.ts @@ -0,0 +1,53 @@ +import type { DomainEventMap, EventType } from '#lib/events/domain-events'; + +/** Fixed notification kinds; the notifier turns each into a subject and a message. */ +export type SystemNotificationKind = + 'access_granted' | 'access_updated' | 'access_revoked' | 'api_key_created'; + +export type SystemNotificationRule = { + eventType: K; + kind: SystemNotificationKind; + /** The user to tell, or `null` when this event needs no notification. */ + recipient(payload: DomainEventMap[K]): string | null; +}; + +type Rules = { [K in EventType]?: SystemNotificationRule }; + +/** + * Notifications nobody configures: people hear about changes to their own access and about new + * personal API keys. They never go to the user who caused the event (the engine skips the actor). + * + * Invitations (`status: 'invited'`) are skipped: the invitation email already tells the user. + */ +export const SYSTEM_NOTIFICATIONS: Rules = { + 'access.granted': { + eventType: 'access.granted', + kind: 'access_granted', + recipient: (payload) => (payload.status === 'active' ? payload.userId : null), + }, + 'access.updated': { + eventType: 'access.updated', + kind: 'access_updated', + recipient: (payload) => + payload.status === 'active' && payload.roleId !== payload.previousRoleId + ? payload.userId + : null, + }, + 'access.revoked': { + eventType: 'access.revoked', + kind: 'access_revoked', + recipient: (payload) => (payload.status === 'active' ? payload.userId : null), + }, + 'api_key.created': { + eventType: 'api_key.created', + kind: 'api_key_created', + // project keys belong to a project, not to a person + recipient: (payload) => (payload.projectId ? null : payload.userId), + }, +}; + +export function getSystemNotification( + type: K, +): SystemNotificationRule | undefined { + return SYSTEM_NOTIFICATIONS[type] as SystemNotificationRule | undefined; +} diff --git a/src/modules/alerts/index.ts b/src/modules/alerts/index.ts new file mode 100644 index 00000000..3726fe2d --- /dev/null +++ b/src/modules/alerts/index.ts @@ -0,0 +1,91 @@ +import { eventBus } from '#lib/server/events'; +import { isSmtpConfigured } from '#lib/server/infra/notifications'; +import { createLogger } from '#lib/server/logger'; +import { cancanService, roleService, userAccessService, apiKeysService } from '../auth'; +import { codeReportSecurityPolicyService, codeReportService } from '../code-report'; +import { organizationService } from '../organization'; +import { projectService } from '../projects'; +import { vaultService } from '../vault'; +import { AlertEngine } from './application/alert-engine'; +import { AlertService } from './application/alert.service'; +import { AlertThrottle } from './application/alert-throttle'; +import { RecipientResolver } from './application/recipient-resolver'; +import { AlertMailNotifier } from './infrastructure/alert-mail.notifier'; +import { PlatformDirectory } from './infrastructure/platform-directory'; +import { AlertRepository } from './infrastructure/repositories/alert.repository'; + +const log = createLogger('alerts'); + +const alertRepository = new AlertRepository(); + +export const alertDirectory = new PlatformDirectory({ + projects: projectService, + organizations: organizationService, + access: userAccessService, + roles: roleService, + codeReportServices: codeReportService, + codeReportPolicies: codeReportSecurityPolicyService, + vaultEnvironments: vaultService, + apiKeys: apiKeysService, +}); + +const recipientResolver = new RecipientResolver(alertDirectory, (userId, permission, context) => + cancanService.can(userId, permission, context), +); + +const ENGINE_KEY = Symbol.for('gitops.alerts.engine'); +type GlobalWithEngine = typeof globalThis & { + [ENGINE_KEY]?: { engine: AlertEngine; attached: boolean }; +}; + +// one engine per process: HMR re-evaluating this module must not subscribe a second one, and the +// throttle windows must survive it +const engineSlot = ((globalThis as GlobalWithEngine)[ENGINE_KEY] ??= { + engine: new AlertEngine({ + repository: alertRepository, + directory: alertDirectory, + recipients: recipientResolver, + notifier: new AlertMailNotifier(), + throttle: new AlertThrottle(), + logger: log, + // without SMTP there is nobody to tell: skip the work instead of logging a failure per event + deliveryEnabled: () => { + try { + return isSmtpConfigured(); + } catch { + return false; + } + }, + }), + attached: false, +}); + +export const alertEngine = engineSlot.engine; + +export const alertService = new AlertService(alertRepository, alertDirectory, { + onChange: () => alertEngine.invalidate(), +}); + +/** Subscribes the alert engine to the bus once per process (`hooks.server.ts`). */ +export function registerAlertEngine(): void { + if (engineSlot.attached) return; + alertEngine.attach(eventBus); + engineSlot.attached = true; + log.info('[alerts] engine registered'); +} + +export { buildSampleEvent } from './domain/sample-event'; +export { + AlertDomain, + AlertNotFoundError, + AlertValidationError, + ALERT_CHANNELS, + type AlertCondition, + type AlertInput, + type AlertLocation, + type AlertRow, + type AlertScope, + type AlertValidationErrors, +} from './domain/alert.domain'; +export type { AlertActor, ReferenceOption, ScopeMember, ScopeRole } from './application/types'; +export type { AlertDryRun } from './application/alert-engine'; diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts new file mode 100644 index 00000000..f796f465 --- /dev/null +++ b/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts @@ -0,0 +1,70 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getEventDefinition, type EventDefinition } from '#lib/events/catalog'; +import { registerTransport, resetTransports } from '#lib/server/infra/notifications'; +import type { AnyDomainEvent } from '#lib/server/events'; +import { AlertMailNotifier } from './alert-mail.notifier'; + +const send = vi.fn( + async (notification: { to: string[]; subject: string; content: string }) => notification, +); + +const event: AnyDomainEvent = { + id: 'event-1', + type: 'code_report.analysis.completed', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: 'org-1', projectId: 'p1' }, + payload: { + analysisId: 'analysis-1', + serviceId: 'svc-gateway', + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: '
', commit: null, version: null }, + summary: { critical: 2, high: 0, medium: 0, low: 0, unknown: 0, total: 2, secrets: 0 }, + policies: { status: 'compliant', totalViolations: 0, blockingFailures: 0, failedPolicyIds: [] }, + }, +}; + +describe('AlertMailNotifier', () => { + beforeEach(() => { + vi.clearAllMocks(); + resetTransports(); + registerTransport('mail', { send } as never); + }); + + afterEach(() => resetTransports()); + + it('sends one email to the recipient with the event fields', async () => { + await new AlertMailNotifier('es').sendAlert({ + recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com' }, + alert: { id: 'a1', name: 'Críticas en api-gateway', description: null }, + event, + definition: getEventDefinition('code_report.analysis.completed') as EventDefinition, + suppressed: 3, + names: new Map([['svc-gateway', 'api-gateway']]), + }); + + expect(send).toHaveBeenCalledTimes(1); + const mail = send.mock.calls[0][0]; + expect(mail.to).toEqual(['ana@example.com']); + expect(mail.subject).toBe('[GitOps] Críticas en api-gateway: Análisis completado'); + expect(mail.content).toContain('api-gateway'); + expect(mail.content).toContain('Trivy'); + // payload values are escaped + expect(mail.content).toContain('<main>'); + expect(mail.content).toContain('3 eventos'); + expect(mail.content).not.toContain('{{'); + }); + + it('renders system notifications in English too', async () => { + await new AlertMailNotifier('en').sendSystemNotification({ + recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com' }, + kind: 'access_granted', + event: { ...event, type: 'access.granted' } as unknown as AnyDomainEvent, + names: { organization: 'Kettu', project: 'Web', role: 'Developer' }, + }); + + const mail = send.mock.calls[0][0]; + expect(mail.subject).toBe('You now have access to the project Web (Kettu)'); + expect(mail.content).toContain('with the role Developer'); + }); +}); diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.ts new file mode 100644 index 00000000..c3c59c71 --- /dev/null +++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts @@ -0,0 +1,116 @@ +import { MailNotification, notify, renderTemplateString } from '#lib/server/infra/notifications'; +import * as messages from '#lib/paraglide/messages.js'; + +// the base locale of `project.inlang`; `#lib/i18n` is client-oriented (stores, `$app/env`) +type SupportedLocale = 'es' | 'en'; +const DEFAULT_LOCALE: SupportedLocale = 'es'; +import type { AlertEmail, AlertNotifierPort, SystemEmail } from '../application/alert-engine'; +import { describeEventFields } from './event-summary'; + +type MessageFunction = ( + values?: Record, + options?: { locale?: SupportedLocale }, +) => string; + +/** Server-side translation of an i18n key; unknown keys fall back to the key itself. */ +export function translateKey( + id: string, + values: Record = {}, + locale: SupportedLocale = DEFAULT_LOCALE, +): string { + const message = (messages as Record)[id] as MessageFunction | undefined; + return message ? message(values, { locale }) : id; +} + +// minimal layout until the alert templates land (#81) +const LAYOUT = ` + +

{{ title }}

+

{{ intro }}

+{{{ details }}} +

{{ footer }}

+`; + +function detailsTable(rows: { label: string; value: string }[]): string { + if (rows.length === 0) return ''; + const body = rows + .map((row) => + renderTemplateString( + '{{ label }}{{ value }}', + row, + ), + ) + .join(''); + return `${body}
`; +} + +/** Emails for alerts and system notifications, one recipient per message. */ +export class AlertMailNotifier implements AlertNotifierPort { + constructor(private readonly locale: SupportedLocale = DEFAULT_LOCALE) {} + + private t(id: string, values?: Record) { + return translateKey(id, values, this.locale); + } + + async sendAlert(email: AlertEmail): Promise { + const eventLabel = this.t(email.definition.label); + const subject = this.t('alerts.email.alertSubject', { + alert: email.alert.name, + event: eventLabel, + }); + const rows = [ + { label: this.t('alerts.email.event'), value: eventLabel }, + { + label: this.t('alerts.email.occurredAt'), + value: new Date(email.event.occurredAt).toUTCString(), + }, + ...describeEventFields(email.event, email.definition, email.names).map((field) => ({ + label: this.t(field.label), + value: field.translate ? this.t(field.value) : field.value, + })), + ]; + const suppressed = + email.suppressed > 0 + ? `

${renderTemplateString('{{ text }}', { + text: this.t('alerts.email.suppressed', { count: email.suppressed }), + })}

` + : ''; + + const content = renderTemplateString(LAYOUT, { + title: email.alert.name, + intro: + email.alert.description || this.t('alerts.email.alertIntro', { alert: email.alert.name }), + details: detailsTable(rows) + suppressed, + footer: this.t('alerts.email.footer'), + }); + + await notify(new MailNotification({ to: email.recipient.email, subject, content })); + } + + async sendSystemNotification(email: SystemEmail): Promise { + const target = email.names.project + ? this.t('alerts.email.system.projectTarget', { + project: email.names.project, + organization: email.names.organization ?? '', + }) + : (email.names.organization ?? 'GitOps'); + const payload = email.event.payload as { name?: string; keyPrefix?: string }; + const values = { + target, + role: email.names.role ?? '', + name: payload.name ?? '', + prefix: payload.keyPrefix ?? '', + }; + const base = `alerts.email.system.${email.kind}`; + const subject = this.t(`${base}.subject`, values); + + const content = renderTemplateString(LAYOUT, { + title: subject, + intro: this.t(`${base}.body`, values), + details: '', + footer: this.t('alerts.email.systemFooter'), + }); + + await notify(new MailNotification({ to: email.recipient.email, subject, content })); + } +} diff --git a/src/modules/alerts/infrastructure/event-summary.ts b/src/modules/alerts/infrastructure/event-summary.ts new file mode 100644 index 00000000..eb3ec0f5 --- /dev/null +++ b/src/modules/alerts/infrastructure/event-summary.ts @@ -0,0 +1,59 @@ +import { getFieldValue, type EventDefinition } from '#lib/events/catalog'; +import type { AnyDomainEvent } from '#lib/server/events'; + +export type EventFieldLine = { + /** i18n key of the field label. */ + label: string; + value: string; + /** `value` is an i18n key (enum options, yes/no). */ + translate?: boolean; +}; + +function safeValue(event: AnyDomainEvent, key: string): unknown { + try { + return getFieldValue(event, key); + } catch { + return undefined; + } +} + +/** + * The catalog fields of an event as label/value lines for an email. Reference ids are replaced by + * the names in `names` when known; enum values and booleans become i18n keys. + */ +export function describeEventFields( + event: AnyDomainEvent, + definition: EventDefinition, + names: ReadonlyMap = new Map(), +): EventFieldLine[] { + const lines: EventFieldLine[] = []; + for (const field of definition.fields) { + const value = safeValue(event, field.key as string); + if (value === undefined || value === null || value === '') continue; + if (Array.isArray(value) && value.length === 0) continue; + + if (typeof value === 'boolean') { + lines.push({ + label: field.label, + value: value ? 'common.yes' : 'common.no', + translate: true, + }); + continue; + } + if (field.type === 'enum' && typeof value === 'string') { + const option = field.options?.find((candidate) => candidate.value === value); + lines.push( + option + ? { label: field.label, value: option.label, translate: true } + : { label: field.label, value }, + ); + continue; + } + const items = Array.isArray(value) ? value : [value]; + lines.push({ + label: field.label, + value: items.map((item) => names.get(String(item)) ?? String(item)).join(', '), + }); + } + return lines; +} diff --git a/src/modules/alerts/infrastructure/platform-directory.ts b/src/modules/alerts/infrastructure/platform-directory.ts new file mode 100644 index 00000000..295c5068 --- /dev/null +++ b/src/modules/alerts/infrastructure/platform-directory.ts @@ -0,0 +1,196 @@ +import type { FieldReference } from '#lib/events/catalog'; +import type { + AlertDirectory, + NameIds, + ReferenceOption, + ResolvedNames, + ScopeMember, + ScopeRole, +} from '../application/types'; +import type { AlertLocation } from '../domain/alert.domain'; + +type Named = { id: string; name: string }; + +type AccessRow = { + userId: string; + username: string; + email: string | null; + disabled?: boolean; + status: string; + scope: string; + organizationId: string | null; + projectId: string | null; + role: { id: string } | null; +}; + +/** The module services the directory reads from; wired in `index.ts`. */ +export type PlatformDirectoryDeps = { + projects: { + getProject(id: string): Promise<(Named & { organization?: Named | null }) | null>; + listProjectsByOrganization(organizationId: string): Promise; + }; + organizations: { getOrganization(id: string): Promise }; + access: { + listUsers( + scope: 'cluster' | 'organization' | 'project', + scopeId?: string, + ): Promise; + }; + roles: { + listRoles(scope: 'organization' | 'project', scopeId: string): Promise; + }; + codeReportServices: { listByProject(projectId: string): Promise }; + codeReportPolicies: { listByProject(projectId: string): Promise }; + vaultEnvironments: { listEnvironments(projectId: string): Promise }; + apiKeys: { listActiveApiKeysByProject(projectId: string): Promise }; +}; + +/** + * `AlertDirectory` on top of the other modules. A location covers an organization and all its + * projects, or one project; a failed lookup of one project yields no entries rather than an error. + */ +export class PlatformDirectory implements AlertDirectory { + constructor(private readonly deps: PlatformDirectoryDeps) {} + + private async projectsOf(location: AlertLocation): Promise { + if (location.scope === 'project' && location.projectId) { + const project = await this.deps.projects.getProject(location.projectId).catch(() => null); + return project && project.organization?.id === location.organizationId ? [project] : []; + } + return this.deps.projects.listProjectsByOrganization(location.organizationId).catch(() => []); + } + + private async perProject( + location: AlertLocation, + read: (projectId: string) => Promise, + ): Promise { + const projects = await this.projectsOf(location); + const rows = await Promise.all( + projects.map((project) => read(project.id).catch(() => [] as Named[])), + ); + return rows.flat().map((row) => ({ id: row.id, label: row.name })); + } + + private async accessRows(location: AlertLocation): Promise { + const organizationRows = await this.deps.access + .listUsers('organization', location.organizationId) + .catch(() => [] as AccessRow[]); + const projects = await this.projectsOf(location); + const projectRows = await Promise.all( + projects.map((project) => + this.deps.access.listUsers('project', project.id).catch(() => [] as AccessRow[]), + ), + ); + return [...organizationRows, ...projectRows.flat()].filter((row) => row.status === 'active'); + } + + async listMembers(location: AlertLocation): Promise { + const members = new Map(); + for (const row of await this.accessRows(location)) { + const member = members.get(row.userId) ?? { + userId: row.userId, + username: row.username, + email: row.email, + disabled: row.disabled ?? false, + roleIds: [], + }; + if (row.role?.id && !member.roleIds.includes(row.role.id)) member.roleIds.push(row.role.id); + members.set(row.userId, member); + } + return [...members.values()]; + } + + async listRoles(location: AlertLocation): Promise { + const organizationRoles = await this.deps.roles + .listRoles('organization', location.organizationId) + .catch(() => [] as Named[]); + const projectRoles = + location.scope === 'project' && location.projectId + ? await this.deps.roles.listRoles('project', location.projectId).catch(() => [] as Named[]) + : []; + return [...organizationRoles, ...projectRoles].map((role) => ({ + id: role.id, + name: role.name, + })); + } + + async listReferences( + reference: FieldReference, + location: AlertLocation, + ): Promise { + switch (reference) { + case 'project': + return (await this.projectsOf(location)).map((project) => ({ + id: project.id, + label: project.name, + })); + case 'code_report_service': + return this.perProject(location, (id) => this.deps.codeReportServices.listByProject(id)); + case 'code_report_policy': + return this.perProject(location, (id) => this.deps.codeReportPolicies.listByProject(id)); + case 'vault_environment': + return this.perProject(location, (id) => this.deps.vaultEnvironments.listEnvironments(id)); + case 'api_key': + return this.perProject(location, (id) => this.deps.apiKeys.listActiveApiKeysByProject(id)); + case 'user': + return (await this.listMembers(location)).map((member) => ({ + id: member.userId, + label: member.username, + })); + case 'role': { + const organizationRoles = await this.listRoles({ + ...location, + scope: 'organization', + projectId: null, + }); + const projectRoles = await this.perProject(location, (id) => + this.deps.roles.listRoles('project', id), + ); + return [ + ...organizationRoles.map((role) => ({ id: role.id, label: role.name })), + ...projectRoles, + ]; + } + default: + return []; + } + } + + async findUser(userId: string): Promise | null> { + const users = await this.deps.access.listUsers('cluster').catch(() => [] as AccessRow[]); + const user = users.find((row) => row.userId === userId); + return user + ? { + userId: user.userId, + username: user.username, + email: user.email, + disabled: user.disabled ?? false, + } + : null; + } + + async resolveNames(ids: NameIds): Promise { + const names: ResolvedNames = {}; + if (ids.organizationId) { + const organization = await this.deps.organizations + .getOrganization(ids.organizationId) + .catch(() => null); + if (organization) names.organization = organization.name; + } + if (ids.projectId) { + const project = await this.deps.projects.getProject(ids.projectId).catch(() => null); + if (project) names.project = project.name; + } + if (ids.roleId && (ids.projectId || ids.organizationId)) { + const roles = await this.deps.roles + .listRoles( + ids.projectId ? 'project' : 'organization', + (ids.projectId ?? ids.organizationId) as string, + ) + .catch(() => [] as Named[]); + const role = roles.find((candidate) => candidate.id === ids.roleId); + if (role) names.role = role.name; + } + return names; + } +} diff --git a/src/modules/alerts/infrastructure/repositories/alert.repository.ts b/src/modules/alerts/infrastructure/repositories/alert.repository.ts new file mode 100644 index 00000000..1cdf85ac --- /dev/null +++ b/src/modules/alerts/infrastructure/repositories/alert.repository.ts @@ -0,0 +1,61 @@ +import { AlertEntity } from '#lib/database/schemas'; +import { Repository } from '#lib/server/infra/repository'; +import { AlertDomain, type AlertFields, type AlertRow } from '../../domain/alert.domain'; + +/** Persistence port of the alerts module; `InMemoryAlertRepository` implements it in tests. */ +export interface AlertRepositoryPort { + findById(id: string): Promise; + listByOrganization(organizationId: string): Promise; + listByProject(projectId: string): Promise; + listEnabledByEventType(eventType: string): Promise; + create(row: AlertRow): Promise; + update(id: string, changes: Partial): Promise; + delete(id: string): Promise; +} + +export class AlertRepository extends Repository implements AlertRepositoryPort { + async findById(id: string): Promise { + const result = await this.db.select().from(AlertEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new AlertDomain(row) : null; + } + + /** Every alert of the organization, including those of its projects. */ + async listByOrganization(organizationId: string): Promise { + const result = await this.db + .select() + .from(AlertEntity) + .where({ organizationId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new AlertDomain(row)); + } + + async listByProject(projectId: string): Promise { + const result = await this.db + .select() + .from(AlertEntity) + .where({ projectId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new AlertDomain(row)); + } + + async listEnabledByEventType(eventType: string): Promise { + const result = await this.db.select().from(AlertEntity).where({ eventType, enabled: true }); + return result.rows.map((row: any) => new AlertDomain(row)); + } + + async create(row: AlertRow): Promise { + await this.db.insert(AlertEntity).values({ ...row }); + } + + async update(id: string, changes: Partial): Promise { + await this.db + .update(AlertEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async delete(id: string): Promise { + await this.db.delete(AlertEntity).where({ id }); + } +} diff --git a/src/modules/alerts/infrastructure/repositories/in-memory-alert.repository.ts b/src/modules/alerts/infrastructure/repositories/in-memory-alert.repository.ts new file mode 100644 index 00000000..1e627b9b --- /dev/null +++ b/src/modules/alerts/infrastructure/repositories/in-memory-alert.repository.ts @@ -0,0 +1,52 @@ +import { AlertDomain, type AlertFields, type AlertRow } from '../../domain/alert.domain'; +import type { AlertRepositoryPort } from './alert.repository'; + +/** In-memory fake for unit tests; stores copies so callers can't mutate the stored rows. */ +export class InMemoryAlertRepository implements AlertRepositoryPort { + rows: AlertRow[] = []; + failWrites = false; + + private copy(row: AlertRow): AlertDomain { + return new AlertDomain(structuredClone(row)); + } + + async findById(id: string) { + const row = this.rows.find((candidate) => candidate.id === id); + return row ? this.copy(row) : null; + } + + async listByOrganization(organizationId: string) { + return this.rows + .filter((row) => row.organizationId === organizationId) + .map((row) => this.copy(row)); + } + + async listByProject(projectId: string) { + return this.rows.filter((row) => row.projectId === projectId).map((row) => this.copy(row)); + } + + async listEnabledByEventType(eventType: string) { + return this.rows + .filter((row) => row.eventType === eventType && row.enabled) + .map((row) => this.copy(row)); + } + + async create(row: AlertRow) { + if (this.failWrites) throw new Error('GitDB write failed'); + this.rows.push(structuredClone(row)); + } + + async update(id: string, changes: Partial) { + if (this.failWrites) throw new Error('GitDB write failed'); + this.rows = this.rows.map((row) => + row.id === id + ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() } + : row, + ); + } + + async delete(id: string) { + if (this.failWrites) throw new Error('GitDB write failed'); + this.rows = this.rows.filter((row) => row.id !== id); + } +} diff --git a/src/modules/auth/application/user-access.service.ts b/src/modules/auth/application/user-access.service.ts index 1f4ef70e..5f8103fd 100644 --- a/src/modules/auth/application/user-access.service.ts +++ b/src/modules/auth/application/user-access.service.ts @@ -20,6 +20,7 @@ type UserAccessRow = { userId: string; username: string; email: string | null; + disabled: boolean; role: ReturnType['toJson']> | null; organizations: Array<{ id: string; name: string; slug: string; role: string | null }>; scope: RoleScope; @@ -581,6 +582,7 @@ export class UserAccessService { userId: entry.userId, username: entry.user?.username ?? 'Unknown user', email: entry.user?.email ?? null, + disabled: entry.user?.disabled ?? false, role: entry.role ? entry.role.toJson() : null, organizations: [], scope: entry.scope, @@ -614,6 +616,7 @@ export class UserAccessService { userId: user.id, username: user.username, email: user.email, + disabled: user.disabled, role: user.role ? user.role.toJson() : null, organizations: access .filter((entry) => entry.userId === user.id && entry.organization) diff --git a/src/modules/auth/domain/role-permissions.data.ts b/src/modules/auth/domain/role-permissions.data.ts index f8fe1d96..d1344b4f 100644 --- a/src/modules/auth/domain/role-permissions.data.ts +++ b/src/modules/auth/domain/role-permissions.data.ts @@ -17,6 +17,7 @@ export const ORGANIZATION_ADMIN_PERMISSIONS = [ 'organization:server-keys:all', 'organization:audit:all', 'organization:events:all', + 'organization:alerts:all', ]; export const ORGANIZATION_DEVELOPER_PERMISSIONS = [ @@ -31,6 +32,7 @@ export const PROJECT_ADMIN_PERMISSIONS = [ 'project:roles:all', 'project:server-keys:all', 'project:audit:all', + 'project:alerts:all', 'project:vault:secrets:all', 'project:vault:environments:all', 'project:vault:settings:all', @@ -44,6 +46,7 @@ export const PROJECT_ADMIN_PERMISSIONS = [ export const PROJECT_DEVELOPER_PERMISSIONS = [ 'project:project:read', + 'project:alerts:read', 'project:vault:secrets:read', 'project:vault:secrets:create', 'project:vault:secrets:update', @@ -80,6 +83,7 @@ export const PROJECT_VIEWER_PERMISSIONS = [ 'project:roles:read', 'project:server-keys:read', 'project:audit:read', + 'project:alerts:read', 'project:vault:secrets:read', 'project:vault:secrets:export', 'project:vault:environments:read', diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index dd18806d..fa0bb74e 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -59,6 +59,7 @@ export async function load({ locals, url }) { canReadOrgServerKeys, canReadOrgAudit, canReadOrgEvents, + canReadOrganizationAlerts, ] = await Promise.all([ orgSectionPermission('organization:projects:read'), orgSectionPermission('organization:users:read'), @@ -68,6 +69,7 @@ export async function load({ locals, url }) { orgSectionPermission('organization:server-keys:read'), orgSectionPermission('organization:audit:read'), orgSectionPermission('organization:events:read'), + orgSectionPermission('organization:alerts:read'), ]); const currentProjectSlug = url.pathname.match(/\/projects\/([^/]+)/)?.[1] ?? null; @@ -118,6 +120,7 @@ export async function load({ locals, url }) { canReadProjectRoles, canReadProjectServerKeys, canReadProjectAudit, + canReadProjectAlerts, canReadProjectVaultSecrets, canReadProjectVaultEnvironments, canReadProjectCodeReportReports, @@ -132,6 +135,7 @@ export async function load({ locals, url }) { projectSectionPermission('project:roles:read'), projectSectionPermission('project:server-keys:read'), projectSectionPermission('project:audit:read'), + projectSectionPermission('project:alerts:read'), projectSectionPermission('project:vault:secrets:read'), projectSectionPermission('project:vault:environments:read'), projectSectionPermission('project:codereport:reports:read'), @@ -170,11 +174,13 @@ export async function load({ locals, url }) { canReadOrgServerKeys, canReadOrgAudit, canReadOrgEvents, + canReadOrganizationAlerts, canReadProjectInfo, canReadProjectUsers, canReadProjectRoles, canReadProjectServerKeys, canReadProjectAudit, + canReadProjectAlerts, canReadProjectVault, canReadProjectCodeReport, canReadProjectStateIac, diff --git a/src/routes/api/alerts/+server.ts b/src/routes/api/alerts/+server.ts new file mode 100644 index 00000000..4ce1da0e --- /dev/null +++ b/src/routes/api/alerts/+server.ts @@ -0,0 +1,26 @@ +import { json } from '@sveltejs/kit'; +import { resolveLocation } from '#lib/server/alerts/access'; +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { createAlert, listAlerts } from '#lib/server/alerts/operations'; + +// GET /api/alerts?organizationId=… organization alerts +// GET /api/alerts?projectId=… project alerts, plus the organization alerts it inherits +export async function GET({ url, locals }) { + const lookup = await resolveLocation({ + organizationId: url.searchParams.get('organizationId'), + projectId: url.searchParams.get('projectId'), + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse(await listAlerts(locals, lookup.location)); +} + +// POST /api/alerts { organizationId | projectId, name, eventType, conditions, recipients, … } +export async function POST({ request, locals }) { + const body = await readJson(request); + const lookup = await resolveLocation({ + organizationId: typeof body.organizationId === 'string' ? body.organizationId : null, + projectId: typeof body.projectId === 'string' ? body.projectId : null, + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse(await createAlert(locals, lookup.location, body)); +} diff --git a/src/routes/api/alerts/[id]/+server.ts b/src/routes/api/alerts/[id]/+server.ts new file mode 100644 index 00000000..5a5d6b2b --- /dev/null +++ b/src/routes/api/alerts/[id]/+server.ts @@ -0,0 +1,18 @@ +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { deleteAlert, getAlert, updateAlert } from '#lib/server/alerts/operations'; + +export async function GET({ params, locals }) { + return toResponse(await getAlert(locals, params.id)); +} + +// partial update: omitted fields keep their value; the location of an alert never changes +export async function PATCH({ params, request, locals }) { + const input = await readJson(request); + delete input.organizationId; + delete input.projectId; + return toResponse(await updateAlert(locals, params.id, input)); +} + +export async function DELETE({ params, locals }) { + return toResponse(await deleteAlert(locals, params.id)); +} diff --git a/src/routes/api/alerts/[id]/test/+server.ts b/src/routes/api/alerts/[id]/test/+server.ts new file mode 100644 index 00000000..e817390d --- /dev/null +++ b/src/routes/api/alerts/[id]/test/+server.ts @@ -0,0 +1,8 @@ +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { testAlert } from '#lib/server/alerts/operations'; + +// POST /api/alerts//test { payload?, sampleProjectId? }: dry run, nothing is sent +export async function POST({ params, request, locals }) { + const body = await readJson(request); + return toResponse(await testAlert(locals, params.id, body)); +} diff --git a/src/routes/api/alerts/server.test.ts b/src/routes/api/alerts/server.test.ts new file mode 100644 index 00000000..62d21992 --- /dev/null +++ b/src/routes/api/alerts/server.test.ts @@ -0,0 +1,353 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +type Grants = Record; + +// grants per caller and context key (`org:` / `project:`) +const grants: { users: Record; apiKeys: Record } = { + users: {}, + apiKeys: {}, +}; + +function contextKey(context: { scope: string; organizationId?: string; projectId?: string }) { + return context.scope === 'project' + ? `project:${context.projectId}` + : `org:${context.organizationId}`; +} + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async (user: { id?: string } | null, permission: string, context: never) => + !!user?.id && (grants.users[user.id]?.[contextKey(context)] ?? []).includes(permission), + canApiKey: ( + apiKey: { id: string; projectId: string | null }, + permission: string, + context: { scope: string; projectId?: string }, + ) => { + if ( + apiKey.projectId && + (context.scope !== 'project' || context.projectId !== apiKey.projectId) + ) { + return false; + } + return (grants.apiKeys[apiKey.id] ?? []).includes(permission); + }, + }, +})); + +vi.mock('#modules/projects', () => ({ + projectService: { + getProject: async (id: string) => + ['p1', 'p2'].includes(id) ? { id, organization: { id: 'org-1' } } : null, + }, +})); + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => (id === 'org-1' ? { id, name: 'Kettu' } : null), + }, +})); + +vi.mock('#modules/alerts', async () => { + const domain = await import('#modules/alerts/domain/alert.domain'); + const { AlertService } = await import('#modules/alerts/application/alert.service'); + const { AlertEngine } = await import('#modules/alerts/application/alert-engine'); + const { RecipientResolver } = await import('#modules/alerts/application/recipient-resolver'); + const { FakeAlertDirectory } = await import('#modules/alerts/application/testing'); + const { InMemoryAlertRepository } = + await import('#modules/alerts/infrastructure/repositories/in-memory-alert.repository'); + const { buildSampleEvent } = await import('#modules/alerts/domain/sample-event'); + + const repository = new InMemoryAlertRepository(); + const directory = new FakeAlertDirectory(); + directory.members = [ + { + organizationId: 'org-1', + projectId: 'p1', + userId: 'admin', + username: 'admin', + email: 'admin@x.io', + disabled: false, + roleIds: ['r-admin'], + }, + ]; + directory.roles = [ + { organizationId: 'org-1', projectId: 'p1', id: 'r-admin', name: 'Project Admin' }, + ]; + let id = 0; + const alertService = new AlertService(repository, directory, { + generateId: () => `alert-${++id}`, + }); + const alertEngine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, async () => true), + notifier: { sendAlert: async () => {}, sendSystemNotification: async () => {} }, + logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }, + }); + return { + ...domain, + alertService, + alertEngine, + alertDirectory: directory, + buildSampleEvent, + repository, + }; +}); + +const alerts = await import('#modules/alerts'); +const repository = (alerts as unknown as { repository: { rows: unknown[] } }).repository; +const collection = await import('./+server'); +const item = await import('./[id]/+server'); +const test = await import('./[id]/test/+server'); + +const ADMIN_GRANTS = [ + 'project:alerts:read', + 'project:alerts:create', + 'project:alerts:update', + 'project:alerts:delete', + 'project:codereport:reports:read', +]; + +const guided = { + projectId: 'p1', + name: 'Críticas en api-gateway', + eventType: 'code_report.analysis.completed', + conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }], + recipients: { roleIds: ['r-admin'] }, + throttleMinutes: 30, +}; + +function call( + handler: (event: never) => Promise, + input: { + locals?: Record; + body?: unknown; + url?: string; + params?: Record; + }, +) { + return handler({ + locals: input.locals ?? {}, + params: input.params ?? {}, + url: new URL(input.url ?? 'http://localhost/api/alerts'), + request: { json: async () => input.body ?? {} }, + } as never); +} + +const admin = { user: { id: 'admin' } }; +const viewer = { user: { id: 'viewer' } }; + +describe('/api/alerts', () => { + beforeEach(() => { + repository.rows = []; + grants.users = { + admin: { 'project:p1': ADMIN_GRANTS }, + viewer: { 'project:p1': ['project:alerts:read', 'project:codereport:reports:read'] }, + // can manage alerts but not read code reports + vaultAdmin: { 'project:p1': ['project:alerts:create', 'project:vault:secrets:read'] }, + }; + grants.apiKeys = { 'key-p1': ADMIN_GRANTS, 'key-p2': ADMIN_GRANTS }; + }); + + it('rejects callers without identity or permission', async () => { + const anonymous = await call(collection.POST, { body: guided }); + expect(anonymous.status).toBe(403); + + const asViewer = await call(collection.POST, { locals: viewer, body: guided }); + expect(asViewer.status).toBe(403); + await expect(asViewer.json()).resolves.toEqual({ error: 'Forbidden' }); + expect(repository.rows).toHaveLength(0); + }); + + it('creates an alert and lists it', async () => { + const created = await call(collection.POST, { locals: admin, body: guided }); + expect(created.status).toBe(201); + const alert = (await created.json()) as { id: string }; + expect(alert).toMatchObject({ scope: 'project', projectId: 'p1', createdByUserId: 'admin' }); + + const listed = await call(collection.GET, { + locals: viewer, + url: 'http://localhost/api/alerts?projectId=p1', + }); + expect(listed.status).toBe(200); + await expect(listed.json()).resolves.toMatchObject({ + alerts: [{ id: alert.id }], + inherited: [], + }); + }); + + it('returns field errors for an invalid alert', async () => { + const response = await call(collection.POST, { + locals: admin, + body: { + ...guided, + conditions: [{ field: 'summary.critical', operator: 'contains', value: 1 }], + }, + }); + expect(response.status).toBe(400); + await expect(response.json()).resolves.toEqual({ + error: 'Invalid alert', + errors: { 'conditions.0.operator': 'invalid_operator' }, + }); + }); + + it('refuses an alert on events its author cannot read (anti-escalation)', async () => { + const response = await call(collection.POST, { + locals: { user: { id: 'vaultAdmin' } }, + body: guided, + }); + expect(response.status).toBe(400); + await expect(response.json()).resolves.toMatchObject({ errors: { eventType: 'forbidden' } }); + }); + + it('confines a project API key to its own project', async () => { + const own = await call(collection.POST, { + locals: { apiKey: { id: 'key-p1', projectId: 'p1', userId: null } }, + body: guided, + }); + expect(own.status).toBe(201); + const { id } = (await own.json()) as { id: string }; + + const foreign = { apiKey: { id: 'key-p2', projectId: 'p2', userId: null } }; + expect((await call(collection.POST, { locals: foreign, body: guided })).status).toBe(403); + expect( + ( + await call(collection.GET, { + locals: foreign, + url: 'http://localhost/api/alerts?projectId=p1', + }) + ).status, + ).toBe(403); + // the alert of another project is not even visible + expect((await call(item.DELETE, { locals: foreign, params: { id } })).status).toBe(404); + expect( + ( + await call(collection.GET, { + locals: foreign, + url: 'http://localhost/api/alerts?organizationId=org-1', + }) + ).status, + ).toBe(403); + }); + + it('validates the location', async () => { + expect( + (await call(collection.GET, { locals: admin, url: 'http://localhost/api/alerts' })).status, + ).toBe(400); + expect( + ( + await call(collection.GET, { + locals: admin, + url: 'http://localhost/api/alerts?projectId=missing', + }) + ).status, + ).toBe(404); + }); + + describe('/api/alerts/[id]', () => { + let id = ''; + beforeEach(async () => { + const created = await call(collection.POST, { locals: admin, body: guided }); + id = ((await created.json()) as { id: string }).id; + }); + + it('updates and deletes with the matching permissions', async () => { + const denied = await call(item.PATCH, { + locals: viewer, + params: { id }, + body: { enabled: false }, + }); + expect(denied.status).toBe(403); + + const patched = await call(item.PATCH, { + locals: admin, + params: { id }, + body: { enabled: false }, + }); + expect(patched.status).toBe(200); + await expect(patched.json()).resolves.toMatchObject({ enabled: false, name: guided.name }); + + expect((await call(item.DELETE, { locals: viewer, params: { id } })).status).toBe(403); + expect((await call(item.DELETE, { locals: admin, params: { id } })).status).toBe(200); + expect((await call(item.GET, { locals: admin, params: { id } })).status).toBe(404); + }); + + it('dry-runs an alert without sending anything', async () => { + expect((await call(test.POST, { locals: viewer, params: { id } })).status).toBe(403); + + const response = await call(test.POST, { locals: admin, params: { id } }); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toMatchObject({ + matched: true, + recipients: [{ userId: 'admin', username: 'admin' }], + deniedCount: 0, + event: { + type: 'code_report.analysis.completed', + payload: { summary: { critical: 1 } }, + projectId: 'p1', + }, + }); + + const noMatch = await call(test.POST, { + locals: admin, + params: { id }, + body: { payload: { summary: { critical: 0 } } }, + }); + await expect(noMatch.json()).resolves.toMatchObject({ matched: false }); + }); + }); +}); + +describe('/api/events/catalog', () => { + const catalog = () => import('../events/catalog/+server'); + + it('lists only the project events the caller can read', async () => { + grants.users = { viewer: { 'project:p1': ['project:codereport:reports:read'] } }; + const { GET } = await catalog(); + const response = await call(GET, { + locals: viewer, + url: 'http://localhost/api/events/catalog?scope=project&projectId=p1', + }); + expect(response.status).toBe(200); + const { events } = (await response.json()) as { + events: Array<{ + type: string; + scope: string; + fields: Array<{ key: string; derived?: boolean }>; + }>; + }; + expect(events.length).toBeGreaterThan(0); + expect(events.every((event) => event.type.startsWith('code_report.'))).toBe(true); + const completed = events.find((event) => event.type === 'code_report.analysis.completed'); + expect(completed?.fields.find((field) => field.key === 'hasVulnerabilities')).toMatchObject({ + derived: true, + }); + // a project alert has no project field to filter on + expect(completed?.fields.some((field) => field.key === 'projectId')).toBe(false); + }); + + it('adds the project field to project events in an organization', async () => { + grants.users = { admin: { 'org:org-1': ['organization:projects:read'] } }; + const { GET } = await catalog(); + const response = await call(GET, { + locals: admin, + url: 'http://localhost/api/events/catalog?scope=organization&organizationId=org-1', + }); + const { events } = (await response.json()) as { + events: Array<{ type: string; fields: Array<{ key: string }> }>; + }; + const completed = events.find((event) => event.type === 'code_report.analysis.completed'); + expect(completed?.fields.some((field) => field.key === 'projectId')).toBe(true); + // organization events need their own permission + expect(events.some((event) => event.type === 'organization.updated')).toBe(false); + }); + + it('requires a project for the project scope', async () => { + const { GET } = await catalog(); + const response = await call(GET, { + locals: admin, + url: 'http://localhost/api/events/catalog?scope=project', + }); + expect(response.status).toBe(400); + }); +}); diff --git a/src/routes/api/alerts/test/+server.ts b/src/routes/api/alerts/test/+server.ts new file mode 100644 index 00000000..b7184e03 --- /dev/null +++ b/src/routes/api/alerts/test/+server.ts @@ -0,0 +1,15 @@ +import { json } from '@sveltejs/kit'; +import { resolveLocation } from '#lib/server/alerts/access'; +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { testDraftAlert } from '#lib/server/alerts/operations'; + +// POST /api/alerts/test { organizationId | projectId, …alert, payload?, sampleProjectId? }: dry run of an unsaved alert +export async function POST({ request, locals }) { + const body = await readJson(request); + const lookup = await resolveLocation({ + organizationId: typeof body.organizationId === 'string' ? body.organizationId : null, + projectId: typeof body.projectId === 'string' ? body.projectId : null, + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse(await testDraftAlert(locals, lookup.location, body)); +} diff --git a/src/routes/api/events/catalog/+server.ts b/src/routes/api/events/catalog/+server.ts new file mode 100644 index 00000000..9e07a7dd --- /dev/null +++ b/src/routes/api/events/catalog/+server.ts @@ -0,0 +1,22 @@ +import { json } from '@sveltejs/kit'; +import { resolveLocation } from '#lib/server/alerts/access'; +import { listCatalog } from '#lib/server/alerts/operations'; + +// GET /api/events/catalog?scope=project&projectId=… | ?scope=organization&organizationId=… +// alertable events the caller may read in that scope, with the fields an alert can filter on +export async function GET({ url, locals }) { + const scope = url.searchParams.get('scope') ?? 'organization'; + if (scope !== 'organization' && scope !== 'project') { + return json({ error: 'scope must be organization or project' }, { status: 400 }); + } + const projectId = scope === 'project' ? url.searchParams.get('projectId') : null; + if (scope === 'project' && !projectId) { + return json({ error: 'projectId is required' }, { status: 400 }); + } + const lookup = await resolveLocation({ + organizationId: url.searchParams.get('organizationId'), + projectId, + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return json({ events: await listCatalog(locals, lookup.location) }); +}