diff --git a/.env.example b/.env.example index 0c869720..08039b46 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,7 @@ GITDB_REPOSITORY_URL=https://github.com/your-org/your-gitdb-repository.git GITDB_ENCRYPTION_KEY=replace-with-a-long-random-secret +# Public URL of the app: SvelteKit's CSRF check and the absolute links in emails ORIGIN=http://localhost:3000 # Optional GitDB configuration @@ -20,15 +21,19 @@ GITDB_SYNC_POLL_SECONDS=60 # GITDB_USERNAME= # GITDB_PASSWORD= -# Optional SMTP notifications +# Optional SMTP notifications: invitations, password resets, alerts and access notices. +# Without HOST and FROM no email is sent (alerts are kept, the UI shows a warning). +# Links in emails are built from ORIGIN above; without it emails go out without links. +# For local testing: `docker compose --profile mail up mailpit`, HOST=localhost, PORT=1025, +# then read the emails at http://localhost:8025 # NOTIFICATION_SMTP_HOST=smtp.example.com -# NOTIFICATION_SMTP_PORT=587 -# NOTIFICATION_SMTP_SECURE=false -# NOTIFICATION_SMTP_USER= +# NOTIFICATION_SMTP_PORT=587 # 465 turns TLS on by default +# NOTIFICATION_SMTP_SECURE=false # force TLS on/off +# NOTIFICATION_SMTP_USER= # USER and PASSWORD go together # NOTIFICATION_SMTP_PASSWORD= # NOTIFICATION_SMTP_FROM=noreply@example.com # NOTIFICATION_SMTP_FROM_NAME=GitOps -# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true +# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true # only set false for self-signed test servers # Optional cluster-wide Google sign-in (OpenID Connect). Shown on the login page when both the # client ID and secret are set. Redirect URI to register in GCP: /auth/sso/google/callback @@ -62,3 +67,8 @@ GITDB_SYNC_POLL_SECONDS=60 # Pepper used to hash user passwords and sign sessions GITDB_ENCRYPTION_KEY="development" + +# How long the organization events page (/org//settings/events) keeps events and their +# acknowledgements, e.g. 30d, 12h, 45m (a bare number means seconds). Default: 7d. +# Events live in memory: a restart clears them and each replica keeps its own list. +# GITOPS_EVENTS_EXPIRATION=7d diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..34fc3d42 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +## 1.3.6 — 2026-11-20 + +- Gestión de alertas con condiciones configurables y destinatarios. +- Motor de alertas por email con plantillas y cola con reintentos. +- Registro de eventos de organización y proyecto con reconocimiento. +- Mejoras de acceso y compatibilidad con Google SSO. diff --git a/CLAUDE.md b/CLAUDE.md index db87a1fc..a6f7e76e 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 @@ -119,6 +119,105 @@ Bitbucket, and GitLab; in production, ensure SSH authentication credentials are SvelteKit's CSRF Origin check depends on this value instead of deriving it from the incoming Host header, preventing bypasses when running behind a proxy that rewrites Host headers. +## Domain events + +Services announce what happened on an in-process event bus in `#lib/server/events`; the design is +in `docs/adr/0001-event-bus-and-alerts.md`. + +- Names: `..`, snake_case, past participle + (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). Declare each type + and its payload in `DomainEventMap` (`src/lib/events/domain-events.ts`, shared with the client). +- Every event needs an `EventDefinition` in the catalog (`src/lib/events/catalog/`, one + `.events.ts` per module): scope, `readPermission`, `alertable` and its filterable fields. + `EVENT_CATALOG` is exhaustive and field keys without `derive` are checked against the payload at + compile time. Labels are i18n keys (`events..label`, `.description`, + `.fields.`, `events.options..`) and must exist in `es.json` and `en.json` + (enforced by a test). +- Publish only **after** the GitDB write succeeded, with the right `scope` + (`organizationId` / `projectId`). `publish()` returns immediately; handlers run asynchronously, + in order per subscriber, and a failing handler is only logged. Use `publishAfterWrite` + (`#lib/server/events/publish`) so resolving the scope or publishing can never fail a write that + already succeeded; `resolveProjectScope` adds the organization to project events. +- Delivery is at-most-once and per process; events are not persisted. +- The actor comes from the request context (`userId` / `apiKeyId` set in `hooks.server.ts`), + falling back to `system`. +- Inject `EventBus` through the service constructor from the module's `index.ts`; only composition + roots import the `eventBus` singleton. In unit tests use `RecordingEventBus` from + `#lib/server/events/testing`. +- Payloads **never** contain secrets (vault values, invitation/reset tokens or URLs, hashes, API + keys), and alert recipients are always filtered with `cancanService`. +- `eventLog` (`#lib/server/events`) keeps recent events in memory for + `/org//settings/events`, where users with `organization:events:read` see the events they + are allowed to read (each definition's `readPermission`, checked in the event's project or + organization) and, with `organization:events:update`, acknowledge them. Only the default + Organization Admin role gets `organization:events:all`; existing roles are not migrated (enable + 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`); a failed email + only affects that recipient. An organization alert and a project alert on the same event fire + independently. +- Email (`#lib/server/infra/notifications`): every email is wrapped by `renderEmail()` in + `src/notifications/email/_layout.html` (header, content, footer with the reason and a manage + link). Alerts use `alert.html` (field table built from the catalog) unless the definition sets + `mailTemplate` (`alert-code-report-analysis.html`); `link(context)` gives the app path of the + resource and `mailSummary(payload)` the subject summary (`[GitOps] : `). System + notices use `system-access-changed.html` / `system-security-notice.html`. Escape every user or + event value with `{{ }}`; `{{{ }}}` only for HTML built internally with `renderTemplateString`. + Texts are `alerts.email.*`, in the recipient's locale or English. Links are absolute with + `ORIGIN` (`absoluteUrl()`), omitted without it. These functions never reach the client: the + catalog endpoint strips them. +- Sending: alert and system emails go through `mailQueue` (concurrency 3, `withRetry` 4 attempts + 1 s → 4 s → 16 s with jitter, only for `isRetryableMailError`: network errors and 4xx replies). + Definitive failures are logged by `createLogger('mail')` with the alert, the event and a + recipient hash, never the content or the address. `registerMailShutdown()` drains it on + `sveltekit:shutdown` (10 s). Invitations and password resets call `notify()` directly: their + tokens must not travel through the bus or the queue. Without SMTP (`isMailConfigured()`), the + engine skips events (debug log), warns once at startup and the alert pages show a banner. +- 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. + +- UI: `/org//settings/alerts` and `/org//projects//settings/alerts` (list, `new`, + `[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`, + `test`, `toggle`, `delete`; everything works without JavaScript). Components live in + `#lib/components/alerts/`: `ConditionBuilder` renders fields, operators and inputs only from the + `CatalogEntry` it receives (tested with `svelte/server` in `ConditionBuilder.test.ts`; Vitest + compiles `.svelte` through `vitest.config.ts`). Project pages also list the inherited + organization alerts, read-only. Error codes map to `alerts.errors.`. + +Making an event alertable: + +1. Declare the payload in `DomainEventMap` and publish it with `publishAfterWrite` and the right + 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, the engine and the UI pick it up. + ## Authorization Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts` @@ -158,8 +257,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` +- **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. @@ -168,11 +267,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 +- **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/README.md b/README.md index 71f56bfd..d6a87575 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ operational data versioned and auditable in Git. - Cluster-wide Google sign-in (OpenID Connect) alongside local email and password login. - Security reporting for vulnerabilities, SBOMs, secrets, licenses, and services. - Pulumi state, history, and lock visibility for S3 and Google Cloud Storage backends. +- Email alerts on platform events (security analyses, vault, projects, access), with filters + built from an event catalog. - Git-backed, auditable application data through GitDB. ## Get started @@ -119,6 +121,74 @@ automatically, because the domain is checked against the Workspace `hd` claim, n address. If the variables are inconsistent (only one credential set, an invalid domain, or automatic sign-up without domains), the Google button is hidden and the reason is logged. +### Alerts + +Organizations and projects can get an email when something happens. Alerts live in **Settings → +Alerts** of the organization (they cover all of its projects) or of a project. Each alert watches +one event, filters it on the event's fields and emails users or roles. The same event can fire an +organization alert and a project alert; each one sends its own email. + +Guided example: *tell the security team when an analysis of the `api-gateway` service has critical +vulnerabilities*. + +1. Open the project's **Settings → Alerts** and click **Create alert**. +2. Event: **Analysis completed** (`code_report.analysis.completed`). +3. Conditions, matching **all**: **Service** *is* `api-gateway`, and **Critical vulnerabilities** + *greater than* `0`. +4. Recipients: the **Project Admin** role. Throttle: one email every **30** minutes at most. +5. **Test alert** shows whether an example event matches and who would get the email, without + sending anything. Then **Create alert**. + +The same alert through the API (`gvs_` project keys only manage alerts of their own project): + +```bash +curl -X POST "$ORIGIN/api/alerts" \ + -H "Authorization: Bearer $GITOPS_API_KEY" -H "Content-Type: application/json" \ + -d '{ + "projectId": "", + "name": "Critical vulnerabilities in api-gateway", + "eventType": "code_report.analysis.completed", + "match": "all", + "conditions": [ + { "field": "serviceId", "operator": "eq", "value": "" }, + { "field": "summary.critical", "operator": "gt", "value": 0 } + ], + "recipients": { "roleIds": [""] }, + "throttleMinutes": 30 + }' +``` + +`GET /api/events/catalog?scope=project&projectId=` lists the events you may alert on and their +fields. Only recipients allowed to view the event get the email, and you can only create alerts on +events you can view yourself. Some notifications are always on: users are told when their access to +an organization or project changes and when a personal API key is created on their account. + +### Email + +Invitations, password resets, alerts and access notices are sent by SMTP: + +| Variable | Default | | +|---|---|---| +| `NOTIFICATION_SMTP_HOST` | — | Required to send email | +| `NOTIFICATION_SMTP_FROM` | — | Required, sender address | +| `NOTIFICATION_SMTP_FROM_NAME` | — | Sender display name | +| `NOTIFICATION_SMTP_PORT` | `587` | `465` turns TLS on by default | +| `NOTIFICATION_SMTP_SECURE` | port-based | Force TLS on or off | +| `NOTIFICATION_SMTP_USER` / `NOTIFICATION_SMTP_PASSWORD` | — | Set both or neither | +| `NOTIFICATION_SMTP_REJECT_UNAUTHORIZED` | `true` | `false` only for self-signed test servers | +| `ORIGIN` | — | Public URL; links in emails are absolute. Without it emails have no links | + +Without SMTP nothing breaks: alerts are kept, the alert pages show a warning and the server logs +it once at startup. Alert and notice emails go through an in-process queue (3 at a time) that +retries network errors and temporary SMTP replies (4 attempts: 1 s, 4 s, 16 s) and is drained for +up to 10 s on shutdown; invitations and password resets are sent directly because their links carry +tokens. Emails are in the recipient's language when known, English otherwise. + +To try them locally, start [Mailpit](https://mailpit.axllent.org/) with +`docker compose --profile mail up mailpit`, set `NOTIFICATION_SMTP_HOST=localhost`, +`NOTIFICATION_SMTP_PORT=1025` and `NOTIFICATION_SMTP_FROM=gitops@localhost`, and open +http://localhost:8025. + ## Development ```bash diff --git a/docker-compose.yml b/docker-compose.yml index b96ea9e2..5f284fdb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,3 +13,13 @@ services: - ./data:/app/data - /run/host-services/ssh-auth.sock:/ssh-agent restart: unless-stopped + + # local SMTP for trying emails: `docker compose --profile mail up`, then set + # NOTIFICATION_SMTP_HOST=mailpit (or localhost outside Docker), NOTIFICATION_SMTP_PORT=1025, + # NOTIFICATION_SMTP_FROM=gitops@localhost and open http://localhost:8025 + mailpit: + image: axllent/mailpit:v1.21 + profiles: ['mail'] + ports: + - '1025:1025' + - '8025:8025' diff --git a/docs/adr/0001-event-bus-and-alerts.md b/docs/adr/0001-event-bus-and-alerts.md new file mode 100644 index 00000000..10d04511 --- /dev/null +++ b/docs/adr/0001-event-bus-and-alerts.md @@ -0,0 +1,128 @@ +# ADR 0001: Local domain event bus and configurable alerts + +- Status: Proposed +- Date: 2026-11-20 +- Issues: #76 (epic), #77 (this ADR and the `EventBus` class) + +## Context + +Notifications are direct calls from services to concrete notifiers (`InvitationNotifier`, +`PasswordResetNotifier`). To let organization and project admins create **configurable alerts** +("when `code_report.analysis.completed` happens for service `api-gateway` with critical +vulnerabilities, email these users or roles"), services need to announce what happened without +knowing who listens. + +Constraints: GitDB is the only persistence layer, the app runs as a single SvelteKit process per +replica, and we do not want to operate a broker (Redis, Kafka, a queue) for this. + +## Decision + +Services publish **typed domain events** on an **in-process event bus** +(`#lib/server/events`). An alert engine (#79) subscribes to every event, matches the alerts +configured for the event's scope and notifies recipients by email. + +``` +Service ──publish(type, payload)──▶ EventBus (in-process) ──▶ AlertEngine ('*') ──▶ notify(Mail) +``` + +### 1. Event names + +`..` in **snake_case**, the action as a **past participle**. The +resource may be omitted when the module is the resource. + +- `code_report.analysis.completed`, `code_report.analysis.failed`, `code_report.policy.violated` +- `vault.secret.created`, `vault.env.imported` +- `project.created`, `access.granted`, `api_key.revoked` + +Each type and its payload is declared in `DomainEventMap` (`src/lib/server/events/types.ts`), so +`publish()` and `subscribe()` are type-checked end to end. + +### 2. Delivery semantics + +- Publish **after** the GitDB write has succeeded (after the repository `await`). A failed write + publishes nothing. +- **Asynchronous** dispatch: `publish()` builds the envelope and returns it immediately; handlers + run on later microtasks and add no latency to the request. +- **At-most-once**: events in flight when the process dies are lost. This is acceptable for + alerts and must not be relied on for anything that needs a guarantee. +- **Per process**: an event published in one replica does not reach the others. Multi-replica + delivery is out of scope for v1. +- **Ordering**: each subscriber receives events in publish order (a per-subscriber queue). A slow + subscriber does not delay other subscribers. +- **Isolation**: every handler runs in its own `try/catch`. A failure is logged through + `createLogger('events')` with the event `type` and `id`, and never reaches the publisher, other + handlers, or later events. +- `drain()` waits for pending handlers (tests, graceful shutdown). + +### 3. Persistence + +- **Alerts** are configuration and are stored in **GitDB** (auditable, consistent with the rest of + the platform). +- **Events are not persisted in GitDB.** For the organization events page (`/org//settings/events`), + an in-memory log (`eventLog`, `InMemoryEventLog`) subscribes to the bus and keeps recent events + together with a shared acknowledgement (who and when). Retention is configured with + `GITOPS_EVENTS_EXPIRATION` (`30d`, `12h`, `45m`, a bare number is seconds; default `7d`), capped + at 10,000 events. Like the bus, it is per process: a restart clears it, including the + acknowledgements, and each replica shows its own list. Persisting events (and acks) in GitDB + was considered and rejected for now: one commit per event and per ack. +- **Alert executions** (firing history) are **not** stored in GitDB in v1, to avoid one commit per + email sent: only logs, plus optionally an in-memory buffer of the last N firings per alert. + +### 4. Actor + +`#lib/server/request-context` (`AsyncLocalStorage`) carries the request actor. Besides the commit +identity (`name`, `email`) it now carries `userId` for sessions and `apiKeyId` / +`apiKeyProjectId` for API keys, set by `hooks.server.ts`. The bus resolves the event actor from it +without changing service signatures: + +| Request context | `event.actor` | +| ------------------------------- | ------------------------------------------ | +| `apiKeyId` set | `{ kind: 'api_key', apiKeyId, projectId }` | +| `userId` set | `{ kind: 'user', userId }` | +| none (startup, background work) | `{ kind: 'system' }` | + +Publishers may pass an explicit `actor` to override it. Only `name` and `email` reach GitDB. + +### 5. Security rules (mandatory for the whole epic) + +- Payloads **never** contain secrets: no vault values, invitation or password reset tokens or + URLs, password or token hashes, or API keys (a `keyPrefix` is fine). +- No recipient receives information about a resource they cannot read: recipients are **always** + filtered with `cancanService` against the event's read permission and scope. + +## Implementation + +``` +src/lib/server/events/ + types.ts DomainEventMap, DomainEvent, EventActor, EventScope + event-bus.ts EventBus interface + InProcessEventBus + testing.ts RecordingEventBus for service unit tests + index.ts HMR-safe `eventBus` singleton + exports + event-bus.test.ts +``` + +- The singleton lives on `globalThis` (`Symbol.for('gitops.events.bus')`) so Vite HMR does not + create a second bus with duplicated subscribers in development. +- Services receive an `EventBus` through their **constructor** from their module's `index.ts` + (composition root); only composition roots import the `eventBus` singleton. Unit tests inject a + `RecordingEventBus` and assert on `events` / `ofType()`. +- No new dependencies. + +## Consequences + +- Services stay decoupled from alerts; adding a new consumer means subscribing, not editing + services. +- Delivery is best effort. If we later need cross-replica delivery or guarantees, the + `EventBus` interface allows swapping the implementation (e.g. an outbox in GitDB or a broker) + without touching publishers. +- Every new event must respect the payload rules above and is covered by a no-leak test (#78). + +## Alternatives considered + +- **External broker (Redis pub/sub, Kafka, a queue)**: delivery across replicas and durability, + at the cost of a new piece of infrastructure to run for a feature that tolerates losses. Rejected + for v1. +- **Node `EventEmitter`**: synchronous dispatch, a throwing listener breaks the publisher, and no + typing per event. Rejected in favour of a small dedicated class. +- **Persisting events in GitDB**: one commit per event is too much write volume and noise in the + audit history. diff --git a/e2e/env-private.ts b/e2e/env-private.ts new file mode 100644 index 00000000..e355c661 --- /dev/null +++ b/e2e/env-private.ts @@ -0,0 +1,31 @@ +// Stand-in for SvelteKit's `$app/env/private` when Playwright's global setup imports app modules +// in-process (GitDB start + seed). Imported after global-setup assigns process.env, so these +// snapshots see the throwaway E2E configuration. Keep in sync with `src/env.ts`. + +export const GITDB_REPOSITORY_URL = process.env.GITDB_REPOSITORY_URL; +export const GITDB_BRANCH = process.env.GITDB_BRANCH; +export const GITDB_TOKEN = process.env.GITDB_TOKEN; +export const GITDB_USERNAME = process.env.GITDB_USERNAME; +export const GITDB_PASSWORD = process.env.GITDB_PASSWORD; +export const GITDB_AUTHOR_NAME = process.env.GITDB_AUTHOR_NAME; +export const GITDB_AUTHOR_EMAIL = process.env.GITDB_AUTHOR_EMAIL; +export const GITDB_SYNC_POLL_SECONDS = process.env.GITDB_SYNC_POLL_SECONDS; +export const GITDB_SYNC_MODE = process.env.GITDB_SYNC_MODE; +export const GITDB_DATA_PATH = process.env.GITDB_DATA_PATH; +export const GITDB_ENCRYPTION_KEY = process.env.GITDB_ENCRYPTION_KEY; +export const VAULT_ENCRYPTION_KEY = process.env.VAULT_ENCRYPTION_KEY; +export const ORIGIN = process.env.ORIGIN; +export const NOTIFICATION_SMTP_HOST = process.env.NOTIFICATION_SMTP_HOST; +export const NOTIFICATION_SMTP_PORT = process.env.NOTIFICATION_SMTP_PORT; +export const NOTIFICATION_SMTP_SECURE = process.env.NOTIFICATION_SMTP_SECURE; +export const NOTIFICATION_SMTP_USER = process.env.NOTIFICATION_SMTP_USER; +export const NOTIFICATION_SMTP_PASSWORD = process.env.NOTIFICATION_SMTP_PASSWORD; +export const NOTIFICATION_SMTP_FROM = process.env.NOTIFICATION_SMTP_FROM; +export const NOTIFICATION_SMTP_FROM_NAME = process.env.NOTIFICATION_SMTP_FROM_NAME; +export const NOTIFICATION_SMTP_REJECT_UNAUTHORIZED = + process.env.NOTIFICATION_SMTP_REJECT_UNAUTHORIZED; +export const GOOGLE_SSO_CLIENT_ID = process.env.GOOGLE_SSO_CLIENT_ID; +export const GOOGLE_SSO_CLIENT_SECRET = process.env.GOOGLE_SSO_CLIENT_SECRET; +export const GOOGLE_SSO_ALLOWED_DOMAINS = process.env.GOOGLE_SSO_ALLOWED_DOMAINS; +export const GOOGLE_SSO_AUTO_PROVISION = process.env.GOOGLE_SSO_AUTO_PROVISION; +export const GITOPS_EVENTS_EXPIRATION = process.env.GITOPS_EVENTS_EXPIRATION; diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index 97ba1be4..eec93581 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -49,6 +49,15 @@ function buildEnv(): Record { GITDB_USERNAME: '', GITDB_TOKEN: '', GITDB_PASSWORD: '', + // never reach a real SMTP from a developer's `.env`: the suite runs with email disabled + NOTIFICATION_SMTP_HOST: '', + NOTIFICATION_SMTP_PORT: '', + NOTIFICATION_SMTP_SECURE: '', + NOTIFICATION_SMTP_USER: '', + NOTIFICATION_SMTP_PASSWORD: '', + NOTIFICATION_SMTP_FROM: '', + NOTIFICATION_SMTP_FROM_NAME: '', + NOTIFICATION_SMTP_REJECT_UNAUTHORIZED: '', PORT: String(E2E_PORT), }; } diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts new file mode 100644 index 00000000..d7e3e1ed --- /dev/null +++ b/e2e/specs/alerts.spec.ts @@ -0,0 +1,194 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { expectAllowed, expectDenied } from '../fixtures/expect-access'; +import { E2E_BASE_URL } from '../global-setup'; + +const seed = getSeed(); +const projectBase = `/org/${seed.primaryOrgSlug}/projects/${seed.primaryProjectSlug}`; +const alertsUrl = `${projectBase}/settings/alerts`; +const orgAlertsUrl = `/org/${seed.primaryOrgSlug}/settings/alerts`; + +const GUIDED_NAME = 'Críticas en el servicio sembrado'; + +// the editor is interactive only once hydrated: before that, a select change is reset by Svelte +async function openEditor(page: import('@playwright/test').Page, url: string) { + await page.goto(url); + await page.waitForLoadState('networkidle'); +} + +test.describe.configure({ mode: 'serial' }); + +test.describe('project alerts', () => { + test('a project admin creates the guided example and tests it first', async ({ + page, + loginAs, + }) => { + await loginAs('projectAdmin'); + await expectAllowed(page, alertsUrl); + await expect(page.getByText('Todavía no hay alertas')).toBeVisible(); + // e2e runs without SMTP: the page says alerts won't be sent + await expect(page.getByTestId('mail-disabled')).toBeVisible(); + await expect(page.getByRole('link', { name: 'Crear alerta' }).first()).toHaveAttribute( + 'href', + `${alertsUrl}/new`, + ); + await openEditor(page, `${alertsUrl}/new`); + + // step 1: event + await page.getByLabel('Nombre', { exact: true }).fill(GUIDED_NAME); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' }); + + // step 2: Servicio es · Vulnerabilidades críticas mayor que 0 + const builder = page.getByTestId('condition-builder'); + await builder.getByRole('button', { name: 'Añadir condición' }).click(); + const first = builder.getByTestId('condition-row').nth(0); + await first.getByLabel('Campo').selectOption({ label: 'Servicio' }); + await first.getByLabel('Operador').selectOption({ label: 'es' }); + await first.getByRole('radio', { name: 'E2E Seeded Service' }).check(); + + await builder.getByRole('button', { name: 'Añadir condición' }).click(); + const second = builder.getByTestId('condition-row').nth(1); + await second.getByLabel('Campo').selectOption({ label: 'Vulnerabilidades críticas' }); + await second.getByLabel('Operador').selectOption({ label: 'mayor que' }); + await second.getByLabel('Valor').fill('0'); + + // step 3: recipients and throttle + await page.getByRole('checkbox', { name: 'Project Admin' }).check(); + await page.getByLabel('No enviar más de un email cada (minutos)').fill('30'); + + // step 4: dry run, nothing is sent + await page.getByRole('button', { name: 'Probar alerta' }).click(); + const result = page.getByTestId('alert-test-result'); + await expect(result).toContainText('El evento de ejemplo cumple las condiciones.'); + await expect(result).toContainText(seed.personas.projectAdmin.username); + await expect(result).toContainText('no se ha enviado ningún email'); + + await page.getByRole('button', { name: 'Crear alerta' }).click(); + await expect(page).toHaveURL(new RegExp(`${alertsUrl}\\?saved=`)); + + const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME }); + await expect(row).toBeVisible(); + await expect(row.getByTestId('alert-summary')).toHaveText( + 'Servicio es E2E Seeded Service y Vulnerabilidades críticas mayor que 0', + ); + await expect(row).toContainText('Project Admin'); + await expect(row).toContainText('Máx. un email cada 30 min'); + await expect(row.getByRole('switch')).toHaveAttribute('aria-checked', 'true'); + }); + + test('server validation errors show next to their field', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await openEditor(page, `${alertsUrl}/new`); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' }); + await page.getByRole('button', { name: 'Crear alerta' }).click(); + + await expect(page.getByText('Este campo es obligatorio.').first()).toBeVisible(); + await expect(page.getByLabel('Nombre', { exact: true })).toHaveAttribute( + 'aria-describedby', + 'alert-name-error', + ); + }); + + test('a project viewer sees the list without any management action', async ({ + page, + loginAs, + }) => { + await loginAs('projectViewer'); + await expectAllowed(page, alertsUrl); + const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME }); + await expect(row).toBeVisible(); + await expect(page.getByRole('link', { name: 'Crear alerta' })).toHaveCount(0); + await expect(row.getByRole('link', { name: 'Editar' })).toHaveCount(0); + await expect(row.getByRole('button', { name: 'Borrar' })).toHaveCount(0); + await expect(row.getByRole('switch')).toHaveCount(0); + + // the server refuses the same actions when they are posted directly + const headers = { origin: E2E_BASE_URL }; + const save = await page.request.post(`${alertsUrl}/new?/save`, { + headers, + form: { name: 'x', eventType: 'code_report.analysis.completed', roleIds: 'any' }, + }); + expect(save.status()).toBe(403); + + const api = await page.request.post('/api/alerts', { + data: { projectId: 'irrelevant', name: 'x' }, + }); + expect([403, 404]).toContain(api.status()); + await expectDenied(page, `${alertsUrl}/new`); + }); + + test('the sidebar only shows alerts to people who can read them', async ({ page, loginAs }) => { + await loginAs('projectViewer'); + await page.goto(`${projectBase}/settings/overview`); + await expect(page.locator(`a[href="${alertsUrl}"]`)).toHaveCount(1); + + await loginAs('vaultSecretsOnly'); + await page.goto(`${projectBase}/vault`); + await expect(page.locator(`a[href="${alertsUrl}"]`)).toHaveCount(0); + await expectDenied(page, alertsUrl); + }); + + test('people outside the project cannot reach its alerts', async ({ page, loginAs }) => { + await loginAs('projectOutsider'); + await expectDenied(page, alertsUrl); + await loginAs('orgOutsider'); + await expectDenied(page, orgAlertsUrl); + }); + + test('the API requires authentication', async ({ playwright }) => { + const anonymous = await playwright.request.newContext({ baseURL: E2E_BASE_URL }); + const response = await anonymous.get(`/api/alerts?organizationId=${seed.primaryOrgId}`); + expect(response.status()).toBe(401); + await anonymous.dispose(); + }); +}); + +test.describe('organization alerts', () => { + test('the project page lists organization alerts as read-only inherited ones', async ({ + page, + loginAs, + }) => { + await loginAs('orgAdmin'); + await expectAllowed(page, orgAlertsUrl); + await openEditor(page, `${orgAlertsUrl}/new`); + await page.getByLabel('Nombre', { exact: true }).fill('Todos los análisis fallidos'); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis fallido' }); + await page.getByRole('checkbox', { name: 'Org Admin' }).check(); + await page.getByRole('button', { name: 'Crear alerta' }).click(); + await expect( + page.getByTestId('alert-row').filter({ hasText: 'Todos los análisis fallidos' }), + ).toBeVisible(); + + await loginAs('projectAdmin'); + await page.goto(alertsUrl); + const inherited = page.getByTestId('inherited-alerts'); + await expect(inherited).toContainText('Todos los análisis fallidos'); + await expect(inherited.getByRole('link', { name: 'Editar' })).toHaveCount(0); + await expect(inherited.getByRole('switch')).toHaveCount(0); + }); +}); + +test.describe('without JavaScript', () => { + test.use({ javaScriptEnabled: false }); + + test('the editor still creates an alert through form actions', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await page.goto(`${alertsUrl}/new`); + + await page.getByLabel('Nombre', { exact: true }).fill('Sin JS'); + await page.getByLabel('Evento', { exact: true }).selectOption({ label: 'Análisis completado' }); + await page.getByRole('button', { name: 'Usar este evento' }).click(); + + // ?/draft re-renders the form with one condition row for the chosen event + await page.getByRole('button', { name: 'Añadir condición' }).click(); + const row = page.getByTestId('condition-row').first(); + await expect(row.getByLabel('Campo')).toHaveValue('serviceId'); + await row.getByRole('radio', { name: 'E2E Seeded Service' }).check(); + await page.getByRole('checkbox', { name: 'Project Admin' }).check(); + + await page.getByRole('button', { name: 'Crear alerta' }).click(); + await expect(page).toHaveURL(new RegExp(`${alertsUrl}\\?saved=`)); + await expect( + page.getByTestId('alert-row').filter({ hasText: 'Sin JS' }).getByTestId('alert-summary'), + ).toHaveText('Servicio es E2E Seeded Service'); + }); +}); diff --git a/e2e/specs/org-events.spec.ts b/e2e/specs/org-events.spec.ts new file mode 100644 index 00000000..5d2178f6 --- /dev/null +++ b/e2e/specs/org-events.spec.ts @@ -0,0 +1,66 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { expectAllowed, expectDenied } from '../fixtures/expect-access'; + +const seed = getSeed(); +const eventsUrl = `/org/${seed.primaryOrgSlug}/settings/events`; + +// a CI run through the machine-to-machine API: the analysis completes and publishes +// code_report.analysis.completed, which the in-memory event log keeps for the page +async function completeAnalysis(request: import('@playwright/test').APIRequestContext) { + const headers = { Authorization: `Bearer ${seed.apiKeys.write}` }; + const started = await request.post('/api/code-report/scan', { + headers, + data: { + status: 'in_progress', + service: seed.seededServiceSlug, + project: seed.primaryProjectSlug, + tool: 'trivy', + }, + }); + expect(started.status()).toBe(200); + const { analysis } = await started.json(); + + const completed = await request.post('/api/code-report/scan', { + headers, + data: { + status: 'completed', + analysisId: analysis.id, + result: { Results: [{ Vulnerabilities: [{ VulnerabilityID: 'CVE-1', Severity: 'HIGH' }] }] }, + }, + }); + expect(completed.status()).toBe(200); +} + +test.describe('organization events page', () => { + test('an org admin sees a CI analysis event and acknowledges it', async ({ + page, + request, + loginAs, + }) => { + await completeAnalysis(request); + await loginAs('orgAdmin'); + + await expectAllowed(page, `${eventsUrl}?status=pending`); + const row = page.locator('li', { hasText: 'Análisis completado' }).first(); + await expect(row).toBeVisible(); + await expect(row).toContainText('API key'); + + await row.getByRole('button', { name: 'Marcar como revisado' }).click(); + await expect(row).toContainText(`Revisado por ${seed.personas.orgAdmin.username}`); + + await page.goto(`${eventsUrl}?status=acked`); + await expect(page.locator('li', { hasText: 'Análisis completado' }).first()).toContainText( + `Revisado por ${seed.personas.orgAdmin.username}`, + ); + }); + + test('users outside the organization cannot open it', async ({ page, loginAs }) => { + await loginAs('orgOutsider'); + await expectDenied(page, eventsUrl); + }); + + test('org roles without organization:events:read cannot open it', async ({ page, loginAs }) => { + await loginAs('orgDeveloper'); + await expectDenied(page, eventsUrl); + }); +}); diff --git a/e2e/specs/organization-settings.spec.ts b/e2e/specs/organization-settings.spec.ts index adfa2dc5..03781643 100644 --- a/e2e/specs/organization-settings.spec.ts +++ b/e2e/specs/organization-settings.spec.ts @@ -12,6 +12,8 @@ const settingsRoutes = [ `/org/${org}/settings/system-backup`, `/org/${org}/settings/server-access-keys`, `/org/${org}/settings/audit`, + `/org/${org}/settings/events`, + `/org/${org}/settings/alerts`, ]; test.describe('organization settings — org admin', () => { diff --git a/e2e/specs/project-settings.spec.ts b/e2e/specs/project-settings.spec.ts index 03d3b4e3..aa514086 100644 --- a/e2e/specs/project-settings.spec.ts +++ b/e2e/specs/project-settings.spec.ts @@ -13,6 +13,7 @@ const settingsRoutes = [ `${base}/settings/roles-permissions`, `${base}/settings/server-access-keys`, `${base}/settings/audit`, + `${base}/settings/alerts`, ]; test('project admin sees every project settings resource', async ({ page, loginAs }) => { diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json index bef3a036..285608e5 100644 --- a/e2e/tsconfig.json +++ b/e2e/tsconfig.json @@ -8,7 +8,7 @@ "#lib/*": ["../src/lib/*"], "$modules": ["../src/modules"], "#modules/*": ["../src/modules/*"], - "$env/dynamic/private": ["../test/env-dynamic-private.ts"] + "$app/env/private": ["./env-private.ts"] } } } diff --git a/src/env.ts b/src/env.ts index fe90f90e..da5dff00 100644 --- a/src/env.ts +++ b/src/env.ts @@ -16,6 +16,7 @@ export const variables = defineEnvVars({ GITDB_DATA_PATH: optional, GITDB_ENCRYPTION_KEY: optional, VAULT_ENCRYPTION_KEY: optional, + ORIGIN: optional, NOTIFICATION_SMTP_HOST: optional, NOTIFICATION_SMTP_PORT: optional, NOTIFICATION_SMTP_SECURE: optional, @@ -28,4 +29,5 @@ export const variables = defineEnvVars({ GOOGLE_SSO_CLIENT_SECRET: optional, GOOGLE_SSO_ALLOWED_DOMAINS: optional, GOOGLE_SSO_AUTO_PROVISION: optional, + GITOPS_EVENTS_EXPIRATION: optional, }); diff --git a/src/hooks.server.ts b/src/hooks.server.ts index bd988fcb..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(); })(); @@ -118,7 +121,12 @@ const authGuard: Handle = async ({ event, resolve }) => { event.locals.apiKey = apiKey; return runWithActor( - { name: `apikey:${apiKey.name}`, email: `apikey+${apiKey.id}@gitops.local` }, + { + name: `apikey:${apiKey.name}`, + email: `apikey+${apiKey.id}@gitops.local`, + apiKeyId: apiKey.id, + apiKeyProjectId: apiKey.projectId, + }, () => resolve(event), ); } @@ -167,6 +175,7 @@ const authGuard: Handle = async ({ event, resolve }) => { const actor = { name: currentUser.username, email: currentUser.email || `${currentUser.username}@gitops.local`, + userId: currentUser.id, }; return runWithActor(actor, () => resolve(event)); }; diff --git a/src/lib/alerts/summary.test.ts b/src/lib/alerts/summary.test.ts new file mode 100644 index 00000000..74722870 --- /dev/null +++ b/src/lib/alerts/summary.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest'; +import { summarizeConditions, summarizeRecipients } from './summary'; +import type { CatalogEntry } from './types'; + +const labels: Record = { + 'f.service': 'Servicio', + 'f.critical': 'Vulnerabilidades críticas', + 'f.tool': 'Herramienta', + 'f.flag': 'Hay vulnerabilidades', + 'o.trivy': 'Trivy', + 'alerts.operators.eq': 'es', + 'alerts.operators.gt': 'mayor que', + 'alerts.operators.in': 'es uno de', + 'alerts.operators.is_true': 'es sí', + 'alerts.summary.and': 'y', + 'alerts.summary.or': 'o', + 'alerts.summary.always': 'Siempre', + 'alerts.summary.noRecipients': 'Nadie', +}; +const t = (key: string) => labels[key] ?? key; + +const definition = { + type: 'code_report.analysis.completed', + fields: [ + { + key: 'serviceId', + label: 'f.service', + type: 'reference', + reference: 'code_report_service', + operators: ['eq', 'in'], + }, + { key: 'summary.critical', label: 'f.critical', type: 'number', operators: ['gt'] }, + { + key: 'tool', + label: 'f.tool', + type: 'enum', + options: [{ value: 'trivy', label: 'o.trivy' }], + operators: ['in'], + }, + { + key: 'hasVulnerabilities', + label: 'f.flag', + type: 'boolean', + operators: ['is_true'], + derived: true, + }, + ], +} as unknown as CatalogEntry; + +const references = { code_report_service: [{ id: 'svc-1', label: 'api-gateway' }] }; + +describe('summarizeConditions', () => { + it('reads like the guided example', () => { + expect( + summarizeConditions( + definition, + [ + { field: 'serviceId', operator: 'eq', value: 'svc-1' }, + { field: 'summary.critical', operator: 'gt', value: 0 }, + ], + 'all', + references, + t, + ), + ).toBe('Servicio es api-gateway y Vulnerabilidades críticas mayor que 0'); + }); + + it('joins with "or", lists values and skips valueless operators', () => { + expect( + summarizeConditions( + definition, + [ + { field: 'tool', operator: 'in', value: ['trivy', 'grype'] }, + { field: 'hasVulnerabilities', operator: 'is_true', value: '' }, + ], + 'any', + references, + t, + ), + ).toBe('Herramienta es uno de Trivy, grype o Hay vulnerabilidades es sí'); + }); + + it('says when an alert has no conditions and keeps unknown fields raw', () => { + expect(summarizeConditions(definition, [], 'all', references, t)).toBe('Siempre'); + expect( + summarizeConditions( + definition, + [{ field: 'gone', operator: 'eq', value: 'x' }], + 'all', + references, + t, + ), + ).toBe('gone es'); + }); +}); + +describe('summarizeRecipients', () => { + it('names roles and users', () => { + expect( + summarizeRecipients( + { userIds: ['u1', 'ghost'], roleIds: ['r1'] }, + [{ id: 'u1', label: 'ana' }], + [{ id: 'r1', label: 'Project Admin' }], + t, + ), + ).toBe('Project Admin, ana, ghost'); + expect(summarizeRecipients({ userIds: [], roleIds: [] }, [], [], t)).toBe('Nadie'); + }); +}); diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts new file mode 100644 index 00000000..c38c820c --- /dev/null +++ b/src/lib/alerts/summary.ts @@ -0,0 +1,76 @@ +import type { Operator } from '#lib/events/catalog'; +import type { AlertOption, CatalogEntry, CatalogField, DraftCondition } from './types'; + +export type Translate = (key: string, options?: { values?: Record }) => string; + +/** Operators that take no value, and those that take a list. */ +export const VALUELESS_OPERATORS: readonly Operator[] = ['is_true', 'is_false', 'exists']; +export const LIST_OPERATORS: readonly Operator[] = ['in', 'not_in']; + +export function operatorLabel(operator: Operator | '', t: Translate): string { + return operator ? t(`alerts.operators.${operator}`) : ''; +} + +/** Human value of a condition: option labels for enums, entity names for references. */ +export function conditionValueLabel( + field: CatalogField, + value: DraftCondition['value'] | undefined, + referenceOptions: Record, + t: Translate, +): string { + const items = Array.isArray(value) ? value : value === undefined || value === '' ? [] : [value]; + return items + .map((item) => { + const text = String(item); + if (field.type === 'enum') { + const option = field.options?.find((candidate) => candidate.value === text); + return option ? t(option.label) : text; + } + if (field.type === 'reference' && field.reference) { + return ( + referenceOptions[field.reference]?.find((option) => option.id === text)?.label ?? text + ); + } + if (field.type === 'date') return new Date(text).toLocaleDateString(); + return text; + }) + .join(', '); +} + +/** + * "Servicio es api-gateway y Vulnerabilidades críticas mayor que 0". Conditions on fields the + * catalog no longer has keep their raw key. + */ +export function summarizeConditions( + definition: CatalogEntry | undefined, + conditions: readonly DraftCondition[], + match: 'all' | 'any', + referenceOptions: Record, + t: Translate, +): string { + if (conditions.length === 0) return t('alerts.summary.always'); + const parts = conditions.map((condition) => { + const field = definition?.fields.find((candidate) => candidate.key === condition.field); + const label = field ? t(field.label) : condition.field; + const operator = operatorLabel(condition.operator, t); + if (!field || VALUELESS_OPERATORS.includes(condition.operator as Operator)) { + return `${label} ${operator}`.trim(); + } + return `${label} ${operator} ${conditionValueLabel(field, condition.value, referenceOptions, t)}`; + }); + return parts.join(` ${t(match === 'any' ? 'alerts.summary.or' : 'alerts.summary.and')} `); +} + +/** "2 usuarios · Project Admin" */ +export function summarizeRecipients( + recipients: { userIds: string[]; roleIds: string[] }, + users: AlertOption[], + roles: AlertOption[], + t: Translate, +): string { + const names = [ + ...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id), + ...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id), + ]; + return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients'); +} diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts new file mode 100644 index 00000000..c552527c --- /dev/null +++ b/src/lib/alerts/types.ts @@ -0,0 +1,83 @@ +/** + * Data shapes of the alert pages, shared by the loaders (`#lib/server/alerts/page`) and the + * components (`#lib/components/alerts`). Type-only: safe to import from the client. + */ +import type { EventDefinition, Operator } from '#lib/events/catalog'; +import type { AlertRow, AlertScope } from '#modules/alerts/domain/alert.domain'; + +/** An alertable event as plain data: `derive` functions are dropped, `derived` marks them. */ +export type CatalogField = Omit & { + derived?: boolean; +}; + +export type CatalogEntry = Omit< + EventDefinition, + 'fields' | 'link' | 'mailSummary' | 'mailTemplate' +> & { + fields: CatalogField[]; +}; + +export type AlertOption = { id: string; label: string }; + +export type DraftCondition = { + field: string; + operator: Operator | ''; + value: string | number | string[]; +}; + +/** The editor's form state; the server validates and normalizes it on save. */ +export type AlertDraft = { + name: string; + description: string; + enabled: boolean; + eventType: string; + match: 'all' | 'any'; + conditions: DraftCondition[]; + recipients: { userIds: string[]; roleIds: string[] }; + throttleMinutes: number; +}; + +type Shared = { + basePath: string; + scope: AlertScope; + catalog: CatalogEntry[]; + /** Entities a `reference` field can point at, per reference kind. */ + referenceOptions: Record; + users: AlertOption[]; + roles: AlertOption[]; + /** `false` when SMTP is not configured: alerts are saved but nothing is sent. */ + mailConfigured: boolean; +}; + +export type AlertListData = Shared & { + alerts: AlertRow[]; + /** Organization alerts that also fire for this project (project pages only). */ + inherited: AlertRow[]; + canCreate: boolean; + canUpdate: boolean; + canDelete: boolean; +}; + +export type AlertEditorData = Shared & { + alertId: string | null; + draft: AlertDraft; + canSave: boolean; + canDelete: boolean; +}; + +export type AlertTestView = { + matched: boolean; + recipients: Array<{ userId: string; username: string }>; + deniedCount: number; + event: { type: string; payload: Record; projectId: string | null }; +}; + +/** What the editor's form actions return. */ +export type AlertFormResult = { + draft?: AlertDraft; + error?: string; + errors?: Record; + test?: AlertTestView; +} | null; + +export type { AlertRow, AlertScope }; diff --git a/src/lib/changelog.test.ts b/src/lib/changelog.test.ts new file mode 100644 index 00000000..67b8dd4c --- /dev/null +++ b/src/lib/changelog.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from 'vitest'; +import { getChangelogEntry, shouldShowWhatsNew } from './changelog'; + +describe('changelog', () => { + it('returns the entry matching the installed package version', () => { + expect(getChangelogEntry('1.3.6')?.es.title).toBe( + 'Alertas, eventos y nuevas opciones de acceso', + ); + }); + + it('does not show Whats New until the version changes', () => { + expect(shouldShowWhatsNew('1.3.6', null)).toBe(true); + expect(shouldShowWhatsNew('1.3.6', '1.3.6')).toBe(false); + }); + + it('does not show for a package version without an entry', () => { + expect(shouldShowWhatsNew('0.0.1', null)).toBe(false); + }); +}); diff --git a/src/lib/changelog.ts b/src/lib/changelog.ts new file mode 100644 index 00000000..b956ed5e --- /dev/null +++ b/src/lib/changelog.ts @@ -0,0 +1,49 @@ +export type ChangelogEntry = { + version: string; + date: string; + es: { + title: string; + summary: string; + changes: string[]; + }; + en: { + title: string; + summary: string; + changes: string[]; + }; +}; + +export const changelog: ChangelogEntry[] = [ + { + version: '1.3.6', + date: '2026-11-20', + es: { + title: 'Alertas, eventos y nuevas opciones de acceso', + summary: 'Esta versión amplía la monitorización y las opciones de comunicación de GitOps.', + changes: [ + 'Gestión de alertas con condiciones configurables y destinatarios.', + 'Motor de alertas por email con plantillas y cola con reintentos.', + 'Registro de eventos de organización y proyecto con reconocimiento.', + 'Mejoras de acceso y compatibilidad con Google SSO.', + ], + }, + en: { + title: 'Alerts, events and more access options', + summary: 'This release expands monitoring and communication options in GitOps.', + changes: [ + 'Alert management with configurable conditions and recipients.', + 'Email alert engine with templates and a retry queue.', + 'Organization and project event log with acknowledgements.', + 'Access improvements and Google SSO compatibility.', + ], + }, + }, +]; + +export function getChangelogEntry(version: string): ChangelogEntry | null { + return changelog.find((entry) => entry.version === version) ?? null; +} + +export function shouldShowWhatsNew(currentVersion: string, seenVersion: string | null): boolean { + return getChangelogEntry(currentVersion) !== null && seenVersion !== currentVersion; +} diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 8d70506a..6296d268 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -1,6 +1,8 @@ + +{#if visible && entry && content} + +{/if} diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte new file mode 100644 index 00000000..f63a2e3d --- /dev/null +++ b/src/lib/components/alerts/AlertEditor.svelte @@ -0,0 +1,444 @@ + + +
+ + + {#if data.canSave} + + {/if} + +
+ + + {$_('alerts.editor.back')} + + {#if message} + + {/if} +
+ + {#if !data.mailConfigured} +

+ + {$_('alerts.mailDisabled')} +

+ {/if} + + +
+

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

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

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

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

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

+ {#if droppedConditions > 0} +

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

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

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

+ + {/if} +
+ + +
+

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

+

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

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

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

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

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

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

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

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

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

+ {:else} +

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

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

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

+ {/if} +

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

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

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

+

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

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

+ + {$_('alerts.mailDisabled')} +

+ {/if} + + {#if error} + + {/if} + + {#if data.alerts.length === 0} +
+ +

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

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

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

+

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

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

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

+ {/if} +
+

{eventLabel(alert)}

+

{moduleLabel(alert)}

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

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

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

    —

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

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

+ {:else} +
+ {#each options as option (option.id)} + + {/each} +
+ {/if} +
diff --git a/src/lib/config/permissions.ts b/src/lib/config/permissions.ts index 91f169f9..9c2bba54 100644 --- a/src/lib/config/permissions.ts +++ b/src/lib/config/permissions.ts @@ -59,6 +59,16 @@ const permissions = { resource: 'audit', permissions: grantsFor('organization', 'audit'), }, + // events page (/org//settings/events): read to see it, update to acknowledge events + events: { + 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: { @@ -81,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/access.events.ts b/src/lib/events/catalog/access.events.ts new file mode 100644 index 00000000..d859ab29 --- /dev/null +++ b/src/lib/events/catalog/access.events.ts @@ -0,0 +1,177 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; +import { organizationPath, projectPath } from './links'; + +export const ACCESS_SCOPES = ['cluster', 'organization', 'project'] as const; + +const READ_USERS = 'organization:users:read'; + +const GRANTED = 'access.granted'; +const UPDATED = 'access.updated'; +const REVOKED = 'access.revoked'; +const INVITED = 'user.invited'; +const ACCEPTED = 'invitation.accepted'; +const ROLE_UPDATED = 'role.updated'; +const KEY_CREATED = 'api_key.created'; +const KEY_REVOKED = 'api_key.revoked'; + +type AccessEvent = typeof GRANTED | typeof UPDATED | typeof REVOKED; +type InvitationEvent = typeof INVITED | typeof ACCEPTED; + +function userField(type: AccessEvent | InvitationEvent) { + return { + key: 'userId', + label: fieldLabel(type, 'userId'), + type: 'reference', + reference: 'user', + operators: OPERATORS.reference, + } as const; +} + +function roleField(type: AccessEvent | InvitationEvent | typeof ROLE_UPDATED) { + return { + key: 'roleId', + label: fieldLabel(type, 'roleId'), + type: 'reference', + reference: 'role', + operators: OPERATORS.reference, + } as const; +} + +function scopeField(type: AccessEvent | typeof ACCEPTED) { + return { + key: 'scope', + label: fieldLabel(type, 'scope'), + type: 'enum', + options: enumOptions('accessScope', ACCESS_SCOPES), + operators: OPERATORS.enum, + } as const; +} + +function accessFields(type: AccessEvent) { + return [userField(type), roleField(type), scopeField(type)] as const; +} + +function permissionsField(key: 'addedPermissions' | 'removedPermissions') { + return { + key, + label: fieldLabel(ROLE_UPDATED, key), + type: 'string', + operators: OPERATORS.list, + } as const; +} + +// access events also feed the fixed system notifications (#81) for the affected user +export const accessEvents: EventDefinitions< + AccessEvent | InvitationEvent | typeof ROLE_UPDATED | typeof KEY_CREATED | typeof KEY_REVOKED +> = { + [GRANTED]: { + link: (context) => + projectPath(context, '/settings/access-control') ?? + organizationPath(context, '/settings/access-control'), + ...eventText(GRANTED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(GRANTED), + }, + [UPDATED]: { + link: (context) => + projectPath(context, '/settings/access-control') ?? + organizationPath(context, '/settings/access-control'), + ...eventText(UPDATED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(UPDATED), + }, + [REVOKED]: { + link: (context) => + projectPath(context, '/settings/access-control') ?? + organizationPath(context, '/settings/access-control'), + ...eventText(REVOKED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(REVOKED), + }, + [INVITED]: { + link: (context) => + projectPath(context, '/settings/access-control') ?? + organizationPath(context, '/settings/access-control'), + ...eventText(INVITED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: [userField(INVITED), roleField(INVITED)], + }, + [ACCEPTED]: { + link: (context) => + projectPath(context, '/settings/access-control') ?? + organizationPath(context, '/settings/access-control'), + ...eventText(ACCEPTED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: [userField(ACCEPTED), roleField(ACCEPTED), scopeField(ACCEPTED)], + }, + [ROLE_UPDATED]: { + link: (context) => + projectPath(context, '/settings/roles-permissions') ?? + organizationPath(context, '/settings/roles-permissions'), + ...eventText(ROLE_UPDATED), + module: 'access', + scope: 'organization', + readPermission: 'organization:roles:read', + alertable: true, + fields: [ + roleField(ROLE_UPDATED), + permissionsField('addedPermissions'), + permissionsField('removedPermissions'), + ], + }, + [KEY_CREATED]: { + link: (context) => projectPath(context, '/settings/server-access-keys'), + ...eventText(KEY_CREATED), + module: 'access', + scope: 'project', + readPermission: 'project:server-keys:read', + alertable: true, + fields: [ + { + key: 'name', + label: fieldLabel(KEY_CREATED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, + [KEY_REVOKED]: { + link: (context) => projectPath(context, '/settings/server-access-keys'), + ...eventText(KEY_REVOKED), + module: 'access', + scope: 'project', + readPermission: 'project:server-keys:read', + alertable: true, + fields: [ + { + key: 'apiKeyId', + label: fieldLabel(KEY_REVOKED, 'apiKeyId'), + type: 'reference', + reference: 'api_key', + operators: OPERATORS.reference, + }, + { + key: 'name', + label: fieldLabel(KEY_REVOKED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, +}; 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/catalog.test.ts b/src/lib/events/catalog/catalog.test.ts new file mode 100644 index 00000000..4e155a94 --- /dev/null +++ b/src/lib/events/catalog/catalog.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vitest'; +import es from '#lib/i18n/locales/es.json'; +import en from '#lib/i18n/locales/en.json'; +import type { CodeReportAnalysisCompletedPayload } from '../domain-events'; +import { + EVENT_CATALOG, + defineEventCatalog, + getEventDefinition, + getFieldValue, + isEventType, + listAlertableEvents, + type EventCatalog, + type EventDefinition, + type EventFieldDefinition, +} from './index'; + +function completedPayload( + overrides: Partial = {}, +): CodeReportAnalysisCompletedPayload { + return { + analysisId: 'analysis-1', + serviceId: 'service-1', + 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, + }; +} + +describe('event catalog: compile-time checks', () => { + it('rejects a field key that is not a path of the payload', () => { + const valid: EventFieldDefinition = { + key: 'gitInfo.branch', + label: 'x', + type: 'string', + operators: ['eq'], + }; + // @ts-expect-error 'gitInfo.tag' is not a path of the payload (and there is no `derive`) + const invalid: EventFieldDefinition = { + key: 'gitInfo.tag', + label: 'x', + type: 'string', + operators: ['eq'], + }; + const derived: EventFieldDefinition = { + key: 'anything', + label: 'x', + type: 'boolean', + operators: ['is_true'], + derive: (payload) => payload.summary.total > 0, + }; + + expect([valid.key, invalid.key, derived.key]).toHaveLength(3); + }); + + it('requires a definition for every event of DomainEventMap', () => { + const incomplete: Partial = { ...EVENT_CATALOG }; + delete incomplete['code_report.analysis.failed']; + // @ts-expect-error 'code_report.analysis.failed' is missing + const catalog: EventCatalog = incomplete; + + expect(Object.keys(catalog)).not.toContain('code_report.analysis.failed'); + }); +}); + +describe('defineEventCatalog', () => { + it('rejects an entry whose type does not match its key', () => { + const completed = EVENT_CATALOG['code_report.analysis.completed']; + expect(() => + defineEventCatalog({ + ...EVENT_CATALOG, + 'code_report.analysis.failed': { + ...completed, + } as unknown as EventDefinition<'code_report.analysis.failed'>, + }), + ).toThrow(/declares type/); + }); + + it('rejects duplicated field keys', () => { + const failed = EVENT_CATALOG['code_report.analysis.failed']; + expect(() => + defineEventCatalog({ + ...EVENT_CATALOG, + 'code_report.analysis.failed': { ...failed, fields: [...failed.fields, failed.fields[0]] }, + }), + ).toThrow(/twice/); + }); +}); + +describe('catalog helpers', () => { + it('looks up definitions and event types', () => { + expect(getEventDefinition('code_report.analysis.completed').readPermission).toBe( + 'project:codereport:reports:read', + ); + expect(isEventType('code_report.analysis.completed')).toBe(true); + expect(isEventType('code_report.analysis.unknown')).toBe(false); + expect(isEventType('toString')).toBe(false); + }); + + it('lists alertable events filtered by scope and module', () => { + const projectEvents = listAlertableEvents({ scope: 'project', module: 'code_report' }); + + expect(projectEvents.map((definition) => definition.type)).toContain( + 'code_report.analysis.completed', + ); + expect(listAlertableEvents({ scope: 'organization', module: 'code_report' })).toEqual([]); + }); + + it('reads nested payload paths', () => { + const event = { type: 'code_report.analysis.completed' as const, payload: completedPayload() }; + + expect(getFieldValue(event, 'gitInfo.branch')).toBe('main'); + expect(getFieldValue(event, 'summary.critical')).toBe(2); + expect(getFieldValue(event, 'serviceId')).toBe('service-1'); + }); + + it('computes derived fields', () => { + const clean = completedPayload({ + summary: { critical: 0, high: 0, medium: 0, low: 0, unknown: 0, total: 0, secrets: 0 }, + }); + const violated = completedPayload({ + policies: { + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }); + const type = 'code_report.analysis.completed' as const; + + expect(getFieldValue({ type, payload: completedPayload() }, 'hasVulnerabilities')).toBe(true); + expect(getFieldValue({ type, payload: clean }, 'hasVulnerabilities')).toBe(false); + expect(getFieldValue({ type, payload: clean }, 'policiesViolated')).toBe(false); + expect(getFieldValue({ type, payload: violated }, 'policiesViolated')).toBe(true); + }); + + it('returns undefined for unknown fields and missing paths', () => { + const type = 'code_report.analysis.completed' as const; + const payload = completedPayload({ gitInfo: null as never }); + + expect(getFieldValue({ type, payload }, 'gitInfo.branch')).toBeUndefined(); + // a real payload path that is not exposed in the catalog is not filterable + expect(getFieldValue({ type, payload }, 'analysisId')).toBeUndefined(); + }); +}); + +describe('catalog translations', () => { + function lookup(messages: unknown, key: string): unknown { + // keys may contain dots both as nesting and inside event types / field paths, so walk the + // object tree trying the longest matching segment first + if (key === '') return messages; + if (messages === null || typeof messages !== 'object') return undefined; + const record = messages as Record; + const segments = key.split('.'); + for (let length = segments.length; length > 0; length -= 1) { + const head = segments.slice(0, length).join('.'); + if (head in record) { + const found = lookup(record[head], segments.slice(length).join('.')); + if (found !== undefined) return found; + } + } + return undefined; + } + + function catalogKeys(): string[] { + return (Object.values(EVENT_CATALOG) as EventDefinition[]).flatMap((definition) => [ + definition.label, + definition.description, + ...definition.fields.flatMap((field) => [ + field.label, + ...(field.options ?? []).map((option) => option.label), + ]), + ]); + } + + it.each([ + ['es', es], + ['en', en], + ])('has a %s translation for every event, field and option', (_locale, messages) => { + const missing = catalogKeys().filter((key) => typeof lookup(messages, key) !== 'string'); + expect(missing).toEqual([]); + }); +}); diff --git a/src/lib/events/catalog/code-report.events.ts b/src/lib/events/catalog/code-report.events.ts new file mode 100644 index 00000000..be3cb18a --- /dev/null +++ b/src/lib/events/catalog/code-report.events.ts @@ -0,0 +1,204 @@ +import { + SECURITY_POLICY_ENFORCEMENTS, + SECURITY_POLICY_TYPES, +} from '#lib/code-report/security-policy'; +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; +import { projectPath } from './links'; + +/** Tools that report analyses: scanners plus the manual upload and the CI/CD API defaults. */ +export const CODE_REPORT_TOOLS = [ + 'trivy', + 'grype', + 'semgrep', + 'gitleaks', + 'trufflehog', + 'sbom', + 'syft', + 'coverage', + 'manual-upload', + 'api', +] as const; + +const READ_REPORTS = 'project:codereport:reports:read'; + +const COMPLETED = 'code_report.analysis.completed'; +const FAILED = 'code_report.analysis.failed'; +const POLICY_VIOLATED = 'code_report.policy.violated'; +const SERVICE_CREATED = 'code_report.service.created'; +const SERVICE_DELETED = 'code_report.service.deleted'; + +function serviceField(type: typeof COMPLETED | typeof FAILED | typeof POLICY_VIOLATED) { + return { + key: 'serviceId', + label: fieldLabel(type, 'serviceId'), + type: 'reference', + reference: 'code_report_service', + operators: OPERATORS.reference, + } as const; +} + +function toolField(type: typeof COMPLETED | typeof FAILED | typeof POLICY_VIOLATED) { + return { + key: 'tool', + label: fieldLabel(type, 'tool'), + type: 'enum', + options: enumOptions('tool', CODE_REPORT_TOOLS), + operators: ['eq', 'neq', 'in'], + } as const; +} + +function branchField(type: typeof COMPLETED | typeof FAILED) { + return { + key: 'gitInfo.branch', + label: fieldLabel(type, 'gitInfo.branch'), + type: 'string', + operators: OPERATORS.string, + } as const; +} + +function countField( + key: K, +) { + return { + key, + label: fieldLabel(COMPLETED, key), + type: 'number', + operators: OPERATORS.number, + } as const; +} + +export const codeReportEvents: EventDefinitions< + | typeof COMPLETED + | typeof FAILED + | typeof POLICY_VIOLATED + | typeof SERVICE_CREATED + | typeof SERVICE_DELETED +> = { + [COMPLETED]: { + mailTemplate: 'alert-code-report-analysis', + link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`), + mailSummary: ({ summary }) => + summary.total === 0 + ? { key: 'alerts.email.summary.noVulnerabilities' } + : { + key: 'alerts.email.summary.vulnerabilities', + values: { critical: summary.critical, high: summary.high, total: summary.total }, + }, + ...eventText(COMPLETED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + serviceField(COMPLETED), + toolField(COMPLETED), + branchField(COMPLETED), + countField('summary.critical'), + countField('summary.high'), + countField('summary.medium'), + countField('summary.low'), + countField('summary.total'), + { + key: 'hasVulnerabilities', + label: fieldLabel(COMPLETED, 'hasVulnerabilities'), + type: 'boolean', + operators: OPERATORS.boolean, + derive: (payload) => payload.summary.total > 0, + }, + { + key: 'policiesViolated', + label: fieldLabel(COMPLETED, 'policiesViolated'), + type: 'boolean', + operators: OPERATORS.boolean, + derive: (payload) => payload.policies.status === 'violated', + }, + ], + }, + [FAILED]: { + mailTemplate: 'alert-code-report-analysis', + link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`), + mailSummary: ({ tool }) => ({ key: 'alerts.email.summary.analysisFailed', values: { tool } }), + ...eventText(FAILED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [serviceField(FAILED), toolField(FAILED), branchField(FAILED)], + }, + [POLICY_VIOLATED]: { + link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`), + mailSummary: ({ policyName, violations }) => ({ + key: 'alerts.email.summary.policyViolated', + values: { policy: policyName, count: violations }, + }), + ...eventText(POLICY_VIOLATED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + serviceField(POLICY_VIOLATED), + { + key: 'policyId', + label: fieldLabel(POLICY_VIOLATED, 'policyId'), + type: 'reference', + reference: 'code_report_policy', + operators: OPERATORS.reference, + }, + { + key: 'policyType', + label: fieldLabel(POLICY_VIOLATED, 'policyType'), + type: 'enum', + options: enumOptions('policyType', SECURITY_POLICY_TYPES), + operators: OPERATORS.enum, + }, + { + key: 'enforcement', + label: fieldLabel(POLICY_VIOLATED, 'enforcement'), + type: 'enum', + options: enumOptions('enforcement', SECURITY_POLICY_ENFORCEMENTS), + operators: OPERATORS.enum, + }, + ], + }, + [SERVICE_CREATED]: { + link: (context) => projectPath(context, '/code-report/services'), + ...eventText(SERVICE_CREATED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + { + key: 'name', + label: fieldLabel(SERVICE_CREATED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, + [SERVICE_DELETED]: { + link: (context) => projectPath(context, '/code-report/services'), + ...eventText(SERVICE_DELETED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + { + key: 'serviceId', + label: fieldLabel(SERVICE_DELETED, 'serviceId'), + type: 'reference', + reference: 'code_report_service', + operators: OPERATORS.reference, + }, + { + key: 'name', + label: fieldLabel(SERVICE_DELETED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/fields.ts b/src/lib/events/catalog/fields.ts new file mode 100644 index 00000000..1ed6d7b9 --- /dev/null +++ b/src/lib/events/catalog/fields.ts @@ -0,0 +1,31 @@ +import type { EventType } from '../domain-events'; +import type { Operator } from './types'; + +/** Operator sets offered by the alert builder, per field type. */ +export const OPERATORS = { + reference: ['eq', 'neq', 'in', 'not_in'], + enum: ['eq', 'neq', 'in', 'not_in'], + string: ['eq', 'neq', 'contains', 'starts_with'], + number: ['eq', 'gt', 'gte', 'lt', 'lte'], + boolean: ['is_true', 'is_false'], + list: ['in', 'not_in'], +} as const satisfies Record; + +/** `label` and `description` i18n keys of an event. */ +export function eventText(type: K) { + return { + type, + label: `events.${type}.label`, + description: `events.${type}.description`, + } as const; +} + +/** i18n key of a field label. */ +export function fieldLabel(type: EventType, key: string): string { + return `events.${type}.fields.${key}`; +} + +/** Enum options whose labels live under `events.options..`. */ +export function enumOptions(group: string, values: readonly string[]) { + return values.map((value) => ({ value, label: `events.options.${group}.${value}` })); +} diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts new file mode 100644 index 00000000..4ee2d846 --- /dev/null +++ b/src/lib/events/catalog/index.ts @@ -0,0 +1,103 @@ +import type { DomainEventMap, EventType } from '../domain-events'; +import { codeReportEvents } from './code-report.events'; +import { vaultEvents } from './vault.events'; +import { projectEvents } from './projects.events'; +import { organizationEvents } from './organization.events'; +import { accessEvents } from './access.events'; +import type { + EventCatalog, + EventDefinition, + EventDefinitionScope, + EventFieldDefinition, + EventModule, +} from './types'; + +export type * from './types'; +export { OPERATORS } from './fields'; +export { CODE_REPORT_TOOLS } from './code-report.events'; +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 + * definition) and checks each field `key` without `derive` against its payload. + */ +export function defineEventCatalog(catalog: C): C { + for (const [type, definition] of Object.entries(catalog) as [string, EventDefinition][]) { + if (definition.type !== type) { + throw new Error(`Event catalog entry "${type}" declares type "${definition.type}"`); + } + const keys = definition.fields.map((field) => field.key); + const duplicate = keys.find((key, index) => keys.indexOf(key) !== index); + if (duplicate) { + throw new Error(`Event "${type}" declares field "${duplicate}" twice`); + } + } + return catalog; +} + +export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ + ...codeReportEvents, + ...vaultEvents, + ...projectEvents, + ...organizationEvents, + ...accessEvents, +}); + +export function isEventType(value: string): value is EventType { + return Object.hasOwn(EVENT_CATALOG, value); +} + +export function getEventDefinition(type: K): EventDefinition { + return EVENT_CATALOG[type] as EventDefinition; +} + +/** Events offered in the alert builder, optionally narrowed by scope and module. */ +export function listAlertableEvents( + filter: { scope?: EventDefinitionScope; module?: EventModule } = {}, +): EventDefinition[] { + return (Object.values(EVENT_CATALOG) as EventDefinition[]).filter( + (definition) => + definition.alertable && + (!filter.scope || definition.scope === filter.scope) && + (!filter.module || definition.module === filter.module), + ); +} + +export function getFieldDefinition( + type: K, + fieldKey: string, +): EventFieldDefinition | undefined { + return getEventDefinition(type).fields.find((field) => field.key === fieldKey); +} + +/** + * Value of a catalog field for an event: `derive(payload)` for computed fields, the dotted path + * otherwise. `undefined` when the field is not in the catalog or the path is missing. + */ +export function getFieldValue( + event: { type: EventType; payload: unknown }, + fieldKey: string, +): unknown { + const field = getFieldDefinition(event.type, fieldKey) as EventFieldDefinition | undefined; + if (!field) return undefined; + if (field.derive) return field.derive(event.payload); + return readPath(event.payload, field.key as string); +} + +function readPath(source: unknown, path: string): unknown { + let current = source; + for (const segment of path.split('.')) { + if (current === null || typeof current !== 'object') return undefined; + current = (current as Record)[segment]; + } + return current; +} diff --git a/src/lib/events/catalog/links.ts b/src/lib/events/catalog/links.ts new file mode 100644 index 00000000..1e521782 --- /dev/null +++ b/src/lib/events/catalog/links.ts @@ -0,0 +1,11 @@ +import type { EventLinkContext } from './types'; + +/** App paths for `EventDefinition.link`; `null` when the slugs needed are unknown. */ +export function organizationPath(context: EventLinkContext, path = ''): string | null { + return context.organizationSlug ? `/org/${context.organizationSlug}${path}` : null; +} + +export function projectPath(context: EventLinkContext, path = ''): string | null { + if (!context.organizationSlug || !context.projectSlug) return null; + return `/org/${context.organizationSlug}/projects/${context.projectSlug}${path}`; +} diff --git a/src/lib/events/catalog/organization.events.ts b/src/lib/events/catalog/organization.events.ts new file mode 100644 index 00000000..f06750dc --- /dev/null +++ b/src/lib/events/catalog/organization.events.ts @@ -0,0 +1,27 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; +import { organizationPath } from './links'; + +export const ORGANIZATION_CHANGED_FIELDS = ['name', 'slug', 'description'] as const; + +const UPDATED = 'organization.updated'; + +export const organizationEvents: EventDefinitions = { + [UPDATED]: { + link: (context) => organizationPath(context, '/settings/global'), + ...eventText(UPDATED), + module: 'organization', + scope: 'organization', + readPermission: 'organization:settings:read', + alertable: true, + fields: [ + { + key: 'changedFields', + label: fieldLabel(UPDATED, 'changedFields'), + type: 'enum', + options: enumOptions('organizationChangedField', ORGANIZATION_CHANGED_FIELDS), + operators: OPERATORS.list, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/projects.events.ts b/src/lib/events/catalog/projects.events.ts new file mode 100644 index 00000000..ce33ea75 --- /dev/null +++ b/src/lib/events/catalog/projects.events.ts @@ -0,0 +1,79 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; +import { organizationPath } from './links'; + +export const PROJECT_CHANGED_FIELDS = [ + 'name', + 'slug', + 'description', + 'status', + 'modules', + 'organization', + 'settings', +] as const; + +const READ_PROJECTS = 'organization:projects:read'; + +const CREATED = 'project.created'; +const UPDATED = 'project.updated'; +const DELETED = 'project.deleted'; + +function nameField(type: K) { + return { + key: 'name', + label: fieldLabel(type, 'name'), + type: 'string', + operators: OPERATORS.string, + } as const; +} + +function projectField(type: K) { + return { + key: 'projectId', + label: fieldLabel(type, 'projectId'), + type: 'reference', + reference: 'project', + operators: OPERATORS.reference, + } as const; +} + +// projects are watched from their organization: an org admin alerts on its projects +export const projectEvents: EventDefinitions = { + [CREATED]: { + link: (context) => organizationPath(context, `/projects/${context.payload.slug}/overview`), + ...eventText(CREATED), + module: 'projects', + scope: 'organization', + readPermission: READ_PROJECTS, + alertable: true, + fields: [nameField(CREATED)], + }, + [UPDATED]: { + link: (context) => organizationPath(context, `/projects/${context.payload.slug}/overview`), + ...eventText(UPDATED), + module: 'projects', + scope: 'organization', + readPermission: READ_PROJECTS, + alertable: true, + fields: [ + projectField(UPDATED), + nameField(UPDATED), + { + key: 'changedFields', + label: fieldLabel(UPDATED, 'changedFields'), + type: 'enum', + options: enumOptions('projectChangedField', PROJECT_CHANGED_FIELDS), + operators: OPERATORS.list, + }, + ], + }, + [DELETED]: { + link: (context) => organizationPath(context, '/settings/projects'), + ...eventText(DELETED), + module: 'projects', + scope: 'organization', + readPermission: READ_PROJECTS, + alertable: true, + fields: [projectField(DELETED), nameField(DELETED)], + }, +}; diff --git a/src/lib/events/catalog/types.ts b/src/lib/events/catalog/types.ts new file mode 100644 index 00000000..d916e1e8 --- /dev/null +++ b/src/lib/events/catalog/types.ts @@ -0,0 +1,109 @@ +import type { PermissionGrant } from '#lib/permissions'; +import type { DomainEventMap, EventType } from '../domain-events'; + +export type FieldType = 'string' | 'number' | 'boolean' | 'enum' | 'date' | 'reference'; + +export type Operator = + // string, enum, reference + | 'eq' + | 'neq' + | 'in' + | 'not_in' + // string + | 'contains' + | 'starts_with' + // number, date + | 'gt' + | 'gte' + | 'lt' + | 'lte' + // boolean + | 'is_true' + | 'is_false' + | 'exists'; + +export type FieldReference = + | 'code_report_service' + | 'code_report_policy' + | 'project' + | 'user' + | 'role' + | 'vault_environment' + | 'api_key'; + +export type EventModule = 'code_report' | 'vault' | 'projects' | 'organization' | 'access'; + +export type EventDefinitionScope = 'organization' | 'project'; + +type Leaf = string | number | boolean | bigint | symbol | null | undefined | Date; + +/** + * Dotted paths to the fields of `T` (`'serviceId' | 'gitInfo' | 'gitInfo.branch' | ...`). Arrays + * are leaves (filtered with `in` / `not_in`). Limited depth keeps the type cheap. + */ +export type PayloadPath = Depth['length'] extends 4 + ? never + : T extends Leaf | readonly unknown[] + ? never + : { + [K in Extract]: NonNullable extends Leaf | readonly unknown[] + ? K + : K | `${K}.${PayloadPath, [...Depth, 1]>}`; + }[Extract]; + +type FieldCommon = { + /** i18n key, `events..fields.` */ + label: string; + type: FieldType; + /** Operators offered by the alert builder for this field. */ + operators: readonly Operator[]; + /** For `enum` fields; `label` is an i18n key. */ + options?: readonly { value: string; label: string }[]; + /** For `reference` fields: the UI lists these entities in the alert's scope; the id is stored. */ + reference?: FieldReference; +}; + +/** + * A filterable field. Without `derive`, `key` must be a path of the payload (checked at compile + * time). With `derive`, `key` is a computed name and the value comes from `derive(payload)`. + */ +export type EventFieldDefinition

= FieldCommon & + ({ key: PayloadPath

; derive?: undefined } | { key: string; derive: (payload: P) => unknown }); + +/** What `link` receives: the payload plus the slugs of where the event happened. */ +export type EventLinkContext

= { + payload: P; + organizationSlug: string | null; + projectSlug: string | null; +}; + +/** An i18n key with its values, e.g. `alerts.email.summary.vulnerabilities` + counts. */ +export type EventMessage = { key: string; values?: Record }; + +export type EventDefinition = { + type: K; + module: EventModule; + scope: EventDefinitionScope; + /** i18n key, `events..label` */ + label: string; + /** i18n key, `events..description` */ + description: string; + /** Needed to create alerts on this event and to receive them. */ + readPermission: PermissionGrant; + fields: readonly EventFieldDefinition[]; + /** `false`: internal use or system notifications only, not offered in the alert builder. */ + alertable: boolean; + /** Email template for alerts on this event (`src/notifications/email/.html`); the generic + * `alert` template otherwise. */ + mailTemplate?: string; + /** App path of the resource the event is about (`/org//…`), made absolute with `ORIGIN`. */ + link?: (context: EventLinkContext) => string | null; + /** Short summary for the email subject (`3 critical, 5 high`); the event label otherwise. */ + mailSummary?: (payload: DomainEventMap[K]) => EventMessage; +}; + +/** Definitions for a subset of events (one module's file). */ +export type EventDefinitions = { [P in K]: EventDefinition

}; + +/** Every event of `DomainEventMap` must have a definition. */ +export type EventCatalog = EventDefinitions; diff --git a/src/lib/events/catalog/vault.events.ts b/src/lib/events/catalog/vault.events.ts new file mode 100644 index 00000000..79bbf064 --- /dev/null +++ b/src/lib/events/catalog/vault.events.ts @@ -0,0 +1,142 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; +import { projectPath } from './links'; + +export const VAULT_SECRET_CHANGED_FIELDS = ['key', 'description', 'folder', 'values'] as const; + +const READ_SECRETS = 'project:vault:secrets:read'; +const READ_ENVIRONMENTS = 'project:vault:environments:read'; + +const SECRET_CREATED = 'vault.secret.created'; +const SECRET_UPDATED = 'vault.secret.updated'; +const SECRET_DELETED = 'vault.secret.deleted'; +const ENV_IMPORTED = 'vault.env.imported'; +const ENVIRONMENT_CREATED = 'vault.environment.created'; +const ENVIRONMENT_DELETED = 'vault.environment.deleted'; + +type SecretEvent = typeof SECRET_CREATED | typeof SECRET_UPDATED | typeof SECRET_DELETED; +type EnvironmentEvent = typeof ENVIRONMENT_CREATED | typeof ENVIRONMENT_DELETED; + +function secretFields(type: K) { + return [ + { key: 'key', label: fieldLabel(type, 'key'), type: 'string', operators: OPERATORS.string }, + { + key: 'environmentIds', + label: fieldLabel(type, 'environmentIds'), + type: 'reference', + reference: 'vault_environment', + operators: OPERATORS.list, + }, + { + key: 'folderPath', + label: fieldLabel(type, 'folderPath'), + type: 'string', + operators: OPERATORS.string, + }, + ] as const; +} + +function environmentFields(type: K) { + return [ + { + key: 'environmentId', + label: fieldLabel(type, 'environmentId'), + type: 'reference', + reference: 'vault_environment', + operators: OPERATORS.reference, + }, + { key: 'name', label: fieldLabel(type, 'name'), type: 'string', operators: OPERATORS.string }, + ] as const; +} + +export const vaultEvents: EventDefinitions = { + [SECRET_CREATED]: { + link: (context) => projectPath(context, '/vault'), + ...eventText(SECRET_CREATED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: secretFields(SECRET_CREATED), + }, + [SECRET_UPDATED]: { + link: (context) => projectPath(context, '/vault'), + ...eventText(SECRET_UPDATED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: [ + ...secretFields(SECRET_UPDATED), + { + key: 'changedFields', + label: fieldLabel(SECRET_UPDATED, 'changedFields'), + type: 'enum', + options: enumOptions('secretChangedField', VAULT_SECRET_CHANGED_FIELDS), + operators: OPERATORS.list, + }, + ], + }, + [SECRET_DELETED]: { + link: (context) => projectPath(context, '/vault'), + ...eventText(SECRET_DELETED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: secretFields(SECRET_DELETED), + }, + [ENV_IMPORTED]: { + link: (context) => projectPath(context, '/vault'), + ...eventText(ENV_IMPORTED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: [ + { + key: 'environmentId', + label: fieldLabel(ENV_IMPORTED, 'environmentId'), + type: 'reference', + reference: 'vault_environment', + operators: OPERATORS.reference, + }, + { + key: 'folderPath', + label: fieldLabel(ENV_IMPORTED, 'folderPath'), + type: 'string', + operators: OPERATORS.string, + }, + { + key: 'created', + label: fieldLabel(ENV_IMPORTED, 'created'), + type: 'number', + operators: OPERATORS.number, + }, + { + key: 'updated', + label: fieldLabel(ENV_IMPORTED, 'updated'), + type: 'number', + operators: OPERATORS.number, + }, + ], + }, + [ENVIRONMENT_CREATED]: { + link: (context) => projectPath(context, '/vault'), + ...eventText(ENVIRONMENT_CREATED), + module: 'vault', + scope: 'project', + readPermission: READ_ENVIRONMENTS, + alertable: true, + fields: environmentFields(ENVIRONMENT_CREATED), + }, + [ENVIRONMENT_DELETED]: { + link: (context) => projectPath(context, '/vault'), + ...eventText(ENVIRONMENT_DELETED), + module: 'vault', + scope: 'project', + readPermission: READ_ENVIRONMENTS, + alertable: true, + fields: environmentFields(ENVIRONMENT_DELETED), + }, +}; diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts new file mode 100644 index 00000000..83d1e5bd --- /dev/null +++ b/src/lib/events/domain-events.ts @@ -0,0 +1,201 @@ +/** + * Domain event payloads, shared by the server (bus, services, alert engine) and the client (alert + * builder UI). Type-only: keep this file free of server imports. + * + * Rules (docs/adr/0001-event-bus-and-alerts.md): names are `..` in + * snake_case with a past participle, and payloads never contain secrets (vault values, invitation + * or reset tokens/URLs, hashes, API keys). + */ + +export type CodeReportVulnerabilityCounts = { + critical: number; + high: number; + medium: number; + low: number; + unknown: number; + total: number; + /** Secrets detected by the scan (a count, never the matches). */ + secrets: number; +}; + +export type CodeReportEventGitInfo = { + repositoryUrl: string | null; + branch: string | null; + commit: string | null; + version: string | null; +}; + +export type CodeReportPolicyStatus = 'no_policies' | 'not_applicable' | 'compliant' | 'violated'; + +export type CodeReportAnalysisCompletedPayload = { + analysisId: string; + serviceId: string; + tool: string; + gitInfo: CodeReportEventGitInfo; + /** Counts computed server-side from the stored result. */ + summary: CodeReportVulnerabilityCounts; + policies: { + status: CodeReportPolicyStatus; + totalViolations: number; + blockingFailures: number; + failedPolicyIds: string[]; + }; +}; + +export type CodeReportAnalysisFailedPayload = { + analysisId: string; + serviceId: string; + tool: string; + gitInfo: CodeReportEventGitInfo; + error: string; +}; + +export type CodeReportPolicyViolatedPayload = { + analysisId: string; + serviceId: string; + tool: string; + policyId: string; + policyName: string; + policyType: string; + enforcement: 'warn' | 'block'; + violations: number; +}; + +export type CodeReportServicePayload = { + serviceId: string; + name: string; + slug: string; +}; + +export type VaultSecretChangedField = 'key' | 'description' | 'folder' | 'values'; + +/** Never carries secret values: only which environments hold (or changed) a value. */ +export type VaultSecretPayload = { + secretId: string; + key: string; + folderId: string | null; + /** `/` for the vault root. */ + folderPath: string; + /** Environments with a value (created/deleted) or whose value changed (updated). */ + environmentIds: string[]; +}; + +export type VaultSecretUpdatedPayload = VaultSecretPayload & { + changedFields: VaultSecretChangedField[]; +}; + +export type VaultEnvImportedPayload = { + environmentId: string; + environmentSlug: string; + folderId: string | null; + folderPath: string; + created: number; + updated: number; +}; + +export type VaultEnvironmentPayload = { + environmentId: string; + name: string; + slug: string; +}; + +export type ProjectChangedField = + 'name' | 'slug' | 'description' | 'status' | 'modules' | 'organization' | 'settings'; + +export type ProjectPayload = { + projectId: string; + name: string; + slug: string; +}; + +export type ProjectUpdatedPayload = ProjectPayload & { + changedFields: ProjectChangedField[]; +}; + +export type OrganizationChangedField = 'name' | 'slug' | 'description'; + +export type OrganizationUpdatedPayload = { + organizationId: string; + name: string; + slug: string; + changedFields: OrganizationChangedField[]; +}; + +export type AccessScope = 'cluster' | 'organization' | 'project'; + +export type AccessStatus = 'active' | 'invited'; + +/** A role assignment: a cluster account role, or a membership in an organization or project. */ +export type AccessPayload = { + /** The user-access entry id (the user id for cluster-level access). */ + accessId: string; + userId: string; + roleId: string | null; + scope: AccessScope; + status: AccessStatus; +}; + +export type AccessUpdatedPayload = AccessPayload & { + previousRoleId: string | null; + previousStatus: AccessStatus; +}; + +/** Never carries the invitation token, its URL or the invitee's email. */ +export type UserInvitedPayload = { + userId: string; + roleId: string; + organizationId: string; +}; + +export type InvitationAcceptedPayload = { + userId: string; + accessId: string; + roleId: string | null; + scope: AccessScope; +}; + +export type RoleUpdatedPayload = { + roleId: string; + name: string; + scope: AccessScope; + nameChanged: boolean; + addedPermissions: string[]; + removedPermissions: string[]; +}; + +/** Never carries the key or its hash: `keyPrefix` is the public, non-secret identifier. */ +export type ApiKeyPayload = { + apiKeyId: string; + name: string; + keyPrefix: string; + projectId: string | null; + userId: string | null; +}; + +export interface DomainEventMap { + 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; + 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; + 'code_report.policy.violated': CodeReportPolicyViolatedPayload; + 'code_report.service.created': CodeReportServicePayload; + 'code_report.service.deleted': CodeReportServicePayload; + 'vault.secret.created': VaultSecretPayload; + 'vault.secret.updated': VaultSecretUpdatedPayload; + 'vault.secret.deleted': VaultSecretPayload; + 'vault.env.imported': VaultEnvImportedPayload; + 'vault.environment.created': VaultEnvironmentPayload; + 'vault.environment.deleted': VaultEnvironmentPayload; + 'project.created': ProjectPayload; + 'project.updated': ProjectUpdatedPayload; + 'project.deleted': ProjectPayload; + 'organization.updated': OrganizationUpdatedPayload; + 'access.granted': AccessPayload; + 'access.updated': AccessUpdatedPayload; + 'access.revoked': AccessPayload; + 'user.invited': UserInvitedPayload; + 'invitation.accepted': InvitationAcceptedPayload; + 'role.updated': RoleUpdatedPayload; + 'api_key.created': ApiKeyPayload; + 'api_key.revoked': ApiKeyPayload; +} + +export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 355f7af0..0c0c0c19 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -55,7 +55,9 @@ "organizations": "Organizations", "database": "Database", "auditLog": "Audit Log", - "registration": "Registration" + "registration": "Registration", + "events": "Events", + "alerts": "Alerts" } }, "footer": { @@ -66,6 +68,11 @@ "slack": "Slack", "gitdbSyncStatus": "GitDB sync status" }, + "whatsNew": { + "title": "What's new in version {version}", + "viewChangelog": "View changelog", + "close": "Dismiss what's new" + }, "profile": { "title": "Profile", "subtitle": "Manage your identity, password and API access from one place.", @@ -382,6 +389,39 @@ "title": "Organization CVEs", "infoMessage": "This list aggregates CVEs from all organization projects using the latest completed analysis for each service.", "emptyMessage": "No CVEs have been detected in this organization yet." + }, + "events": { + "title": "Events", + "description": "What happened in the organization and its projects. Mark each event as reviewed once you have dealt with it.", + "retentionNotice": "Events are kept in memory for {retention}: they are lost when the server restarts.", + "retentionDays": "{count} days", + "retentionHours": "{count} hours", + "retentionMinutes": "{count} minutes", + "pendingCount": "{count} pending review", + "filterModule": "Module", + "filterStatus": "Status", + "allModules": "All modules", + "statusAll": "All", + "statusPending": "Pending", + "statusAcked": "Reviewed", + "applyFilters": "Filter", + "emptyTitle": "No events", + "emptyDescription": "Analyses, vault changes, access changes and other organization activity will show up here.", + "actorSystem": "System", + "actorApiKey": "API key {name}", + "actorApiKeyUnknown": "API key", + "inProject": "in {name}", + "details": "Show details", + "ack": "Mark as reviewed", + "ackedBy": "Reviewed by {name} · {date}", + "ackFailed": "The event could not be marked as reviewed.", + "modules": { + "code_report": "Code Report", + "vault": "Vault", + "projects": "Projects", + "organization": "Organization", + "access": "Access" + } } }, "project": { @@ -948,5 +988,471 @@ "defaultRootLabel": "Projects", "select": "Select", "notAvailable": "N/A" + }, + "events": { + "code_report": { + "analysis": { + "completed": { + "label": "Analysis completed", + "description": "A scan tool finished analyzing a service.", + "fields": { + "serviceId": "Service", + "tool": "Tool", + "gitInfo": { + "branch": "Branch" + }, + "summary": { + "critical": "Critical vulnerabilities", + "high": "High vulnerabilities", + "medium": "Medium vulnerabilities", + "low": "Low vulnerabilities", + "total": "Total vulnerabilities" + }, + "hasVulnerabilities": "Has vulnerabilities", + "policiesViolated": "Violates security policies" + } + }, + "failed": { + "label": "Analysis failed", + "description": "A scan tool could not complete the analysis of a service.", + "fields": { + "serviceId": "Service", + "tool": "Tool", + "gitInfo": { + "branch": "Branch" + } + } + } + }, + "policy": { + "violated": { + "label": "Security policy violated", + "description": "A completed analysis violates a project security policy.", + "fields": { + "serviceId": "Service", + "policyId": "Policy", + "policyType": "Policy type", + "enforcement": "Enforcement" + } + } + }, + "service": { + "created": { + "label": "Service created", + "description": "A Code Report service was created.", + "fields": { + "name": "Name" + } + }, + "deleted": { + "label": "Service deleted", + "description": "A Code Report service was deleted.", + "fields": { + "serviceId": "Service", + "name": "Name" + } + } + } + }, + "options": { + "tool": { + "trivy": "Trivy", + "grype": "Grype", + "semgrep": "Semgrep", + "gitleaks": "Gitleaks", + "trufflehog": "TruffleHog", + "sbom": "SBOM", + "syft": "Syft", + "coverage": "Coverage", + "manual-upload": "Manual upload", + "api": "API" + }, + "policyType": { + "vulnerabilities": "Vulnerabilities", + "license": "Licenses", + "code_coverage": "Code coverage", + "secrets": "Secrets" + }, + "enforcement": { + "warn": "Warning", + "block": "Blocking" + }, + "secretChangedField": { + "key": "Key", + "description": "Description", + "folder": "Folder", + "values": "Values" + }, + "projectChangedField": { + "name": "Name", + "slug": "Slug", + "description": "Description", + "status": "Status", + "modules": "Modules", + "organization": "Organization", + "settings": "Settings" + }, + "organizationChangedField": { + "name": "Name", + "slug": "Slug", + "description": "Description" + }, + "accessScope": { + "cluster": "GitOps", + "organization": "Organization", + "project": "Project" + } + }, + "vault": { + "secret": { + "created": { + "label": "Secret created", + "description": "A secret was created in the project vault.", + "fields": { + "key": "Secret key", + "environmentIds": "Environments", + "folderPath": "Folder" + } + }, + "updated": { + "label": "Secret updated", + "description": "A secret of the project vault was modified.", + "fields": { + "key": "Secret key", + "environmentIds": "Environments", + "folderPath": "Folder", + "changedFields": "Changed fields" + } + }, + "deleted": { + "label": "Secret deleted", + "description": "A secret was deleted from the project vault.", + "fields": { + "key": "Secret key", + "environmentIds": "Environments", + "folderPath": "Folder" + } + } + }, + "env": { + "imported": { + "label": ".env file imported", + "description": "Secrets were imported from a .env file.", + "fields": { + "environmentId": "Environment", + "folderPath": "Folder", + "created": "Secrets created", + "updated": "Secrets updated" + } + } + }, + "environment": { + "created": { + "label": "Environment created", + "description": "An environment was created in the project vault.", + "fields": { + "environmentId": "Environment", + "name": "Name" + } + }, + "deleted": { + "label": "Environment deleted", + "description": "An environment was deleted from the project vault.", + "fields": { + "environmentId": "Environment", + "name": "Name" + } + } + } + }, + "project": { + "created": { + "label": "Project created", + "description": "A project was created in the organization.", + "fields": { + "name": "Name" + } + }, + "updated": { + "label": "Project updated", + "description": "A project of the organization was modified.", + "fields": { + "projectId": "Project", + "name": "Name", + "changedFields": "Changed fields" + } + }, + "deleted": { + "label": "Project deleted", + "description": "A project was deleted from the organization.", + "fields": { + "projectId": "Project", + "name": "Name" + } + } + }, + "organization": { + "updated": { + "label": "Organization updated", + "description": "The organization details were modified.", + "fields": { + "changedFields": "Changed fields" + } + } + }, + "access": { + "granted": { + "label": "Access granted", + "description": "A user was given access with a role.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + }, + "updated": { + "label": "Access changed", + "description": "The role or status of a user access changed.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + }, + "revoked": { + "label": "Access revoked", + "description": "A user access was removed.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + } + }, + "user": { + "invited": { + "label": "User invited", + "description": "A user was invited to the organization.", + "fields": { + "userId": "User", + "roleId": "Role" + } + } + }, + "invitation": { + "accepted": { + "label": "Invitation accepted", + "description": "A user accepted their invitation.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + } + }, + "role": { + "updated": { + "label": "Role updated", + "description": "The name or permissions of a role changed.", + "fields": { + "roleId": "Role", + "addedPermissions": "Added permissions", + "removedPermissions": "Removed permissions" + } + } + }, + "api_key": { + "created": { + "label": "API key created", + "description": "An API key was created.", + "fields": { + "name": "Name" + } + }, + "revoked": { + "label": "API key revoked", + "description": "An API key was revoked.", + "fields": { + "apiKeyId": "API key", + "name": "Name" + } + } + }, + "scopeFields": { + "projectId": "Project" + } + }, + "alerts": { + "email": { + "alertSubject": "[GitOps] {alert}: {summary}", + "alertIntro": "“{event}” happened in {where} and matches this alert.", + "occurredAt": "Date", + "suppressed": "{count} more matching events were skipped during the previous window.", + "footer": "You receive this email because of the alert “{alert}” in {where}.", + "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.", + "warning": "If it wasn’t you, revoke the API key and change your password as soon as possible." + }, + "openProfile": "Open my profile" + }, + "manageAlert": "Manage the alert", + "viewInApp": "View in GitOps", + "project": "Project", + "greeting": "Hi {name},", + "service": "Service", + "tool": "Tool", + "branch": "Branch", + "commit": "Commit", + "severity": { + "critical": "Critical", + "high": "High", + "medium": "Medium", + "low": "Low" + }, + "policiesViolated": "{count} security policies were violated ({blocking} blocking).", + "summary": { + "vulnerabilities": "{critical} critical, {high} high ({total} in total)", + "noVulnerabilities": "no vulnerabilities", + "analysisFailed": "{tool} analysis failed", + "policyViolated": "“{policy}” violated ({count})" + } + }, + "operators": { + "eq": "is", + "neq": "is not", + "in": "is one of", + "not_in": "is none of", + "contains": "contains", + "starts_with": "starts with", + "gt": "greater than", + "gte": "greater than or equal to", + "lt": "less than", + "lte": "less than or equal to", + "is_true": "is yes", + "is_false": "is no", + "exists": "has a value" + }, + "summary": { + "and": "and", + "or": "or", + "always": "Always (no conditions)", + "noRecipients": "No recipients" + }, + "errors": { + "required": "This field is required.", + "too_long": "It is too long.", + "invalid": "The value is not valid.", + "unknown_event": "That event does not exist.", + "not_alertable": "That event does not support alerts.", + "scope_mismatch": "This event can only be watched from the organization.", + "forbidden": "You are not allowed to view this event, so you cannot create alerts on it.", + "unknown_field": "This field does not exist for the chosen event.", + "invalid_operator": "Operator not allowed for this field.", + "unknown_option": "Pick one of the options.", + "unknown_reference": "Pick an item from this scope.", + "too_many": "There are too many items.", + "unknown_user": "Some user does not belong to this scope.", + "unknown_role": "Some role does not belong to this scope.", + "invalid_channel": "Channel not available." + }, + "channels": { + "mail": "Email", + "in_app": "In-app notification", + "slack": "Slack", + "soon": "Coming soon" + }, + "list": { + "title": "Alerts", + "descriptionOrganization": "Get an email when an event happens in the organization or in any of its projects.", + "descriptionProject": "Get an email when an event happens in this project.", + "create": "Create alert", + "emptyTitle": "No alerts yet", + "example1": "Tell the security team when an analysis has critical vulnerabilities", + "example2": "Tell me when someone deletes a production secret", + "example3": "Tell me when a project API key is created", + "name": "Name", + "event": "Event", + "conditions": "Filters", + "recipients": "Recipients", + "status": "Status", + "actions": "Actions", + "enabled": "Active", + "disabled": "Inactive", + "toggle": "Turn “{name}” on or off", + "edit": "Edit", + "delete": "Delete", + "confirmDelete": "Delete this alert? This cannot be undone.", + "throttle": "At most one email every {minutes} min", + "inheritedTitle": "Organization alerts", + "inheritedDescription": "These alerts are defined in the organization and also fire for this project’s events. They can only be changed from the organization settings." + }, + "editor": { + "newTitle": "New alert", + "editTitle": "Edit alert", + "subtitle": "Pick an event, filter on its fields and choose who gets the email.", + "back": "Back to alerts", + "stepEvent": "Event", + "stepConditions": "Conditions", + "stepRecipients": "Recipients and delivery", + "stepSave": "Test and save", + "name": "Name", + "description": "Description (optional)", + "enabled": "Alert active", + "event": "Event", + "chooseEvent": "Pick an event…", + "eventHelp": "Only events you can view are listed.", + "applyEvent": "Use this event", + "chooseEventFirst": "Pick an event first to see its fields.", + "droppedConditions": "{count} conditions that do not exist in the new event were removed.", + "matchLabel": "Match", + "matchAll": "all conditions (AND)", + "matchAny": "any of them (OR)", + "noConditions": "No conditions: the alert fires on every event of this type.", + "field": "Field", + "operator": "Operator", + "value": "Value", + "addCondition": "Add condition", + "removeCondition": "Remove condition {index}", + "search": "Search…", + "searchIn": "Search in {label}", + "noOptions": "No items available.", + "roles": "Roles", + "users": "Users", + "recipientsNotice": "Only recipients allowed to view this event will get the email.", + "channels": "Channel", + "throttle": "Send at most one email every (minutes)", + "throttleHelp": "0 = no limit. Skipped events are summed up in the next email.", + "sampleProject": "Project of the example event", + "sampleProjectAny": "The one the conditions name", + "test": "Test alert", + "create": "Create alert", + "saveChanges": "Save changes", + "fixErrors": "Check the highlighted fields." + }, + "test": { + "matched": "The example event matches the conditions.", + "notMatched": "The example event does not match the conditions.", + "recipients": "It would be sent to: {names}", + "noRecipients": "It would not be sent to anyone.", + "denied": "{count} recipients would not get it because they cannot view this event.", + "nothingSent": "This is a test: no email was sent." + }, + "mailDisabled": "Email is not configured (NOTIFICATION_SMTP_*): alerts are saved but will not be sent." } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 6427c05d..c0670ca3 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -55,7 +55,9 @@ "organizations": "Organizaciones", "database": "Base de datos", "auditLog": "Registro de auditoría", - "registration": "Registro" + "registration": "Registro", + "events": "Eventos", + "alerts": "Alertas" } }, "footer": { @@ -66,6 +68,11 @@ "slack": "Slack", "gitdbSyncStatus": "Estado de sincronización GitDB" }, + "whatsNew": { + "title": "Novedades de la versión {version}", + "viewChangelog": "Ver changelog", + "close": "Cerrar novedades" + }, "profile": { "title": "Perfil", "subtitle": "Gestiona tu identidad, contraseña y acceso API desde un solo lugar.", @@ -382,6 +389,39 @@ "title": "CVEs de la organización", "infoMessage": "Este listado agrupa los CVEs de todos los proyectos de la organización usando el último análisis completado de cada servicio.", "emptyMessage": "Todavía no se han detectado CVEs en esta organización." + }, + "events": { + "title": "Eventos", + "description": "Lo que ha ocurrido en la organización y en sus proyectos. Marca cada evento como revisado cuando lo hayas atendido.", + "retentionNotice": "Los eventos se guardan en memoria durante {retention}: se pierden al reiniciar el servidor.", + "retentionDays": "{count} días", + "retentionHours": "{count} horas", + "retentionMinutes": "{count} minutos", + "pendingCount": "{count} pendientes de revisar", + "filterModule": "Módulo", + "filterStatus": "Estado", + "allModules": "Todos los módulos", + "statusAll": "Todos", + "statusPending": "Pendientes", + "statusAcked": "Revisados", + "applyFilters": "Filtrar", + "emptyTitle": "No hay eventos", + "emptyDescription": "Aquí aparecerán los análisis, cambios en el vault, accesos y demás actividad de la organización.", + "actorSystem": "Sistema", + "actorApiKey": "API key {name}", + "actorApiKeyUnknown": "API key", + "inProject": "en {name}", + "details": "Ver detalles", + "ack": "Marcar como revisado", + "ackedBy": "Revisado por {name} · {date}", + "ackFailed": "No se ha podido marcar el evento como revisado.", + "modules": { + "code_report": "Code Report", + "vault": "Vault", + "projects": "Proyectos", + "organization": "Organización", + "access": "Accesos" + } } }, "project": { @@ -948,5 +988,471 @@ "defaultRootLabel": "Proyectos", "select": "Seleccionar", "notAvailable": "N/D" + }, + "events": { + "code_report": { + "analysis": { + "completed": { + "label": "Análisis completado", + "description": "Una herramienta de análisis ha terminado de analizar un servicio.", + "fields": { + "serviceId": "Servicio", + "tool": "Herramienta", + "gitInfo": { + "branch": "Rama" + }, + "summary": { + "critical": "Vulnerabilidades críticas", + "high": "Vulnerabilidades altas", + "medium": "Vulnerabilidades medias", + "low": "Vulnerabilidades bajas", + "total": "Total de vulnerabilidades" + }, + "hasVulnerabilities": "Tiene vulnerabilidades", + "policiesViolated": "Incumple políticas de seguridad" + } + }, + "failed": { + "label": "Análisis fallido", + "description": "Una herramienta de análisis no ha podido completar el análisis de un servicio.", + "fields": { + "serviceId": "Servicio", + "tool": "Herramienta", + "gitInfo": { + "branch": "Rama" + } + } + } + }, + "policy": { + "violated": { + "label": "Política de seguridad incumplida", + "description": "Un análisis completado incumple una política de seguridad del proyecto.", + "fields": { + "serviceId": "Servicio", + "policyId": "Política", + "policyType": "Tipo de política", + "enforcement": "Aplicación" + } + } + }, + "service": { + "created": { + "label": "Servicio creado", + "description": "Se ha creado un servicio en Code Report.", + "fields": { + "name": "Nombre" + } + }, + "deleted": { + "label": "Servicio eliminado", + "description": "Se ha eliminado un servicio de Code Report.", + "fields": { + "serviceId": "Servicio", + "name": "Nombre" + } + } + } + }, + "options": { + "tool": { + "trivy": "Trivy", + "grype": "Grype", + "semgrep": "Semgrep", + "gitleaks": "Gitleaks", + "trufflehog": "TruffleHog", + "sbom": "SBOM", + "syft": "Syft", + "coverage": "Cobertura", + "manual-upload": "Subida manual", + "api": "API" + }, + "policyType": { + "vulnerabilities": "Vulnerabilidades", + "license": "Licencias", + "code_coverage": "Cobertura de código", + "secrets": "Secretos" + }, + "enforcement": { + "warn": "Aviso", + "block": "Bloqueante" + }, + "secretChangedField": { + "key": "Key", + "description": "Descripción", + "folder": "Carpeta", + "values": "Valores" + }, + "projectChangedField": { + "name": "Nombre", + "slug": "Slug", + "description": "Descripción", + "status": "Estado", + "modules": "Módulos", + "organization": "Organización", + "settings": "Ajustes" + }, + "organizationChangedField": { + "name": "Nombre", + "slug": "Slug", + "description": "Descripción" + }, + "accessScope": { + "cluster": "GitOps", + "organization": "Organización", + "project": "Proyecto" + } + }, + "vault": { + "secret": { + "created": { + "label": "Secreto creado", + "description": "Se ha creado un secreto en el vault del proyecto.", + "fields": { + "key": "Key del secreto", + "environmentIds": "Entornos", + "folderPath": "Carpeta" + } + }, + "updated": { + "label": "Secreto actualizado", + "description": "Se ha modificado un secreto del vault del proyecto.", + "fields": { + "key": "Key del secreto", + "environmentIds": "Entornos", + "folderPath": "Carpeta", + "changedFields": "Campos modificados" + } + }, + "deleted": { + "label": "Secreto eliminado", + "description": "Se ha eliminado un secreto del vault del proyecto.", + "fields": { + "key": "Key del secreto", + "environmentIds": "Entornos", + "folderPath": "Carpeta" + } + } + }, + "env": { + "imported": { + "label": "Fichero .env importado", + "description": "Se han importado secretos desde un fichero .env.", + "fields": { + "environmentId": "Entorno", + "folderPath": "Carpeta", + "created": "Secretos creados", + "updated": "Secretos actualizados" + } + } + }, + "environment": { + "created": { + "label": "Entorno creado", + "description": "Se ha creado un entorno en el vault del proyecto.", + "fields": { + "environmentId": "Entorno", + "name": "Nombre" + } + }, + "deleted": { + "label": "Entorno eliminado", + "description": "Se ha eliminado un entorno del vault del proyecto.", + "fields": { + "environmentId": "Entorno", + "name": "Nombre" + } + } + } + }, + "project": { + "created": { + "label": "Proyecto creado", + "description": "Se ha creado un proyecto en la organización.", + "fields": { + "name": "Nombre" + } + }, + "updated": { + "label": "Proyecto actualizado", + "description": "Se ha modificado un proyecto de la organización.", + "fields": { + "projectId": "Proyecto", + "name": "Nombre", + "changedFields": "Campos modificados" + } + }, + "deleted": { + "label": "Proyecto eliminado", + "description": "Se ha eliminado un proyecto de la organización.", + "fields": { + "projectId": "Proyecto", + "name": "Nombre" + } + } + }, + "organization": { + "updated": { + "label": "Organización actualizada", + "description": "Se han modificado los datos de la organización.", + "fields": { + "changedFields": "Campos modificados" + } + } + }, + "access": { + "granted": { + "label": "Acceso concedido", + "description": "Se ha dado acceso a un usuario con un rol.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + }, + "updated": { + "label": "Acceso modificado", + "description": "Ha cambiado el rol o el estado del acceso de un usuario.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + }, + "revoked": { + "label": "Acceso retirado", + "description": "Se ha retirado el acceso de un usuario.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + } + }, + "user": { + "invited": { + "label": "Usuario invitado", + "description": "Se ha invitado a un usuario a la organización.", + "fields": { + "userId": "Usuario", + "roleId": "Rol" + } + } + }, + "invitation": { + "accepted": { + "label": "Invitación aceptada", + "description": "Un usuario ha aceptado su invitación.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + } + }, + "role": { + "updated": { + "label": "Rol modificado", + "description": "Han cambiado el nombre o los permisos de un rol.", + "fields": { + "roleId": "Rol", + "addedPermissions": "Permisos añadidos", + "removedPermissions": "Permisos retirados" + } + } + }, + "api_key": { + "created": { + "label": "API key creada", + "description": "Se ha creado una API key.", + "fields": { + "name": "Nombre" + } + }, + "revoked": { + "label": "API key revocada", + "description": "Se ha revocado una API key.", + "fields": { + "apiKeyId": "API key", + "name": "Nombre" + } + } + }, + "scopeFields": { + "projectId": "Proyecto" + } + }, + "alerts": { + "email": { + "alertSubject": "[GitOps] {alert}: {summary}", + "alertIntro": "Ha ocurrido «{event}» en {where} y cumple las condiciones de esta alerta.", + "occurredAt": "Fecha", + "suppressed": "Además, se omitieron {count} eventos que coincidían con la alerta durante la ventana anterior.", + "footer": "Recibes este email por la alerta «{alert}» en {where}.", + "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.", + "warning": "Si no has sido tú, revoca la API key y cambia tu contraseña cuanto antes." + }, + "openProfile": "Abrir mi perfil" + }, + "manageAlert": "Gestionar la alerta", + "viewInApp": "Ver en GitOps", + "project": "Proyecto", + "greeting": "Hola, {name}:", + "service": "Servicio", + "tool": "Herramienta", + "branch": "Rama", + "commit": "Commit", + "severity": { + "critical": "Críticas", + "high": "Altas", + "medium": "Medias", + "low": "Bajas" + }, + "policiesViolated": "Se han incumplido {count} políticas de seguridad ({blocking} bloqueantes).", + "summary": { + "vulnerabilities": "{critical} críticas, {high} altas ({total} en total)", + "noVulnerabilities": "sin vulnerabilidades", + "analysisFailed": "falló el análisis de {tool}", + "policyViolated": "«{policy}» incumplida ({count})" + } + }, + "operators": { + "eq": "es", + "neq": "no es", + "in": "es uno de", + "not_in": "no es ninguno de", + "contains": "contiene", + "starts_with": "empieza por", + "gt": "mayor que", + "gte": "mayor o igual que", + "lt": "menor que", + "lte": "menor o igual que", + "is_true": "es sí", + "is_false": "es no", + "exists": "tiene valor" + }, + "summary": { + "and": "y", + "or": "o", + "always": "Siempre (sin condiciones)", + "noRecipients": "Sin destinatarios" + }, + "errors": { + "required": "Este campo es obligatorio.", + "too_long": "Es demasiado largo.", + "invalid": "El valor no es válido.", + "unknown_event": "Ese evento no existe.", + "not_alertable": "Ese evento no admite alertas.", + "scope_mismatch": "Este evento solo se puede vigilar desde la organización.", + "forbidden": "No tienes permiso para ver este evento, así que no puedes crear alertas sobre él.", + "unknown_field": "Este campo no existe para el evento elegido.", + "invalid_operator": "Operador no permitido para este campo.", + "unknown_option": "Elige una de las opciones.", + "unknown_reference": "Elige un elemento de este ámbito.", + "too_many": "Hay demasiados elementos.", + "unknown_user": "Algún usuario no pertenece a este ámbito.", + "unknown_role": "Algún rol no pertenece a este ámbito.", + "invalid_channel": "Canal no disponible." + }, + "channels": { + "mail": "Email", + "in_app": "Notificación en la app", + "slack": "Slack", + "soon": "Próximamente" + }, + "list": { + "title": "Alertas", + "descriptionOrganization": "Recibe un email cuando ocurra un evento en la organización o en cualquiera de sus proyectos.", + "descriptionProject": "Recibe un email cuando ocurra un evento en este proyecto.", + "create": "Crear alerta", + "emptyTitle": "Todavía no hay alertas", + "example1": "Avisar al equipo de seguridad si un análisis tiene vulnerabilidades críticas", + "example2": "Avisar cuando alguien borre un secreto de producción", + "example3": "Avisar cuando se cree una API key del proyecto", + "name": "Nombre", + "event": "Evento", + "conditions": "Filtros", + "recipients": "Destinatarios", + "status": "Estado", + "actions": "Acciones", + "enabled": "Activa", + "disabled": "Inactiva", + "toggle": "Activar o desactivar «{name}»", + "edit": "Editar", + "delete": "Borrar", + "confirmDelete": "¿Borrar esta alerta? No se puede deshacer.", + "throttle": "Máx. un email cada {minutes} min", + "inheritedTitle": "Alertas de la organización", + "inheritedDescription": "Estas alertas se definen en la organización y también se disparan con los eventos de este proyecto. Solo se pueden cambiar desde los ajustes de la organización." + }, + "editor": { + "newTitle": "Nueva alerta", + "editTitle": "Editar alerta", + "subtitle": "Elige un evento, filtra por sus campos y decide quién recibe el email.", + "back": "Volver a las alertas", + "stepEvent": "Evento", + "stepConditions": "Condiciones", + "stepRecipients": "Destinatarios y envío", + "stepSave": "Probar y guardar", + "name": "Nombre", + "description": "Descripción (opcional)", + "enabled": "Alerta activa", + "event": "Evento", + "chooseEvent": "Elige un evento…", + "eventHelp": "Solo aparecen los eventos que puedes ver.", + "applyEvent": "Usar este evento", + "chooseEventFirst": "Elige primero un evento para ver sus campos.", + "droppedConditions": "Se han quitado {count} condiciones que no existen en el nuevo evento.", + "matchLabel": "Coincidir con", + "matchAll": "todas las condiciones (Y)", + "matchAny": "cualquiera de ellas (O)", + "noConditions": "Sin condiciones: la alerta salta con cada evento de este tipo.", + "field": "Campo", + "operator": "Operador", + "value": "Valor", + "addCondition": "Añadir condición", + "removeCondition": "Quitar la condición {index}", + "search": "Buscar…", + "searchIn": "Buscar en {label}", + "noOptions": "No hay elementos disponibles.", + "roles": "Roles", + "users": "Usuarios", + "recipientsNotice": "Solo recibirán el email los destinatarios con permiso para ver este evento.", + "channels": "Canal", + "throttle": "No enviar más de un email cada (minutos)", + "throttleHelp": "0 = sin límite. Los eventos que se salten se resumen en el siguiente email.", + "sampleProject": "Proyecto del evento de ejemplo", + "sampleProjectAny": "El que indiquen las condiciones", + "test": "Probar alerta", + "create": "Crear alerta", + "saveChanges": "Guardar cambios", + "fixErrors": "Revisa los campos marcados." + }, + "test": { + "matched": "El evento de ejemplo cumple las condiciones.", + "notMatched": "El evento de ejemplo no cumple las condiciones.", + "recipients": "Se enviaría a: {names}", + "noRecipients": "No se enviaría a nadie.", + "denied": "{count} destinatarios no lo recibirían porque no pueden ver este evento.", + "nothingSent": "Es una prueba: no se ha enviado ningún email." + }, + "mailDisabled": "El email no está configurado (NOTIFICATION_SMTP_*): las alertas se guardan, pero no se enviarán." } } 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..128bc4bf --- /dev/null +++ b/src/lib/server/alerts/operations.ts @@ -0,0 +1,270 @@ +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 type { CatalogEntry } from '#lib/alerts/types'; +import { actorFor, callerCan, canManageAlerts, contextOf, type AlertLocals } from './access'; + +export type { CatalogEntry }; + +/** Outcome of an alert operation, mapped to JSON by the API and to `fail()` by form actions. */ +export type AlertResult = + | { ok: true; status: number; data: T } + | { 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; +} + +// loaders and JSON responses can't carry functions: keep only data +function serializable(definition: EventDefinition, location: AlertLocation): CatalogEntry { + const { + link: _link, + mailSummary: _mailSummary, + mailTemplate: _mailTemplate, + ...data + } = definition; + void _link; + void _mailSummary; + void _mailTemplate; + return { + ...data, + 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/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts new file mode 100644 index 00000000..38938202 --- /dev/null +++ b/src/lib/server/alerts/page.ts @@ -0,0 +1,393 @@ +import { error, fail, redirect } from '@sveltejs/kit'; +import { + alertDirectory, + alertService, + isMailConfigured, + type AlertLocation, + type AlertRow, +} from '#modules/alerts'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { + getEventDefinition, + isEventType, + listAlertFields, + type EventDefinition, + type FieldReference, +} from '#lib/events/catalog'; +import type { + AlertDraft, + AlertEditorData, + AlertListData, + AlertOption, + DraftCondition, +} from '#lib/alerts/types'; +import { canManageAlerts, type AlertLocals } from './access'; +import { + createAlert, + deleteAlert, + listAlerts, + listCatalog, + testDraftAlert, + updateAlert, + type CatalogEntry, +} from './operations'; + +/** Where the pages of a location live and how they link back. */ +export type AlertPageContext = { + location: AlertLocation; + /** `/org//settings/alerts` or `/org//projects//settings/alerts` */ + basePath: string; +}; + +async function permissions(locals: AlertLocals, location: AlertLocation) { + const [canRead, canCreate, canUpdate, canDelete] = await Promise.all([ + canManageAlerts(locals, location, 'read'), + canManageAlerts(locals, location, 'create'), + canManageAlerts(locals, location, 'update'), + canManageAlerts(locals, location, 'delete'), + ]); + return { canRead, canCreate, canUpdate, canDelete }; +} + +/** Options for every reference the catalog fields use, all inside the location. */ +async function referenceOptions( + catalog: CatalogEntry[], + location: AlertLocation, +): Promise> { + const references = new Set(); + for (const definition of catalog) { + for (const field of definition.fields) if (field.reference) references.add(field.reference); + } + const entries = await Promise.all( + [...references].map( + async (reference) => + [ + reference, + await alertDirectory.listReferences(reference, location).catch(() => []), + ] as const, + ), + ); + return Object.fromEntries( + entries.map(([reference, options]) => [ + reference, + options.map((option) => ({ id: option.id, label: option.label })), + ]), + ); +} + +async function recipientOptions(location: AlertLocation) { + const [members, roles] = await Promise.all([ + alertDirectory.listMembers(location).catch(() => []), + alertDirectory.listRoles(location).catch(() => []), + ]); + return { + users: members + .filter((member) => !member.disabled) + .map((member) => ({ id: member.userId, label: member.username })) + .sort((a, b) => a.label.localeCompare(b.label)), + roles: roles.map((role) => ({ id: role.id, label: role.name })), + }; +} + +export async function loadAlertList( + locals: AlertLocals, + context: AlertPageContext, +): Promise { + const { location } = context; + const allowed = await permissions(locals, location); + if (!allowed.canRead) throw error(403, 'Forbidden'); + + const listed = await listAlerts(locals, location); + if (!listed.ok) throw error(listed.status, listed.error); + + // the organization catalog knows every event the inherited alerts may watch + const catalog = await listCatalog(locals, location); + const inheritedCatalog = + location.scope === 'project' + ? await listCatalog(locals, { ...location, scope: 'organization', projectId: null }) + : []; + const organizationLocation: AlertLocation = { + ...location, + scope: 'organization', + projectId: null, + }; + const [references, own, organizationRecipients] = await Promise.all([ + referenceOptions([...catalog, ...inheritedCatalog], organizationLocation), + recipientOptions(location), + location.scope === 'project' ? recipientOptions(organizationLocation) : null, + ]); + // names for the recipients of the location's alerts and of the inherited organization ones + const merge = (a: AlertOption[], b: AlertOption[] = []) => [ + ...a, + ...b.filter((option) => !a.some((existing) => existing.id === option.id)), + ]; + const recipients = { + users: merge(own.users, organizationRecipients?.users), + roles: merge(own.roles, organizationRecipients?.roles), + }; + + return { + basePath: context.basePath, + scope: location.scope, + alerts: listed.data.alerts, + inherited: listed.data.inherited, + catalog: [ + ...catalog, + ...inheritedCatalog.filter((entry) => !catalog.some((c) => c.type === entry.type)), + ], + referenceOptions: references, + users: recipients.users, + roles: recipients.roles, + mailConfigured: isMailConfigured(), + canCreate: allowed.canCreate, + canUpdate: allowed.canUpdate, + canDelete: allowed.canDelete, + }; +} + +function emptyDraft(eventType: string | null): AlertDraft { + return { + name: '', + description: '', + enabled: true, + eventType: eventType ?? '', + match: 'all', + conditions: [], + recipients: { userIds: [], roleIds: [] }, + throttleMinutes: 0, + }; +} + +function toDraft(alert: AlertRow): AlertDraft { + return { + name: alert.name, + description: alert.description ?? '', + enabled: alert.enabled, + eventType: alert.eventType, + match: alert.match, + conditions: alert.conditions.map((condition) => ({ + field: condition.field, + operator: condition.operator, + value: condition.value === undefined ? '' : condition.value, + })), + recipients: { ...alert.recipients }, + throttleMinutes: alert.throttleMinutes, + }; +} + +export async function loadAlertEditor( + locals: AlertLocals, + context: AlertPageContext, + options: { alertId?: string; eventType?: string | null }, +): Promise { + const { location } = context; + const allowed = await permissions(locals, location); + if (!allowed.canRead) throw error(403, 'Forbidden'); + + let alert: AlertRow | null = null; + if (options.alertId) { + alert = (await alertService.get(options.alertId).catch(() => null))?.toJson() ?? null; + const sameLocation = + alert && + alert.organizationId === location.organizationId && + alert.scope === location.scope && + (location.scope === 'organization' || alert.projectId === location.projectId); + if (!alert || !sameLocation) throw error(404, 'Alert not found'); + } else if (!allowed.canCreate) { + throw error(403, 'Forbidden'); + } + + const catalog = await listCatalog(locals, location); + const [references, recipients] = await Promise.all([ + referenceOptions(catalog, location), + recipientOptions(location), + ]); + + const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null); + if (!alert && options.eventType && !catalog.some((entry) => entry.type === options.eventType)) { + draft.eventType = ''; + } + + return { + basePath: context.basePath, + scope: location.scope, + alertId: alert?.id ?? null, + draft, + catalog, + referenceOptions: references, + users: recipients.users, + roles: recipients.roles, + mailConfigured: isMailConfigured(), + canSave: alert ? allowed.canUpdate : allowed.canCreate, + canDelete: Boolean(alert) && allowed.canDelete, + }; +} + +/** `conditions..` names → condition list; rows without a field are dropped. */ +export function parseAlertForm(form: FormData): AlertDraft { + const indices = new Set(); + for (const key of form.keys()) { + const match = key.match(/^conditions\.(\d+)\.field$/); + if (match) indices.add(Number(match[1])); + } + + const conditions = [...indices] + .sort((a, b) => a - b) + .map((index) => { + const values = form + .getAll(`conditions.${index}.value`) + .map(String) + .filter((value) => value !== ''); + const multiple = form.get(`conditions.${index}.multiple`) === 'true'; + return { + field: String(form.get(`conditions.${index}.field`) ?? ''), + // validated by the service; the draft only echoes it back + operator: String( + form.get(`conditions.${index}.operator`) ?? '', + ) as DraftCondition['operator'], + value: multiple ? values : (values[0] ?? ''), + }; + }) + .filter((condition) => condition.field); + + return { + name: String(form.get('name') ?? ''), + description: String(form.get('description') ?? ''), + enabled: form.get('enabled') === 'on' || form.get('enabled') === 'true', + eventType: String(form.get('eventType') ?? ''), + match: form.get('match') === 'any' ? 'any' : 'all', + conditions, + recipients: { + userIds: form.getAll('userIds').map(String), + roleIds: form.getAll('roleIds').map(String), + }, + throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0, + }; +} + +/** The draft as service input: empty optional values become `undefined`. */ +function toInput(draft: AlertDraft) { + return { + ...draft, + conditions: draft.conditions.map((condition) => ({ + ...condition, + value: condition.value === '' ? undefined : condition.value, + })), + }; +} + +/** Form actions shared by the organization and project alert pages. */ +export function alertActions( + resolve: (event: { + params: Record; + locals: AlertLocals; + }) => Promise, +) { + return { + /** + * Without JavaScript the editor posts here to add/remove a condition row or to switch the + * event: nothing is saved, the page comes back with the updated draft. + */ + async draft(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const intent = String(form.get('intent') ?? ''); + if (intent === 'add_condition' && isEventType(draft.eventType)) { + const definition = getEventDefinition(draft.eventType) as EventDefinition; + const [first] = listAlertFields(definition, context.location.scope); + if (first) { + draft.conditions.push({ + field: first.key as string, + operator: first.operators[0], + value: '', + }); + } + } else if (intent.startsWith('remove_condition:')) { + const index = Number(intent.split(':')[1]); + draft.conditions.splice(index, 1); + } else if (intent === 'change_event') { + draft.conditions = []; + } + return { draft }; + }, + + async save(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const alertId = String(form.get('alertId') ?? '') || null; + const result = alertId + ? await updateAlert(event.locals, alertId, toInput(draft)) + : await createAlert(event.locals, context.location, toInput(draft)); + if (!result.ok) { + return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} }); + } + throw redirect(303, `${context.basePath}?saved=${result.data.id}`); + }, + + async test(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const sampleProjectId = String(form.get('sampleProjectId') ?? '') || undefined; + const result = await testDraftAlert(event.locals, context.location, { + ...toInput(draft), + sampleProjectId, + }); + if (!result.ok) { + return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} }); + } + return { draft, test: result.data }; + }, + + async toggle(event: { request: Request; params: Record; locals: AlertLocals }) { + await resolve(event); + const form = await event.request.formData(); + const alertId = String(form.get('alertId') ?? ''); + const result = await updateAlert(event.locals, alertId, { + enabled: form.get('enabled') === 'true', + }); + if (!result.ok) return fail(result.status, { error: result.error, alertId }); + return { toggled: alertId }; + }, + + async delete(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const alertId = String(form.get('alertId') ?? ''); + const result = await deleteAlert(event.locals, alertId); + if (!result.ok) return fail(result.status, { error: result.error, alertId }); + if (form.get('redirect') === 'list') throw redirect(303, context.basePath); + return { deleted: alertId }; + }, + }; +} + +/** `/org//settings/alerts/…` */ +export async function organizationAlertContext(event: { + params: Record; +}): Promise { + const organization = await organizationService.tryFindBySlug(event.params.org); + if (!organization) throw error(404, 'Organization not found'); + return { + location: { scope: 'organization', organizationId: organization.id, projectId: null }, + basePath: `/org/${organization.slug}/settings/alerts`, + }; +} + +/** `/org//projects//settings/alerts/…` */ +export async function projectAlertContext(event: { + params: Record; +}): Promise { + const project = await projectService.getProjectBySlug(event.params.slug).catch(() => null); + const organization = project?.organization; + if (!project || !organization || organization.slug !== event.params.org) { + throw error(404, 'Project not found'); + } + return { + location: { scope: 'project', organizationId: organization.id, projectId: project.id }, + basePath: `/org/${organization.slug}/projects/${project.slug}/settings/alerts`, + }; +} diff --git a/src/lib/server/events/config.ts b/src/lib/server/events/config.ts new file mode 100644 index 00000000..648b2c8f --- /dev/null +++ b/src/lib/server/events/config.ts @@ -0,0 +1,34 @@ +import * as env from '$app/env/private'; + +export const DEFAULT_EVENTS_EXPIRATION = '7d'; + +const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } as const; + +/** + * Parses a duration such as `30d`, `12h`, `45m` or `90s` (a bare number means seconds) into + * milliseconds. Returns `null` for anything else. + */ +export function parseDuration(value: string): number | null { + const match = /^(\d+)\s*([smhd]?)$/i.exec(value.trim()); + if (!match) return null; + const amount = Number(match[1]); + if (!Number.isSafeInteger(amount) || amount <= 0) return null; + const unit = (match[2] || 's').toLowerCase() as keyof typeof UNIT_MS; + return amount * UNIT_MS[unit]; +} + +/** + * How long the organization events page keeps events (`GITOPS_EVENTS_EXPIRATION`, default 7 days). + * An invalid value falls back to the default and is reported through `onInvalid`. + */ +export function readEventsExpirationMs(onInvalid?: (value: string) => void): number { + const raw = env.GITOPS_EVENTS_EXPIRATION?.trim(); + const fallback = parseDuration(DEFAULT_EVENTS_EXPIRATION)!; + if (!raw) return fallback; + const parsed = parseDuration(raw); + if (parsed === null) { + onInvalid?.(raw); + return fallback; + } + return parsed; +} diff --git a/src/lib/server/events/event-bus.test.ts b/src/lib/server/events/event-bus.test.ts new file mode 100644 index 00000000..ce940131 --- /dev/null +++ b/src/lib/server/events/event-bus.test.ts @@ -0,0 +1,285 @@ +import { describe, expect, it, vi } from 'vitest'; +import { runWithActor } from '#lib/server/request-context'; +import { InProcessEventBus, actorFromRequest } from './event-bus'; +import { RecordingEventBus } from './testing'; + +type TestEvents = { + 'test.item.created': { itemId: string }; + 'test.item.deleted': { itemId: string; reason: string }; +}; + +function createBus() { + const logger = { error: vi.fn() }; + const bus = new InProcessEventBus({ logger }); + return { bus, logger }; +} + +describe('InProcessEventBus', () => { + it('builds the envelope and returns it from publish', () => { + const bus = new InProcessEventBus({ + logger: { error: vi.fn() }, + now: () => new Date('2026-11-20T10:00:00.000Z'), + generateId: () => 'event-1', + }); + + const event = bus.publish( + 'test.item.created', + { itemId: 'a' }, + { scope: { organizationId: 'org-1', projectId: 'project-1' } }, + ); + + expect(event).toEqual({ + id: 'event-1', + type: 'test.item.created', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + payload: { itemId: 'a' }, + }); + }); + + it('delivers each event only to the subscribers of its type', async () => { + const { bus } = createBus(); + const created = vi.fn(); + const deleted = vi.fn(); + bus.subscribe('test.item.created', created); + bus.subscribe('test.item.deleted', deleted); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(created).toHaveBeenCalledTimes(1); + expect(created.mock.calls[0][0].payload).toEqual({ itemId: 'a' }); + expect(deleted).not.toHaveBeenCalled(); + }); + + it("delivers every event to '*' subscribers", async () => { + const { bus } = createBus(); + const all = vi.fn(); + bus.subscribe('*', all); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.deleted', { itemId: 'a', reason: 'gone' }); + await bus.drain(); + + expect(all.mock.calls.map(([event]) => event.type)).toEqual([ + 'test.item.created', + 'test.item.deleted', + ]); + }); + + it('stops delivering after unsubscribe', async () => { + const { bus } = createBus(); + const handler = vi.fn(); + const unsubscribe = bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + unsubscribe(); + bus.publish('test.item.created', { itemId: 'b' }); + await bus.drain(); + + expect(handler).toHaveBeenCalledTimes(1); + }); + + it('does not deliver events already queued when the subscriber unsubscribes', async () => { + const { bus } = createBus(); + const handler = vi.fn(); + const unsubscribe = bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + unsubscribe(); + await bus.drain(); + + expect(handler).not.toHaveBeenCalled(); + }); + + it('isolates a failing handler and logs it with the event type and id', async () => { + const { bus, logger } = createBus(); + const healthy = vi.fn(); + bus.subscribe('test.item.created', () => { + throw new Error('sync boom'); + }); + bus.subscribe('test.item.created', async () => { + throw new Error('async boom'); + }); + bus.subscribe('test.item.created', healthy); + + const event = bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(healthy).toHaveBeenCalledTimes(1); + expect(logger.error).toHaveBeenCalledTimes(2); + expect(logger.error).toHaveBeenCalledWith( + expect.objectContaining({ eventType: 'test.item.created', eventId: event.id }), + expect.any(String), + ); + }); + + it('keeps delivering later events to a subscriber whose handler failed', async () => { + const { bus } = createBus(); + const seen: string[] = []; + bus.subscribe('test.item.created', (event) => { + if (event.payload.itemId === 'a') throw new Error('boom'); + seen.push(event.payload.itemId); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.created', { itemId: 'b' }); + await bus.drain(); + + expect(seen).toEqual(['b']); + }); + + it('does not wait for handlers in publish', async () => { + const { bus } = createBus(); + let release!: () => void; + const handler = vi.fn(() => new Promise((resolve) => (release = resolve))); + bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + + // handlers are scheduled, not called inline + expect(handler).not.toHaveBeenCalled(); + + await Promise.resolve(); + await Promise.resolve(); + expect(handler).toHaveBeenCalledTimes(1); + release(); + await bus.drain(); + }); + + it('preserves publish order per subscriber even with async handlers', async () => { + const { bus } = createBus(); + const seen: string[] = []; + bus.subscribe('test.item.created', async (event) => { + // the first event takes longer: it must still be handled first + await new Promise((resolve) => setTimeout(resolve, event.payload.itemId === 'a' ? 20 : 0)); + seen.push(event.payload.itemId); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.created', { itemId: 'b' }); + bus.publish('test.item.created', { itemId: 'c' }); + await bus.drain(); + + expect(seen).toEqual(['a', 'b', 'c']); + }); + + it('does not let a slow subscriber delay the others', async () => { + const { bus } = createBus(); + let release!: () => void; + bus.subscribe('test.item.created', () => new Promise((resolve) => (release = resolve))); + const fast = vi.fn(); + bus.subscribe('test.item.created', fast); + + bus.publish('test.item.created', { itemId: 'a' }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(fast).toHaveBeenCalledTimes(1); + release(); + await bus.drain(); + }); + + it('drain waits for pending handlers, including events they publish', async () => { + const { bus } = createBus(); + const finished: string[] = []; + bus.subscribe('test.item.created', async (event) => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished.push('created'); + bus.publish('test.item.deleted', { itemId: event.payload.itemId, reason: 'cascade' }); + }); + bus.subscribe('test.item.deleted', async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished.push('deleted'); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(finished).toEqual(['created', 'deleted']); + }); + + it('drain resolves immediately with nothing pending', async () => { + const { bus } = createBus(); + await expect(bus.drain()).resolves.toBeUndefined(); + }); + + describe('actor', () => { + it('resolves a user actor from the request context', () => { + const { bus } = createBus(); + + const event = runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'user-1' }, () => + bus.publish('test.item.created', { itemId: 'a' }), + ); + + expect(event.actor).toEqual({ kind: 'user', userId: 'user-1' }); + }); + + it('resolves an API key actor from the request context', () => { + const { bus } = createBus(); + + const event = runWithActor( + { + name: 'apikey:ci', + email: 'apikey+key-1@gitops.local', + apiKeyId: 'key-1', + apiKeyProjectId: 'project-1', + }, + () => bus.publish('test.item.created', { itemId: 'a' }), + ); + + expect(event.actor).toEqual({ kind: 'api_key', apiKeyId: 'key-1', projectId: 'project-1' }); + }); + + it('falls back to the system actor outside a request', () => { + const { bus } = createBus(); + + expect(bus.publish('test.item.created', { itemId: 'a' }).actor).toEqual({ kind: 'system' }); + }); + + it('lets the publisher override the actor', () => { + const { bus } = createBus(); + + const event = runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'user-1' }, () => + bus.publish('test.item.created', { itemId: 'a' }, { actor: { kind: 'system' } }), + ); + + expect(event.actor).toEqual({ kind: 'system' }); + }); + + it('maps request actors without ids to the system actor', () => { + expect(actorFromRequest({ name: 'legacy', email: 'legacy@example.com' })).toEqual({ + kind: 'system', + }); + expect(actorFromRequest(null)).toEqual({ kind: 'system' }); + }); + }); +}); + +describe('RecordingEventBus', () => { + it('records published events in order and still notifies subscribers', async () => { + const bus = new RecordingEventBus(); + const handler = vi.fn(); + bus.subscribe('test.item.deleted', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.deleted', { itemId: 'a', reason: 'gone' }); + await bus.drain(); + + expect(bus.types()).toEqual(['test.item.created', 'test.item.deleted']); + expect(bus.ofType('test.item.deleted').map((event) => event.payload)).toEqual([ + { itemId: 'a', reason: 'gone' }, + ]); + expect(handler).toHaveBeenCalledTimes(1); + }); + + it('clears recorded events', () => { + const bus = new RecordingEventBus(); + bus.publish('test.item.created', { itemId: 'a' }); + + bus.clear(); + + expect(bus.events).toEqual([]); + }); +}); diff --git a/src/lib/server/events/event-bus.ts b/src/lib/server/events/event-bus.ts new file mode 100644 index 00000000..34d855b3 --- /dev/null +++ b/src/lib/server/events/event-bus.ts @@ -0,0 +1,153 @@ +import type { Logger } from 'pino'; +import { createLogger } from '#lib/server/logger'; +import { getCurrentActor, type RequestActor } from '#lib/server/request-context'; +import type { + AnyEventEnvelope, + DomainEventMap, + EventActor, + EventEnvelope, + EventHandler, + EventTypeOf, + PublishOptions, + Unsubscribe, +} from './types'; + +export interface EventBus { + /** + * Publishes `type` and returns its envelope immediately; handlers run asynchronously. + * Call it only after the GitDB write it describes has succeeded. + */ + publish>( + type: K, + payload: M[K], + opts?: PublishOptions, + ): EventEnvelope; + + /** Subscribes to one event type, or to every type with `'*'`. Returns the unsubscribe function. */ + subscribe>( + type: K, + handler: EventHandler>, + ): Unsubscribe; + subscribe(type: '*', handler: EventHandler>): Unsubscribe; + + /** Resolves once every handler scheduled so far (and any they schedule) has finished. */ + drain(): Promise; +} + +type Subscription = { + type: EventTypeOf | '*'; + handler: EventHandler>; + active: boolean; + /** Per-subscriber queue: keeps delivery in publish order even for async handlers. */ + tail: Promise; +}; + +export type InProcessEventBusOptions = { + logger?: Pick; + resolveActor?: () => RequestActor | null; + now?: () => Date; + generateId?: () => string; +}; + +/** Maps the request context onto an event actor; no context means a system event. */ +export function actorFromRequest(actor: RequestActor | null): EventActor { + if (actor?.apiKeyId) { + return { kind: 'api_key', apiKeyId: actor.apiKeyId, projectId: actor.apiKeyProjectId ?? null }; + } + if (actor?.userId) return { kind: 'user', userId: actor.userId }; + return { kind: 'system' }; +} + +/** + * In-process, at-most-once event bus. Events are not persisted and never leave the process. + * + * - `publish()` never waits for handlers and never throws because of them. + * - Each subscriber receives events in publish order; a slow subscriber does not delay others. + * - A failing handler is logged with the event `type` and `id` and does not affect other handlers + * or later events. + */ +export class InProcessEventBus implements EventBus { + private readonly subscriptions = new Set>(); + private readonly log: Pick; + private readonly resolveActor: () => RequestActor | null; + private readonly now: () => Date; + private readonly generateId: () => string; + + constructor(options: InProcessEventBusOptions = {}) { + this.log = options.logger ?? createLogger('events'); + this.resolveActor = options.resolveActor ?? getCurrentActor; + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + } + + publish>( + type: K, + payload: M[K], + opts: PublishOptions = {}, + ): EventEnvelope { + const event: EventEnvelope = { + id: this.generateId(), + type, + occurredAt: this.now().toISOString(), + actor: opts.actor ?? actorFromRequest(this.resolveActor()), + scope: { ...opts.scope }, + payload, + }; + + this.dispatch(event as unknown as AnyEventEnvelope); + return event; + } + + subscribe>( + type: K, + handler: EventHandler>, + ): Unsubscribe; + subscribe(type: '*', handler: EventHandler>): Unsubscribe; + subscribe( + type: EventTypeOf | '*', + handler: EventHandler> | EventHandler, + ): Unsubscribe { + const subscription: Subscription = { + type, + handler: handler as EventHandler>, + active: true, + tail: Promise.resolve(), + }; + this.subscriptions.add(subscription); + + return () => { + subscription.active = false; + this.subscriptions.delete(subscription); + }; + } + + async drain(): Promise { + // handlers may publish more events while we wait: loop until every queue is settled + for (;;) { + const tails = [...this.subscriptions].map((s) => s.tail); + await Promise.all(tails); + const settled = [...this.subscriptions].every((s, i) => s.tail === tails[i]); + if (settled && tails.length === this.subscriptions.size) return; + } + } + + private dispatch(event: AnyEventEnvelope): void { + for (const subscription of this.subscriptions) { + if (subscription.type !== '*' && subscription.type !== event.type) continue; + // `.then` defers to a microtask, so publish() returns before any handler runs + subscription.tail = subscription.tail.then(() => this.run(subscription, event)); + } + } + + private async run(subscription: Subscription, event: AnyEventEnvelope): Promise { + if (!subscription.active) return; + try { + await subscription.handler(event); + } catch (error) { + this.log.error( + { err: error, eventType: event.type, eventId: event.id, subscribedTo: subscription.type }, + `[events] handler failed for ${event.type} (${event.id})`, + ); + } + } +} diff --git a/src/lib/server/events/event-log.test.ts b/src/lib/server/events/event-log.test.ts new file mode 100644 index 00000000..96472a34 --- /dev/null +++ b/src/lib/server/events/event-log.test.ts @@ -0,0 +1,152 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { InProcessEventBus } from './event-bus'; +import { InMemoryEventLog } from './event-log'; +import { parseDuration, readEventsExpirationMs } from './config'; +import type { AnyDomainEvent } from './types'; + +const HOUR = 3_600_000; +const START = Date.parse('2026-11-20T10:00:00.000Z'); + +function event(id: string, overrides: Partial = {}): AnyDomainEvent { + return { + id, + type: 'project.created', + occurredAt: new Date(START).toISOString(), + actor: { kind: 'user', userId: 'ana' }, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + payload: { projectId: 'project-1', name: 'Shop', slug: 'shop' }, + ...overrides, + } as AnyDomainEvent; +} + +function createLog(options: { ttlMs?: number; maxEvents?: number } = {}) { + let now = START; + const log = new InMemoryEventLog({ + ttlMs: options.ttlMs ?? 24 * HOUR, + maxEvents: options.maxEvents, + now: () => now, + }); + return { log, advance: (ms: number) => (now += ms), at: () => now }; +} + +describe('InMemoryEventLog', () => { + it('lists an organization events newest first', () => { + const { log } = createLog(); + log.record(event('a')); + log.record(event('b')); + log.record(event('other', { scope: { organizationId: 'org-2', projectId: null } })); + + expect(log.list({ organizationId: 'org-1' }).map((entry) => entry.event.id)).toEqual([ + 'b', + 'a', + ]); + }); + + it('filters by type, ack status and limit', () => { + const { log } = createLog(); + log.record(event('a')); + log.record(event('b', { type: 'project.deleted' } as Partial)); + log.record(event('c')); + log.ack('c', { userId: 'ana', username: 'ana' }); + + expect( + log.list({ organizationId: 'org-1', types: ['project.created'] }).map((e) => e.event.id), + ).toEqual(['c', 'a']); + expect(log.list({ organizationId: 'org-1', acked: true }).map((e) => e.event.id)).toEqual([ + 'c', + ]); + expect(log.list({ organizationId: 'org-1', acked: false }).map((e) => e.event.id)).toEqual([ + 'b', + 'a', + ]); + expect(log.list({ organizationId: 'org-1', limit: 1 })).toHaveLength(1); + }); + + it('records who acknowledged an event and when, keeping the first ack', () => { + const { log, advance, at } = createLog(); + log.record(event('a')); + advance(1000); + const ackedAt = new Date(at()).toISOString(); + + log.ack('a', { userId: 'ana', username: 'ana' }); + advance(1000); + log.ack('a', { userId: 'bob', username: 'bob' }); + + expect(log.get('a')?.ack).toEqual({ userId: 'ana', username: 'ana', at: ackedAt }); + expect(log.ack('missing', { userId: 'ana', username: 'ana' })).toBeNull(); + }); + + it('drops events once they expire', () => { + const { log, advance } = createLog({ ttlMs: 2 * HOUR }); + log.record(event('old')); + advance(HOUR); + log.record(event('new', { occurredAt: new Date(START + HOUR).toISOString() })); + advance(HOUR + 1); + + expect(log.list({ organizationId: 'org-1' }).map((entry) => entry.event.id)).toEqual(['new']); + expect(log.get('old')).toBeNull(); + }); + + it('keeps at most maxEvents, dropping the oldest', () => { + const { log } = createLog({ maxEvents: 2 }); + log.record(event('a')); + log.record(event('b')); + log.record(event('c')); + + expect(log.size).toBe(2); + expect(log.get('a')).toBeNull(); + }); + + it('records every event published on the bus it is attached to', async () => { + const bus = new InProcessEventBus({ logger: { error: vi.fn() } }); + const log = new InMemoryEventLog({ ttlMs: HOUR }); + log.attach(bus); + + bus.publish( + 'project.created', + { projectId: 'p', name: 'P', slug: 'p' }, + { scope: { organizationId: 'org-1', projectId: 'p' } }, + ); + await bus.drain(); + + expect(log.list({ organizationId: 'org-1' }).map((entry) => entry.event.type)).toEqual([ + 'project.created', + ]); + }); +}); + +describe('events expiration config', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it.each([ + ['30d', 30 * 24 * HOUR], + ['12h', 12 * HOUR], + ['45m', 45 * 60_000], + ['90s', 90_000], + ['3600', 3_600_000], + [' 2D ', 2 * 24 * HOUR], + ])('parses %s', (value, expected) => { + expect(parseDuration(value)).toBe(expected); + }); + + it.each(['', '0d', '-1h', '1w', 'ten days', '1.5h'])('rejects %j', (value) => { + expect(parseDuration(value)).toBeNull(); + }); + + it('reads GITOPS_EVENTS_EXPIRATION, defaulting to 7 days', () => { + expect(readEventsExpirationMs()).toBe(7 * 24 * HOUR); + + vi.stubEnv('GITOPS_EVENTS_EXPIRATION', '30d'); + expect(readEventsExpirationMs()).toBe(30 * 24 * HOUR); + }); + + it('falls back to the default and reports an invalid value', () => { + vi.stubEnv('GITOPS_EVENTS_EXPIRATION', 'forever'); + const onInvalid = vi.fn(); + + expect(readEventsExpirationMs(onInvalid)).toBe(7 * 24 * HOUR); + expect(onInvalid).toHaveBeenCalledWith('forever'); + }); +}); diff --git a/src/lib/server/events/event-log.ts b/src/lib/server/events/event-log.ts new file mode 100644 index 00000000..f3f3e522 --- /dev/null +++ b/src/lib/server/events/event-log.ts @@ -0,0 +1,111 @@ +import type { EventBus } from './event-bus'; +import type { AnyDomainEvent, EventType, Unsubscribe } from './types'; + +export type EventAck = { + userId: string; + username: string; + /** ISO 8601 */ + at: string; +}; + +export type LoggedEvent = { + event: AnyDomainEvent; + ack: EventAck | null; +}; + +export type EventLogQuery = { + organizationId: string; + types?: readonly EventType[]; + /** `true`: only acknowledged, `false`: only pending, omitted: both. */ + acked?: boolean; + limit?: number; +}; + +export type InMemoryEventLogOptions = { + /** How long an event is kept, in milliseconds. */ + ttlMs: number; + /** Upper bound on retained events; the oldest are dropped first. */ + maxEvents?: number; + now?: () => number; +}; + +export const DEFAULT_MAX_LOGGED_EVENTS = 10_000; + +/** + * Recent domain events, kept in memory for the organization events page, with a shared + * acknowledgement per event (who and when). + * + * Per process and not persisted: a restart empties it and each replica keeps its own log. + * Events older than `ttlMs` are dropped, and the log never holds more than `maxEvents`. + */ +export class InMemoryEventLog { + // insertion order is publish order, so the oldest entries are always first + private readonly entries = new Map(); + private readonly ttlMs: number; + private readonly maxEvents: number; + private readonly now: () => number; + + constructor(options: InMemoryEventLogOptions) { + this.ttlMs = options.ttlMs; + this.maxEvents = options.maxEvents ?? DEFAULT_MAX_LOGGED_EVENTS; + this.now = options.now ?? Date.now; + } + + /** Records every event published on `bus` from now on. */ + attach(bus: Pick): Unsubscribe { + return bus.subscribe('*', (event) => this.record(event)); + } + + record(event: AnyDomainEvent): void { + this.entries.set(event.id, { event, ack: null }); + this.prune(); + while (this.entries.size > this.maxEvents) { + const oldest = this.entries.keys().next().value; + if (oldest === undefined) break; + this.entries.delete(oldest); + } + } + + /** Events of an organization (including its projects), newest first. */ + list(query: EventLogQuery): LoggedEvent[] { + this.prune(); + const types = query.types ? new Set(query.types) : null; + const result: LoggedEvent[] = []; + + for (const entry of [...this.entries.values()].reverse()) { + if (entry.event.scope.organizationId !== query.organizationId) continue; + if (types && !types.has(entry.event.type)) continue; + if (query.acked !== undefined && (entry.ack !== null) !== query.acked) continue; + result.push(entry); + if (query.limit !== undefined && result.length >= query.limit) break; + } + return result; + } + + get(id: string): LoggedEvent | null { + this.prune(); + return this.entries.get(id) ?? null; + } + + /** Acknowledges an event. Idempotent: the first acknowledgement is kept. */ + ack(id: string, by: { userId: string; username: string }): LoggedEvent | null { + const entry = this.get(id); + if (!entry) return null; + entry.ack ??= { ...by, at: new Date(this.now()).toISOString() }; + return entry; + } + + /** Drops expired events. */ + prune(): void { + const cutoff = this.now() - this.ttlMs; + for (const [id, entry] of this.entries) { + // entries are in publish order: stop at the first one that is still fresh + if (Date.parse(entry.event.occurredAt) >= cutoff) break; + this.entries.delete(id); + } + } + + get size(): number { + return this.entries.size; + } +} diff --git a/src/lib/server/events/index.ts b/src/lib/server/events/index.ts new file mode 100644 index 00000000..3ae12ee5 --- /dev/null +++ b/src/lib/server/events/index.ts @@ -0,0 +1,47 @@ +import { InProcessEventBus, type EventBus } from './event-bus'; +import { InMemoryEventLog } from './event-log'; +import { readEventsExpirationMs } from './config'; +import { createLogger } from '#lib/server/logger'; + +export { InProcessEventBus, actorFromRequest } from './event-bus'; +export type { EventBus, InProcessEventBusOptions } from './event-bus'; +export type * from './types'; +export { resolveProjectScope, type ProjectScopeLookup } from './scope'; +export { publishAfterWrite, type EventPublisher } from './publish'; +export { InMemoryEventLog } from './event-log'; +export type { EventAck, EventLogQuery, LoggedEvent } from './event-log'; + +const GLOBAL_KEY = Symbol.for('gitops.events.bus'); +const LOG_KEY = Symbol.for('gitops.events.log'); + +type GlobalWithBus = typeof globalThis & { + [GLOBAL_KEY]?: EventBus; + [LOG_KEY]?: InMemoryEventLog; +}; + +/** + * Process-wide event bus. Stored on `globalThis` so Vite HMR re-evaluating this module in + * development keeps the same instance instead of piling up duplicate subscribers. + * + * Services receive it through their constructor from their module's `index.ts`; only composition + * roots import this singleton. + */ +export const eventBus: EventBus = ((globalThis as GlobalWithBus)[GLOBAL_KEY] ??= + new InProcessEventBus()); + +/** + * Recent events for the organization events page, kept for `GITOPS_EVENTS_EXPIRATION`. Attached + * to the bus once per process (also HMR-safe). + */ +export const eventLog: InMemoryEventLog = ((globalThis as GlobalWithBus)[LOG_KEY] ??= (() => { + const log = new InMemoryEventLog({ + ttlMs: readEventsExpirationMs((value) => + createLogger('events').warn( + { value }, + '[events] invalid GITOPS_EVENTS_EXPIRATION, using the default', + ), + ), + }); + log.attach(eventBus); + return log; +})()); diff --git a/src/lib/server/events/publish.ts b/src/lib/server/events/publish.ts new file mode 100644 index 00000000..6ee48601 --- /dev/null +++ b/src/lib/server/events/publish.ts @@ -0,0 +1,25 @@ +import type { Logger } from 'pino'; +import type { EventBus } from './event-bus'; +import type { DomainEventMap, EventScope, EventType } from './types'; + +export type EventPublisher = Pick; + +/** + * Publishes an event describing a write that already succeeded. Resolving the scope or publishing + * never throws back into the caller: a failure is logged and the request carries on. + */ +export async function publishAfterWrite( + events: EventPublisher | undefined, + log: Pick, + type: K, + payload: DomainEventMap[K], + scope: EventScope | (() => Promise), +): Promise { + if (!events) return; + try { + const resolved = typeof scope === 'function' ? await scope() : scope; + events.publish(type, payload, { scope: resolved }); + } catch (error) { + log.error({ err: error, eventType: type }, `[events] failed to publish ${type}`); + } +} diff --git a/src/lib/server/events/scope.ts b/src/lib/server/events/scope.ts new file mode 100644 index 00000000..7c488f3a --- /dev/null +++ b/src/lib/server/events/scope.ts @@ -0,0 +1,19 @@ +import type { EventScope } from './types'; + +/** Project lookup used to add the organization to a project-scoped event. */ +export type ProjectScopeLookup = { + getProject(id: string): Promise<{ organization?: { id: string } | null } | null>; +}; + +/** + * Scope of an event that happened inside a project. A failed lookup only drops the organization: + * resolving the scope must never fail the write that already succeeded. + */ +export async function resolveProjectScope( + projectId: string | null | undefined, + projects: ProjectScopeLookup | undefined, +): Promise { + if (!projectId) return { organizationId: null, projectId: null }; + const project = projects ? await projects.getProject(projectId).catch(() => null) : null; + return { organizationId: project?.organization?.id ?? null, projectId }; +} diff --git a/src/lib/server/events/testing.ts b/src/lib/server/events/testing.ts new file mode 100644 index 00000000..32239f5c --- /dev/null +++ b/src/lib/server/events/testing.ts @@ -0,0 +1,51 @@ +import { InProcessEventBus, type InProcessEventBusOptions } from './event-bus'; +import type { + AnyEventEnvelope, + DomainEventMap, + EventEnvelope, + EventTypeOf, + PublishOptions, +} from './types'; + +/** + * Event bus for unit tests: records every published event so services can be asserted on what + * they emit. Subscribers still work, so it can also wire a subscriber under test. + * + * ```ts + * const events = new RecordingEventBus(); + * const service = new VaultService(repository, events); + * await service.createSecret(input); + * expect(events.ofType('vault.secret.created')).toHaveLength(1); + * ``` + */ +export class RecordingEventBus extends InProcessEventBus { + readonly events: AnyEventEnvelope[] = []; + + constructor(options: InProcessEventBusOptions = {}) { + super({ logger: { error: () => {} }, ...options }); + } + + override publish>( + type: K, + payload: M[K], + opts?: PublishOptions, + ): EventEnvelope { + const event = super.publish(type, payload, opts); + this.events.push(event as unknown as AnyEventEnvelope); + return event; + } + + /** Recorded events of one type, in publish order. */ + ofType>(type: K): EventEnvelope[] { + return this.events.filter((event) => event.type === type) as unknown as EventEnvelope[]; + } + + /** Event types recorded so far, in publish order. */ + types(): EventTypeOf[] { + return this.events.map((event) => event.type); + } + + clear(): void { + this.events.length = 0; + } +} diff --git a/src/lib/server/events/types.ts b/src/lib/server/events/types.ts new file mode 100644 index 00000000..dc0cea70 --- /dev/null +++ b/src/lib/server/events/types.ts @@ -0,0 +1,62 @@ +import type { DomainEventMap } from '#lib/events/domain-events'; + +/** + * Domain event types. See `docs/adr/0001-event-bus-and-alerts.md` for the design and rules. + * + * Event names follow `..` in snake_case, with the action as a past + * participle (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). + */ + +/** Who caused the event. Resolved from the request context when the publisher does not pass one. */ +export type EventActor = + | { kind: 'user'; userId: string } + | { kind: 'api_key'; apiKeyId: string; projectId: string | null } + | { kind: 'system' }; + +/** Where the event happened; the alert engine matches alerts by this scope. */ +export type EventScope = { + organizationId?: string | null; + projectId?: string | null; +}; + +/** + * Event type → payload. Declared in `#lib/events/domain-events` so the alert builder UI can share + * it without importing server code. + */ +export type { DomainEventMap }; + +/** Event names of an event map. */ +export type EventTypeOf = Extract; + +/** Envelope published on the bus for event `K` of map `M`. */ +export type EventEnvelope> = { + /** `crypto.randomUUID()` */ + id: string; + type: K; + /** ISO 8601 */ + occurredAt: string; + actor: EventActor; + scope: EventScope; + payload: M[K]; +}; + +/** Discriminated union of every envelope of map `M` (what a `'*'` subscriber receives). */ +export type AnyEventEnvelope = { + [K in EventTypeOf]: EventEnvelope; +}[EventTypeOf]; + +export type EventType = EventTypeOf; + +export type DomainEvent = EventEnvelope; + +export type AnyDomainEvent = AnyEventEnvelope; + +export type PublishOptions = { + scope?: EventScope; + /** Overrides the actor resolved from the request context (e.g. background jobs). */ + actor?: EventActor; +}; + +export type EventHandler = (event: E) => void | Promise; + +export type Unsubscribe = () => void; diff --git a/src/lib/server/gitdb/index.ts b/src/lib/server/gitdb/index.ts index c39c0233..d9f12494 100644 --- a/src/lib/server/gitdb/index.ts +++ b/src/lib/server/gitdb/index.ts @@ -97,5 +97,6 @@ export function getGitDb(): CachedGitDb { } const actor = getCurrentActor(); - return actor ? instance.as(actor) : instance; + // only the commit identity reaches GitDB; ids in the request context are for domain events + return actor ? instance.as({ name: actor.name, email: actor.email }) : instance; } diff --git a/src/lib/server/infra/notifications/config.ts b/src/lib/server/infra/notifications/config.ts index 98be157e..4fabfa6e 100644 --- a/src/lib/server/infra/notifications/config.ts +++ b/src/lib/server/infra/notifications/config.ts @@ -73,3 +73,26 @@ export function isSmtpConfigured(): boolean { export function formatSender(config: SmtpConfig): string { return config.fromName ? `${config.fromName} <${config.from}>` : config.from; } + +/** + * Public origin used for absolute links in emails (`ORIGIN`, e.g. `https://gitops.example.com`), + * without a trailing slash. `null` when unset or not an http(s) URL: emails then go without links. + */ +export function readPublicOrigin(): string | null { + const raw = value('ORIGIN'); + if (!raw) return null; + try { + const url = new URL(raw); + if (url.protocol !== 'http:' && url.protocol !== 'https:') return null; + return url.origin; + } catch { + return null; + } +} + +/** `origin + path`, or `null` without a usable origin or path. */ +export function absoluteUrl(path: string | null | undefined): string | null { + const origin = readPublicOrigin(); + if (!origin || !path || !path.startsWith('/')) return null; + return `${origin}${path}`; +} diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts index a0e51eb1..c703a27a 100644 --- a/src/lib/server/infra/notifications/index.ts +++ b/src/lib/server/infra/notifications/index.ts @@ -7,6 +7,53 @@ export { renderTemplate, renderTemplateString, clearTemplateCache, + renderEmail, + PRODUCT_NAME, + type EmailLayout, type TemplateVariables, } from './template'; -export { isSmtpConfigured, readSmtpConfig, requireSmtpConfig, type SmtpConfig } from './config'; +export { + absoluteUrl, + isSmtpConfigured, + readPublicOrigin, + readSmtpConfig, + requireSmtpConfig, + type SmtpConfig, +} from './config'; +export { withRetry, isRetryableMailError, type RetryOptions } from './retry'; +export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue'; + +import { createLogger } from '#lib/server/logger'; +import { MailQueue as Queue } from './mail-queue'; +import { notify as send } from './notify'; + +const QUEUE_KEY = Symbol.for('gitops.mail.queue'); +const SHUTDOWN_KEY = Symbol.for('gitops.mail.shutdown'); +type GlobalWithQueue = typeof globalThis & { [QUEUE_KEY]?: Queue; [SHUTDOWN_KEY]?: boolean }; + +/** + * Process-wide queue for alert and system emails (3 at a time, 4 attempts with backoff). Kept on + * `globalThis` so HMR doesn't create a second one. Invitations and password resets don't use it: + * their links carry tokens and are sent directly. + */ +export const mailQueue: Queue = ((globalThis as GlobalWithQueue)[QUEUE_KEY] ??= new Queue({ + send: (notification) => send(notification), + concurrency: 3, + logger: createLogger('mail'), +})); + +/** Time the shutdown waits for queued emails. */ +export const MAIL_SHUTDOWN_TIMEOUT_MS = 10_000; + +/** + * Drains the queue when adapter-node shuts down (`SIGTERM`/`SIGINT` emit `sveltekit:shutdown`). + * Registered once per process. + */ +export function registerMailShutdown(): void { + const scope = globalThis as GlobalWithQueue; + if (scope[SHUTDOWN_KEY]) return; + scope[SHUTDOWN_KEY] = true; + process.once('sveltekit:shutdown' as never, () => { + void mailQueue.drain(MAIL_SHUTDOWN_TIMEOUT_MS); + }); +} diff --git a/src/lib/server/infra/notifications/mail-queue.test.ts b/src/lib/server/infra/notifications/mail-queue.test.ts new file mode 100644 index 00000000..7b237430 --- /dev/null +++ b/src/lib/server/infra/notifications/mail-queue.test.ts @@ -0,0 +1,167 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { MailNotification } from './mail-notification'; +import { MailQueue, recipientHash } from './mail-queue'; +import { isRetryableMailError, withRetry } from './retry'; + +function mail(to: string) { + return new MailNotification({ to, subject: 'Alert', content: '

secret details

' }); +} + +function smtpError(props: { code?: string; responseCode?: number }) { + return Object.assign(new Error('smtp failure for someone@example.com'), props); +} + +function logger() { + return { warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; +} + +describe('isRetryableMailError', () => { + it.each([ + [{ code: 'ETIMEDOUT' }, true], + [{ code: 'ECONNECTION' }, true], + [{ code: 'ESOCKET' }, true], + [{ responseCode: 421 }, true], + [{ responseCode: 451 }, true], + [{ responseCode: 550 }, false], + [{ responseCode: 553 }, false], + [{ code: 'EAUTH' }, false], + [{ code: 'EENVELOPE' }, false], + ])('%j → %s', (props, expected) => { + expect(isRetryableMailError(smtpError(props))).toBe(expected); + }); + + it('does not retry plain errors (validation)', () => { + expect(isRetryableMailError(new Error('MailNotification requires a subject'))).toBe(false); + }); +}); + +describe('withRetry', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('waits 1 s → 4 s → 16 s between the 4 attempts', async () => { + const fn = vi.fn().mockRejectedValue(smtpError({ code: 'ETIMEDOUT' })); + const delays: number[] = []; + const promise = withRetry(fn, { + isRetryable: isRetryableMailError, + random: () => 0.5, // no jitter + onRetry: (_error, _attempt, delayMs) => delays.push(delayMs), + }); + const settled = promise.catch((error) => error); + + await vi.advanceTimersByTimeAsync(1000); + expect(fn).toHaveBeenCalledTimes(2); + await vi.advanceTimersByTimeAsync(4000); + expect(fn).toHaveBeenCalledTimes(3); + await vi.advanceTimersByTimeAsync(16000); + expect(fn).toHaveBeenCalledTimes(4); + + expect(await settled).toMatchObject({ code: 'ETIMEDOUT' }); + expect(delays).toEqual([1000, 4000, 16000]); + }); + + it('applies jitter around each delay', async () => { + const delays: number[] = []; + const fn = vi.fn().mockRejectedValueOnce(new Error('x')).mockResolvedValue('ok'); + const promise = withRetry(fn, { random: () => 1, onRetry: (_e, _a, d) => delays.push(d) }); + await vi.advanceTimersByTimeAsync(1200); + await expect(promise).resolves.toBe('ok'); + expect(delays).toEqual([1200]); + }); + + it('fails at once on permanent errors', async () => { + const fn = vi.fn().mockRejectedValue(smtpError({ responseCode: 550 })); + await expect(withRetry(fn, { isRetryable: isRetryableMailError })).rejects.toMatchObject({ + responseCode: 550, + }); + expect(fn).toHaveBeenCalledTimes(1); + }); +}); + +describe('MailQueue', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(() => vi.useRealTimers()); + + it('sends one email per job with at most `concurrency` at a time', async () => { + let active = 0; + let peak = 0; + const sent: string[] = []; + const queue = new MailQueue({ + concurrency: 3, + logger: logger(), + send: async (notification) => { + active += 1; + peak = Math.max(peak, active); + await new Promise((resolve) => setTimeout(resolve, 100)); + sent.push(notification.to[0]); + active -= 1; + }, + }); + + const jobs = Array.from({ length: 7 }, (_, i) => queue.enqueue(mail(`user${i}@example.com`))); + expect(queue.size).toBe(7); + await vi.advanceTimersByTimeAsync(300); + await Promise.all(jobs); + + expect(sent).toHaveLength(7); + expect(new Set(sent).size).toBe(7); + expect(peak).toBe(3); + expect(queue.size).toBe(0); + }); + + it('retries temporary failures and logs a definitive one without content or address', async () => { + const log = logger(); + const send = vi + .fn() + .mockRejectedValueOnce(smtpError({ code: 'ECONNECTION' })) + .mockResolvedValueOnce(undefined) + .mockRejectedValue(smtpError({ responseCode: 550 })); + const queue = new MailQueue({ send, logger: log, retry: { random: () => 0.5 } }); + + const first = queue.enqueue(mail('ok@example.com'), { alertId: 'a1', eventId: 'e1' }); + await vi.advanceTimersByTimeAsync(1000); + await first; + expect(send).toHaveBeenCalledTimes(2); + expect(log.error).not.toHaveBeenCalled(); + + await queue.enqueue(mail('gone@example.com'), { alertId: 'a1', eventId: 'e2' }); + expect(send).toHaveBeenCalledTimes(3); + expect(log.error).toHaveBeenCalledTimes(1); + const [fields] = log.error.mock.calls[0]; + expect(fields).toEqual({ + alertId: 'a1', + eventId: 'e2', + recipients: [recipientHash('gone@example.com')], + code: 550, + }); + expect(JSON.stringify(log.error.mock.calls)).not.toContain('gone@example.com'); + expect(JSON.stringify(log.error.mock.calls)).not.toContain('secret details'); + }); + + it('drains pending emails on shutdown, up to a time limit', async () => { + const send = vi.fn(() => new Promise((resolve) => setTimeout(resolve, 2000))); + const queue = new MailQueue({ send, concurrency: 1, logger: logger() }); + void queue.enqueue(mail('a@example.com')); + void queue.enqueue(mail('b@example.com')); + + const drained = queue.drain(10_000); + await vi.advanceTimersByTimeAsync(4000); + await expect(drained).resolves.toBe(true); + expect(send).toHaveBeenCalledTimes(2); + + const log = logger(); + const slow = new MailQueue({ + send: () => new Promise((resolve) => setTimeout(resolve, 60_000)), + logger: log, + }); + void slow.enqueue(mail('c@example.com')); + const timedOut = slow.drain(10_000); + await vi.advanceTimersByTimeAsync(10_000); + await expect(timedOut).resolves.toBe(false); + expect(log.warn).toHaveBeenCalledWith({ remaining: 1 }, expect.any(String)); + }); + + it('resolves drain at once when idle', async () => { + await expect(new MailQueue({ send: vi.fn(), logger: logger() }).drain()).resolves.toBe(true); + }); +}); diff --git a/src/lib/server/infra/notifications/mail-queue.ts b/src/lib/server/infra/notifications/mail-queue.ts new file mode 100644 index 00000000..690d0a85 --- /dev/null +++ b/src/lib/server/infra/notifications/mail-queue.ts @@ -0,0 +1,126 @@ +import crypto from 'node:crypto'; +import type { Logger } from 'pino'; +import type { MailNotification } from './mail-notification'; +import { isRetryableMailError, withRetry, type RetryOptions } from './retry'; + +/** What the logs may say about an email: never its content or the address in clear. */ +export type MailContext = { alertId?: string; eventId?: string; kind?: string }; + +type Job = { + notification: MailNotification; + context: MailContext; + done: () => void; +}; + +export type MailQueueOptions = { + send: (notification: MailNotification) => Promise; + /** Emails sent at the same time; a burst of events waits in the queue. */ + concurrency?: number; + retry?: RetryOptions; + logger: Pick; +}; + +/** Short, stable hash of an address, to correlate log lines without logging the address. */ +export function recipientHash(address: string): string { + return crypto + .createHash('sha256') + .update(address.trim().toLowerCase()) + .digest('hex') + .slice(0, 12); +} + +/** + * In-process email queue with limited concurrency and retries (`withRetry`, SMTP-aware). Each job + * is one email; a definitive failure is logged and dropped, never thrown at the caller. Per + * process: pending emails are lost on a crash, and `drain()` flushes them on shutdown. + */ +export class MailQueue { + private readonly pending: Job[] = []; + private active = 0; + private readonly idle = new Set<() => void>(); + private readonly concurrency: number; + + constructor(private readonly options: MailQueueOptions) { + this.concurrency = Math.max(1, options.concurrency ?? 3); + } + + /** Queues one email; resolves once it was sent or definitively failed. */ + enqueue(notification: MailNotification, context: MailContext = {}): Promise { + return new Promise((resolve) => { + this.pending.push({ notification, context, done: resolve }); + this.pump(); + }); + } + + /** Emails waiting or being sent. */ + get size(): number { + return this.pending.length + this.active; + } + + /** + * Resolves when the queue is empty, or after `timeoutMs` with what is left (`true` when + * everything was sent). + */ + drain(timeoutMs = 10_000): Promise { + if (this.size === 0) return Promise.resolve(true); + return new Promise((resolve) => { + const onIdle = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this.idle.delete(onIdle); + this.options.logger.warn( + { remaining: this.size }, + '[mail] shutdown timeout: emails left unsent', + ); + resolve(false); + }, timeoutMs); + this.idle.add(onIdle); + }); + } + + private pump(): void { + while (this.active < this.concurrency && this.pending.length > 0) { + const job = this.pending.shift()!; + this.active += 1; + void this.run(job).finally(() => { + this.active -= 1; + job.done(); + if (this.size === 0) { + for (const resolve of [...this.idle]) resolve(); + this.idle.clear(); + } else { + this.pump(); + } + }); + } + } + + private async run(job: Job): Promise { + const recipients = job.notification.to.map(recipientHash); + try { + await withRetry(() => this.options.send(job.notification), { + isRetryable: isRetryableMailError, + ...this.options.retry, + onRetry: (error, attempt, delayMs) => + this.options.logger.debug( + { ...job.context, recipients, attempt, delayMs, code: errorCode(error) }, + '[mail] retrying email', + ), + }); + } catch (error) { + this.options.logger.error( + // only the error code: SMTP messages may quote the recipient address + { ...job.context, recipients, code: errorCode(error) }, + '[mail] email could not be sent', + ); + } + } +} + +function errorCode(error: unknown): unknown { + if (!error || typeof error !== 'object') return undefined; + const { code, responseCode } = error as { code?: unknown; responseCode?: unknown }; + return responseCode ?? code; +} diff --git a/src/lib/server/infra/notifications/retry.ts b/src/lib/server/infra/notifications/retry.ts new file mode 100644 index 00000000..48ac0607 --- /dev/null +++ b/src/lib/server/infra/notifications/retry.ts @@ -0,0 +1,64 @@ +export type RetryOptions = { + /** Total attempts, the first one included. */ + attempts?: number; + /** Delay before the second attempt; each later delay is `factor` times the previous one. */ + baseDelayMs?: number; + factor?: number; + /** ± fraction of each delay added at random, so retries of a burst don't line up. */ + jitter?: number; + isRetryable?: (error: unknown) => boolean; + sleep?: (ms: number) => Promise; + random?: () => number; + onRetry?: (error: unknown, attempt: number, delayMs: number) => void; +}; + +const defaultSleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** + * Runs `fn`, retrying retryable failures with exponential backoff. Defaults: 4 attempts, waiting + * 1 s → 4 s → 16 s (±20 %). A permanent error, or the last attempt's error, is rethrown. + */ +export async function withRetry(fn: () => Promise, options: RetryOptions = {}): Promise { + const attempts = options.attempts ?? 4; + const baseDelayMs = options.baseDelayMs ?? 1000; + const factor = options.factor ?? 4; + const jitter = options.jitter ?? 0.2; + const isRetryable = options.isRetryable ?? (() => true); + const sleep = options.sleep ?? defaultSleep; + const random = options.random ?? Math.random; + + for (let attempt = 1; ; attempt += 1) { + try { + return await fn(); + } catch (error) { + if (attempt >= attempts || !isRetryable(error)) throw error; + const delay = baseDelayMs * factor ** (attempt - 1); + const delayMs = Math.max(0, Math.round(delay * (1 + jitter * (random() * 2 - 1)))); + options.onRetry?.(error, attempt, delayMs); + await sleep(delayMs); + } + } +} + +const RETRYABLE_CODES = new Set([ + 'ECONNECTION', + 'ECONNRESET', + 'ECONNREFUSED', + 'ETIMEDOUT', + 'ESOCKET', + 'EDNS', + 'EAI_AGAIN', + 'EPIPE', +]); + +/** + * Whether an SMTP failure may succeed later: network errors, timeouts and temporary (4xx) replies. + * Permanent replies (5xx, e.g. unknown mailbox), authentication errors and invalid messages are + * not retried. + */ +export function isRetryableMailError(error: unknown): boolean { + if (!error || typeof error !== 'object') return false; + const { code, responseCode } = error as { code?: unknown; responseCode?: unknown }; + if (typeof responseCode === 'number') return responseCode >= 400 && responseCode < 500; + return typeof code === 'string' && RETRYABLE_CODES.has(code); +} diff --git a/src/lib/server/infra/notifications/template.ts b/src/lib/server/infra/notifications/template.ts index 5ca95149..320c4025 100644 --- a/src/lib/server/infra/notifications/template.ts +++ b/src/lib/server/infra/notifications/template.ts @@ -69,3 +69,42 @@ async function readFromDisk(name: string): Promise { export function clearTemplateCache(): void { cache.clear(); } + +export type EmailLayout = { + subject: string; + /** `lang` of the document. */ + lang?: string; + productName?: string; + /** Why the recipient gets this email (plain text, escaped). */ + footer: string; + /** Absolute link shown after the footer text, e.g. to manage the alert. */ + footerLink?: { url: string; label: string } | null; +}; + +export const PRODUCT_NAME = 'GitOps'; + +/** + * Renders template `name` and wraps it in the shared layout (`_layout.html`): header with the + * product, the content, and a footer explaining why the email was sent. + */ +export async function renderEmail( + name: string, + variables: TemplateVariables, + layout: EmailLayout, +): Promise { + const content = await renderTemplate(name, variables); + const footerLink = layout.footerLink + ? renderTemplateString('{{ label }}', { + url: layout.footerLink.url, + label: layout.footerLink.label, + }) + : ''; + return renderTemplate('_layout', { + lang: layout.lang ?? 'en', + subject: layout.subject, + productName: layout.productName ?? PRODUCT_NAME, + content, + footer: layout.footer, + footerLink, + }); +} diff --git a/src/lib/server/request-context.test.ts b/src/lib/server/request-context.test.ts new file mode 100644 index 00000000..c20cf3ae --- /dev/null +++ b/src/lib/server/request-context.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it, vi } from 'vitest'; + +describe('request context', () => { + it('shares one store across re-evaluations of the module (Vite HMR)', async () => { + const first = await import('./request-context'); + vi.resetModules(); + const second = await import('./request-context'); + + expect(second).not.toBe(first); + const seen = first.runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'u1' }, () => + second.getCurrentActor(), + ); + expect(seen?.userId).toBe('u1'); + }); + + it('has no actor outside a request', async () => { + const { getCurrentActor } = await import('./request-context'); + expect(getCurrentActor()).toBeNull(); + }); +}); diff --git a/src/lib/server/request-context.ts b/src/lib/server/request-context.ts index 3938892a..42509eea 100644 --- a/src/lib/server/request-context.ts +++ b/src/lib/server/request-context.ts @@ -1,13 +1,30 @@ import { AsyncLocalStorage } from 'node:async_hooks'; export type RequestActor = { + /** Commit author name written by GitDB. */ name: string; + /** Commit author email written by GitDB. */ email: string; + /** Set when the request is authenticated with a session. */ + userId?: string; + /** Set when the request is authenticated with an `Authorization: Bearer gvs_...` API key. */ + apiKeyId?: string; + /** Project the API key is confined to (`null` for keys that are not project-scoped). */ + apiKeyProjectId?: string | null; }; -const storage = new AsyncLocalStorage(); +// one store per process: long-lived singletons (the event bus on `globalThis`) keep a reference +// to `getCurrentActor`, so a second store created when Vite re-evaluates this module in dev would +// leave them reading an empty context (every event would look like a system event) +const STORAGE_KEY = Symbol.for('gitops.request-context'); +const storage: AsyncLocalStorage = (( + globalThis as typeof globalThis & { [STORAGE_KEY]?: AsyncLocalStorage } +)[STORAGE_KEY] ??= new AsyncLocalStorage()); -/** Runs `fn` with `actor` available to any `getGitDb()` call made during its execution. */ +/** + * Runs `fn` with `actor` available to anything that reads the request context during its + * execution: `getGitDb()` (commit author) and the domain event bus (event actor). + */ export function runWithActor(actor: RequestActor, fn: () => T): T { return storage.run(actor, fn); } 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..55054a6d --- /dev/null +++ b/src/modules/alerts/application/alert-engine.ts @@ -0,0 +1,273 @@ +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; + /** Names and slugs of where the event happened, for the texts and the links. */ + where: ResolvedNames; +}; + +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()) { + this.options.logger.debug( + { eventType: event.type, eventId: event.id }, + '[alerts] email is not configured, event skipped', + ); + 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(), + ); + const where: ResolvedNames = await this.options.directory + .resolveNames({ + organizationId: event.scope.organizationId, + projectId: event.scope.projectId, + }) + .catch(() => ({})); + + 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, + where, + }); + 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..f14db3dc --- /dev/null +++ b/src/modules/alerts/application/recipient-resolver.ts @@ -0,0 +1,61 @@ +import type { PermissionGrant } from '#lib/permissions'; +import type { AlertLocation, AlertRecipients } from '../domain/alert.domain'; +import type { AlertDirectory, PermissionContext, ScopeMember, UserPermissionCheck } from './types'; + +/** `locale` is the recipient's language when the platform knows it (emails default to English). */ +export type Recipient = Pick & { + email: string; + locale?: 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..2d140793 --- /dev/null +++ b/src/modules/alerts/application/testing.ts @@ -0,0 +1,82 @@ +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]; + if (ids.organizationId && this.names[`${ids.organizationId}:slug`]) { + names.organizationSlug = this.names[`${ids.organizationId}:slug`]; + } + if (ids.projectId && this.names[`${ids.projectId}:slug`]) { + names.projectSlug = this.names[`${ids.projectId}:slug`]; + } + 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..96d6d5f4 --- /dev/null +++ b/src/modules/alerts/application/types.ts @@ -0,0 +1,87 @@ +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; + organizationSlug?: string; + project?: string; + projectSlug?: 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..aff53c1a --- /dev/null +++ b/src/modules/alerts/index.ts @@ -0,0 +1,108 @@ +import { eventBus } from '#lib/server/events'; +import { + isSmtpConfigured, + mailQueue, + readPublicOrigin, + registerMailShutdown, +} 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(mailQueue), + throttle: new AlertThrottle(), + logger: log, + // without SMTP there is nobody to tell: skip the work instead of logging a failure per event + deliveryEnabled: () => isMailConfigured(), + }), + 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); + registerMailShutdown(); + engineSlot.attached = true; + log.info('[alerts] engine registered'); + + // said once at startup; skipped events are only logged in debug + if (!isMailConfigured()) { + log.warn('[alerts] NOTIFICATION_SMTP_* is not configured: alerts and notices will not be sent'); + } + if (!readPublicOrigin()) { + log.warn('[alerts] ORIGIN is not set: emails will be sent without links'); + } +} + +/** Whether emails can be sent; a broken SMTP configuration counts as not configured. */ +export function isMailConfigured(): boolean { + try { + return isSmtpConfigured(); + } catch { + return false; + } +} + +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..4c7bda84 --- /dev/null +++ b/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts @@ -0,0 +1,247 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { getEventDefinition, type EventDefinition } from '#lib/events/catalog'; +import type { MailNotification } from '#lib/server/infra/notifications'; +import type { AnyDomainEvent } from '#lib/server/events'; +import type { AlertEmail, SystemEmail } from '../application/alert-engine'; +import { AlertMailNotifier } from './alert-mail.notifier'; + +class RecordingSender { + sent: { notification: MailNotification; context?: Record }[] = []; + async enqueue(notification: MailNotification, context?: Record) { + this.sent.push({ notification, context }); + } + get last() { + return this.sent[this.sent.length - 1].notification; + } +} + +const XSS = ''; +const ORIGIN = 'https://gitops.example.com'; + +function analysisEvent(): AnyDomainEvent { + return { + 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: 'feature/', + commit: 'abcdef1234567890', + version: null, + }, + summary: { critical: 3, high: 5, medium: 1, low: 0, unknown: 0, total: 9, secrets: 0 }, + policies: { + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }, + }; +} + +function alertEmail(overrides: Partial = {}): AlertEmail { + return { + recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com' }, + alert: { id: 'alert-1', name: 'Críticas en api-gateway', description: null, scope: 'project' }, + event: analysisEvent(), + definition: getEventDefinition('code_report.analysis.completed') as EventDefinition, + suppressed: 0, + names: new Map([['svc-gateway', `api-gateway ${XSS}`]]), + where: { organization: 'Kettu', organizationSlug: 'kettu', project: 'Web', projectSlug: 'web' }, + ...overrides, + }; +} + +function expectClean(html: string) { + expect(html).not.toMatch(/\{\{|\}\}/); + expect(html).not.toContain(' + + + Changelog · GitOps + + +
+
+

GitOps

+

+ {$locale === 'es' ? 'Novedades' : 'Changelog'} +

+
+ +
+ {#each changelog as entry (entry.version)} + {@const content = $locale === 'es' ? entry.es : entry.en} +
+
+

{content.title}

+ + v{entry.version} + +
+

{entry.date}

+

{content.summary}

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

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

+

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

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

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

+

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

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

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

+

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

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

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

+

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

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/settings/events/+page.server.ts b/src/routes/org/[org]/settings/events/+page.server.ts new file mode 100644 index 00000000..1b3bc0a0 --- /dev/null +++ b/src/routes/org/[org]/settings/events/+page.server.ts @@ -0,0 +1,119 @@ +import { error, fail } from '@sveltejs/kit'; +import type { RequestEvent } from './$types'; + +type Locals = RequestEvent['locals']; +import { apiKeysService, cancanService, roleService, userAccessService } from '#modules/auth'; +import { codeReportService } from '#modules/code-report'; +import { projectService } from '#modules/projects'; +import { listAlertableEvents } from '#lib/events/catalog'; +import type { EventType } from '#lib/events/domain-events'; +import { organizationService } from '#modules/organization'; +import { eventLog } from '#lib/server/events'; +import { readEventsExpirationMs } from '#lib/server/events/config'; +import { + EVENT_MODULES, + createEventVisibility, + parseModuleFilter, + parseStatusFilter, + toEventView, + type EventView, +} from './event-view'; + +const PAGE_SIZE = 200; + +function canEvents(locals: Locals, organizationId: string, action: 'read' | 'update') { + return cancanService.canSessionUser(locals.user, `organization:events:${action}`, { + scope: 'organization', + organizationId, + }); +} + +function visibilityFor(locals: Locals, organizationId: string) { + return createEventVisibility(organizationId, (permission, context) => + cancanService.canSessionUser(locals.user, permission, context), + ); +} + +export async function load({ parent, locals, url }) { + const { organization } = await parent(); + if (!(await canEvents(locals, organization.id, 'read'))) { + throw error(403, 'Forbidden'); + } + const canAck = await canEvents(locals, organization.id, 'update'); + + const module = parseModuleFilter(url.searchParams.get('module')); + const status = parseStatusFilter(url.searchParams.get('status')); + const types = module + ? (listAlertableEvents({ module }).map((definition) => definition.type) as EventType[]) + : undefined; + + const isVisible = visibilityFor(locals, organization.id); + const candidates = eventLog.list({ + organizationId: organization.id, + types, + acked: status === 'all' ? undefined : status === 'acked', + }); + + const visible = []; + for (const entry of candidates) { + if (await isVisible(entry)) visible.push(entry); + if (visible.length >= PAGE_SIZE) break; + } + + const projects = await projectService.listProjectsByOrganization(organization.id); + // names for the ids events carry; a failed lookup only leaves the raw id on screen + const perProject = (read: (projectId: string) => Promise) => + Promise.all(projects.map((project) => read(project.id).catch(() => [] as T[]))).then((rows) => + rows.flat(), + ); + const [users, apiKeys, services, roles] = await Promise.all([ + userAccessService.listAssignableUsers(), + perProject((projectId) => apiKeysService.listActiveApiKeysByProject(projectId)), + perProject((projectId) => codeReportService.listByProject(projectId)), + Promise.all([ + roleService.listRoles('organization', organization.id).catch(() => []), + perProject((projectId) => roleService.listRoles('project', projectId)), + ]).then((rows) => rows.flat()), + ]); + + const lookups = { + usernames: new Map(users.map((user) => [user.id, user.username])), + projectNames: new Map(projects.map((project) => [project.id, project.name])), + apiKeyNames: new Map(apiKeys.map((key) => [key.id, key.name])), + serviceNames: new Map(services.map((service) => [service.id, service.name])), + roleNames: new Map(roles.map((role) => [role.id, role.name])), + }; + + return { + orgSlug: organization.slug, + events: visible.map((entry) => toEventView(entry, lookups)).filter((e): e is EventView => !!e), + filters: { module, status }, + canAck, + modules: EVENT_MODULES, + retentionMs: readEventsExpirationMs(), + }; +} + +export const actions = { + async ack({ request, locals, params }) { + const organization = await organizationService.tryFindBySlug(params.org); + if (!organization) return fail(404, { error: 'Organization not found' }); + + const user = locals.user; + if (!user || !(await canEvents(locals, organization.id, 'update'))) { + return fail(403, { error: 'Forbidden' }); + } + + const form = await request.formData(); + const eventId = String(form.get('eventId') ?? ''); + const entry = eventLog.get(eventId); + + // an expired or foreign event is indistinguishable from one the viewer cannot see + if (!entry || !(await visibilityFor(locals, organization.id)(entry))) { + return fail(404, { error: 'Event not found' }); + } + + eventLog.ack(eventId, { userId: user.id, username: user.username }); + return { success: true }; + }, +}; diff --git a/src/routes/org/[org]/settings/events/+page.svelte b/src/routes/org/[org]/settings/events/+page.svelte new file mode 100644 index 00000000..3431c54e --- /dev/null +++ b/src/routes/org/[org]/settings/events/+page.svelte @@ -0,0 +1,209 @@ + + + + {$_('org.events.title')} - GitOps + + +
+
+
+

{$_('org.events.title')}

+

{$_('org.events.description')}

+

+ {$_('org.events.retentionNotice', { values: { retention } })} +

+
+
+ + {$_('org.events.pendingCount', { values: { count: pendingCount } })} +
+
+ +
+ + + +
+ + {#if error} +
+ {error} +
+ {/if} + + {#if data.events.length === 0} +
+ +

{$_('org.events.emptyTitle')}

+

{$_('org.events.emptyDescription')}

+
+ {:else} +
    + {#each data.events as event (event.id)} +
  • +
    +
    + + {$_(`org.events.modules.${event.module}`)} + +

    {$_(event.label)}

    +
    +

    + {formatDate(event.occurredAt)} · {actorName(event)} + {#if event.project} + · {$_('org.events.inProject', { + values: { name: event.project.name ?? event.project.id }, + })} + {/if} +

    + {#if event.fields.length > 0} +
    + + {$_('org.events.details')} + +
    + {#each event.fields as field (field.label)} +
    +
    {$_(field.label)}:
    +
    + {field.translate ? $_(field.value) : field.value} +
    +
    + {/each} +
    +
    + {/if} +
    + +
    + {#if event.ack} +
    + + + {$_('org.events.ackedBy', { + values: { name: event.ack.username, date: formatDate(event.ack.at) }, + })} + +
    + {:else if data.canAck} +
    + + +
    + {/if} +
    +
  • + {/each} +
+ {/if} +
diff --git a/src/routes/org/[org]/settings/events/event-view.test.ts b/src/routes/org/[org]/settings/events/event-view.test.ts new file mode 100644 index 00000000..cdb268d9 --- /dev/null +++ b/src/routes/org/[org]/settings/events/event-view.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { AnyDomainEvent, LoggedEvent } from '#lib/server/events'; +import { + createEventVisibility, + parseModuleFilter, + parseStatusFilter, + toEventView, +} from './event-view'; + +function logged(event: Partial, ack: LoggedEvent['ack'] = null): LoggedEvent { + return { + event: { + id: 'event-1', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'user', userId: 'user-1' }, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + ...event, + } as AnyDomainEvent, + ack, + }; +} + +const secretCreated = logged({ + type: 'vault.secret.created', + payload: { + secretId: 's1', + key: 'DB_PASSWORD', + folderId: null, + folderPath: '/', + environmentIds: ['env-prod'], + }, +}); + +const projectUpdated = logged({ + type: 'project.updated', + payload: { projectId: 'project-1', name: 'Shop', slug: 'shop', changedFields: ['name'] }, +}); + +describe('createEventVisibility', () => { + it("checks the event's read permission in the project for project grants", async () => { + const can = vi.fn(async () => true); + const isVisible = createEventVisibility('org-1', can); + + await expect(isVisible(secretCreated)).resolves.toBe(true); + expect(can).toHaveBeenCalledWith('project:vault:secrets:read', { + scope: 'project', + organizationId: 'org-1', + projectId: 'project-1', + }); + }); + + it('checks organization grants in the organization', async () => { + const can = vi.fn(async () => false); + const isVisible = createEventVisibility('org-1', can); + + await expect(isVisible(projectUpdated)).resolves.toBe(false); + expect(can).toHaveBeenCalledWith('organization:projects:read', { + scope: 'organization', + organizationId: 'org-1', + }); + }); + + it('caches checks per permission and project', async () => { + const can = vi.fn(async () => true); + const isVisible = createEventVisibility('org-1', can); + + await isVisible(secretCreated); + await isVisible({ ...secretCreated, event: { ...secretCreated.event, id: 'event-2' } }); + + expect(can).toHaveBeenCalledTimes(1); + }); + + it('hides events of other organizations, unknown types and failed checks', async () => { + const isVisible = createEventVisibility('org-2', async () => true); + const failing = createEventVisibility('org-1', async () => { + throw new Error('boom'); + }); + + await expect(isVisible(secretCreated)).resolves.toBe(false); + await expect( + createEventVisibility('org-1', async () => true)(logged({ type: 'unknown.event' as never })), + ).resolves.toBe(false); + await expect(failing(secretCreated)).resolves.toBe(false); + }); +}); + +describe('toEventView', () => { + const lookups = { + usernames: new Map([['user-1', 'ana']]), + projectNames: new Map([['project-1', 'Shop']]), + apiKeyNames: new Map([['key-1', 'CI']]), + }; + + it('resolves the actor, project and catalog fields, never secret values', () => { + const view = toEventView(secretCreated, lookups); + + expect(view).toMatchObject({ + id: 'event-1', + module: 'vault', + label: 'events.vault.secret.created.label', + actor: { kind: 'user', name: 'ana' }, + project: { id: 'project-1', name: 'Shop' }, + ack: null, + }); + expect(view?.fields).toEqual([ + { label: 'events.vault.secret.created.fields.key', value: 'DB_PASSWORD' }, + { label: 'events.vault.secret.created.fields.environmentIds', value: 'env-prod' }, + { label: 'events.vault.secret.created.fields.folderPath', value: '/' }, + ]); + }); + + it('shows API key and system actors and the acknowledgement', () => { + const byKey = toEventView( + logged( + { ...projectUpdated.event, actor: { kind: 'api_key', apiKeyId: 'key-1', projectId: null } }, + { userId: 'user-2', username: 'bob', at: '2026-11-20T11:00:00.000Z' }, + ), + lookups, + ); + const bySystem = toEventView( + logged({ ...projectUpdated.event, actor: { kind: 'system' } }), + lookups, + ); + + expect(byKey?.actor).toEqual({ kind: 'api_key', name: 'CI' }); + expect(byKey?.ack).toEqual({ username: 'bob', at: '2026-11-20T11:00:00.000Z' }); + expect(bySystem?.actor).toEqual({ kind: 'system', name: null }); + }); + + it('resolves reference fields to names', () => { + const view = toEventView(projectUpdated, lookups); + + expect(view?.fields[0]).toEqual({ + label: 'events.project.updated.fields.projectId', + value: 'Shop', + }); + }); +}); + +describe('filters', () => { + it('parses status and module filters, ignoring unknown values', () => { + expect(parseStatusFilter('pending')).toBe('pending'); + expect(parseStatusFilter('nope')).toBe('all'); + expect(parseModuleFilter('vault')).toBe('vault'); + expect(parseModuleFilter('nope')).toBeNull(); + }); +}); diff --git a/src/routes/org/[org]/settings/events/event-view.ts b/src/routes/org/[org]/settings/events/event-view.ts new file mode 100644 index 00000000..d1d7cdf9 --- /dev/null +++ b/src/routes/org/[org]/settings/events/event-view.ts @@ -0,0 +1,155 @@ +import { + getEventDefinition, + getFieldValue, + isEventType, + type EventDefinition, + type EventModule, +} from '#lib/events/catalog'; +import type { LoggedEvent } from '#lib/server/events'; + +export const EVENT_MODULES: readonly EventModule[] = [ + 'code_report', + 'vault', + 'projects', + 'organization', + 'access', +]; + +export type EventStatusFilter = 'all' | 'pending' | 'acked'; + +export type EventFieldView = { + /** i18n key */ + label: string; + value: string; + /** `value` is an i18n key (booleans) rather than display text. */ + translate?: boolean; +}; + +export type EventView = { + id: string; + type: string; + module: EventModule; + /** i18n key */ + label: string; + occurredAt: string; + actor: { kind: 'user' | 'api_key' | 'system'; name: string | null }; + project: { id: string; name: string | null } | null; + fields: EventFieldView[]; + ack: { username: string; at: string } | null; +}; + +type PermissionContext = + | { scope: 'organization'; organizationId: string } + | { scope: 'project'; organizationId: string; projectId: string }; + +export type PermissionCheck = (permission: string, context: PermissionContext) => Promise; + +/** + * Whether the viewer may see (and acknowledge) an event: the event's `readPermission` checked in + * the scope it belongs to. Results are cached per permission and project for one request. + */ +export function createEventVisibility(organizationId: string, can: PermissionCheck) { + const cache = new Map>(); + + return (entry: LoggedEvent): Promise => { + if (!isEventType(entry.event.type)) return Promise.resolve(false); + if (entry.event.scope.organizationId !== organizationId) return Promise.resolve(false); + + const { readPermission } = getEventDefinition(entry.event.type); + const projectId = entry.event.scope.projectId ?? null; + // project grants are checked against the project; organization grants against the org + const context: PermissionContext = + readPermission.startsWith('project:') && projectId + ? { scope: 'project', organizationId, projectId } + : { scope: 'organization', organizationId }; + + const key = `${readPermission}|${context.scope === 'project' ? context.projectId : ''}`; + let allowed = cache.get(key); + if (!allowed) { + allowed = can(readPermission, context).catch(() => false); + cache.set(key, allowed); + } + return allowed; + }; +} + +export type EventViewLookups = { + usernames: Map; + projectNames: Map; + apiKeyNames?: Map; + serviceNames?: Map; + roleNames?: Map; +}; + +const REFERENCE_LOOKUP: Partial< + Record, keyof EventViewLookups> +> = { + user: 'usernames', + project: 'projectNames', + api_key: 'apiKeyNames', + code_report_service: 'serviceNames', + role: 'roleNames', +}; + +function formatValue( + value: unknown, + reference: EventDefinition['fields'][number]['reference'], + lookups: EventViewLookups, +): string { + if (value === null || value === undefined || value === '') return '—'; + if (Array.isArray(value)) { + return value.length === 0 + ? '—' + : value.map((item) => formatValue(item, reference, lookups)).join(', '); + } + if (typeof value === 'string') { + const lookup = reference ? REFERENCE_LOOKUP[reference] : undefined; + return (lookup && lookups[lookup]?.get(value)) || value; + } + return String(value); +} + +export function toEventView(entry: LoggedEvent, lookups: EventViewLookups): EventView | null { + const { event } = entry; + if (!isEventType(event.type)) return null; + const definition = getEventDefinition(event.type) as EventDefinition; + + const actor: EventView['actor'] = + event.actor.kind === 'user' + ? { kind: 'user', name: lookups.usernames.get(event.actor.userId) ?? event.actor.userId } + : event.actor.kind === 'api_key' + ? { + kind: 'api_key', + name: lookups.apiKeyNames?.get(event.actor.apiKeyId) ?? null, + } + : { kind: 'system', name: null }; + + const projectId = event.scope.projectId ?? null; + + return { + id: event.id, + type: event.type, + module: definition.module, + label: definition.label, + occurredAt: event.occurredAt, + actor, + project: projectId + ? { id: projectId, name: lookups.projectNames.get(projectId) ?? null } + : null, + fields: definition.fields.map((field) => { + const value = getFieldValue(event, field.key as string); + return typeof value === 'boolean' + ? { label: field.label, value: value ? 'common.yes' : 'common.no', translate: true } + : { label: field.label, value: formatValue(value, field.reference, lookups) }; + }), + ack: entry.ack ? { username: entry.ack.username, at: entry.ack.at } : null, + }; +} + +export function parseStatusFilter(value: string | null): EventStatusFilter { + return value === 'pending' || value === 'acked' ? value : 'all'; +} + +export function parseModuleFilter(value: string | null): EventModule | null { + return EVENT_MODULES.find((module) => module === value) ?? null; +} diff --git a/vitest.config.ts b/vitest.config.ts index 1b12b932..ff235cf4 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,7 +1,10 @@ import path from 'path'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; import { defineConfig } from 'vitest/config'; export default defineConfig({ + // compiles `.svelte` files so components can be rendered in tests (`svelte/server`) + plugins: [svelte({ configFile: false })], resolve: { alias: { $lib: path.resolve(import.meta.dirname, 'src/lib'),