From 23fe1b4675d5c91be437554c565dad8c3e684343 Mon Sep 17 00:00:00 2001 From: "Liam Verdejo (ES)" Date: Tue, 24 Nov 2026 11:43:23 +0100 Subject: [PATCH] Feat: Add base notifications channel --- .github/copilot-instructions.md | 15 +- CLAUDE.md | 50 ++- README.md | 22 ++ src/lib/alerts/summary.ts | 6 + src/lib/alerts/types.ts | 13 + src/lib/components/AppSidebar.svelte | 7 + src/lib/components/alerts/AlertEditor.svelte | 86 ++++- src/lib/components/alerts/AlertList.svelte | 5 +- .../notifications/ChannelsSection.svelte | 316 +++++++++++++++ src/lib/database/schemas.ts | 23 ++ src/lib/i18n/locales/en.json | 74 +++- src/lib/i18n/locales/es.json | 74 +++- src/lib/notifications/types.ts | 41 ++ src/lib/server/alerts/operations.ts | 10 +- src/lib/server/alerts/page.ts | 30 +- .../server/infra/http/webhook-request.test.ts | 125 ++++++ src/lib/server/infra/http/webhook-request.ts | 149 ++++++++ .../infra/notifications/chat-notification.ts | 99 +++++ .../server/infra/notifications/chat-types.ts | 7 + .../infra/notifications/delivery-queue.ts | 140 +++++++ src/lib/server/infra/notifications/index.ts | 25 +- .../server/infra/notifications/mail-queue.ts | 128 +------ .../infra/notifications/notification.ts | 3 +- src/lib/server/infra/notifications/retry.ts | 8 +- src/lib/server/notifications/channels-page.ts | 106 ++++++ src/lib/server/notifications/channels.ts | 175 +++++++++ .../alerts/application/alert-engine.test.ts | 1 + .../alerts/application/alert-engine.ts | 161 ++++++-- .../alerts/application/alert.channels.test.ts | 359 ++++++++++++++++++ .../alerts/application/alert.service.test.ts | 2 +- .../alerts/application/alert.service.ts | 89 ++++- src/modules/alerts/application/types.ts | 24 ++ src/modules/alerts/domain/alert.domain.ts | 13 +- src/modules/alerts/index.ts | 40 +- .../infrastructure/alert-channel-message.ts | 52 +++ .../infrastructure/alert-mail.notifier.ts | 29 +- .../alerts/infrastructure/event-summary.ts | 47 ++- .../notification-channel.service.test.ts | 240 ++++++++++++ .../notification-channel.service.ts | 333 ++++++++++++++++ .../notifications/application/testing.ts | 90 +++++ .../domain/notification-channel.domain.ts | 131 +++++++ src/modules/notifications/index.ts | 74 +++- .../infrastructure/channel-test-message.ts | 28 ++ .../crypto/channel-cipher.test.ts | 35 ++ .../infrastructure/crypto/channel-cipher.ts | 66 ++++ .../repositories/in-memory.repositories.ts | 43 +++ .../notification-channel.repository.ts | 55 +++ src/routes/+layout.server.ts | 3 + src/routes/+layout.svelte | 1 + .../api/notification-channels/+server.ts | 33 ++ .../api/notification-channels/[id]/+server.ts | 23 ++ .../[id]/test/+server.ts | 7 + .../api/notification-channels/server.test.ts | 260 +++++++++++++ .../settings/notifications/+page.server.ts | 21 + .../settings/notifications/+page.svelte | 21 + .../settings/notifications/+page.server.ts | 11 +- .../[org]/settings/notifications/+page.svelte | 6 + 57 files changed, 3802 insertions(+), 233 deletions(-) create mode 100644 src/lib/components/notifications/ChannelsSection.svelte create mode 100644 src/lib/server/infra/http/webhook-request.test.ts create mode 100644 src/lib/server/infra/http/webhook-request.ts create mode 100644 src/lib/server/infra/notifications/chat-notification.ts create mode 100644 src/lib/server/infra/notifications/chat-types.ts create mode 100644 src/lib/server/infra/notifications/delivery-queue.ts create mode 100644 src/lib/server/notifications/channels-page.ts create mode 100644 src/lib/server/notifications/channels.ts create mode 100644 src/modules/alerts/application/alert.channels.test.ts create mode 100644 src/modules/alerts/infrastructure/alert-channel-message.ts create mode 100644 src/modules/notifications/application/notification-channel.service.test.ts create mode 100644 src/modules/notifications/application/notification-channel.service.ts create mode 100644 src/modules/notifications/domain/notification-channel.domain.ts create mode 100644 src/modules/notifications/infrastructure/channel-test-message.ts create mode 100644 src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts create mode 100644 src/modules/notifications/infrastructure/crypto/channel-cipher.ts create mode 100644 src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts create mode 100644 src/routes/api/notification-channels/+server.ts create mode 100644 src/routes/api/notification-channels/[id]/+server.ts create mode 100644 src/routes/api/notification-channels/[id]/test/+server.ts create mode 100644 src/routes/api/notification-channels/server.test.ts create mode 100644 src/routes/org/[org]/projects/[slug]/settings/notifications/+page.server.ts create mode 100644 src/routes/org/[org]/projects/[slug]/settings/notifications/+page.svelte diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c4273384..8ae00c01 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -80,6 +80,14 @@ con dominio permitido (configurado en `/org//settings/notifications`). Las campos sensibles y links al app para externals. Rutas públicas sin sesión: `/notifications/verify` y `/notifications/unsubscribe` aceptan POST con tokens HMAC. +**Canales de notificación:** Alertas también posean a canales (webhooks genéricos, Slack, Google +Chat): un mensaje por canal, además de emails. Los canales se gestionan en Settings → Notifications +de org o proyecto, con permisos `organization:notifications:*` o `project:notifications:*`. Las +URLs se cifran (AES-GCM, nunca mostradas nuevamente) y solo se aceptan URLs `https` del host del +proveedor (validadas al guardar y antes de cada envío). Los mensajes omiten campos sensibles y +nunca van a canales (acceso diferente). Los reintentos solo aplican a errores de red, 429 y 5xx. +Un error permanente (4xx, URL inválida) se muestra en el canal como `lastError`. + Las rutas deben importar desde el `index.ts` publico. GitDB es la unica fuente de verdad para usuarios, roles, API keys, organizaciones, proyectos, @@ -102,12 +110,13 @@ con scope `cluster`, `organization` o `project`. Usar siempre `can()` o `isAdmin **Permisos de org:** `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`, -`organization:notifications:read` (leer destinatarios externos y dominios permitidos), -`organization:notifications:update` (añadir direcciones externas, cambiar dominios). +`organization:notifications:read` (leer destinatarios externos, dominios, canales), +`organization:notifications:update` (añadir direcciones, canales, cambiar dominios). **Permisos de proyecto:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read` -(leer destinatarios externos de alertas), `project:notifications:update` (añadir direcciones). +(leer destinatarios externos y canales de alertas), `project:notifications:update` (añadir +direcciones y canales). **Gating de permisos en UI:** En loaders de rutas, usar `cancanService.canSessionUser()` para verificar permisos específicos y pasarlos a componentes como props (`canCreate`, `canUpdate`, `canDelete`) para diff --git a/CLAUDE.md b/CLAUDE.md index 83b8e83d..04ff0ab5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -199,7 +199,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`. 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. + engine skips emails and system notifications (debug log) but still posts to channels, warns once + at startup and the alert pages show a banner. `MailQueue` is a `DeliveryQueue` + (`#lib/server/infra/notifications/delivery-queue.ts`), the generic queue channels reuse. - 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` @@ -235,7 +237,45 @@ in `docs/adr/0001-event-bus-and-alerts.md`. (read with `organization:settings:read` or `organization:notifications:read`, changed with `organization:settings:update` or `organization:notifications:update`) and the external recipients status (`organization:notifications:read`, resend confirmation with `organization:notifications:update`). - Notification channels (#95) will live on this page too. + Its channels section is described below. +- Notification channels (`$modules/notifications`, #95): `NotificationChannelEntity` (GitDB + `notification_channels`), owned by an organization (usable by alerts of the organization and of + all its projects) or a project (only its alerts). `type` is `webhook`, `slack` or `google-chat`; + a type is available only once its transport is registered with `registerChatTransport()` + (`#lib/server/infra/notifications/chat-notification.ts`, it also calls `registerTransport`). + This base registers none: each transport sub-task (#96 webhook, #97 Slack, #98 Google Chat) + activates its own, and the tests use `FakeChatTransport`. A `ChatTransport` implements `send()` + and `validateDestination()`, the anti-SSRF check (`validateWebhookUrl()`: https, no credentials, + no IP literal, default port, allowed host and path) run before saving and again before every + send. The destination (`webhookUrl`) is encrypted with `GITDB_ENCRYPTION_KEY` + (`channel-cipher.ts`, AES-GCM bound to the channel id) and only ever leaves the server masked + (`https://hooks.slack.com/…/••••1a2b`); changing it means typing it again. +- Channel delivery: alerts store `channelIds` (`ALERT_CHANNELS` is derived on save: `mail` when + there are email recipients, plus the channel types). Adding a channel needs + `:notifications:update` (`forbidden_channel`), and a channel must be usable from the + alert's location (`unknown_channel`). The engine's `deliver()` emails each recipient and posts + **one message per channel** in parallel; a failing channel never affects the emails or the other + channels, and system notifications never go to channels. The message is a provider-neutral + `ChannelMessage` (`buildAlertChannelMessage()`: default language, no `sensitive` fields, "View in + GitOps" link, throttled count); transports format it. Deliveries go through the process-wide + `channelQueue` (concurrency 3; `postJson()` from `#lib/server/infra/http/webhook-request.ts` with + a 5 s timeout and no redirects; `withRetry` only on network errors, 429 honoring `Retry-After`, + and 5xx). A permanent failure (4xx, invalid or undecryptable destination, type without transport) + sets `lastError`; a success clears it. `lastDeliveryAt` is only refreshed hourly, since each + write is a commit. Logs carry the channel id and type, never the URL nor the message. +- Channels HTTP: `#lib/server/notifications/channels.ts` (permission-first, a channel the caller + can't read is a 404). Routes: `GET|POST /api/notification-channels` (`organizationId` or + `projectId`), `GET|PATCH|DELETE /api/notification-channels/[id]` and + `POST /api/notification-channels/[id]/test` (posts a test even to a disabled channel). UI: the + `ChannelsSection` component (`#lib/components/notifications/`) on + `/org//settings/notifications` and `/org//projects//settings/notifications` + (form actions in `src/lib/server/notifications/channels-page.ts`, no JavaScript needed; project + pages list the inherited organization channels read-only), and a channel picker in the alert editor + that shows the alert's `channelIds`, loading channel options from the page loader's `data.channels`. +- Dev reloads: the alert engine, the mail and channel queues and the verification limiters live on + `globalThis`. Their collaborators are resolved on every call (`latest()` and the engine slot's + `dependencies` in `alerts/index.ts`, `sendWithLatestNotify()` for the queues), and the engine is + rebuilt when its class or `ENGINE_WIRING` changes: bump it when the engine's wiring changes. - 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 @@ -292,8 +332,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`, `project:alerts:read`, `project:notifications: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`, `organization:notifications:read` +- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`, `project:notifications:update`, 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`, `organization:notifications:read`, `organization:notifications:update` This ensures the UI only displays navigation items for sections the user has permission to view. @@ -308,7 +348,7 @@ Permissions always include their scope as a prefix (e.g., `organization:projects - **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 -`organization:notifications:read` and `organization:notifications:update` gate external email recipient management at the organization level. At the project level, `project:notifications:read` and `project:notifications:update` control external recipients of project alerts (externals of alerts that scope to a project). +`organization:notifications:read` and `organization:notifications:update` gate external email recipients and notification channels at the organization level. At the project level, `project:notifications:read` and `project:notifications:update` control external recipients and channels for project alerts. 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 6752db2d..cc1aacae 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,28 @@ sensitive fields and links into the app. Removing a domain blocks its addresses them, and allowing it again restores them. `ORIGIN` must be set: without it, confirmation and unsubscribe links can't be built and nothing is sent to external addresses. +#### Notification channels + +Alerts can also post to chat channels and webhooks: one message per channel, next to the emails. +Channels are managed in **Settings → Notifications** of the organization (usable by the alerts of +the organization and all its projects) or of a project (only that project's alerts), with +`organization:notifications:*` or `project:notifications:*`. Each channel has a **Send test +message** button, and the alert editor lists the channels the alert can use. + +- The channel URL is stored encrypted and never shown again in full. To change it, type it again. +- Only `https` URLs of the provider's own host are accepted, checked when saving and before every + message. +- A message never includes fields marked sensitive, since people reading the channel may not be + allowed to see the event. Access and role notices never go to channels. +- Failed messages are retried on network errors, rate limits and server errors. A permanent error, + such as a deleted webhook, shows on the channel as its last error. + +The channel types (generic webhooks, Slack and Google Chat) become available as their transports +are added; until then the page says that no type is available. Each one will need an incoming +webhook created on the provider side: in Slack, an app with **Incoming Webhooks** enabled and a +webhook for the target channel (`https://hooks.slack.com/services/...`); in Google Chat, the space's +**Apps & integrations → Webhooks** (`https://chat.googleapis.com/v1/spaces/.../messages?...`). + ### Email Invitations, password resets, alerts and access notices are sent by SMTP: diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts index b01822f2..479bf8c1 100644 --- a/src/lib/alerts/summary.ts +++ b/src/lib/alerts/summary.ts @@ -67,11 +67,17 @@ export function summarizeRecipients( users: AlertOption[], roles: AlertOption[], t: Translate, + /** Channels of the alert, by id, with their names. */ + channels: { ids: string[]; options: Array<{ id: string; name: string }> } = { + ids: [], + options: [], + }, ): 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), ...(recipients.externalEmails ?? []), + ...channels.ids.map((id) => channels.options.find((option) => option.id === id)?.name ?? 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 index edb1243f..554603f1 100644 --- a/src/lib/alerts/types.ts +++ b/src/lib/alerts/types.ts @@ -34,9 +34,19 @@ export type AlertDraft = { match: 'all' | 'any'; conditions: DraftCondition[]; recipients: { userIds: string[]; roleIds: string[]; externalEmails: string[] }; + channelIds: string[]; throttleMinutes: number; }; +/** A notification channel the alert can post to (its project's or its organization's). */ +export type AlertChannelOption = { + id: string; + name: string; + type: string; + scope: 'organization' | 'project'; + enabled: boolean; +}; + /** External email recipients as the editor needs them. */ export type ExternalRecipientsEditorData = { /** `:notifications:update`: needed to add addresses. */ @@ -57,6 +67,8 @@ type Shared = { referenceOptions: Record; users: AlertOption[]; roles: AlertOption[]; + /** Channels alerts of the location can post to. */ + channels: AlertChannelOption[]; /** `false` when SMTP is not configured: alerts are saved but nothing is sent. */ mailConfigured: boolean; }; @@ -83,6 +95,7 @@ export type AlertTestView = { recipients: Array<{ userId: string; username: string }>; deniedCount: number; external: Array<{ email: string; status: string; delivers: boolean }>; + channels: Array<{ id: string; name: string; type: string; delivers: boolean }>; /** Present when a real test email was sent. */ delivery?: { sent: number; failed: number }; event: { type: string; payload: Record; projectId: string | null }; diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 3095f1ab..f7ed2dfb 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -58,6 +58,7 @@ export let canReadProjectServerKeys = false; export let canReadProjectAudit = false; export let canReadProjectAlerts = false; + export let canReadProjectNotifications = false; export let canReadProjectVault = false; export let canReadProjectCodeReport = false; export let canReadProjectStateIac = false; @@ -240,6 +241,12 @@ icon: BellRing, visible: canReadProjectAlerts, }, + { + label: $_('sidebar.items.notifications'), + href: `${projectBase}/settings/notifications`, + icon: Mail, + visible: canReadProjectNotifications, + }, { label: $_('sidebar.items.serverKeys'), href: `${projectBase}/settings/server-access-keys`, diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte index e21278a9..a4a05a1c 100644 --- a/src/lib/components/alerts/AlertEditor.svelte +++ b/src/lib/components/alerts/AlertEditor.svelte @@ -408,22 +408,67 @@ {/if} -
+
{$_('alerts.editor.channels')} - - {#each ['in_app', 'slack'] as channel (channel)} - - {/each} +

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

+ {#if data.channels.length === 0} +

+ {$_('alerts.editor.noChannels')} + {#if data.external.settingsPath} + + {$_('alerts.editor.channelsSettingsLink')} + + {/if} +

+ {:else} + {#each data.channels as channel (channel.id)} + {@const selected = draft.channelIds.includes(channel.id)} + + {#if selected && !data.canSave} + + {/if} + {/each} + {#if draft.channelIds.length > 0} +

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

+ {/if} + {#if !data.external.canManage} +

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

+ {/if} + {/if} + {#if errors.channelIds} + + {/if}
@@ -500,6 +545,17 @@ {:else}

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

{/if} + {#if test.channels?.length > 0} +
    + {#each test.channels as channel (channel.id)} +
  • + {channel.name}: {channel.delivers + ? $_('alerts.test.channelDelivers') + : $_('alerts.test.channelSkipped')} +
  • + {/each} +
+ {/if} {#if test.external.length > 0}
    {#each test.external as recipient (recipient.email)} diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte index 6adbd62e..cbc1812f 100644 --- a/src/lib/components/alerts/AlertList.svelte +++ b/src/lib/components/alerts/AlertList.svelte @@ -159,7 +159,10 @@ >{conditionsOf(alert)} - {summarizeRecipients(alert.recipients, data.users, data.roles, t)} + {summarizeRecipients(alert.recipients, data.users, data.roles, t, { + ids: alert.channelIds ?? [], + options: data.channels, + })} {#if !readonly && data.canUpdate} diff --git a/src/lib/components/notifications/ChannelsSection.svelte b/src/lib/components/notifications/ChannelsSection.svelte new file mode 100644 index 00000000..06b8824e --- /dev/null +++ b/src/lib/components/notifications/ChannelsSection.svelte @@ -0,0 +1,316 @@ + + +
    +
    +

    + + {$_('notifications.channels.title')} +

    +

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

    +
    + +

    + + {$_('notifications.channels.privacyNotice')} +

    + + {#if form?.channelTest} +

    + {form.channelTest.sent + ? $_('notifications.channels.testSent') + : $_('notifications.channels.testFailed', { + values: { reason: form.channelTest.error ?? '—' }, + })} +

    + {:else if form?.channelError && form.channelForm !== 'create' && !form.channelErrors} + + {/if} + + {#if data.channels.length === 0} +

    + {$_('notifications.channels.empty')} +

    + {:else} +
      + {#each data.channels as channel (channel.id)} + {@const errors = rowErrors(channel)} +
    • +
      +
      +

      + {channel.name} + + {$_(`notifications.channels.types.${channel.type}`)} + + {#if !channel.enabled} + + {$_('notifications.channels.disabled')} + + {/if} + {#if !channel.available} + + {$_('notifications.channels.unavailable')} + + {/if} +

      +

      {channel.destinationMasked}

      +

      + {$_('notifications.channels.lastDelivery', { + values: { date: formatDate(channel.lastDeliveryAt) }, + })} +

      + {#if channel.lastError} +

      + {$_('notifications.channels.lastError', { values: { error: channel.lastError } })} +

      + {/if} +
      + +
      + {#if data.canUpdate} +
      + + +
      +
      + + + +
      + {/if} + {#if data.canDelete} +
      { + if (!confirm($_('notifications.channels.confirmDelete'))) cancel(); + }} + > + + +
      + {/if} +
      +
      + + {#if data.canUpdate} +
      0}> + + {$_('notifications.channels.edit')} + +
      + + + +
      + +
      +
      +
      + {/if} +
    • + {/each} +
    + {/if} + + {#if data.inherited.length > 0} +
    +
    + {$_('notifications.channels.inheritedTitle')} +
    +

    {$_('notifications.channels.inheritedDescription')}

    +
      + {#each data.inherited as channel (channel.id)} +
    • + {channel.name} + + {$_(`notifications.channels.types.${channel.type}`)} + + {#if !channel.enabled} + {$_('notifications.channels.disabled')} + {/if} +
    • + {/each} +
    +
    + {/if} + + {#if data.canCreate} +
    +
    + + {$_('notifications.channels.create')} +
    + {#if data.availableTypes.length === 0} +

    + {$_('notifications.channels.noTypes')} +

    + {:else} +
    + + + +
    + +
    +
    + {/if} +
    + {/if} +
    diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index bf8a8f66..ce7d14a3 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -346,6 +346,29 @@ export const ExternalRecipientEntity = entity('external_recipients', { .$defaultFn(() => new Date().toISOString()), }); +// chat / webhook destination of alerts (#95), owned by an organization (usable by all its +// projects' alerts) or by one project. `webhookUrl` is encrypted with GITDB_ENCRYPTION_KEY and +// never leaves the server in clear +export const NotificationChannelEntity = entity('notification_channels', { + id: uuid().primaryKey(), + type: text().notNull(), + name: text().notNull(), + scope: text().notNull(), + organizationId: uuid().notNull(), + projectId: uuid().$defaultFn(() => null), + webhookUrl: text().notNull(), + enabled: bool().notNull().default(true), + createdByUserId: uuid().notNull(), + createdAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), + lastDeliveryAt: timestamp(), + lastError: text(), +}); + relations.for(ProjectEntity, ({ one, many }) => ({ roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }), organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index fb0167ad..ca03163a 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1379,7 +1379,9 @@ "domain_not_allowed": "The domain is not allowed for external recipients.", "forbidden_external": "You are not allowed to add external recipients.", "mail_not_configured": "SMTP is not configured: the test email can't be sent.", - "test_rate_limited": "You sent too many test emails. Wait a few minutes." + "test_rate_limited": "You sent too many test emails. Wait a few minutes.", + "unknown_channel": "Some channel does not exist or can't be used from here.", + "forbidden_channel": "You are not allowed to add channels to the alert." }, "channels": { "mail": "Email", @@ -1445,7 +1447,7 @@ "roles": "Roles", "users": "Users", "recipientsNotice": "Only recipients allowed to view this event will get the email.", - "channels": "Channel", + "channels": "Channels", "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", @@ -1463,7 +1465,13 @@ "externalStatus": "Status of the external emails", "sendTest": "Send test email", "sendingTest": "Sending…", - "sendTestHelp": "Sends a real email with an example event to the alert's recipients that would get it (external ones only once confirmed)." + "sendTestHelp": "Sends a real email with an example event to the alert's recipients that would get it (external ones only once confirmed).", + "channelsHelp": "The email goes to the recipients above. You can also post the alert to chat channels or webhooks: one message per channel.", + "noChannels": "There are no channels for this scope.", + "channelsSettingsLink": "Configure channels", + "channelFromOrganization": "(from the organization)", + "channelsNotice": "A channel is read by people who may not be allowed to see this event. The message leaves out sensitive fields.", + "channelsReadonly": "Only people who manage notifications can add channels." }, "test": { "matched": "The example event matches the conditions.", @@ -1475,7 +1483,9 @@ "externalDelivers": "would get it", "externalSkipped": "would not get it ({status})", "delivered": "Test email sent: {sent} sent, {failed} failed.", - "externalVerificationSent": "does not get the test until it confirms: the confirmation email was sent. Once confirmed, send the test again." + "externalVerificationSent": "does not get the test until it confirms: the confirmation email was sent. Once confirmed, send the test again.", + "channelDelivers": "would get the message", + "channelSkipped": "would not get it (disabled or deleted)" }, "mailDisabled": "Email is not configured (NOTIFICATION_SMTP_*): alerts are saved but will not be sent." }, @@ -1508,7 +1518,8 @@ "lastSent": "Last confirmation email", "actions": "Actions", "resend": "Resend confirmation", - "resent": "Confirmation email sent again." + "resent": "Confirmation email sent again.", + "projectDescription": "Chat channels and webhooks this project's alerts can use." }, "errors": { "invalid": "The value is not valid.", @@ -1518,7 +1529,18 @@ "invalid_status": "This recipient does not need a confirmation.", "rate_limited": "Too many confirmation emails were sent. Try again later.", "send_failed": "The confirmation email could not be sent.", - "Forbidden": "You are not allowed to do this." + "Forbidden": "You are not allowed to do this.", + "required": "This field is required.", + "too_long": "It is too long.", + "invalid_type": "Invalid channel type.", + "type_unavailable": "This channel type is not available yet.", + "invalid_url": "The URL is not valid.", + "not_https": "The URL must use https.", + "credentials": "The URL can't include a user or a password.", + "ip_address": "The URL can't point to an IP address.", + "port": "The URL can't use another port.", + "host_not_allowed": "That domain is not allowed for this channel type.", + "path_not_allowed": "The URL path does not match this channel type." }, "link": { "invalid": "This link is not valid or has already been used.", @@ -1547,6 +1569,46 @@ "ignore": "If you did not expect this email, ignore it: you will not get anything.", "footer": "You receive this email because someone in a GitOps organization added your address to an alert." } + }, + "channels": { + "title": "Channels", + "descriptionOrganization": "Chat channels and webhooks the alerts of the organization and its projects can post to.", + "descriptionProject": "Channels only this project's alerts can use.", + "privacyNotice": "A channel is read by people who may have no GitOps account or permissions. The channel URL is stored encrypted and never shown in full again.", + "empty": "No channels yet.", + "types": { + "webhook": "Webhook", + "slack": "Slack", + "google-chat": "Google Chat" + }, + "disabled": "Disabled", + "unavailable": "Type not available", + "lastDelivery": "Last delivery: {date}", + "lastError": "Last error: {error}", + "test": "Send test message", + "testSent": "Test message sent.", + "testFailed": "The test message could not be sent ({reason}).", + "enable": "Enable", + "disable": "Disable", + "delete": "Delete", + "confirmDelete": "Delete this channel? Alerts using it will stop posting to it.", + "edit": "Edit", + "name": "Name", + "newDestination": "New URL (empty keeps the current one)", + "save": "Save", + "inheritedTitle": "Organization channels", + "inheritedDescription": "This project's alerts can also use these channels. They are managed from the organization settings.", + "create": "Add channel", + "noTypes": "No channel type is available yet.", + "type": "Type", + "destination": "Webhook URL", + "testMessage": { + "title": "GitOps test message for {channel}", + "summary": "This channel will get the alerts of {where}.", + "event": "Test message", + "channel": "Channel", + "open": "Open in GitOps" + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index cb3e564c..6c116734 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1379,7 +1379,9 @@ "domain_not_allowed": "El dominio no está permitido para destinatarios externos.", "forbidden_external": "No tienes permiso para añadir destinatarios externos.", "mail_not_configured": "El SMTP no está configurado: no se puede enviar el email de prueba.", - "test_rate_limited": "Has enviado demasiados emails de prueba. Espera unos minutos." + "test_rate_limited": "Has enviado demasiados emails de prueba. Espera unos minutos.", + "unknown_channel": "Algún canal no existe o no se puede usar desde aquí.", + "forbidden_channel": "No tienes permiso para añadir canales a la alerta." }, "channels": { "mail": "Email", @@ -1445,7 +1447,7 @@ "roles": "Roles", "users": "Usuarios", "recipientsNotice": "Solo recibirán el email los destinatarios con permiso para ver este evento.", - "channels": "Canal", + "channels": "Canales", "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", @@ -1463,7 +1465,13 @@ "externalStatus": "Estado de los emails externos", "sendTest": "Enviar email de prueba", "sendingTest": "Enviando…", - "sendTestHelp": "Envía un email real con un evento de ejemplo a los destinatarios de la alerta que lo recibirían (los externos solo si están confirmados)." + "sendTestHelp": "Envía un email real con un evento de ejemplo a los destinatarios de la alerta que lo recibirían (los externos solo si están confirmados).", + "channelsHelp": "El email llega a los destinatarios de arriba. Además, puedes publicar la alerta en canales de chat o webhooks: un mensaje por canal.", + "noChannels": "No hay canales configurados para este ámbito.", + "channelsSettingsLink": "Configurar canales", + "channelFromOrganization": "(de la organización)", + "channelsNotice": "Un canal lo lee gente que puede no tener permiso para ver este evento. El mensaje no incluye los campos sensibles.", + "channelsReadonly": "Solo quien puede gestionar las notificaciones puede añadir canales." }, "test": { "matched": "El evento de ejemplo cumple las condiciones.", @@ -1475,7 +1483,9 @@ "externalDelivers": "lo recibiría", "externalSkipped": "no lo recibiría ({status})", "delivered": "Email de prueba enviado: {sent} enviados, {failed} fallidos.", - "externalVerificationSent": "no recibe la prueba hasta que confirme: se le ha enviado el email de confirmación. Cuando confirme, vuelve a enviar la prueba." + "externalVerificationSent": "no recibe la prueba hasta que confirme: se le ha enviado el email de confirmación. Cuando confirme, vuelve a enviar la prueba.", + "channelDelivers": "recibiría el mensaje", + "channelSkipped": "no lo recibiría (deshabilitado o eliminado)" }, "mailDisabled": "El email no está configurado (NOTIFICATION_SMTP_*): las alertas se guardan, pero no se enviarán." }, @@ -1508,7 +1518,8 @@ "lastSent": "Último email de confirmación", "actions": "Acciones", "resend": "Reenviar confirmación", - "resent": "Email de confirmación reenviado." + "resent": "Email de confirmación reenviado.", + "projectDescription": "Canales de chat y webhooks que pueden usar las alertas de este proyecto." }, "errors": { "invalid": "El valor no es válido.", @@ -1518,7 +1529,18 @@ "invalid_status": "Este destinatario no necesita confirmación.", "rate_limited": "Se han enviado demasiados emails de confirmación. Inténtalo más tarde.", "send_failed": "No se ha podido enviar el email de confirmación.", - "Forbidden": "No tienes permiso para hacer esto." + "Forbidden": "No tienes permiso para hacer esto.", + "required": "Este campo es obligatorio.", + "too_long": "Es demasiado largo.", + "invalid_type": "Tipo de canal no válido.", + "type_unavailable": "Este tipo de canal todavía no está disponible.", + "invalid_url": "La URL no es válida.", + "not_https": "La URL debe usar https.", + "credentials": "La URL no puede incluir usuario ni contraseña.", + "ip_address": "La URL no puede apuntar a una dirección IP.", + "port": "La URL no puede usar otro puerto.", + "host_not_allowed": "Ese dominio no está permitido para este tipo de canal.", + "path_not_allowed": "La ruta de la URL no corresponde a este tipo de canal." }, "link": { "invalid": "Este enlace no es válido o ya se ha usado.", @@ -1547,6 +1569,46 @@ "ignore": "Si no esperabas este email, ignóralo: no recibirás nada.", "footer": "Recibes este email porque alguien de una organización de GitOps añadió tu dirección a una alerta." } + }, + "channels": { + "title": "Canales", + "descriptionOrganization": "Canales de chat y webhooks donde las alertas de la organización y de sus proyectos pueden publicar.", + "descriptionProject": "Canales que solo pueden usar las alertas de este proyecto.", + "privacyNotice": "Un canal lo lee gente que puede no tener cuenta ni permisos en GitOps. La URL del canal se guarda cifrada y nunca se vuelve a mostrar completa.", + "empty": "Todavía no hay canales.", + "types": { + "webhook": "Webhook", + "slack": "Slack", + "google-chat": "Google Chat" + }, + "disabled": "Deshabilitado", + "unavailable": "Tipo no disponible", + "lastDelivery": "Último envío: {date}", + "lastError": "Último error: {error}", + "test": "Enviar mensaje de prueba", + "testSent": "Mensaje de prueba enviado.", + "testFailed": "No se ha podido enviar el mensaje de prueba ({reason}).", + "enable": "Habilitar", + "disable": "Deshabilitar", + "delete": "Eliminar", + "confirmDelete": "¿Eliminar este canal? Las alertas que lo usan dejarán de publicar en él.", + "edit": "Editar", + "name": "Nombre", + "newDestination": "Nueva URL (vacío para mantener la actual)", + "save": "Guardar", + "inheritedTitle": "Canales de la organización", + "inheritedDescription": "Las alertas de este proyecto también pueden usar estos canales. Se gestionan desde los ajustes de la organización.", + "create": "Añadir canal", + "noTypes": "Todavía no hay ningún tipo de canal disponible.", + "type": "Tipo", + "destination": "URL del webhook", + "testMessage": { + "title": "Mensaje de prueba de GitOps para {channel}", + "summary": "Este canal recibirá las alertas de {where}.", + "event": "Mensaje de prueba", + "channel": "Canal", + "open": "Abrir en GitOps" + } } } } diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts index cd358c49..b7ca176a 100644 --- a/src/lib/notifications/types.ts +++ b/src/lib/notifications/types.ts @@ -2,3 +2,44 @@ export type NotificationLinkState = | { state: 'ready' | 'done'; email: string; organization: string } | { state: 'invalid' | 'expired' }; + +/** A notification channel as the pages show it: the destination only masked. */ +export type ChannelView = { + id: string; + type: string; + name: string; + scope: 'organization' | 'project'; + organizationId: string; + projectId: string | null; + enabled: boolean; + destinationMasked: string; + available: boolean; + createdByUserId: string; + createdAt: string; + updatedAt: string; + lastDeliveryAt: string | null; + lastError: string | null; +}; + +export type ChannelsSectionData = { + scope: 'organization' | 'project'; + channels: ChannelView[]; + /** Organization channels the project's alerts can also use (project pages only). */ + inherited: ChannelView[]; + /** Types that can be created now. */ + availableTypes: string[]; + canCreate: boolean; + canUpdate: boolean; + canDelete: boolean; +}; + +/** What the channel form actions return. */ +export type ChannelsFormResult = { + channelForm?: string; + channelDraft?: { type: string; name: string }; + channelError?: string; + channelErrors?: Record; + channelSaved?: string; + channelDeleted?: string; + channelTest?: { channelId: string; sent: boolean; error: string | null }; +} | null; diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts index dddd9246..4c8bd33a 100644 --- a/src/lib/server/alerts/operations.ts +++ b/src/lib/server/alerts/operations.ts @@ -195,6 +195,8 @@ export type AlertTestResult = { deniedCount: number; /** External addresses, their status and whether they would get the email. */ external: Array<{ email: string; status: string; delivers: boolean }>; + /** The alert's channels and whether they would get the message. */ + channels: Array<{ id: string; name: string; type: string; delivers: boolean }>; /** Only when `send` was asked: emails really sent and failed. */ delivery?: { sent: number; failed: number }; event: { type: string; payload: Record; projectId: string | null }; @@ -218,6 +220,7 @@ async function dryRun( | 'conditions' | 'match' | 'recipients' + | 'channelIds' | 'location' | 'appliesTo' >, @@ -297,6 +300,7 @@ async function dryRun( recipients: result.recipients.map(({ userId, username }) => ({ userId, username })), deniedCount: result.denied.length, external: result.external, + channels: result.channels, ...(delivery ? { delivery } : {}), event: { type: alert.eventType, payload: sample.payload, projectId }, }, @@ -334,9 +338,11 @@ export async function testDraftAlert( existing && existing.organizationId === location.organizationId && existing.projectId === location.projectId; - const previousExternal = sameLocation ? existing.recipients.externalEmails : []; + const previous = sameLocation + ? { externalEmails: existing.recipients.externalEmails, channelIds: existing.channelIds } + : {}; try { - const fields = await alertService.validate(location, input, actor, previousExternal); + const fields = await alertService.validate(location, input, actor, previous); // the stored id keeps the email's "manage the alert" link working const draft = new AlertDomain({ id: sameLocation ? existing.id : 'draft', diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts index f3d31d52..b70397c8 100644 --- a/src/lib/server/alerts/page.ts +++ b/src/lib/server/alerts/page.ts @@ -6,7 +6,11 @@ import { type AlertLocation, type AlertRow, } from '#modules/alerts'; -import { externalRecipientService, notificationSettingsService } from '#modules/notifications'; +import { + externalRecipientService, + notificationChannelService, + notificationSettingsService, +} from '#modules/notifications'; import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; import { @@ -19,6 +23,7 @@ import { import type { AlertDraft, AlertEditorData, + AlertChannelOption, AlertListData, AlertOption, DraftCondition, @@ -77,6 +82,18 @@ async function referenceOptions( ); } +/** Channels alerts of `location` can post to: its project's and its organization's. */ +async function channelOptions(location: AlertLocation): Promise { + const channels = await notificationChannelService.listUsable(location).catch(() => []); + return channels.map((channel) => ({ + id: channel.id, + name: channel.name, + type: channel.type, + scope: channel.scope, + enabled: channel.enabled, + })); +} + async function recipientOptions(location: AlertLocation) { const [members, roles] = await Promise.all([ alertDirectory.listMembers(location).catch(() => []), @@ -113,10 +130,11 @@ export async function loadAlertList( scope: 'organization', projectId: null, }; - const [references, own, organizationRecipients] = await Promise.all([ + const [references, own, organizationRecipients, channels] = await Promise.all([ referenceOptions([...catalog, ...inheritedCatalog], organizationLocation), recipientOptions(location), location.scope === 'project' ? recipientOptions(organizationLocation) : null, + channelOptions(location), ]); // names for the recipients of the location's alerts and of the inherited organization ones const merge = (a: AlertOption[], b: AlertOption[] = []) => [ @@ -140,6 +158,7 @@ export async function loadAlertList( referenceOptions: references, users: recipients.users, roles: recipients.roles, + channels, mailConfigured: isMailConfigured(), canCreate: allowed.canCreate, canUpdate: allowed.canUpdate, @@ -156,6 +175,7 @@ function emptyDraft(eventType: string | null): AlertDraft { match: 'all', conditions: [], recipients: { userIds: [], roleIds: [], externalEmails: [] }, + channelIds: [], throttleMinutes: 0, }; } @@ -177,6 +197,7 @@ function toDraft(alert: AlertRow): AlertDraft { roleIds: [...alert.recipients.roleIds], externalEmails: [...alert.recipients.externalEmails], }, + channelIds: [...alert.channelIds], throttleMinutes: alert.throttleMinutes, }; } @@ -231,10 +252,11 @@ export async function loadAlertEditor( } const catalog = await listCatalog(locals, location); - const [references, recipients, external] = await Promise.all([ + const [references, recipients, external, channels] = await Promise.all([ referenceOptions(catalog, location), recipientOptions(location), externalRecipientsData(locals, location, alert?.recipients.externalEmails ?? []), + channelOptions(location), ]); const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null); @@ -251,6 +273,7 @@ export async function loadAlertEditor( referenceOptions: references, users: recipients.users, roles: recipients.roles, + channels, external, mailConfigured: isMailConfigured(), canSave: alert ? allowed.canUpdate : allowed.canCreate, @@ -302,6 +325,7 @@ export function parseAlertForm(form: FormData): AlertDraft { .map((value) => value.trim()) .filter(Boolean), }, + channelIds: form.getAll('channelIds').map(String).filter(Boolean), throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0, }; } diff --git a/src/lib/server/infra/http/webhook-request.test.ts b/src/lib/server/infra/http/webhook-request.test.ts new file mode 100644 index 00000000..f268ae8d --- /dev/null +++ b/src/lib/server/infra/http/webhook-request.test.ts @@ -0,0 +1,125 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { withRetry } from '../notifications/retry'; +import { + WebhookDeliveryError, + isRetryableWebhookError, + postJson, + validateWebhookUrl, + webhookRetryAfter, +} from './webhook-request'; + +const rule = { hosts: ['hooks.slack.com'], pathPrefix: '/services/' }; + +describe('validateWebhookUrl (anti-SSRF)', () => { + it('accepts an https URL of an allowed host and path', () => { + const result = validateWebhookUrl('https://hooks.slack.com/services/T0/B0/abc', rule); + expect(result).toMatchObject({ ok: true }); + }); + + it.each([ + ['http://hooks.slack.com/services/T0', 'not_https'], + ['https://user:pass@hooks.slack.com/services/T0', 'credentials'], + ['https://127.0.0.1/services/T0', 'ip_address'], + ['https://[::1]/services/T0', 'ip_address'], + ['https://169.254.169.254/services/T0', 'ip_address'], + ['https://hooks.slack.com:8443/services/T0', 'port'], + ['https://evil.com/services/T0', 'host_not_allowed'], + ['https://hooks.slack.com.evil.com/services/T0', 'host_not_allowed'], + ['https://hooks.slack.com/other/T0', 'path_not_allowed'], + ['javascript:alert(1)', 'not_https'], + ['not a url', 'invalid_url'], + ['', 'invalid_url'], + ])('rejects %s', (url, error) => { + expect(validateWebhookUrl(url, rule)).toEqual({ ok: false, error }); + }); +}); + +function response(status: number, headers: Record = {}) { + return new Response(status === 204 ? null : 'secret body', { status, headers }); +} + +describe('postJson', () => { + afterEach(() => vi.useRealTimers()); + + it('posts JSON without following redirects and accepts any 2xx', async () => { + const fetch = vi.fn(async () => response(204)); + await postJson('https://hooks.slack.com/services/x', { text: 'hi' }, { fetch }); + expect(fetch).toHaveBeenCalledWith( + 'https://hooks.slack.com/services/x', + expect.objectContaining({ + method: 'POST', + redirect: 'manual', + body: '{"text":"hi"}', + headers: expect.objectContaining({ 'content-type': 'application/json' }), + }), + ); + }); + + it('treats 429 and 5xx as retryable, honoring Retry-After', async () => { + const tooMany = await postJson( + 'https://h/x', + {}, + { + fetch: async () => response(429, { 'retry-after': '7' }), + }, + ).catch((error) => error); + expect(tooMany).toBeInstanceOf(WebhookDeliveryError); + expect(tooMany).toMatchObject({ status: 429, retryable: true, retryAfterMs: 7000 }); + + const down = await postJson('https://h/x', {}, { fetch: async () => response(503) }).catch( + (error) => error, + ); + expect(down).toMatchObject({ status: 503, retryable: true }); + }); + + it('treats other 4xx and redirects as permanent', async () => { + for (const status of [400, 403, 404, 410, 301, 302]) { + const error = await postJson( + 'https://h/x', + {}, + { fetch: async () => response(status) }, + ).catch((caught) => caught); + expect(error).toMatchObject({ status, retryable: false }); + expect(error.summary).toBe(`HTTP ${status}`); + // the response body never ends up in the error + expect(String(error.message)).not.toContain('secret body'); + } + }); + + it('times out after 5 s and calls it retryable', async () => { + vi.useFakeTimers(); + const fetch = vi.fn( + (_url: string, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => reject(new Error('aborted'))); + }), + ); + const pending = postJson('https://h/x', {}, { fetch: fetch as never }).catch((error) => error); + await vi.advanceTimersByTimeAsync(5_000); + expect(await pending).toMatchObject({ status: null, retryable: true, reason: 'timeout' }); + }); + + it('retries with withRetry only what may succeed later', async () => { + const sleep = vi.fn(async (_ms: number) => {}); + const statuses = [429, 503, 200]; + const fetch = vi.fn(async () => response(statuses.shift()!, { 'retry-after': '2' })); + await withRetry(() => postJson('https://h/x', {}, { fetch }), { + isRetryable: isRetryableWebhookError, + retryAfterMs: webhookRetryAfter, + sleep, + random: () => 0.5, + }); + expect(fetch).toHaveBeenCalledTimes(3); + // 429 waits its Retry-After, 503 the regular backoff (4 s for the second retry) + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([2000, 4000]); + + const gone = vi.fn(async () => response(404)); + await expect( + withRetry(() => postJson('https://h/x', {}, { fetch: gone }), { + isRetryable: isRetryableWebhookError, + sleep, + }), + ).rejects.toMatchObject({ status: 404 }); + expect(gone).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/lib/server/infra/http/webhook-request.ts b/src/lib/server/infra/http/webhook-request.ts new file mode 100644 index 00000000..66292d4b --- /dev/null +++ b/src/lib/server/infra/http/webhook-request.ts @@ -0,0 +1,149 @@ +import { isIP } from 'node:net'; + +/** Why a webhook URL is refused; the UI maps them to `notifications.errors.`. */ +export type WebhookUrlError = + | 'invalid_url' + | 'not_https' + | 'credentials' + | 'ip_address' + | 'port' + | 'host_not_allowed' + | 'path_not_allowed'; + +export type WebhookUrlRule = { + /** Exact host names the URL may point at (`hooks.slack.com`). */ + hosts: readonly string[]; + /** Required path prefix (`/services/`). */ + pathPrefix?: string; +}; + +const MAX_URL_LENGTH = 2048; + +/** + * Anti-SSRF check of a webhook URL whose provider is known: `https` only, no credentials, no IP + * literal, the default port, an allowed host and path. Run it before saving **and** before every + * send (the stored value could have been changed in GitDB by hand). + */ +export function validateWebhookUrl( + raw: unknown, + rule: WebhookUrlRule, +): { ok: true; url: URL } | { ok: false; error: WebhookUrlError } { + if (typeof raw !== 'string' || !raw.trim() || raw.length > MAX_URL_LENGTH) { + return { ok: false, error: 'invalid_url' }; + } + let url: URL; + try { + url = new URL(raw.trim()); + } catch { + return { ok: false, error: 'invalid_url' }; + } + if (url.protocol !== 'https:') return { ok: false, error: 'not_https' }; + if (url.username || url.password) return { ok: false, error: 'credentials' }; + const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase(); + if (isIP(host)) return { ok: false, error: 'ip_address' }; + if (url.port && url.port !== '443') return { ok: false, error: 'port' }; + if (!rule.hosts.includes(host)) return { ok: false, error: 'host_not_allowed' }; + if (rule.pathPrefix && !url.pathname.startsWith(rule.pathPrefix)) { + return { ok: false, error: 'path_not_allowed' }; + } + return { ok: true, url }; +} + +/** A webhook delivery that failed; `retryable` tells whether trying again may help. */ +export class WebhookDeliveryError extends Error { + constructor( + /** HTTP status, or `null` for network errors and timeouts. */ + readonly status: number | null, + readonly retryable: boolean, + /** `Retry-After` of a 429, in ms. */ + readonly retryAfterMs: number | null = null, + readonly reason: 'timeout' | 'network' | 'redirect' | 'http' = 'http', + ) { + super( + status === null ? `Webhook delivery failed (${reason})` : `Webhook answered HTTP ${status}`, + ); + this.name = 'WebhookDeliveryError'; + } + + /** Short description for `lastError` and the logs: never the URL nor the response body. */ + get summary(): string { + if (this.status !== null) return `HTTP ${this.status}`; + return this.reason; + } +} + +export const WEBHOOK_TIMEOUT_MS = 5_000; +/** Longest `Retry-After` honored; longer waits fall back to the regular backoff. */ +const MAX_RETRY_AFTER_MS = 60_000; + +function parseRetryAfter(value: string | null, now: number): number | null { + if (!value) return null; + const seconds = Number(value); + const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - now; + if (!Number.isFinite(ms) || ms < 0) return null; + return Math.min(ms, MAX_RETRY_AFTER_MS); +} + +export type PostJsonOptions = { + timeoutMs?: number; + headers?: Record; + fetch?: typeof fetch; + now?: () => number; +}; + +/** + * POSTs `body` as JSON. Any 2xx is a success; the response body is discarded. Redirects are not + * followed (they would bypass the URL check). Throws `WebhookDeliveryError`: retryable for network + * errors, timeouts, 429 (with its `Retry-After`) and 5xx; permanent for 3xx and other 4xx. + */ +export async function postJson( + url: string, + body: unknown, + options: PostJsonOptions = {}, +): Promise { + const send = options.fetch ?? fetch; + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? WEBHOOK_TIMEOUT_MS); + let response: Response; + try { + response = await send(url, { + method: 'POST', + headers: { 'content-type': 'application/json', ...options.headers }, + body: JSON.stringify(body), + redirect: 'manual', + signal: controller.signal, + }); + } catch { + throw new WebhookDeliveryError( + null, + true, + null, + controller.signal.aborted ? 'timeout' : 'network', + ); + } finally { + clearTimeout(timer); + } + // nothing of the answer is kept: it is not ours to log + await response.body?.cancel().catch(() => {}); + + const { status } = response; + if (status >= 200 && status < 300) return; + if (status >= 300 && status < 400) + throw new WebhookDeliveryError(status, false, null, 'redirect'); + if (status === 429) { + const retryAfter = parseRetryAfter( + response.headers.get('retry-after'), + (options.now ?? Date.now)(), + ); + throw new WebhookDeliveryError(status, true, retryAfter); + } + throw new WebhookDeliveryError(status, status >= 500); +} + +export function isRetryableWebhookError(error: unknown): boolean { + return error instanceof WebhookDeliveryError && error.retryable; +} + +export function webhookRetryAfter(error: unknown): number | null { + return error instanceof WebhookDeliveryError ? error.retryAfterMs : null; +} diff --git a/src/lib/server/infra/notifications/chat-notification.ts b/src/lib/server/infra/notifications/chat-notification.ts new file mode 100644 index 00000000..9a82ab7e --- /dev/null +++ b/src/lib/server/infra/notifications/chat-notification.ts @@ -0,0 +1,99 @@ +import { Notification } from './notification'; +import type { NotificationTransport } from './transport'; +import { registerTransport } from './notify'; +import type { WebhookUrlError } from '../http/webhook-request'; + +import { CHAT_CHANNEL_TYPES, type ChatChannelType } from './chat-types'; + +export { CHAT_CHANNEL_TYPES, isChatChannelType, type ChatChannelType } from './chat-types'; + +/** + * Provider-neutral content of a channel message; each transport turns it into its own format + * (Block Kit, Cards v2, signed JSON). Texts are already translated and plain: transports escape + * them for their format. + */ +export type ChannelMessage = { + /** The alert's name, or the channel's for a test message. */ + title: string; + /** One line: `3 critical, 5 high` or the event label. */ + summary: string; + /** Translated event label (`Analysis completed`). */ + eventLabel: string; + /** Catalog fields as label/value, sensitive ones left out. */ + fields: Array<{ label: string; value: string }>; + /** Absolute link to the resource in GitOps (`ORIGIN`), when there is one. */ + link: { url: string; label: string } | null; + /** Matching events skipped by the throttle since the previous message. */ + suppressed: number; + /** Plain-text fallback (mobile notifications, clients without rich formatting). */ + text: string; + /** A test from the UI, not a real event. */ + test: boolean; + /** Raw event data for formats that carry it (generic webhooks); absent for test messages. */ + event?: { id: string; type: string; occurredAt: string; scope: Record }; + alert?: { id: string; name: string }; +}; + +export type ChatNotificationInput = { + channel: ChatChannelType; + /** Destination URL in clear: only ever held in memory, right before sending. */ + destination: string; + message: ChannelMessage; +}; + +export class ChatNotification extends Notification { + readonly channel: ChatChannelType; + readonly destination: string; + readonly message: ChannelMessage; + + constructor(input: ChatNotificationInput) { + super(); + this.channel = input.channel; + this.destination = input.destination; + this.message = input.message; + } + + validate(): void { + if (!this.destination) throw new Error('ChatNotification requires a destination'); + if (!this.message.title.trim()) throw new Error('ChatNotification requires a title'); + } +} + +/** + * Transport of one chat channel type. `validateDestination` is the anti-SSRF check of the + * provider's URL, run before saving a channel and again before every send. + */ +export interface ChatTransport extends NotificationTransport { + validateDestination(raw: unknown): { ok: true; url: URL } | { ok: false; error: WebhookUrlError }; +} + +const CHAT_TRANSPORTS_KEY = Symbol.for('gitops.notifications.chat-transports'); +type GlobalWithChatTransports = typeof globalThis & { + [CHAT_TRANSPORTS_KEY]?: Map; +}; + +function registry(): Map { + return ((globalThis as GlobalWithChatTransports)[CHAT_TRANSPORTS_KEY] ??= new Map()); +} + +/** + * Activates a channel type: its channels can then be created and receive messages. Each + * transport sub-task (#96 webhook, #97 Slack, #98 Google Chat) registers its own. + */ +export function registerChatTransport(type: ChatChannelType, transport: ChatTransport): void { + registry().set(type, transport); + registerTransport(type, transport as NotificationTransport); +} + +export function getChatTransport(type: ChatChannelType): ChatTransport | null { + return registry().get(type) ?? null; +} + +/** Channel types with a registered transport, in catalog order. */ +export function availableChatTypes(): ChatChannelType[] { + return CHAT_CHANNEL_TYPES.filter((type) => registry().has(type)); +} + +export function resetChatTransports(): void { + registry().clear(); +} diff --git a/src/lib/server/infra/notifications/chat-types.ts b/src/lib/server/infra/notifications/chat-types.ts new file mode 100644 index 00000000..680be4fe --- /dev/null +++ b/src/lib/server/infra/notifications/chat-types.ts @@ -0,0 +1,7 @@ +/** Channel types that post a message to a destination URL (`notification_channels.type`). */ +export const CHAT_CHANNEL_TYPES = ['webhook', 'slack', 'google-chat'] as const; +export type ChatChannelType = (typeof CHAT_CHANNEL_TYPES)[number]; + +export function isChatChannelType(value: unknown): value is ChatChannelType { + return (CHAT_CHANNEL_TYPES as readonly unknown[]).includes(value); +} diff --git a/src/lib/server/infra/notifications/delivery-queue.ts b/src/lib/server/infra/notifications/delivery-queue.ts new file mode 100644 index 00000000..84e902e8 --- /dev/null +++ b/src/lib/server/infra/notifications/delivery-queue.ts @@ -0,0 +1,140 @@ +import type { Logger } from 'pino'; +import { withRetry, type RetryOptions } from './retry'; + +type Job = { + item: T; + context: Record; + done: (sent: boolean) => void; +}; + +export type DeliveryQueueOptions = { + /** Delivers one item; a rejection is retried when `retry.isRetryable` allows it. */ + send: (item: T) => Promise; + /** Deliveries in flight at the same time; a burst waits in the queue. */ + concurrency?: number; + retry?: RetryOptions; + logger: Pick; + /** Log prefix and noun: `[mail]` / `email`, `[channels]` / `message`. */ + label: { prefix: string; noun: string; plural: string }; + /** Extra log fields for an item; never its content nor a secret destination. */ + describe?: (item: T) => Record; + /** Short code of a definitive failure for the logs (never a message: it may quote secrets). */ + errorCode?: (error: unknown) => unknown; + /** Called once per item after its last attempt. */ + onSettled?: (item: T, outcome: { sent: true } | { sent: false; error: unknown }) => void; +}; + +/** + * In-process delivery queue with limited concurrency and retries (`withRetry`). Each job is one + * delivery; a definitive failure is logged and dropped, never thrown at the caller. Per process: + * pending jobs are lost on a crash, and `drain()` flushes them on shutdown. + */ +export class DeliveryQueue { + private readonly pending: Job[] = []; + private active = 0; + private readonly idle = new Set<() => void>(); + private readonly concurrency: number; + + constructor(protected readonly options: DeliveryQueueOptions) { + this.concurrency = Math.max(1, options.concurrency ?? 3); + } + + /** + * Queues one delivery; resolves once it succeeded (`true`) or definitively failed (`false`, + * already logged). It never rejects. + */ + enqueue(item: T, context: Record = {}): Promise { + return new Promise((resolve) => { + this.pending.push({ item, context, done: resolve }); + this.pump(); + }); + } + + /** Deliveries waiting or in flight. */ + 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 delivered). + */ + 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); + const { prefix, plural } = this.options.label; + this.options.logger.warn( + { remaining: this.size }, + `${prefix} shutdown timeout: ${plural} 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; + let sent = false; + void this.run(job) + .then((result) => { + sent = result; + }) + .finally(() => { + this.active -= 1; + job.done(sent); + if (this.size === 0) { + for (const resolve of [...this.idle]) resolve(); + this.idle.clear(); + } else { + this.pump(); + } + }); + } + } + + private async run(job: Job): Promise { + const { prefix, noun } = this.options.label; + const fields = { ...job.context, ...this.options.describe?.(job.item) }; + const code = this.options.errorCode ?? defaultErrorCode; + try { + await withRetry(() => this.options.send(job.item), { + ...this.options.retry, + onRetry: (error, attempt, delayMs) => + this.options.logger.debug( + { ...fields, attempt, delayMs, code: code(error) }, + `${prefix} retrying ${noun}`, + ), + }); + this.options.onSettled?.(job.item, { sent: true }); + return true; + } catch (error) { + this.options.logger.error( + { ...fields, code: code(error) }, + `${prefix} ${noun} could not be sent`, + ); + this.options.onSettled?.(job.item, { sent: false, error }); + return false; + } + } +} + +/** The error's code, HTTP/SMTP status or name; never its message. */ +export function defaultErrorCode(error: unknown): unknown { + if (!error || typeof error !== 'object') return undefined; + const { code, responseCode, status, name } = error as { + code?: unknown; + responseCode?: unknown; + status?: unknown; + name?: unknown; + }; + return responseCode ?? status ?? code ?? name; +} diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts index 9fc2a7d0..f3b21bac 100644 --- a/src/lib/server/infra/notifications/index.ts +++ b/src/lib/server/infra/notifications/index.ts @@ -26,6 +26,20 @@ export { withRetry, isRetryableMailError, type RetryOptions } from './retry'; // `./i18n` is not re-exported on purpose: it loads the paraglide messages, and this entry point is // imported by `$modules/auth`, which also runs outside Vite (the e2e seed). Import it directly export { emailButton, emailNote } from './email-parts'; +export { + CHAT_CHANNEL_TYPES, + ChatNotification, + availableChatTypes, + getChatTransport, + isChatChannelType, + registerChatTransport, + resetChatTransports, + type ChannelMessage, + type ChatChannelType, + type ChatNotificationInput, + type ChatTransport, +} from './chat-notification'; +export { DeliveryQueue, defaultErrorCode, type DeliveryQueueOptions } from './delivery-queue'; export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue'; import { createLogger } from '#lib/server/logger'; @@ -41,17 +55,22 @@ type GlobalWithQueue = typeof globalThis & { [SEND_KEY]?: typeof send; }; -// the queue outlives module reloads (dev HMR); it must send with the latest `notify`, whose -// `instanceof Notification` check matches the classes the current code builds emails with +// queues outlive module reloads (dev HMR); they must send with the latest `notify`, whose +// `instanceof Notification` check matches the classes the current code builds messages with (globalThis as GlobalWithQueue)[SEND_KEY] = send; +/** `notify` of the latest evaluation of this module: what process-wide queues send with. */ +export function sendWithLatestNotify(notification: Parameters[0]): Promise { + return ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification); +} + /** * 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) => ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification), + send: (notification) => sendWithLatestNotify(notification), concurrency: 3, logger: createLogger('mail'), })); diff --git a/src/lib/server/infra/notifications/mail-queue.ts b/src/lib/server/infra/notifications/mail-queue.ts index dfb112a8..0fd5b6da 100644 --- a/src/lib/server/infra/notifications/mail-queue.ts +++ b/src/lib/server/infra/notifications/mail-queue.ts @@ -1,17 +1,12 @@ import crypto from 'node:crypto'; import type { Logger } from 'pino'; +import { DeliveryQueue } from './delivery-queue'; import type { MailNotification } from './mail-notification'; -import { isRetryableMailError, withRetry, type RetryOptions } from './retry'; +import { isRetryableMailError, 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: (sent: boolean) => void; -}; - export type MailQueueOptions = { send: (notification: MailNotification) => Promise; /** Emails sent at the same time; a burst of events waits in the queue. */ @@ -30,115 +25,22 @@ export function recipientHash(address: string): string { } /** - * 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. + * In-process email queue: a `DeliveryQueue` with SMTP-aware retries whose logs carry recipient + * hashes, never the content or the address. */ -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 (`true`) or definitively failed (`false`, already - * logged). It never rejects. - */ - 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); +export class MailQueue extends DeliveryQueue { + constructor(options: MailQueueOptions) { + super({ + send: options.send, + concurrency: options.concurrency, + retry: { isRetryable: isRetryableMailError, ...options.retry }, + logger: options.logger, + label: { prefix: '[mail]', noun: 'email', plural: 'emails' }, + describe: (notification) => ({ recipients: notification.to.map(recipientHash) }), }); } - private pump(): void { - while (this.active < this.concurrency && this.pending.length > 0) { - const job = this.pending.shift()!; - this.active += 1; - let sent = false; - void this.run(job) - .then((result) => { - sent = result; - }) - .finally(() => { - this.active -= 1; - job.done(sent); - 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', - ), - }); - return true; - } 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', - ); - return false; - } + enqueue(notification: MailNotification, context: MailContext = {}): Promise { + return super.enqueue(notification, context); } } - -/** - * SMTP reply or network code; for other errors (a bug, an invalid email) the error's name. Never - * the message: SMTP and validation messages may quote the recipient address. - */ -function errorCode(error: unknown): unknown { - if (!error || typeof error !== 'object') return undefined; - const { code, responseCode, name } = error as { - code?: unknown; - responseCode?: unknown; - name?: unknown; - }; - return responseCode ?? code ?? name; -} diff --git a/src/lib/server/infra/notifications/notification.ts b/src/lib/server/infra/notifications/notification.ts index 1244b065..5c80ed24 100644 --- a/src/lib/server/infra/notifications/notification.ts +++ b/src/lib/server/infra/notifications/notification.ts @@ -1,4 +1,5 @@ -export type NotificationChannel = 'mail' | 'slack'; +/** `mail` sends emails; the others post to a chat or webhook destination (`ChatNotification`). */ +export type NotificationChannel = 'mail' | 'slack' | 'google-chat' | 'webhook'; export abstract class Notification { abstract readonly channel: NotificationChannel; diff --git a/src/lib/server/infra/notifications/retry.ts b/src/lib/server/infra/notifications/retry.ts index 48ac0607..278737d3 100644 --- a/src/lib/server/infra/notifications/retry.ts +++ b/src/lib/server/infra/notifications/retry.ts @@ -7,6 +7,8 @@ export type RetryOptions = { /** ± fraction of each delay added at random, so retries of a burst don't line up. */ jitter?: number; isRetryable?: (error: unknown) => boolean; + /** Wait the error asks for (an HTTP `Retry-After`), instead of the computed backoff. */ + retryAfterMs?: (error: unknown) => number | null | undefined; sleep?: (ms: number) => Promise; random?: () => number; onRetry?: (error: unknown, attempt: number, delayMs: number) => void; @@ -33,7 +35,11 @@ export async function withRetry(fn: () => Promise, options: RetryOptions = } 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)))); + const requested = options.retryAfterMs?.(error); + const delayMs = + typeof requested === 'number' && requested >= 0 + ? Math.round(requested) + : Math.max(0, Math.round(delay * (1 + jitter * (random() * 2 - 1)))); options.onRetry?.(error, attempt, delayMs); await sleep(delayMs); } diff --git a/src/lib/server/notifications/channels-page.ts b/src/lib/server/notifications/channels-page.ts new file mode 100644 index 00000000..4dea0869 --- /dev/null +++ b/src/lib/server/notifications/channels-page.ts @@ -0,0 +1,106 @@ +import { fail } from '@sveltejs/kit'; +import type { ChannelLocation } from '#modules/notifications'; +import type { AlertLocals } from '#lib/server/alerts/access'; +import type { ChannelsSectionData } from '#lib/notifications/types'; +import { + canManageChannels, + createChannel, + deleteChannel, + listChannels, + testChannel, + updateChannel, +} from './channels'; + +/** The channels section of a notifications page; `null` without `:notifications:read`. */ +export async function loadChannelsSection( + locals: AlertLocals, + location: ChannelLocation, +): Promise { + const listed = await listChannels(locals, location); + if (!listed.ok) return null; + const [canCreate, canUpdate, canDelete] = await Promise.all([ + canManageChannels(locals, location, 'create'), + canManageChannels(locals, location, 'update'), + canManageChannels(locals, location, 'delete'), + ]); + return { ...listed.data, scope: location.scope, canCreate, canUpdate, canDelete }; +} + +type ActionEvent = { request: Request; params: Record; locals: AlertLocals }; + +/** Form actions of the channels section, shared by the organization and project pages. */ +export function channelActions(resolve: (event: ActionEvent) => Promise) { + return { + async createChannel(event: ActionEvent) { + const location = await resolve(event); + const form = await event.request.formData(); + const input = { + type: String(form.get('type') ?? ''), + name: String(form.get('name') ?? ''), + destination: String(form.get('destination') ?? ''), + enabled: true, + }; + const result = await createChannel(event.locals, location, input); + if (!result.ok) { + // the destination is never echoed back: it has to be typed again + return fail(result.status, { + channelForm: 'create', + channelDraft: { type: input.type, name: input.name }, + channelError: result.error, + channelErrors: result.errors ?? {}, + }); + } + return { channelSaved: result.data.id }; + }, + + async updateChannel(event: ActionEvent) { + await resolve(event); + const form = await event.request.formData(); + const channelId = String(form.get('channelId') ?? ''); + const result = await updateChannel(event.locals, channelId, { + name: String(form.get('name') ?? ''), + destination: String(form.get('destination') ?? ''), + }); + if (!result.ok) { + return fail(result.status, { + channelForm: channelId, + channelError: result.error, + channelErrors: result.errors ?? {}, + }); + } + return { channelSaved: channelId }; + }, + + async toggleChannel(event: ActionEvent) { + await resolve(event); + const form = await event.request.formData(); + const channelId = String(form.get('channelId') ?? ''); + const result = await updateChannel(event.locals, channelId, { + enabled: form.get('enabled') === 'true', + }); + if (!result.ok) + return fail(result.status, { channelForm: channelId, channelError: result.error }); + return { channelSaved: channelId }; + }, + + async deleteChannel(event: ActionEvent) { + await resolve(event); + const form = await event.request.formData(); + const channelId = String(form.get('channelId') ?? ''); + const result = await deleteChannel(event.locals, channelId); + if (!result.ok) + return fail(result.status, { channelForm: channelId, channelError: result.error }); + return { channelDeleted: channelId }; + }, + + async testChannel(event: ActionEvent) { + await resolve(event); + const form = await event.request.formData(); + const channelId = String(form.get('channelId') ?? ''); + const result = await testChannel(event.locals, channelId); + if (!result.ok) + return fail(result.status, { channelForm: channelId, channelError: result.error }); + return { channelTest: { channelId, ...result.data } }; + }, + }; +} diff --git a/src/lib/server/notifications/channels.ts b/src/lib/server/notifications/channels.ts new file mode 100644 index 00000000..a8be8b0b --- /dev/null +++ b/src/lib/server/notifications/channels.ts @@ -0,0 +1,175 @@ +import { + NotificationChannelNotFoundError, + NotificationChannelValidationError, + buildChannelTestMessage, + notificationChannelService, + type ChannelInput, + type ChannelLocation, + type NotificationChannelView, +} from '#modules/notifications'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { absoluteUrl, type ChatChannelType } from '#lib/server/infra/notifications'; +import { actorFor, callerCan, contextOf, type AlertLocals } from '#lib/server/alerts/access'; + +export type ChannelAction = 'read' | 'create' | 'update' | 'delete'; + +/** Outcome of a channel operation, mapped to JSON by the API and to `fail()` by form actions. */ +export type ChannelResult = + | { 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: 'Channel not found' }; + +/** `:notifications:` in the channel's (or the page's) location. */ +export function canManageChannels( + locals: AlertLocals, + location: ChannelLocation, + action: ChannelAction, +): Promise { + return callerCan(locals, `${location.scope}:notifications:${action}`, contextOf(location)); +} + +function failure(error: unknown): ChannelResult { + if (error instanceof NotificationChannelValidationError) { + return { ok: false, status: 400, error: 'Invalid channel', errors: error.errors }; + } + if (error instanceof NotificationChannelNotFoundError) return notFound; + throw error; +} + +async function loadAuthorized(locals: AlertLocals, id: string, action: ChannelAction) { + const channel = await notificationChannelService.get(id).catch(() => null); + if (!channel) return notFound; + // a channel the caller can't read is indistinguishable from a missing one + if (!(await canManageChannels(locals, channel.location, 'read'))) return notFound; + if (action !== 'read' && !(await canManageChannels(locals, channel.location, action))) { + return forbidden; + } + return { ok: true as const, status: 200, data: channel }; +} + +export type ChannelList = { + channels: NotificationChannelView[]; + /** Organization channels a project's alerts can also use (project locations only). */ + inherited: NotificationChannelView[]; + /** Types that can be created now (a transport is registered for them). */ + availableTypes: ChatChannelType[]; +}; + +export async function listChannels( + locals: AlertLocals, + location: ChannelLocation, +): Promise> { + if (!(await canManageChannels(locals, location, 'read'))) return forbidden; + const own = await notificationChannelService.list(location); + const inherited = + location.scope === 'project' + ? await notificationChannelService.list({ + organizationId: location.organizationId, + projectId: null, + }) + : []; + return { + ok: true, + status: 200, + data: { + channels: own.map((channel) => notificationChannelService.toView(channel)), + inherited: inherited.map((channel) => notificationChannelService.toView(channel)), + availableTypes: notificationChannelService.availableTypes(), + }, + }; +} + +export async function getChannel( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'read'); + return loaded.ok + ? { ok: true, status: 200, data: notificationChannelService.toView(loaded.data) } + : loaded; +} + +export async function createChannel( + locals: AlertLocals, + location: ChannelLocation, + input: ChannelInput, +): Promise> { + if (!(await canManageChannels(locals, location, 'create'))) return forbidden; + const actor = actorFor(locals); + if (!actor) return forbidden; + try { + const channel = await notificationChannelService.create(location, input, actor.userId); + return { ok: true, status: 201, data: notificationChannelService.toView(channel) }; + } catch (error) { + return failure(error); + } +} + +export async function updateChannel( + locals: AlertLocals, + id: string, + input: ChannelInput, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + try { + // the type can't change: a different provider is a different channel + const { type: _type, ...changes } = input; + void _type; + const channel = await notificationChannelService.update(id, changes); + return { ok: true, status: 200, data: notificationChannelService.toView(channel) }; + } catch (error) { + return failure(error); + } +} + +export async function deleteChannel( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'delete'); + if (!loaded.ok) return loaded; + try { + await notificationChannelService.delete(id); + return { ok: true, status: 200, data: { id } }; + } catch (error) { + return failure(error); + } +} + +/** Names and settings path of a channel's location, for the test message. */ +async function describeLocation(location: ChannelLocation) { + const organization = await organizationService + .getOrganization(location.organizationId) + .catch(() => null); + const project = location.projectId + ? await projectService.getProject(location.projectId).catch(() => null) + : null; + const where = project?.name ?? organization?.name ?? 'GitOps'; + const path = + organization && project + ? `/org/${organization.slug}/projects/${project.slug}/settings/notifications` + : organization + ? `/org/${organization.slug}/settings/notifications` + : null; + return { where, link: absoluteUrl(path) }; +} + +/** "Send test message": posts a test to the channel, even a disabled one, and tells the result. */ +export async function testChannel( + locals: AlertLocals, + id: string, +): Promise> { + const loaded = await loadAuthorized(locals, id, 'update'); + if (!loaded.ok) return loaded; + const channel = loaded.data; + const { where, link } = await describeLocation(channel.location); + const result = await notificationChannelService.test( + id, + buildChannelTestMessage({ channelName: channel.name, where, link }), + ); + return { ok: true, status: 200, data: result }; +} diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts index 38905b46..00192e30 100644 --- a/src/modules/alerts/application/alert-engine.test.ts +++ b/src/modules/alerts/application/alert-engine.test.ts @@ -111,6 +111,7 @@ function alertRow(overrides: Partial = {}): AlertRow { conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }], recipients: { userIds: [], roleIds: ['project-reporter'], externalEmails: [] }, channels: ['mail'], + channelIds: [], throttleMinutes: 0, createdByUserId: 'author', createdAt: TIMESTAMP, diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts index cb871bd4..c8f8dfe9 100644 --- a/src/modules/alerts/application/alert-engine.ts +++ b/src/modules/alerts/application/alert-engine.ts @@ -11,10 +11,12 @@ import { import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository'; import { AlertThrottle } from './alert-throttle'; import { RecipientResolver, type Recipient } from './recipient-resolver'; +import type { ChannelMessage } from '#lib/server/infra/notifications/chat-notification'; import { eventContext, type AlertDirectory, type ExternalRecipientsPort, + type NotificationChannelsPort, type ResolvedNames, } from './types'; @@ -42,11 +44,23 @@ export type AlertEmail = { /** What a test send reached. */ export type AlertTestDelivery = { - /** Emails handed to the notifier (members and verified external addresses). */ + /** Emails (members and verified external addresses) and channel messages delivered. */ sent: number; failed: number; }; +type AlertToDeliver = Pick< + AlertDomain, + | 'id' + | 'name' + | 'description' + | 'scope' + | 'organizationId' + | 'location' + | 'recipients' + | 'channelIds' +>; + export type SystemEmail = { recipient: Recipient; kind: SystemNotificationKind; @@ -71,8 +85,15 @@ export type AlertEngineOptions = { /** 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. */ + /** + * `false` when no email can be sent (SMTP not configured): emails and system notifications are + * skipped, channel messages still go. + */ deliveryEnabled?: () => boolean; + /** Without it, the channels of alerts are ignored. */ + channels?: NotificationChannelsPort; + /** Builds the provider-neutral message of an alert for its channels. */ + channelMessage?: (input: Omit) => ChannelMessage; }; export type AlertDryRun = { @@ -82,6 +103,8 @@ export type AlertDryRun = { denied: string[]; /** The alert's external addresses, their status and whether they would get it. */ external: Array<{ email: string; status: string; delivers: boolean }>; + /** The alert's channels and whether they would get the message (enabled and still there). */ + channels: Array<{ id: string; name: string; type: string; delivers: boolean }>; }; const DEFAULT_CACHE_TTL_MS = 60_000; @@ -114,7 +137,8 @@ export class AlertEngine { async handle(event: AnyDomainEvent): Promise { if (!isEventType(event.type)) return; - if (this.options.deliveryEnabled && !this.options.deliveryEnabled()) { + // nothing can be delivered at all: skip the work instead of logging a failure per event + if (!this.mailEnabled() && !this.options.channels) { this.options.logger.debug( { eventType: event.type, eventId: event.id }, '[alerts] email is not configured, event skipped', @@ -123,13 +147,20 @@ export class AlertEngine { } 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', - ), - ); + // system notifications first: they don't depend on anyone configuring an alert. They are + // emails only: never to external addresses nor to channels + if (!this.mailEnabled()) { + this.options.logger.debug( + { eventType: event.type, eventId: event.id }, + '[alerts] email is not configured, emails skipped', + ); + } else + 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; @@ -152,20 +183,49 @@ export class AlertEngine { async dryRun( alert: Pick & { appliesTo: AlertDomain['appliesTo']; + channelIds?: string[]; }, 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: [], external: [] }; + if (!context) return { matched, recipients: [], denied: [], external: [], channels: [] }; const resolved = await this.options.recipients.resolve( alert.location, alert.recipients, definition.readPermission, context, ); - return { matched, ...resolved, external: await this.externalPreview(alert) }; + return { + matched, + ...resolved, + external: await this.externalPreview(alert), + channels: await this.channelPreview(alert), + }; + } + + private mailEnabled(): boolean { + return !this.options.deliveryEnabled || this.options.deliveryEnabled(); + } + + private async channelPreview(alert: { + location: AlertDomain['location']; + channelIds?: string[]; + }) { + const port = this.options.channels; + const ids = alert.channelIds ?? []; + if (!port || ids.length === 0) return []; + const usable = await port.listUsable(alert.location).catch(() => []); + return ids.map((id) => { + const channel = usable.find((candidate) => candidate.id === id); + return { + id, + name: channel?.name ?? id, + type: channel?.type ?? 'unknown', + delivers: Boolean(channel?.enabled), + }; + }); } private async externalPreview(alert: Pick) { @@ -229,13 +289,7 @@ export class AlertEngine { * the same rules as a real event: members that can read it and verified external addresses. * The throttle is neither checked nor touched. */ - async sendTest( - alert: Pick< - AlertDomain, - 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients' - >, - event: AnyDomainEvent, - ): Promise { + async sendTest(alert: AlertToDeliver, event: AnyDomainEvent): Promise { const definition = getEventDefinition(event.type) as EventDefinition; const { sent, failed } = await this.deliver(alert, event, definition, 0, true); this.options.logger.info( @@ -246,18 +300,24 @@ export class AlertEngine { } private async deliver( - alert: Pick< - AlertDomain, - 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients' - >, + alert: AlertToDeliver, event: AnyDomainEvent, definition: EventDefinition, suppressed: number, test: boolean, - ): Promise<{ recipients: number; externalRecipients: number; sent: number; failed: number }> { + ): Promise<{ + recipients: number; + externalRecipients: number; + channels: number; + sent: number; + failed: number; + }> { const log = this.options.logger; const context = eventContext(event.scope); - if (!context) return { recipients: 0, externalRecipients: 0, sent: 0, failed: 0 }; + if (!context) { + return { recipients: 0, externalRecipients: 0, channels: 0, sent: 0, failed: 0 }; + } + const mail = this.mailEnabled(); const { recipients, denied } = await this.options.recipients.resolve( alert.location, @@ -284,12 +344,15 @@ export class AlertEngine { // external addresses: no cancan (they have no account), only verified ones of an allowed // domain, and system notifications never reach them (they only come from `fire`) - const external = await this.externalRecipientsOf(alert); + const external = mail ? await this.externalRecipientsOf(alert) : []; - const targets: AlertEmailRecipient[] = [ - ...recipients.map((recipient) => ({ kind: 'member' as const, ...recipient })), - ...external.map((recipient) => ({ kind: 'external' as const, ...recipient })), - ]; + // without SMTP there is nobody to email, but channels still get their message + const targets: AlertEmailRecipient[] = mail + ? [ + ...recipients.map((recipient) => ({ kind: 'member' as const, ...recipient })), + ...external.map((recipient) => ({ kind: 'external' as const, ...recipient })), + ] + : []; let sent = 0; // one email per recipient: addresses are never shared, and a failure only affects one person @@ -321,11 +384,45 @@ export class AlertEngine { } } + // one message per channel (not per recipient); a failing channel never stops the others + const channelIds = alert.channelIds ?? []; + let channelsSent = 0; + if (channelIds.length > 0 && this.options.channels && this.options.channelMessage) { + const message = this.options.channelMessage({ + alert, + event, + definition, + suppressed, + names, + where, + ...(test ? { test: true } : {}), + }); + const results = await Promise.all( + channelIds.map((channelId) => + this.options + .channels!.deliver(channelId, message, { + alertId: alert.id, + eventId: event.id, + kind: test ? 'alert_test' : 'alert', + }) + .catch((error) => { + log.warn( + { err: error, alertId: alert.id, eventId: event.id, channelId }, + '[alerts] channel message failed', + ); + return false; + }), + ), + ); + channelsSent = results.filter(Boolean).length; + } + return { recipients: recipients.length, externalRecipients: external.length, - sent, - failed: targets.length - sent, + channels: channelIds.length, + sent: sent + channelsSent, + failed: targets.length - sent + (channelIds.length - channelsSent), }; } diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts new file mode 100644 index 00000000..a85d4ee1 --- /dev/null +++ b/src/modules/alerts/application/alert.channels.test.ts @@ -0,0 +1,359 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { getEventDefinition, type EventDefinition } from '#lib/events/catalog'; +import type { AnyDomainEvent } from '#lib/server/events'; +import { createChannelsFixture } from '#modules/notifications/application/testing'; +import { + AlertDomain, + AlertValidationError, + type AlertInput, + type AlertLocation, +} from '../domain/alert.domain'; +import { buildAlertChannelMessage } from '../infrastructure/alert-channel-message'; +import { InMemoryAlertRepository } from '../infrastructure/repositories/in-memory-alert.repository'; +import { + AlertEngine, + type AlertEmail, + type AlertNotifierPort, + type SystemEmail, +} from './alert-engine'; +import { AlertService } from './alert.service'; +import { AlertThrottle } from './alert-throttle'; +import { RecipientResolver } from './recipient-resolver'; +import { FakeAlertDirectory, actor } from './testing'; +import type { NotificationChannelsPort } from './types'; + +const ORG = 'org-1'; +const orgLocation: AlertLocation = { scope: 'organization', organizationId: ORG, projectId: null }; +const p1: AlertLocation = { scope: 'project', organizationId: ORG, projectId: 'p1' }; +const HOOK = 'https://hooks.example.com/hook/T0/B0/xyz'; +const WITHOUT_NOTIFICATIONS = ['project:codereport:reports:read', 'organization:projects:read']; + +function input(overrides: AlertInput = {}): AlertInput { + return { + name: 'Críticas', + eventType: 'code_report.analysis.completed', + recipients: { userIds: ['u1'] }, + ...overrides, + }; +} + +function analysisEvent(): AnyDomainEvent { + return { + id: 'evt-1', + type: 'code_report.analysis.completed', + occurredAt: '2026-11-24T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: ORG, projectId: 'p1' }, + payload: { + analysisId: 'a1', + serviceId: 'svc-1', + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc', version: null }, + summary: { critical: 1, high: 0, medium: 0, low: 0, unknown: 0, total: 1, secrets: 0 }, + policies: { + status: 'compliant', + totalViolations: 0, + blockingFailures: 0, + failedPolicyIds: [], + }, + }, + } as unknown as AnyDomainEvent; +} + +async function validationErrors(promise: Promise) { + const error = await promise.catch((caught) => caught); + expect(error).toBeInstanceOf(AlertValidationError); + return (error as AlertValidationError).errors; +} + +class RecordingNotifier implements AlertNotifierPort { + alerts: AlertEmail[] = []; + system: SystemEmail[] = []; + fail = false; + async sendAlert(email: AlertEmail) { + if (this.fail) throw new Error('SMTP down'); + this.alerts.push(email); + } + async sendSystemNotification(email: SystemEmail) { + this.system.push(email); + } +} + +describe('alerts with notification channels', () => { + let channels: ReturnType; + let port: NotificationChannelsPort; + let repository: InMemoryAlertRepository; + let directory: FakeAlertDirectory; + let service: AlertService; + let orgChannel: string; + let p1Channel: string; + let p2Channel: string; + + beforeEach(async () => { + channels = createChannelsFixture(); + port = { + listUsable: async (location) => + (await channels.service.listUsable(location)).map((channel) => ({ + id: channel.id, + name: channel.name, + type: channel.type, + scope: channel.scope, + enabled: channel.enabled, + })), + deliver: (id, message, context) => channels.service.deliver(id, message, context), + }; + orgChannel = ( + await channels.service.create( + orgLocation, + { type: 'slack', name: '#org', destination: HOOK }, + 'a', + ) + ).id; + p1Channel = ( + await channels.service.create(p1, { type: 'slack', name: '#p1', destination: HOOK }, 'a') + ).id; + p2Channel = ( + await channels.service.create( + { ...p1, projectId: 'p2' }, + { type: 'slack', name: '#p2', destination: HOOK }, + 'a', + ) + ).id; + + repository = new InMemoryAlertRepository(); + directory = new FakeAlertDirectory(); + directory.members = [ + { + organizationId: ORG, + projectId: 'p1', + userId: 'u1', + username: 'ana', + email: 'ana@kettu.io', + disabled: false, + roleIds: [], + }, + ]; + let id = 0; + service = new AlertService(repository, directory, { + generateId: () => `alert-${++id}`, + channels: port, + }); + }); + + describe('validation', () => { + it('accepts the project and organization channels a project alert may use', async () => { + const alert = await service.create( + p1, + input({ channelIds: [p1Channel, orgChannel, p1Channel] }), + actor('admin'), + ); + expect(alert.channelIds).toEqual([p1Channel, orgChannel]); + expect(alert.channels).toEqual(['mail', 'slack']); + }); + + it('rejects channels of another project or another location', async () => { + expect( + ( + await validationErrors( + service.create(p1, input({ channelIds: [p2Channel] }), actor('admin')), + ) + ).channelIds, + ).toBe('unknown_channel'); + // an organization alert can't use a project channel either + expect( + ( + await validationErrors( + service.create(orgLocation, input({ channelIds: [p1Channel] }), actor('admin')), + ) + ).channelIds, + ).toBe('unknown_channel'); + }); + + it('needs :notifications:update to add channels, not to keep them', async () => { + const refused = await validationErrors( + service.create(p1, input({ channelIds: [p1Channel] }), actor('dev', WITHOUT_NOTIFICATIONS)), + ); + expect(refused.channelIds).toBe('forbidden_channel'); + + const alert = await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + const editor = actor('dev', [...WITHOUT_NOTIFICATIONS, 'project:alerts:update']); + await expect(service.update(alert.id, { name: 'Renamed' }, editor)).resolves.toMatchObject({ + channelIds: [p1Channel], + }); + expect( + ( + await validationErrors( + service.update(alert.id, { channelIds: [p1Channel, orgChannel] }, editor), + ) + ).channelIds, + ).toBe('forbidden_channel'); + }); + + it('accepts an alert whose only destination is a channel', async () => { + const alert = await service.create( + p1, + input({ recipients: {}, channelIds: [p1Channel] }), + actor('admin'), + ); + expect(alert.channels).toEqual(['slack']); + }); + }); + + describe('engine', () => { + let notifier: RecordingNotifier; + let mail: boolean; + let engine: AlertEngine; + + beforeEach(() => { + notifier = new RecordingNotifier(); + mail = true; + engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, async () => true), + notifier, + channels: port, + channelMessage: buildAlertChannelMessage, + deliveryEnabled: () => mail, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }); + }); + + it('emails the recipients and posts one message per channel', async () => { + await service.create(p1, input({ channelIds: [p1Channel, orgChannel] }), actor('admin')); + await engine.handle(analysisEvent()); + + expect(notifier.alerts).toHaveLength(1); + expect(channels.transport.sent).toHaveLength(2); + expect(channels.transport.sent[0].message).toMatchObject({ + title: 'Críticas', + summary: '1 critical, 0 high (1 in total)', + test: false, + alert: { name: 'Críticas' }, + }); + }); + + it('keeps going when a channel fails, and the other way around', async () => { + await service.create(p1, input({ channelIds: [p1Channel, orgChannel] }), actor('admin')); + channels.transport.failWith = [404]; + notifier.fail = true; + await engine.handle(analysisEvent()); + + // the email failed, one channel answered 404: the other channel still got its message + expect(channels.transport.sent).toHaveLength(1); + expect(channels.repository.rows.find((row) => row.lastError === 'HTTP 404')).toBeDefined(); + }); + + it('still posts to channels without SMTP, but sends no emails', async () => { + mail = false; + await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + await engine.handle(analysisEvent()); + expect(notifier.alerts).toHaveLength(0); + expect(channels.transport.sent).toHaveLength(1); + }); + + it('never posts system notifications to channels', async () => { + await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + directory.users = [{ userId: 'u1', username: 'ana', email: 'ana@kettu.io', disabled: false }]; + await engine.handle({ + id: 'evt-2', + type: 'access.granted', + occurredAt: '2026-11-24T10:00:00.000Z', + actor: { kind: 'user', userId: 'admin' }, + scope: { organizationId: ORG, projectId: 'p1' }, + payload: { accessId: 'x', userId: 'u1', roleId: 'r1', scope: 'project', status: 'active' }, + } as unknown as AnyDomainEvent); + expect(notifier.system).toHaveLength(1); + expect(channels.transport.sent).toHaveLength(0); + }); + + it('reports throttled events in the next channel message', async () => { + let now = 0; + engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, async () => true), + notifier, + channels: port, + channelMessage: buildAlertChannelMessage, + now: () => now, + throttle: new AlertThrottle(() => now), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }); + await service.create( + p1, + input({ throttleMinutes: 10, channelIds: [p1Channel] }), + actor('admin'), + ); + await engine.handle(analysisEvent()); + await engine.handle(analysisEvent()); + expect(channels.transport.sent).toHaveLength(1); + expect(channels.transport.sent[0].message.suppressed).toBe(0); + + now = 11 * 60 * 1000; + await engine.handle(analysisEvent()); + expect(channels.transport.sent).toHaveLength(2); + expect(channels.transport.sent[1].message.suppressed).toBe(1); + }); + + it('includes the channels in test sends and dry runs', async () => { + const alert = await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + await channels.service.update(orgChannel, { enabled: false }); + + const delivery = await engine.sendTest(alert, analysisEvent()); + expect(delivery).toEqual({ sent: 2, failed: 0 }); + expect(channels.transport.sent[0].message.test).toBe(true); + + const dry = await engine.dryRun( + new AlertDomain({ ...alert.toJson(), channelIds: [p1Channel, orgChannel] }), + analysisEvent(), + ); + expect(dry.channels).toEqual([ + { id: p1Channel, name: '#p1', type: 'slack', delivers: true }, + { id: orgChannel, name: '#org', type: 'slack', delivers: false }, + ]); + }); + }); + + describe('channel message', () => { + it('leaves out sensitive fields and links to the resource', () => { + process.env.ORIGIN = 'https://gitops.example.com'; + const definition = getEventDefinition('vault.secret.deleted') as EventDefinition; + const message = buildAlertChannelMessage({ + alert: { id: 'a1', name: 'Secretos', description: null, scope: 'project' }, + event: { + id: 'e1', + type: 'vault.secret.deleted', + occurredAt: '2026-11-24T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: ORG, projectId: 'p1' }, + payload: { + secretId: 's1', + key: 'DB_PASSWORD', + folderId: null, + folderPath: '/pay', + environmentIds: ['e'], + }, + } as never, + definition, + suppressed: 3, + names: new Map([['e', 'Production']]), + where: { + organization: 'Kettu', + organizationSlug: 'kettu', + project: 'Web', + projectSlug: 'web', + }, + }); + const text = JSON.stringify(message); + expect(text).not.toContain('DB_PASSWORD'); + expect(text).not.toContain('/pay'); + expect(text).toContain('Production'); + expect(message.suppressed).toBe(3); + expect(message.link).toEqual({ + url: 'https://gitops.example.com/org/kettu/projects/web/vault', + label: 'View in GitOps', + }); + }); + }); +}); diff --git a/src/modules/alerts/application/alert.service.test.ts b/src/modules/alerts/application/alert.service.test.ts index 4c716667..3344cb9e 100644 --- a/src/modules/alerts/application/alert.service.test.ts +++ b/src/modules/alerts/application/alert.service.test.ts @@ -105,7 +105,7 @@ describe('AlertService', () => { const errors = await validationErrors( service.create( projectLocation, - { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['slack'] }, + { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['pigeon'] }, actor(), ), ); diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts index c266bf6b..58758443 100644 --- a/src/modules/alerts/application/alert.service.ts +++ b/src/modules/alerts/application/alert.service.ts @@ -28,7 +28,9 @@ import { type AlertActor, type AlertDirectory, type ExternalRecipientsPort, + type NotificationChannelsPort, type ReferenceOption, + type UsableChannel, } from './types'; const MAX_NAME_LENGTH = 120; @@ -37,6 +39,8 @@ const MAX_CONDITIONS = 20; const MAX_LIST_VALUES = 100; /** External addresses one alert may email. */ export const MAX_EXTERNAL_EMAILS = 50; +/** Notification channels one alert may post to. */ +export const MAX_ALERT_CHANNELS = 20; const VALUELESS_OPERATORS = new Set(['is_true', 'is_false', 'exists']); const LIST_OPERATORS = new Set(['in', 'not_in']); @@ -48,6 +52,8 @@ export type AlertServiceOptions = { onChange?: () => void; /** Without it, alerts can't have external email recipients. */ externalRecipients?: ExternalRecipientsPort; + /** Without it, alerts can't post to notification channels. */ + channels?: Pick; logger?: { warn: (object: object, message: string) => void }; }; @@ -65,6 +71,7 @@ export class AlertService { private readonly generateId: () => string; private readonly onChange: () => void; private readonly externalRecipients: ExternalRecipientsPort | null; + private readonly channelsPort: Pick | null; private readonly logger: AlertServiceOptions['logger']; constructor( @@ -76,6 +83,7 @@ export class AlertService { this.generateId = options.generateId ?? (() => crypto.randomUUID()); this.onChange = options.onChange ?? (() => {}); this.externalRecipients = options.externalRecipients ?? null; + this.channelsPort = options.channels ?? null; this.logger = options.logger; } @@ -121,15 +129,17 @@ export class AlertService { /** * Validates `input` for `location` and returns the normalized fields, without saving. - * `previousExternalEmails` are the external addresses the alert already had: keeping them does + * `previous` holds the external addresses and channels the alert already had: keeping them does * not need `:notifications:update`, adding new ones does. */ async validate( location: AlertLocation, input: AlertInput, actor: AlertActor, - previousExternalEmails: readonly string[] = [], + previous: { externalEmails?: readonly string[]; channelIds?: readonly string[] } = {}, ): Promise { + const previousExternalEmails = previous.externalEmails ?? []; + const previousChannelIds = previous.channelIds ?? []; const errors: AlertValidationErrors = {}; const references: ReferenceCache = new Map(); @@ -165,7 +175,25 @@ export class AlertService { errors, ); - const channels = this.validateChannels(input.channels, errors); + this.validateChannels(input.channels, errors); + const { channelIds, selected } = await this.validateChannelIds( + location, + input.channelIds, + actor, + previousChannelIds, + errors, + ); + const hasEmailRecipients = + recipients.userIds.length + recipients.roleIds.length + recipients.externalEmails.length > 0; + if (errors.recipients === 'required' && channelIds.length > 0) delete errors.recipients; + // what the alert really delivers through: email when it has email recipients, plus the types + // of its channels + const channels = [ + ...new Set([ + ...(hasEmailRecipients || channelIds.length === 0 ? (['mail'] as const) : []), + ...selected.map((channel) => channel.type as AlertChannel), + ]), + ].filter((channel) => (ALERT_CHANNELS as readonly string[]).includes(channel)); const throttleMinutes = Number(input.throttleMinutes ?? 0); if ( @@ -189,6 +217,7 @@ export class AlertService { conditions, recipients, channels, + channelIds, throttleMinutes, }; } @@ -227,15 +256,14 @@ export class AlertService { conditions: current.conditions, recipients: current.recipients, channels: current.channels, + channelIds: current.channelIds, throttleMinutes: current.throttleMinutes, ...Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)), }; - const fields = await this.validate( - current.location, - merged, - actor, - current.recipients.externalEmails, - ); + const fields = await this.validate(current.location, merged, actor, { + externalEmails: current.recipients.externalEmails, + channelIds: current.channelIds, + }); await this.repository.update(id, fields); this.onChange(); await this.registerExternal(current.location, fields.recipients.externalEmails, actor); @@ -524,6 +552,49 @@ export class AlertService { return emails; } + /** + * Channels: usable from the location (a project channel only by its project's alerts), and + * only added by someone with `:notifications:update`: a chat channel is read by people + * who may not be allowed to see the event. + */ + private async validateChannelIds( + location: AlertLocation, + value: unknown, + actor: AlertActor, + previous: readonly string[], + errors: AlertValidationErrors, + ): Promise<{ channelIds: string[]; selected: UsableChannel[] }> { + if (value === undefined || value === null) return { channelIds: [], selected: [] }; + if (!Array.isArray(value)) { + errors.channelIds = 'invalid'; + return { channelIds: [], selected: [] }; + } + const channelIds = [ + ...new Set(value.filter((id): id is string => typeof id === 'string' && !!id)), + ]; + if (channelIds.length === 0) return { channelIds, selected: [] }; + if (channelIds.length > MAX_ALERT_CHANNELS) { + errors.channelIds = 'too_many'; + return { channelIds: [], selected: [] }; + } + const usable = this.channelsPort ? await this.channelsPort.listUsable(location) : []; + const selected = channelIds + .map((id) => usable.find((channel) => channel.id === id)) + .filter((channel): channel is UsableChannel => !!channel); + if (selected.length !== channelIds.length) { + errors.channelIds = 'unknown_channel'; + return { channelIds, selected }; + } + const known = new Set(previous); + if (channelIds.some((id) => !known.has(id))) { + const permission = `${location.scope}:notifications:update` as const; + if (!(await actor.canRead(permission, locationContext(location)))) { + errors.channelIds = 'forbidden_channel'; + } + } + return { channelIds, selected }; + } + private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] { if (value === undefined || value === null) return ['mail']; const list = Array.isArray(value) ? value : [value]; diff --git a/src/modules/alerts/application/types.ts b/src/modules/alerts/application/types.ts index 63999b00..cc91d4e5 100644 --- a/src/modules/alerts/application/types.ts +++ b/src/modules/alerts/application/types.ts @@ -77,6 +77,30 @@ export interface ExternalRecipientsPort { statuses(organizationId: string, emails: readonly string[]): Promise>; } +/** A notification channel an alert may use, as the alerts module sees it. */ +export type UsableChannel = { + id: string; + name: string; + type: string; + scope: 'organization' | 'project'; + enabled: boolean; +}; + +/** Notification channels (chat, webhooks) as the alerts module sees them. */ +export interface NotificationChannelsPort { + /** Channels an alert of `location` may use: its project's and its organization's. */ + listUsable(location: { + organizationId: string; + projectId: string | null; + }): Promise; + /** Queues one message for the channel; `false` when it was skipped or definitively failed. */ + deliver( + channelId: string, + message: import('#lib/server/infra/notifications/chat-notification').ChannelMessage, + context?: Record, + ): Promise; +} + /** * Who creates or edits an alert; `canRead` checks any grant in a context for that actor (named * after its first use, the anti-escalation read check). diff --git a/src/modules/alerts/domain/alert.domain.ts b/src/modules/alerts/domain/alert.domain.ts index 1b2e648b..ef9812f8 100644 --- a/src/modules/alerts/domain/alert.domain.ts +++ b/src/modules/alerts/domain/alert.domain.ts @@ -4,8 +4,11 @@ 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; +/** + * How an alert is delivered: `mail` to its users, roles and external addresses, the others to + * the notification channels in `channelIds`. Derived from the recipients on every save. + */ +export const ALERT_CHANNELS = ['mail', 'webhook', 'slack', 'google-chat'] as const; export type AlertChannel = (typeof ALERT_CHANNELS)[number]; export const ALERT_MATCHES = ['all', 'any'] as const; @@ -49,6 +52,7 @@ export type AlertInput = { conditions?: unknown; recipients?: unknown; channels?: unknown; + channelIds?: unknown; throttleMinutes?: unknown; }; @@ -62,6 +66,8 @@ export type AlertFields = { conditions: AlertCondition[]; recipients: AlertRecipients; channels: AlertChannel[]; + /** Notification channels (`$modules/notifications`) that get one message per firing. */ + channelIds: string[]; throttleMinutes: number; }; @@ -97,6 +103,7 @@ export class AlertDomain implements AlertRow { conditions: AlertCondition[]; recipients: AlertRecipients; channels: AlertChannel[]; + channelIds: string[]; throttleMinutes: number; createdByUserId: string; createdAt: string; @@ -122,6 +129,7 @@ export class AlertDomain implements AlertRow { (ALERT_CHANNELS as readonly string[]).includes(channel), ); this.channels = channels.length > 0 ? channels : ['mail']; + this.channelIds = stringArray(row.channelIds); this.throttleMinutes = Number.isFinite(Number(row.throttleMinutes)) ? Number(row.throttleMinutes) : 0; @@ -163,6 +171,7 @@ export class AlertDomain implements AlertRow { externalEmails: [...this.recipients.externalEmails], }, channels: [...this.channels], + channelIds: [...this.channelIds], throttleMinutes: this.throttleMinutes, createdByUserId: this.createdByUserId, createdAt: this.createdAt, diff --git a/src/modules/alerts/index.ts b/src/modules/alerts/index.ts index 3688a2a2..dce15b25 100644 --- a/src/modules/alerts/index.ts +++ b/src/modules/alerts/index.ts @@ -8,7 +8,11 @@ import { import { createLogger } from '#lib/server/logger'; import { cancanService, roleService, userAccessService, apiKeysService } from '../auth'; import { codeReportSecurityPolicyService, codeReportService } from '../code-report'; -import { externalRecipientService } from '../notifications'; +import { + externalRecipientService, + notificationChannelService, + registerChannelShutdown, +} from '../notifications'; import { organizationService } from '../organization'; import { projectService } from '../projects'; import { vaultService } from '../vault'; @@ -17,6 +21,8 @@ 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 { buildAlertChannelMessage } from './infrastructure/alert-channel-message'; +import type { NotificationChannelsPort } from './application/types'; import { PlatformDirectory } from './infrastructure/platform-directory'; import { AlertRepository } from './infrastructure/repositories/alert.repository'; @@ -39,13 +45,35 @@ const recipientResolver = new RecipientResolver(alertDirectory, (userId, permiss cancanService.can(userId, permission, context), ); +/** The notifications module's channels, as the alerts module needs them. */ +const alertChannels: NotificationChannelsPort = { + async listUsable(location) { + const channels = await notificationChannelService.listUsable(location); + return channels.map((channel) => ({ + id: channel.id, + name: channel.name, + type: channel.type, + scope: channel.scope, + enabled: channel.enabled, + })); + }, + deliver: (channelId, message, context) => + notificationChannelService.deliver(channelId, message, context), +}; + const ENGINE_KEY = Symbol.for('gitops.alerts.engine'); type EngineDependencies = Pick< AlertEngineOptions, - 'repository' | 'directory' | 'recipients' | 'externalRecipients' | 'notifier' + | 'repository' + | 'directory' + | 'recipients' + | 'externalRecipients' + | 'notifier' + | 'channels' + | 'channelMessage' >; /** Bump when the way the engine is built changes, so a running dev server rebuilds it. */ -const ENGINE_WIRING = 2; +const ENGINE_WIRING = 3; type EngineSlot = { engine: AlertEngine | null; @@ -76,6 +104,8 @@ const dependencies: EngineDependencies = { recipients: recipientResolver, externalRecipients: externalRecipientService, notifier: new AlertMailNotifier(mailQueue), + channels: alertChannels, + channelMessage: buildAlertChannelMessage, }; // one engine per process: HMR re-evaluating this module must not subscribe a second one, and the @@ -99,6 +129,8 @@ function createEngine(): AlertEngine { recipients: latest(() => engineSlot.dependencies.recipients), externalRecipients: latest(() => engineSlot.dependencies.externalRecipients!), notifier: latest(() => engineSlot.dependencies.notifier), + channels: latest(() => engineSlot.dependencies.channels!), + channelMessage: (input) => engineSlot.dependencies.channelMessage!(input), throttle: engineSlot.throttle, logger: log, // without SMTP there is nobody to tell: skip the work instead of logging a failure per event @@ -120,6 +152,7 @@ export const alertEngine: AlertEngine = engineSlot.engine; export const alertService = new AlertService(alertRepository, alertDirectory, { onChange: () => alertEngine.invalidate(), externalRecipients: externalRecipientService, + channels: alertChannels, logger: log, }); @@ -128,6 +161,7 @@ export function registerAlertEngine(): void { if (engineSlot.attached) return; engineSlot.detach = alertEngine.attach(eventBus); registerMailShutdown(); + registerChannelShutdown(); engineSlot.attached = true; log.info('[alerts] engine registered'); diff --git a/src/modules/alerts/infrastructure/alert-channel-message.ts b/src/modules/alerts/infrastructure/alert-channel-message.ts new file mode 100644 index 00000000..b8a5e80e --- /dev/null +++ b/src/modules/alerts/infrastructure/alert-channel-message.ts @@ -0,0 +1,52 @@ +import { absoluteUrl, type ChannelMessage } from '#lib/server/infra/notifications'; +import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n'; +import type { AlertEmail } from '../application/alert-engine'; +import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary'; + +/** What a channel message is built from: an alert email without its recipient. */ +export type AlertMessageInput = Omit; + +/** + * Provider-neutral message of an alert for a notification channel. In the default language (a + * channel is shared by people with different ones) and without sensitive fields (people reading + * the channel may not be allowed to see the event); transports format it. + */ +export function buildAlertChannelMessage(input: AlertMessageInput): ChannelMessage { + const t = translator(DEFAULT_MAIL_LOCALE); + const { event, definition, where, alert } = input; + const eventLabel = t(definition.label); + const summary = eventSummaryText(event, definition, t); + const url = absoluteUrl(eventResourcePath(event, definition, where)); + + const fields = [ + { label: t('alerts.email.occurredAt'), value: new Date(event.occurredAt).toUTCString() }, + ...(where.project ? [{ label: t('alerts.email.project'), value: where.project }] : []), + ...describeEventFields(event, definition, input.names, { omitSensitive: true }).map( + (field) => ({ + label: t(field.label), + value: field.translate ? t(field.value) : field.value, + }), + ), + ]; + + const headline = t('alerts.email.alertSubject', { alert: alert.name, summary }); + const text = input.test ? t('alerts.email.testSubject', { subject: headline }) : headline; + + return { + title: alert.name, + summary, + eventLabel, + fields, + link: url ? { url, label: t('alerts.email.viewInApp') } : null, + suppressed: input.suppressed, + text, + test: input.test === true, + event: { + id: event.id, + type: event.type, + occurredAt: event.occurredAt, + scope: { ...event.scope }, + }, + alert: { id: alert.id, name: alert.name }, + }; +} diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.ts index 1c744736..4a767b67 100644 --- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts +++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts @@ -15,10 +15,10 @@ import { type MailLocale, type Translate, } from '#lib/server/infra/notifications/i18n'; -import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog'; +import { getFieldValue, type EventDefinition } from '#lib/events/catalog'; import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events'; import type { AlertEmail, AlertNotifierPort, SystemEmail } from '../application/alert-engine'; -import { describeEventFields } from './event-summary'; +import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary'; export { DEFAULT_MAIL_LOCALE, translateKey, type MailLocale }; @@ -36,14 +36,6 @@ export class MailNotSentError extends Error { } } -function safely(run: () => T): T | undefined { - try { - return run(); - } catch { - return undefined; - } -} - function fieldsTable(rows: { label: string; value: string }[]): string { if (rows.length === 0) return ''; const body = rows @@ -78,28 +70,17 @@ export class AlertMailNotifier implements AlertNotifierPort { const locale = external ? DEFAULT_MAIL_LOCALE : mailLocale(recipient.locale); const t: Translate = translator(locale); const { event, where } = email; - const definition = email.definition as EventDefinition & { - link?: (context: unknown) => string | null; - mailSummary?: (payload: unknown) => EventMessage; - }; + const definition = email.definition as EventDefinition & { mailTemplate?: string }; const eventLabel = t(definition.label); // a definition callback that chokes on the payload must not cost the email - const message = safely(() => definition.mailSummary?.(event.payload)); - const summary = message ? t(message.key, message.values) : eventLabel; + const summary = eventSummaryText(event, definition, t); const baseSubject = t('alerts.email.alertSubject', { alert: email.alert.name, summary }); const subject = email.test ? t('alerts.email.testSubject', { subject: baseSubject }) : baseSubject; - const resourcePath = - safely(() => - definition.link?.({ - payload: event.payload, - organizationSlug: where.organizationSlug ?? null, - projectSlug: where.projectSlug ?? null, - }), - ) ?? null; + const resourcePath = eventResourcePath(event, definition, where); const scopeName = email.alert.scope === 'project' && where.project ? where.project : (where.organization ?? ''); diff --git a/src/modules/alerts/infrastructure/event-summary.ts b/src/modules/alerts/infrastructure/event-summary.ts index 24b8e79f..6d42c25b 100644 --- a/src/modules/alerts/infrastructure/event-summary.ts +++ b/src/modules/alerts/infrastructure/event-summary.ts @@ -1,4 +1,4 @@ -import { getFieldValue, type EventDefinition } from '#lib/events/catalog'; +import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog'; import type { AnyDomainEvent } from '#lib/server/events'; export type EventFieldLine = { @@ -64,3 +64,48 @@ export function describeEventFields( } return lines; } + +type Translate = (key: string, values?: Record) => string; + +type DefinitionCallbacks = EventDefinition & { + link?: (context: unknown) => string | null; + mailSummary?: (payload: unknown) => EventMessage; +}; + +function safely(run: () => T): T | undefined { + try { + return run(); + } catch { + return undefined; + } +} + +/** + * One-line summary of an event (`3 critical, 5 high`), or its label. A definition callback that + * chokes on the payload (an incomplete example event) falls back to the label. + */ +export function eventSummaryText( + event: Pick, + definition: EventDefinition, + t: Translate, +): string { + const message = safely(() => (definition as DefinitionCallbacks).mailSummary?.(event.payload)); + return message ? t(message.key, message.values) : t(definition.label); +} + +/** App path of the resource the event is about (`/org/…`), or `null`. */ +export function eventResourcePath( + event: Pick, + definition: EventDefinition, + where: { organizationSlug?: string; projectSlug?: string }, +): string | null { + return ( + safely(() => + (definition as DefinitionCallbacks).link?.({ + payload: event.payload, + organizationSlug: where.organizationSlug ?? null, + projectSlug: where.projectSlug ?? null, + }), + ) ?? null + ); +} diff --git a/src/modules/notifications/application/notification-channel.service.test.ts b/src/modules/notifications/application/notification-channel.service.test.ts new file mode 100644 index 00000000..93508121 --- /dev/null +++ b/src/modules/notifications/application/notification-channel.service.test.ts @@ -0,0 +1,240 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import type { ChannelMessage } from '#lib/server/infra/notifications'; +import { NotificationChannelValidationError } from '../domain/notification-channel.domain'; +import { createChannelsFixture } from './testing'; + +const ORG = 'org-1'; +const orgLocation = { scope: 'organization' as const, organizationId: ORG, projectId: null }; +const p1 = { scope: 'project' as const, organizationId: ORG, projectId: 'p1' }; +const HOOK = 'https://hooks.example.com/hook/T000/B000/secret1a2b'; + +const message: ChannelMessage = { + title: 'Críticas', + summary: '1 critical', + eventLabel: 'Analysis completed', + fields: [], + link: null, + suppressed: 0, + text: '[GitOps] Críticas: 1 critical', + test: false, +}; + +async function validationErrors(promise: Promise) { + const error = await promise.catch((caught) => caught); + expect(error).toBeInstanceOf(NotificationChannelValidationError); + return (error as NotificationChannelValidationError).errors; +} + +describe('NotificationChannelService', () => { + let f: ReturnType; + + beforeEach(() => { + f = createChannelsFixture(); + }); + + describe('create and storage', () => { + it('stores the destination encrypted and only ever shows it masked', async () => { + const channel = await f.service.create( + orgLocation, + { type: 'slack', name: ' #alertas ', destination: HOOK }, + 'admin', + ); + + const [row] = f.repository.rows; + expect(row).toMatchObject({ id: 'channel-1', name: '#alertas', scope: 'organization' }); + expect(row.webhookUrl).not.toContain('hooks.example.com'); + expect(row.webhookUrl).not.toContain('secret'); + + const view = f.service.toView(channel); + expect(view.destinationMasked).toBe('https://hooks.example.com/…/••••1a2b'); + expect(view).not.toHaveProperty('webhookUrl'); + expect(JSON.stringify(view)).not.toContain('secret'); + expect(view.available).toBe(true); + }); + + it('validates type, name and destination (anti-SSRF) before saving', async () => { + const errors = await validationErrors( + f.service.create( + orgLocation, + { type: 'slack', name: '', destination: 'http://hooks.example.com/hook/x' }, + 'a', + ), + ); + expect(errors).toEqual({ name: 'required', destination: 'not_https' }); + + for (const [destination, code] of [ + ['https://evil.com/hook/x', 'host_not_allowed'], + ['https://10.0.0.1/hook/x', 'ip_address'], + ['https://u:p@hooks.example.com/hook/x', 'credentials'], + ['https://hooks.example.com/other', 'path_not_allowed'], + ]) { + expect( + await validationErrors( + f.service.create(orgLocation, { type: 'slack', name: 'x', destination }, 'a'), + ), + ).toEqual({ destination: code }); + } + expect(f.repository.rows).toHaveLength(0); + }); + + it('only accepts types with a registered transport', async () => { + expect( + await validationErrors( + f.service.create(orgLocation, { type: 'google-chat', name: 'x', destination: HOOK }, 'a'), + ), + ).toEqual({ type: 'type_unavailable' }); + expect( + await validationErrors( + f.service.create(orgLocation, { type: 'sms', name: 'x', destination: HOOK }, 'a'), + ), + ).toEqual({ type: 'invalid_type' }); + expect(f.service.availableTypes()).toEqual(['slack']); + }); + + it('keeps the destination when an update leaves it empty, and re-encrypts a new one', async () => { + const channel = await f.service.create( + orgLocation, + { type: 'slack', name: 'a', destination: HOOK }, + 'x', + ); + const before = f.repository.rows[0].webhookUrl; + + await f.service.update(channel.id, { name: 'b', destination: '' }); + expect(f.repository.rows[0]).toMatchObject({ name: 'b', webhookUrl: before }); + + await f.service.update(channel.id, { destination: 'https://hooks.example.com/hook/new9z9z' }); + expect(f.repository.rows[0].webhookUrl).not.toBe(before); + expect(f.service.toView(await f.service.get(channel.id)).destinationMasked).toMatch(/9z9z$/); + }); + }); + + describe('scopes', () => { + it('lets a project channel serve only its project, and an organization channel all of them', async () => { + const org = await f.service.create( + orgLocation, + { type: 'slack', name: 'org', destination: HOOK }, + 'a', + ); + const own = await f.service.create(p1, { type: 'slack', name: 'p1', destination: HOOK }, 'a'); + await f.service.create( + { ...p1, projectId: 'p2' }, + { type: 'slack', name: 'p2', destination: HOOK }, + 'a', + ); + + const usable = await f.service.listUsable({ organizationId: ORG, projectId: 'p1' }); + expect(usable.map((channel) => channel.id).sort()).toEqual([org.id, own.id].sort()); + expect( + (await f.service.listUsable({ organizationId: ORG, projectId: null })).map((c) => c.id), + ).toEqual([org.id]); + expect(await f.service.listUsable({ organizationId: 'other', projectId: null })).toEqual([]); + expect((await f.service.list(p1)).map((channel) => channel.name)).toEqual(['p1']); + }); + }); + + describe('delivery', () => { + let channelId: string; + + beforeEach(async () => { + channelId = ( + await f.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x') + ).id; + }); + + it('sends to the decrypted destination', async () => { + expect(await f.service.deliver(channelId, message)).toBe(true); + expect(f.transport.sent).toHaveLength(1); + expect(f.transport.sent[0]).toMatchObject({ channel: 'slack', destination: HOOK, message }); + }); + + it('skips disabled and deleted channels', async () => { + await f.service.update(channelId, { enabled: false }); + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(await f.service.deliver('missing', message)).toBe(false); + expect(f.transport.sent).toHaveLength(0); + }); + + it('records a permanent 4xx in lastError without retrying, and clears it on success', async () => { + f.transport.failWith = [404]; + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(f.repository.rows[0].lastError).toBe('HTTP 404'); + expect(f.transport.sent).toHaveLength(0); + expect(f.transport.failWith).toEqual([]); + + expect(await f.service.deliver(channelId, message)).toBe(true); + expect(f.repository.rows[0]).toMatchObject({ lastError: null }); + expect(f.repository.rows[0].lastDeliveryAt).toBe(f.clock.now.toISOString()); + }); + + it('retries 429, 5xx and network errors before giving up', async () => { + f.transport.failWith = [429, 503, 'network']; + expect(await f.service.deliver(channelId, message)).toBe(true); + expect(f.transport.sent).toHaveLength(1); + + f.transport.failWith = [500, 500, 500, 500]; + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(f.repository.rows[0].lastError).toBe('HTTP 500'); + }); + + it('checks the stored destination again before sending', async () => { + // someone edits GitDB by hand and points the channel elsewhere + const { createChannelCipher } = await import('../infrastructure/crypto/channel-cipher'); + f.repository.rows[0].webhookUrl = createChannelCipher(() => 'test-encryption-key').encrypt( + channelId, + 'https://169.254.169.254/hook/latest', + ); + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(f.transport.sent).toHaveLength(0); + expect(f.repository.rows[0].lastError).toBe('invalid_destination'); + }); + + it('does not commit a delivery stamp on every success', async () => { + await f.service.deliver(channelId, message); + const writes = () => + f.repository.writes.filter((write) => typeof write.changes.lastDeliveryAt === 'string'); + expect(writes()).toHaveLength(1); + await f.service.deliver(channelId, message); + await f.service.deliver(channelId, message); + expect(writes()).toHaveLength(1); + f.advance(60 * 60 * 1000); + await f.service.deliver(channelId, message); + expect(writes()).toHaveLength(2); + }); + + it('never logs the destination nor the message', async () => { + const lines: unknown[] = []; + const record = (...args: unknown[]) => void lines.push(args); + const g = createChannelsFixture({ logger: { warn: record, error: record, debug: record } }); + const id = ( + await g.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x') + ).id; + g.transport.failWith = [503, 503, 503, 503]; + await g.service.deliver(id, message, { alertId: 'alert-1' }); + + expect(lines.length).toBeGreaterThan(0); + const logged = JSON.stringify(lines); + expect(logged).toContain(id); + expect(logged).not.toContain('hooks.example.com'); + expect(logged).not.toContain('secret'); + expect(logged).not.toContain('Críticas'); + }); + + it('sends test messages even to a disabled channel and reports failures', async () => { + await f.service.update(channelId, { enabled: false }); + expect(await f.service.test(channelId, { ...message, test: true })).toEqual({ + sent: true, + error: null, + }); + f.transport.failWith = [403]; + expect(await f.service.test(channelId, message)).toEqual({ sent: false, error: 'HTTP 403' }); + }); + + it('marks channels whose type lost its transport as unavailable', async () => { + const g = createChannelsFixture({ types: [] }); + g.repository.rows = structuredClone(f.repository.rows); + expect(await g.service.deliver(channelId, message)).toBe(false); + expect(g.repository.rows[0].lastError).toBe('unavailable'); + expect(g.service.toView(await g.service.get(channelId)).available).toBe(false); + }); + }); +}); diff --git a/src/modules/notifications/application/notification-channel.service.ts b/src/modules/notifications/application/notification-channel.service.ts new file mode 100644 index 00000000..ef98c6a8 --- /dev/null +++ b/src/modules/notifications/application/notification-channel.service.ts @@ -0,0 +1,333 @@ +import { + CHAT_CHANNEL_TYPES, + isChatChannelType, + type ChatChannelType, +} from '#lib/server/infra/notifications/chat-types'; +import type { + ChannelMessage, + ChatTransport, +} from '#lib/server/infra/notifications/chat-notification'; +import { WebhookDeliveryError } from '#lib/server/infra/http/webhook-request'; +import { + MAX_CHANNEL_NAME_LENGTH, + NotificationChannelDomain, + NotificationChannelNotFoundError, + NotificationChannelValidationError, + maskDestination, + type ChannelLocation, + type NotificationChannelView, +} from '../domain/notification-channel.domain'; +import type { ChannelCipher } from '../infrastructure/crypto/channel-cipher'; +import type { + NotificationChannelChanges, + NotificationChannelRepositoryPort, +} from '../infrastructure/repositories/notification-channel.repository'; + +/** One message on its way to one channel; the destination is only held in memory. */ +export type ChannelDelivery = { + channelId: string; + type: ChatChannelType; + destination: string; + message: ChannelMessage; + /** Called by the queue once the delivery succeeded or definitively failed. */ + report: (outcome: { sent: true } | { sent: false; error: unknown }) => void; +}; + +/** Where deliveries go: the channel queue in production, a direct sender in tests. */ +export type ChannelSender = { + enqueue(delivery: ChannelDelivery, context?: Record): Promise; +}; + +export type ChannelTransports = { + get(type: ChatChannelType): ChatTransport | null; + available(): ChatChannelType[]; +}; + +export type ChannelInput = { + type?: unknown; + name?: unknown; + /** Destination URL; on update an empty value keeps the stored one. */ + destination?: unknown; + enabled?: unknown; +}; + +export type NotificationChannelServiceOptions = { + now?: () => Date; + generateId?: () => string; + /** How often a healthy channel records `lastDeliveryAt` (each record is a GitDB commit). */ + deliveryStampIntervalMs?: number; + logger?: { warn: (object: object, message: string) => void }; +}; + +const DEFAULT_STAMP_INTERVAL_MS = 60 * 60 * 1000; + +/** + * Notification channels (chat and webhook destinations) of organizations and projects. The + * destination is validated by its type's transport (anti-SSRF) before saving and before every + * send, stored encrypted and only ever shown masked. Deliveries go through a queue with retries; + * a permanent failure is recorded in `lastError`. + */ +export class NotificationChannelService { + private readonly now: () => Date; + private readonly generateId: () => string; + private readonly stampIntervalMs: number; + + constructor( + private readonly repository: NotificationChannelRepositoryPort, + private readonly cipher: ChannelCipher, + private readonly transports: ChannelTransports, + private readonly sender: ChannelSender, + private readonly options: NotificationChannelServiceOptions = {}, + ) { + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + this.stampIntervalMs = options.deliveryStampIntervalMs ?? DEFAULT_STAMP_INTERVAL_MS; + } + + /** Channel types that can be created now (a transport is registered for them). */ + availableTypes(): ChatChannelType[] { + return this.transports.available(); + } + + async get(id: string): Promise { + const channel = await this.repository.findById(id); + if (!channel) throw new NotificationChannelNotFoundError(id); + return channel; + } + + /** The location's own channels: organization-level ones, or one project's. */ + async list(location: Pick) { + const channels = await this.repository.listByOrganization(location.organizationId); + return channels.filter((channel) => + location.projectId + ? channel.projectId === location.projectId + : channel.scope === 'organization', + ); + } + + /** Channels an alert of `location` may use: its project's and its organization's. */ + async listUsable(location: Pick) { + const channels = await this.repository.listByOrganization(location.organizationId); + return channels.filter((channel) => channel.usableFrom(location)); + } + + toView(channel: NotificationChannelDomain): NotificationChannelView { + const { webhookUrl: _secret, ...rest } = channel.toJson(); + void _secret; + let destinationMasked = '••••'; + try { + destinationMasked = maskDestination(this.cipher.decrypt(channel.id, channel.webhookUrl)); + } catch { + // an undecryptable destination (rotated key) shows as fully masked + } + return { + ...rest, + destinationMasked, + available: this.transports.get(channel.type) !== null, + }; + } + + async create( + location: ChannelLocation, + input: ChannelInput, + actorUserId: string, + ): Promise { + const errors: Record = {}; + const type = this.validateType(input.type, errors); + const name = this.validateName(input.name, errors); + const destination = type ? this.validateDestination(type, input.destination, errors) : null; + if (Object.keys(errors).length > 0 || !type || !destination) { + throw new NotificationChannelValidationError(errors); + } + + const id = this.generateId(); + const timestamp = this.now().toISOString(); + const row = new NotificationChannelDomain({ + id, + type, + name, + ...location, + projectId: location.scope === 'project' ? location.projectId : null, + webhookUrl: this.cipher.encrypt(id, destination), + enabled: + input.enabled === undefined ? true : input.enabled === true || input.enabled === 'true', + createdByUserId: actorUserId, + createdAt: timestamp, + updatedAt: timestamp, + lastDeliveryAt: null, + lastError: null, + }).toJson(); + await this.repository.create(row); + return new NotificationChannelDomain(row); + } + + /** Name, enabled and destination; the type can't change. An empty destination keeps it. */ + async update(id: string, input: ChannelInput): Promise { + const channel = await this.get(id); + const errors: Record = {}; + const changes: NotificationChannelChanges = {}; + if (input.name !== undefined) changes.name = this.validateName(input.name, errors); + if (input.enabled !== undefined) { + changes.enabled = input.enabled === true || input.enabled === 'true'; + } + if (typeof input.destination === 'string' && input.destination.trim()) { + const destination = this.validateDestination(channel.type, input.destination, errors); + if (destination) { + changes.webhookUrl = this.cipher.encrypt(channel.id, destination); + // a new destination starts with a clean slate + changes.lastError = null; + } + } + if (Object.keys(errors).length > 0) throw new NotificationChannelValidationError(errors); + await this.repository.update(id, changes); + return new NotificationChannelDomain({ ...channel.toJson(), ...changes }); + } + + async delete(id: string): Promise { + await this.get(id); + await this.repository.delete(id); + } + + /** + * Queues `message` for the channel and resolves with whether it was delivered. Disabled, + * deleted, unavailable or invalid channels resolve `false` without sending; nothing throws. + */ + async deliver( + channelId: string, + message: ChannelMessage, + context: Record = {}, + ): Promise { + const channel = await this.repository.findById(channelId).catch(() => null); + if (!channel || !channel.enabled) return false; + return this.send(channel, message, context); + } + + /** "Send test message": delivers `message` even to a disabled channel, and tells the result. */ + async test( + id: string, + message: ChannelMessage, + ): Promise<{ sent: boolean; error: string | null }> { + const channel = await this.get(id); + const sent = await this.send(channel, message, { kind: 'channel_test' }); + const after = await this.repository.findById(id).catch(() => null); + return { sent, error: sent ? null : (after?.lastError ?? 'unavailable') }; + } + + private async send( + channel: NotificationChannelDomain, + message: ChannelMessage, + context: Record, + ): Promise { + const transport = this.transports.get(channel.type); + if (!transport) { + await this.recordFailure(channel, 'unavailable'); + return false; + } + let destination: string; + try { + destination = this.cipher.decrypt(channel.id, channel.webhookUrl); + } catch { + await this.recordFailure(channel, 'undecryptable'); + return false; + } + // the stored value is checked again: GitDB can be edited outside the app + if (!transport.validateDestination(destination).ok) { + await this.recordFailure(channel, 'invalid_destination'); + return false; + } + + let outcome: { sent: true } | { sent: false; error: unknown } = { sent: false, error: null }; + const sent = await this.sender.enqueue( + { + channelId: channel.id, + type: channel.type, + destination, + message, + report: (result) => { + outcome = result; + }, + }, + { channelId: channel.id, type: channel.type, ...context }, + ); + if (sent) await this.recordSuccess(channel); + else { + const error = (outcome as { error?: unknown }).error; + await this.recordFailure( + channel, + error instanceof WebhookDeliveryError + ? error.summary + : error instanceof Error + ? error.name + : 'failed', + ); + } + return sent; + } + + private async recordSuccess(channel: NotificationChannelDomain) { + const last = channel.lastDeliveryAt ? Date.parse(channel.lastDeliveryAt) : 0; + const stale = this.now().getTime() - last >= this.stampIntervalMs; + // each write is a commit: only when the error clears or the stamp got old + if (!channel.lastError && !stale) return; + await this.repository + .update(channel.id, { lastDeliveryAt: this.now().toISOString(), lastError: null }) + .catch((error) => this.logWriteFailure(channel, error)); + } + + private async recordFailure(channel: NotificationChannelDomain, reason: string) { + if (channel.lastError === reason) return; + await this.repository + .update(channel.id, { lastError: reason }) + .catch((error) => this.logWriteFailure(channel, error)); + } + + private logWriteFailure(channel: NotificationChannelDomain, error: unknown) { + this.options.logger?.warn( + { channelId: channel.id, err: error instanceof Error ? error.name : 'unknown' }, + '[channels] delivery outcome could not be recorded', + ); + } + + private validateType(value: unknown, errors: Record): ChatChannelType | null { + if (!isChatChannelType(value)) { + errors.type = typeof value === 'string' && value ? 'invalid_type' : 'required'; + return null; + } + if (!this.transports.get(value)) { + errors.type = 'type_unavailable'; + return null; + } + return value; + } + + private validateName(value: unknown, errors: Record): string { + const name = typeof value === 'string' ? value.trim() : ''; + if (!name) errors.name = 'required'; + else if (name.length > MAX_CHANNEL_NAME_LENGTH) errors.name = 'too_long'; + return name; + } + + private validateDestination( + type: ChatChannelType, + value: unknown, + errors: Record, + ): string | null { + if (typeof value !== 'string' || !value.trim()) { + errors.destination = 'required'; + return null; + } + const transport = this.transports.get(type); + if (!transport) { + errors.type = 'type_unavailable'; + return null; + } + const checked = transport.validateDestination(value.trim()); + if (!checked.ok) { + errors.destination = checked.error; + return null; + } + return checked.url.toString(); + } +} + +export { CHAT_CHANNEL_TYPES }; diff --git a/src/modules/notifications/application/testing.ts b/src/modules/notifications/application/testing.ts index cc6c7fc1..eb4649a6 100644 --- a/src/modules/notifications/application/testing.ts +++ b/src/modules/notifications/application/testing.ts @@ -1,3 +1,18 @@ +import { + DeliveryQueue, + type ChatChannelType, + type ChatNotification, + type ChatTransport, +} from '#lib/server/infra/notifications'; +import { + isRetryableWebhookError, + validateWebhookUrl, + webhookRetryAfter, + WebhookDeliveryError, +} from '#lib/server/infra/http/webhook-request'; +import { InMemoryNotificationChannelRepository } from '../infrastructure/repositories/in-memory.repositories'; +import { createChannelCipher } from '../infrastructure/crypto/channel-cipher'; +import { NotificationChannelService, type ChannelDelivery } from './notification-channel.service'; import { RateLimiter } from '#lib/server/infra/rate-limit'; import { InMemoryExternalRecipientRepository, @@ -62,3 +77,78 @@ export function createNotificationsFixture(options: { origin?: string | null } = }, }; } + +// --- notification channels ------------------------------------------------------------------- + +/** + * Fake chat transport: accepts `https://hooks.example.com/hook/...` and records what it would + * post. `failWith` makes the next sends throw (a `WebhookDeliveryError` status, or `'network'`). + */ +export class FakeChatTransport implements ChatTransport { + sent: ChatNotification[] = []; + failWith: Array = []; + + validateDestination(raw: unknown) { + return validateWebhookUrl(raw, { hosts: ['hooks.example.com'], pathPrefix: '/hook/' }); + } + + async send(notification: ChatNotification) { + const failure = this.failWith.shift(); + if (failure === 'network') throw new WebhookDeliveryError(null, true, null, 'network'); + if (typeof failure === 'number') { + throw new WebhookDeliveryError(failure, failure === 429 || failure >= 500); + } + this.sent.push(notification); + } +} + +/** The channels service with in-memory storage, a fake transport and an instant retry queue. */ +export function createChannelsFixture( + options: { + types?: ChatChannelType[]; + logger?: { warn: () => void; error: () => void; debug: () => void }; + } = {}, +) { + const clock = { now: new Date('2026-11-24T10:00:00.000Z') }; + const repository = new InMemoryNotificationChannelRepository(); + const transport = new FakeChatTransport(); + const types = options.types ?? ['slack']; + const logger = options.logger ?? { warn: () => {}, error: () => {}, debug: () => {} }; + const queue = new DeliveryQueue({ + send: (delivery) => + transport.send({ + channel: delivery.type, + destination: delivery.destination, + message: delivery.message, + } as ChatNotification), + retry: { + isRetryable: isRetryableWebhookError, + retryAfterMs: webhookRetryAfter, + sleep: async () => {}, + }, + logger, + label: { prefix: '[channels]', noun: 'message', plural: 'messages' }, + describe: (delivery) => ({ channelId: delivery.channelId, type: delivery.type }), + onSettled: (delivery, outcome) => delivery.report(outcome), + }); + let id = 0; + const service = new NotificationChannelService( + repository, + createChannelCipher(() => 'test-encryption-key'), + { + get: (type) => (types.includes(type) ? transport : null), + available: () => [...types], + }, + queue, + { now: () => clock.now, generateId: () => `channel-${++id}` }, + ); + return { + clock, + repository, + transport, + service, + advance(ms: number) { + clock.now = new Date(clock.now.getTime() + ms); + }, + }; +} diff --git a/src/modules/notifications/domain/notification-channel.domain.ts b/src/modules/notifications/domain/notification-channel.domain.ts new file mode 100644 index 00000000..b55f107d --- /dev/null +++ b/src/modules/notifications/domain/notification-channel.domain.ts @@ -0,0 +1,131 @@ +import { + isChatChannelType, + type ChatChannelType, +} from '#lib/server/infra/notifications/chat-types'; + +export type ChannelScope = 'organization' | 'project'; + +/** Where a channel lives: an organization channel has no project. */ +export type ChannelLocation = { + scope: ChannelScope; + organizationId: string; + projectId: string | null; +}; + +export type NotificationChannelRow = ChannelLocation & { + id: string; + type: ChatChannelType; + name: string; + /** Destination URL, encrypted (`channel-cipher.ts`): never returned nor logged. */ + webhookUrl: string; + enabled: boolean; + createdByUserId: string; + createdAt: string; + updatedAt: string; + lastDeliveryAt: string | null; + /** Short reason of the last failed delivery (`HTTP 404`, `timeout`), cleared on success. */ + lastError: string | null; +}; + +/** What the API and the pages may show: the destination only masked. */ +export type NotificationChannelView = Omit & { + /** `https://hooks.slack.com/…/••••1a2b` */ + destinationMasked: string; + /** Whether its type has a transport: channels of other types are kept but send nothing. */ + available: boolean; +}; + +export const MAX_CHANNEL_NAME_LENGTH = 80; + +function toIso(value: unknown): string | null { + if (value instanceof Date) return value.toISOString(); + return typeof value === 'string' && value ? value : null; +} + +export class NotificationChannelDomain implements NotificationChannelRow { + id: string; + type: ChatChannelType; + name: string; + scope: ChannelScope; + organizationId: string; + projectId: string | null; + webhookUrl: string; + enabled: boolean; + createdByUserId: string; + createdAt: string; + updatedAt: string; + lastDeliveryAt: string | null; + lastError: string | null; + + constructor(row: Record) { + this.id = row.id; + this.type = isChatChannelType(row.type) ? row.type : 'webhook'; + this.name = row.name ?? ''; + this.scope = row.scope === 'project' ? 'project' : 'organization'; + this.organizationId = row.organizationId; + this.projectId = this.scope === 'project' ? (row.projectId ?? null) : null; + this.webhookUrl = row.webhookUrl ?? ''; + this.enabled = row.enabled !== false; + this.createdByUserId = row.createdByUserId; + this.createdAt = toIso(row.createdAt) ?? new Date(0).toISOString(); + this.updatedAt = toIso(row.updatedAt) ?? this.createdAt; + this.lastDeliveryAt = toIso(row.lastDeliveryAt); + this.lastError = row.lastError ?? null; + } + + get location(): ChannelLocation { + return { scope: this.scope, organizationId: this.organizationId, projectId: this.projectId }; + } + + /** + * Whether an alert of `location` may use it: an organization channel serves the organization + * and all its projects, a project channel only alerts of its project. + */ + usableFrom(location: Pick): boolean { + if (location.organizationId !== this.organizationId) return false; + return this.scope === 'organization' || location.projectId === this.projectId; + } + + toJson(): NotificationChannelRow { + return { + id: this.id, + type: this.type, + name: this.name, + scope: this.scope, + organizationId: this.organizationId, + projectId: this.projectId, + webhookUrl: this.webhookUrl, + enabled: this.enabled, + createdByUserId: this.createdByUserId, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + lastDeliveryAt: this.lastDeliveryAt, + lastError: this.lastError, + }; + } +} + +/** `https://hooks.slack.com/services/T0/B0/xyz1a2b` → `https://hooks.slack.com/…/••••1a2b`. */ +export function maskDestination(url: string): string { + try { + const parsed = new URL(url); + const tail = url.replace(/[?#].*$/, '').slice(-4); + return `${parsed.protocol}//${parsed.host}/…/••••${tail}`; + } catch { + return '••••'; + } +} + +export class NotificationChannelValidationError extends Error { + constructor(readonly errors: Record) { + super(`Invalid notification channel: ${Object.keys(errors).join(', ')}`); + this.name = 'NotificationChannelValidationError'; + } +} + +export class NotificationChannelNotFoundError extends Error { + constructor(id: string) { + super(`Notification channel not found: ${id}`); + this.name = 'NotificationChannelNotFoundError'; + } +} diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts index 3586811b..1e8a5c8e 100644 --- a/src/modules/notifications/index.ts +++ b/src/modules/notifications/index.ts @@ -1,10 +1,25 @@ -import { absoluteUrl, notify } from '#lib/server/infra/notifications'; +import { + ChatNotification, + DeliveryQueue, + absoluteUrl, + availableChatTypes, + getChatTransport, + notify, + sendWithLatestNotify, +} from '#lib/server/infra/notifications'; +import { isRetryableWebhookError, webhookRetryAfter } from '#lib/server/infra/http/webhook-request'; import { RateLimiter } from '#lib/server/infra/rate-limit'; import { createLogger } from '#lib/server/logger'; import { passwordService } from '../auth'; import { organizationService } from '../organization'; import { ExternalRecipientService } from './application/external-recipient.service'; import { NotificationSettingsService } from './application/notification-settings.service'; +import { + NotificationChannelService, + type ChannelDelivery, +} from './application/notification-channel.service'; +import { createChannelCipher } from './infrastructure/crypto/channel-cipher'; +import { NotificationChannelRepository } from './infrastructure/repositories/notification-channel.repository'; import { ExternalRecipientMailNotifier } from './infrastructure/external-recipient-mail.notifier'; import { ExternalRecipientRepository } from './infrastructure/repositories/external-recipient.repository'; import { NotificationSettingsRepository } from './infrastructure/repositories/notification-settings.repository'; @@ -46,6 +61,55 @@ export const notificationSettingsService = new NotificationSettingsService( externalRecipientService, ); +const CHANNEL_QUEUE_KEY = Symbol.for('gitops.notifications.channel-queue'); +const CHANNEL_SHUTDOWN_KEY = Symbol.for('gitops.notifications.channel-shutdown'); +type GlobalWithChannelQueue = typeof globalThis & { + [CHANNEL_QUEUE_KEY]?: DeliveryQueue; + [CHANNEL_SHUTDOWN_KEY]?: boolean; +}; + +/** + * Process-wide queue of channel messages (3 at a time; 4 attempts only on network errors, 429 + * honoring `Retry-After`, and 5xx). Logs carry the channel id and type, never the URL nor the + * message. Kept on `globalThis` like the mail queue; it sends through the latest `notify`. + */ +export const channelQueue: DeliveryQueue = ((globalThis as GlobalWithChannelQueue)[ + CHANNEL_QUEUE_KEY +] ??= new DeliveryQueue({ + send: (delivery) => + sendWithLatestNotify( + new ChatNotification({ + channel: delivery.type, + destination: delivery.destination, + message: delivery.message, + }), + ), + concurrency: 3, + retry: { isRetryable: isRetryableWebhookError, retryAfterMs: webhookRetryAfter }, + logger: createLogger('channels'), + label: { prefix: '[channels]', noun: 'message', plural: 'messages' }, + describe: (delivery) => ({ channelId: delivery.channelId, type: delivery.type }), + onSettled: (delivery, outcome) => delivery.report(outcome), +})); + +export const notificationChannelService = new NotificationChannelService( + new NotificationChannelRepository(), + createChannelCipher(() => passwordService.ensureEncryptionKey()), + { get: (type) => getChatTransport(type), available: () => availableChatTypes() }, + channelQueue, + { logger: log }, +); + +/** Drains the channel queue when adapter-node shuts down; registered once per process. */ +export function registerChannelShutdown(): void { + const scope = globalThis as GlobalWithChannelQueue; + if (scope[CHANNEL_SHUTDOWN_KEY]) return; + scope[CHANNEL_SHUTDOWN_KEY] = true; + process.once('sveltekit:shutdown' as never, () => { + void channelQueue.drain(10_000); + }); +} + export { ExternalRecipientService, MAX_EXTERNAL_EMAILS, @@ -66,4 +130,12 @@ export { type ExternalRecipientView, } from './domain/external-recipient.domain'; export type { NotificationSettings } from './domain/notification-settings.domain'; +export { + NotificationChannelNotFoundError, + NotificationChannelValidationError, + type ChannelLocation, + type NotificationChannelView, +} from './domain/notification-channel.domain'; +export type { ChannelInput } from './application/notification-channel.service'; +export { buildChannelTestMessage } from './infrastructure/channel-test-message'; export { normalizeEmail } from './domain/email-address'; diff --git a/src/modules/notifications/infrastructure/channel-test-message.ts b/src/modules/notifications/infrastructure/channel-test-message.ts new file mode 100644 index 00000000..21fe6b12 --- /dev/null +++ b/src/modules/notifications/infrastructure/channel-test-message.ts @@ -0,0 +1,28 @@ +import type { ChannelMessage } from '#lib/server/infra/notifications'; +import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n'; + +/** + * The message of "Send test message": says it is a test and where it was sent from, nothing about + * any real event. In the default language: a channel is shared by people with different ones. + */ +export function buildChannelTestMessage(input: { + channelName: string; + where: string; + /** Absolute link to the channel settings, when `ORIGIN` is known. */ + link: string | null; +}): ChannelMessage { + const t = translator(DEFAULT_MAIL_LOCALE); + const summary = t('notifications.channels.testMessage.summary', { where: input.where }); + return { + title: t('notifications.channels.testMessage.title', { channel: input.channelName }), + summary, + eventLabel: t('notifications.channels.testMessage.event'), + fields: [{ label: t('notifications.channels.testMessage.channel'), value: input.channelName }], + link: input.link + ? { url: input.link, label: t('notifications.channels.testMessage.open') } + : null, + suppressed: 0, + text: `${t('notifications.channels.testMessage.title', { channel: input.channelName })}: ${summary}`, + test: true, + }; +} diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts new file mode 100644 index 00000000..270bdf67 --- /dev/null +++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { createChannelCipher } from './channel-cipher'; + +const url = 'https://hooks.slack.com/services/T000/B000/abcdef1a2b'; + +describe('channel cipher', () => { + it('round-trips a destination without keeping it readable', () => { + const cipher = createChannelCipher(() => 'key-1'); + const stored = cipher.encrypt('channel-1', url); + expect(stored).toMatch(/^v1:/); + expect(stored).not.toContain('hooks.slack.com'); + expect(cipher.decrypt('channel-1', stored)).toBe(url); + // a fresh IV each time + expect(cipher.encrypt('channel-1', url)).not.toBe(stored); + }); + + it('does not decrypt on another channel nor with another key', () => { + const stored = createChannelCipher(() => 'key-1').encrypt('channel-1', url); + expect(() => createChannelCipher(() => 'key-1').decrypt('channel-2', stored)).toThrow( + /could not be decrypted/, + ); + expect(() => createChannelCipher(() => 'key-2').decrypt('channel-1', stored)).toThrow( + /could not be decrypted/, + ); + expect(() => createChannelCipher(() => 'key-1').decrypt('channel-1', url)).toThrow( + /no encrypted destination/, + ); + }); + + it('refuses to work without a key', () => { + expect(() => createChannelCipher(() => ' ').encrypt('channel-1', url)).toThrow( + /GITDB_ENCRYPTION_KEY/, + ); + }); +}); diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts new file mode 100644 index 00000000..5ab63ecb --- /dev/null +++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts @@ -0,0 +1,66 @@ +import crypto from 'node:crypto'; + +const ALGORITHM = 'aes-256-gcm'; +const VERSION = 'v1'; +const KEY_SALT = 'gitops:notifications:channel-destination:v1'; +const IV_BYTES = 12; +const AUTH_TAG_BYTES = 16; + +export interface ChannelCipher { + encrypt(channelId: string, value: string): string; + decrypt(channelId: string, stored: string): string; +} + +/** + * AES-256-GCM for channel destinations (same scheme as the vault secrets), keyed from + * `GITDB_ENCRYPTION_KEY`. The channel id is authenticated data: a value copied onto another + * channel does not decrypt. + */ +export function createChannelCipher(secret: () => string): ChannelCipher { + let cached: { material: string; key: Buffer } | null = null; + const key = () => { + const material = secret().trim(); + if (!material) throw new Error('Missing GITDB_ENCRYPTION_KEY environment variable'); + if (cached?.material !== material) { + cached = { material, key: crypto.scryptSync(material, KEY_SALT, 32) }; + } + return cached.key; + }; + const aad = (channelId: string) => Buffer.from(`${VERSION}:channel:${channelId}`, 'utf8'); + + return { + encrypt(channelId, value) { + const iv = crypto.randomBytes(IV_BYTES); + const cipher = crypto.createCipheriv(ALGORITHM, key(), iv, { + authTagLength: AUTH_TAG_BYTES, + }); + cipher.setAAD(aad(channelId)); + const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]); + return [ + VERSION, + iv.toString('base64'), + cipher.getAuthTag().toString('base64'), + ciphertext.toString('base64'), + ].join(':'); + }, + decrypt(channelId, stored) { + const [version, iv, authTag, ciphertext, ...rest] = stored.split(':'); + if (version !== VERSION || !iv || !authTag || !ciphertext || rest.length > 0) { + throw new Error(`Channel ${channelId} has no encrypted destination`); + } + try { + const decipher = crypto.createDecipheriv(ALGORITHM, key(), Buffer.from(iv, 'base64'), { + authTagLength: AUTH_TAG_BYTES, + }); + decipher.setAAD(aad(channelId)); + decipher.setAuthTag(Buffer.from(authTag, 'base64')); + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8'); + } catch { + throw new Error(`Channel ${channelId} destination could not be decrypted`); + } + }, + }; +} diff --git a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts index 99abd3d3..ad07c98b 100644 --- a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts +++ b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts @@ -11,6 +11,14 @@ import type { ExternalRecipientRepositoryPort, } from './external-recipient.repository'; import type { NotificationSettingsRepositoryPort } from './notification-settings.repository'; +import { + NotificationChannelDomain, + type NotificationChannelRow, +} from '../../domain/notification-channel.domain'; +import type { + NotificationChannelChanges, + NotificationChannelRepositoryPort, +} from './notification-channel.repository'; /** In-memory fakes for unit tests; they store copies so callers can't mutate the stored rows. */ export class InMemoryNotificationSettingsRepository implements NotificationSettingsRepositoryPort { @@ -71,3 +79,38 @@ export class InMemoryExternalRecipientRepository implements ExternalRecipientRep ); } } + +export class InMemoryNotificationChannelRepository implements NotificationChannelRepositoryPort { + rows: NotificationChannelRow[] = []; + /** Every write, to assert what reached "GitDB". */ + writes: Array<{ id: string; changes: Record }> = []; + + async findById(id: string) { + const row = this.rows.find((candidate) => candidate.id === id); + return row ? new NotificationChannelDomain(structuredClone(row)) : null; + } + + async listByOrganization(organizationId: string) { + return this.rows + .filter((row) => row.organizationId === organizationId) + .map((row) => new NotificationChannelDomain(structuredClone(row))); + } + + async create(row: NotificationChannelRow) { + this.rows.push(structuredClone(row)); + this.writes.push({ id: row.id, changes: { ...row } }); + } + + async update(id: string, changes: NotificationChannelChanges) { + this.writes.push({ id, changes: { ...changes } }); + this.rows = this.rows.map((row) => + row.id === id + ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() } + : row, + ); + } + + async delete(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} diff --git a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts new file mode 100644 index 00000000..8f116374 --- /dev/null +++ b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts @@ -0,0 +1,55 @@ +import { NotificationChannelEntity } from '#lib/database/schemas'; +import { Repository } from '#lib/server/infra/repository'; +import { + NotificationChannelDomain, + type NotificationChannelRow, +} from '../../domain/notification-channel.domain'; + +export type NotificationChannelChanges = Partial< + Pick +>; + +/** Persistence port; `InMemoryNotificationChannelRepository` implements it in tests. */ +export interface NotificationChannelRepositoryPort { + findById(id: string): Promise; + /** Every channel of the organization, including those of its projects. */ + listByOrganization(organizationId: string): Promise; + create(row: NotificationChannelRow): Promise; + update(id: string, changes: NotificationChannelChanges): Promise; + delete(id: string): Promise; +} + +export class NotificationChannelRepository + extends Repository + implements NotificationChannelRepositoryPort +{ + async findById(id: string) { + const result = await this.db.select().from(NotificationChannelEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new NotificationChannelDomain(row) : null; + } + + async listByOrganization(organizationId: string) { + const result = await this.db + .select() + .from(NotificationChannelEntity) + .where({ organizationId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new NotificationChannelDomain(row)); + } + + async create(row: NotificationChannelRow) { + await this.db.insert(NotificationChannelEntity).values({ ...row }); + } + + async update(id: string, changes: NotificationChannelChanges) { + await this.db + .update(NotificationChannelEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async delete(id: string) { + await this.db.delete(NotificationChannelEntity).where({ id }); + } +} diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 793d7e23..6cdbca43 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -125,6 +125,7 @@ export async function load({ locals, url }) { canReadProjectServerKeys, canReadProjectAudit, canReadProjectAlerts, + canReadProjectNotifications, canReadProjectVaultSecrets, canReadProjectVaultEnvironments, canReadProjectCodeReportReports, @@ -140,6 +141,7 @@ export async function load({ locals, url }) { projectSectionPermission('project:server-keys:read'), projectSectionPermission('project:audit:read'), projectSectionPermission('project:alerts:read'), + projectSectionPermission('project:notifications:read'), projectSectionPermission('project:vault:secrets:read'), projectSectionPermission('project:vault:environments:read'), projectSectionPermission('project:codereport:reports:read'), @@ -186,6 +188,7 @@ export async function load({ locals, url }) { canReadProjectServerKeys, canReadProjectAudit, canReadProjectAlerts, + canReadProjectNotifications, canReadProjectVault, canReadProjectCodeReport, canReadProjectStateIac, diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 7740ad20..0000edbd 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -69,6 +69,7 @@ canReadOrgEvents={data.canReadOrgEvents} canReadOrganizationAlerts={data.canReadOrganizationAlerts} canReadOrgNotifications={data.canReadOrgNotifications} + canReadProjectNotifications={data.canReadProjectNotifications} canReadProjectInfo={data.canReadProjectInfo} canReadProjectUsers={data.canReadProjectUsers} canReadProjectRoles={data.canReadProjectRoles} diff --git a/src/routes/api/notification-channels/+server.ts b/src/routes/api/notification-channels/+server.ts new file mode 100644 index 00000000..3303cfec --- /dev/null +++ b/src/routes/api/notification-channels/+server.ts @@ -0,0 +1,33 @@ +import { json } from '@sveltejs/kit'; +import { resolveLocation } from '#lib/server/alerts/access'; +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { createChannel, listChannels } from '#lib/server/notifications/channels'; + +// GET /api/notification-channels?organizationId=…|projectId=…: the location's channels (and, for a +// project, the organization ones it inherits). The destination is only ever returned masked +export async function GET({ url, locals }) { + const lookup = await resolveLocation({ + organizationId: url.searchParams.get('organizationId'), + projectId: url.searchParams.get('projectId'), + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse(await listChannels(locals, lookup.location)); +} + +// POST /api/notification-channels { organizationId | projectId, type, name, destination, enabled? } +export async function POST({ request, locals }) { + const body = await readJson(request); + const lookup = await resolveLocation({ + organizationId: typeof body.organizationId === 'string' ? body.organizationId : null, + projectId: typeof body.projectId === 'string' ? body.projectId : null, + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse( + await createChannel(locals, lookup.location, { + type: body.type, + name: body.name, + destination: body.destination, + enabled: body.enabled, + }), + ); +} diff --git a/src/routes/api/notification-channels/[id]/+server.ts b/src/routes/api/notification-channels/[id]/+server.ts new file mode 100644 index 00000000..6a1a3e6f --- /dev/null +++ b/src/routes/api/notification-channels/[id]/+server.ts @@ -0,0 +1,23 @@ +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { deleteChannel, getChannel, updateChannel } from '#lib/server/notifications/channels'; + +export async function GET({ params, locals }) { + return toResponse(await getChannel(locals, params.id)); +} + +// PATCH /api/notification-channels/ { name?, destination?, enabled? }: the type can't change and +// an omitted destination keeps the stored one +export async function PATCH({ params, request, locals }) { + const body = await readJson(request); + return toResponse( + await updateChannel(locals, params.id, { + name: body.name, + destination: body.destination, + enabled: body.enabled, + }), + ); +} + +export async function DELETE({ params, locals }) { + return toResponse(await deleteChannel(locals, params.id)); +} diff --git a/src/routes/api/notification-channels/[id]/test/+server.ts b/src/routes/api/notification-channels/[id]/test/+server.ts new file mode 100644 index 00000000..6097f64f --- /dev/null +++ b/src/routes/api/notification-channels/[id]/test/+server.ts @@ -0,0 +1,7 @@ +import { toResponse } from '#lib/server/alerts/http'; +import { testChannel } from '#lib/server/notifications/channels'; + +// POST /api/notification-channels//test: posts a test message, even to a disabled channel +export async function POST({ params, locals }) { + return toResponse(await testChannel(locals, params.id)); +} diff --git a/src/routes/api/notification-channels/server.test.ts b/src/routes/api/notification-channels/server.test.ts new file mode 100644 index 00000000..a3559901 --- /dev/null +++ b/src/routes/api/notification-channels/server.test.ts @@ -0,0 +1,260 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// grants per caller and context key (`org:` / `project:`) +const grants: { + users: Record>; + apiKeys: Record; +} = { users: {}, apiKeys: {} }; + +function contextKey(context: { scope: string; organizationId?: string; projectId?: string }) { + return context.scope === 'project' + ? `project:${context.projectId}` + : `org:${context.organizationId}`; +} + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async (user: { id?: string } | null, permission: string, context: never) => + !!user?.id && (grants.users[user.id]?.[contextKey(context)] ?? []).includes(permission), + canApiKey: ( + apiKey: { id: string; projectId: string | null }, + permission: string, + context: { scope: string; projectId?: string }, + ) => { + if ( + apiKey.projectId && + (context.scope !== 'project' || context.projectId !== apiKey.projectId) + ) { + return false; + } + return (grants.apiKeys[apiKey.id] ?? []).includes(permission); + }, + }, +})); + +vi.mock('#modules/projects', () => ({ + projectService: { + getProject: async (id: string) => + ['p1', 'p2'].includes(id) + ? { id, name: `Project ${id}`, slug: id, organization: { id: 'org-1', slug: 'kettu' } } + : null, + }, +})); + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => + id === 'org-1' ? { id, name: 'Kettu', slug: 'kettu' } : null, + }, +})); + +vi.mock('#modules/notifications', async () => { + const { createChannelsFixture } = await import('#modules/notifications/application/testing'); + const domain = await import('#modules/notifications/domain/notification-channel.domain'); + const { buildChannelTestMessage } = + await import('#modules/notifications/infrastructure/channel-test-message'); + const fixture = createChannelsFixture(); + return { + ...domain, + buildChannelTestMessage, + notificationChannelService: fixture.service, + fixture, + }; +}); + +const notifications = (await import('#modules/notifications')) as unknown as { + fixture: ReturnType< + typeof import('#modules/notifications/application/testing').createChannelsFixture + >; +}; +const collection = await import('./+server'); +const item = await import('./[id]/+server'); +const test = await import('./[id]/test/+server'); + +const HOOK = 'https://hooks.example.com/hook/T0/B0/topsecret1a2b'; +const ORG_ADMIN = ['read', 'create', 'update', 'delete'].map( + (a) => `organization:notifications:${a}`, +); +const PROJECT_ADMIN = ['read', 'create', 'update', 'delete'].map( + (a) => `project:notifications:${a}`, +); + +function call( + handler: (event: never) => Promise, + input: { + locals?: Record; + body?: unknown; + url?: string; + params?: Record; + }, +) { + return handler({ + locals: input.locals ?? {}, + params: input.params ?? {}, + url: new URL(input.url ?? 'http://localhost/api/notification-channels'), + request: { json: async () => input.body ?? {} }, + } as never); +} + +const as = (id: string) => ({ user: { id } }); + +async function createOrgChannel() { + const response = await call(collection.POST, { + locals: as('orgAdmin'), + body: { organizationId: 'org-1', type: 'slack', name: '#alerts', destination: HOOK }, + }); + expect(response.status).toBe(201); + return (await response.json()) as { id: string }; +} + +describe('/api/notification-channels', () => { + beforeEach(() => { + notifications.fixture.repository.rows = []; + notifications.fixture.transport.sent = []; + grants.users = { + orgAdmin: { 'org:org-1': ORG_ADMIN }, + orgReader: { 'org:org-1': ['organization:notifications:read'] }, + alertsOnly: { 'org:org-1': ['organization:alerts:all', 'organization:alerts:read'] }, + projectAdmin: { 'project:p1': PROJECT_ADMIN }, + }; + grants.apiKeys = { 'key-p1': PROJECT_ADMIN }; + }); + + it('never returns the destination in clear', async () => { + const created = await createOrgChannel(); + const listed = await call(collection.GET, { + locals: as('orgReader'), + url: 'http://localhost/api/notification-channels?organizationId=org-1', + }); + const fetched = await call(item.GET, { locals: as('orgReader'), params: { id: created.id } }); + for (const response of [listed, fetched]) { + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).not.toContain('topsecret'); + expect(text).not.toContain('webhookUrl'); + expect(text).toContain('••••1a2b'); + } + }); + + it('needs *:notifications:* to see or manage channels', async () => { + const created = await createOrgChannel(); + + for (const locals of [{}, as('alertsOnly')]) { + const listed = await call(collection.GET, { + locals, + url: 'http://localhost/api/notification-channels?organizationId=org-1', + }); + expect(listed.status).toBe(403); + // a channel the caller can't read looks missing + expect((await call(item.GET, { locals, params: { id: created.id } })).status).toBe(404); + } + + const reader = as('orgReader'); + expect( + ( + await call(collection.POST, { + locals: reader, + body: { organizationId: 'org-1', type: 'slack', name: 'x', destination: HOOK }, + }) + ).status, + ).toBe(403); + expect( + (await call(item.PATCH, { locals: reader, params: { id: created.id }, body: { name: 'y' } })) + .status, + ).toBe(403); + expect((await call(item.DELETE, { locals: reader, params: { id: created.id } })).status).toBe( + 403, + ); + expect((await call(test.POST, { locals: reader, params: { id: created.id } })).status).toBe( + 403, + ); + expect(notifications.fixture.transport.sent).toHaveLength(0); + }); + + it('keeps project admins and project keys inside their project', async () => { + const created = await call(collection.POST, { + locals: as('projectAdmin'), + body: { projectId: 'p1', type: 'slack', name: '#p1', destination: HOOK }, + }); + expect(created.status).toBe(201); + + // no organization channels for a project admin + const orgChannel = await call(collection.POST, { + locals: as('projectAdmin'), + body: { organizationId: 'org-1', type: 'slack', name: '#org', destination: HOOK }, + }); + expect(orgChannel.status).toBe(403); + + const key = { apiKey: { id: 'key-p1', projectId: 'p1', userId: null, role: null } }; + expect( + ( + await call(collection.GET, { + locals: key, + url: 'http://localhost/api/notification-channels?projectId=p1', + }) + ).status, + ).toBe(200); + expect( + ( + await call(collection.GET, { + locals: key, + url: 'http://localhost/api/notification-channels?projectId=p2', + }) + ).status, + ).toBe(403); + expect( + ( + await call(collection.GET, { + locals: key, + url: 'http://localhost/api/notification-channels?organizationId=org-1', + }) + ).status, + ).toBe(403); + }); + + it('validates the destination on the server', async () => { + const response = await call(collection.POST, { + locals: as('orgAdmin'), + body: { + organizationId: 'org-1', + type: 'slack', + name: 'x', + destination: 'https://127.0.0.1/hook/x', + }, + }); + expect(response.status).toBe(400); + await expect(response.json()).resolves.toEqual({ + error: 'Invalid channel', + errors: { destination: 'ip_address' }, + }); + }); + + it('sends a test message with the fake transport', async () => { + const created = await createOrgChannel(); + const response = await call(test.POST, { locals: as('orgAdmin'), params: { id: created.id } }); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ sent: true, error: null }); + expect(notifications.fixture.transport.sent[0].message).toMatchObject({ + title: 'GitOps test message for #alerts', + test: true, + }); + }); + + it('updates and deletes with the right permissions', async () => { + const created = await createOrgChannel(); + const updated = await call(item.PATCH, { + locals: as('orgAdmin'), + params: { id: created.id }, + body: { name: '#renamed', enabled: false, type: 'google-chat' }, + }); + await expect(updated.json()).resolves.toMatchObject({ + name: '#renamed', + enabled: false, + type: 'slack', + }); + expect( + (await call(item.DELETE, { locals: as('orgAdmin'), params: { id: created.id } })).status, + ).toBe(200); + expect(notifications.fixture.repository.rows).toHaveLength(0); + }); +}); diff --git a/src/routes/org/[org]/projects/[slug]/settings/notifications/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/notifications/+page.server.ts new file mode 100644 index 00000000..2194222e --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/notifications/+page.server.ts @@ -0,0 +1,21 @@ +import { error } from '@sveltejs/kit'; +import { projectService } from '#modules/projects'; +import { channelActions, loadChannelsSection } from '#lib/server/notifications/channels-page'; + +/** `/org//projects//settings/notifications`: the project's channels. */ +async function projectLocation(params: Record) { + const project = await projectService.getProjectBySlug(params.slug).catch(() => null); + const organization = project?.organization; + if (!project || !organization || organization.slug !== params.org) { + throw error(404, 'Project not found'); + } + return { scope: 'project' as const, organizationId: organization.id, projectId: project.id }; +} + +export async function load({ params, locals }) { + const channels = await loadChannelsSection(locals, await projectLocation(params)); + if (!channels) throw error(403, 'Forbidden'); + return { channels }; +} + +export const actions = channelActions(({ params }) => projectLocation(params)); diff --git a/src/routes/org/[org]/projects/[slug]/settings/notifications/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/notifications/+page.svelte new file mode 100644 index 00000000..6c8bb44b --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/notifications/+page.svelte @@ -0,0 +1,21 @@ + + + + {$_('notifications.settings.title')} - {$_('projectSettings.title')} + + +
    +
    +

    {$_('notifications.settings.title')}

    +

    {$_('notifications.settings.projectDescription')}

    +
    + + +
    diff --git a/src/routes/org/[org]/settings/notifications/+page.server.ts b/src/routes/org/[org]/settings/notifications/+page.server.ts index 62c5413e..00c58a1d 100644 --- a/src/routes/org/[org]/settings/notifications/+page.server.ts +++ b/src/routes/org/[org]/settings/notifications/+page.server.ts @@ -1,5 +1,6 @@ import { error, fail } from '@sveltejs/kit'; import { organizationService } from '#modules/organization'; +import { channelActions, loadChannelsSection } from '#lib/server/notifications/channels-page'; import { loadNotificationSettings, resendVerification, @@ -10,10 +11,18 @@ export async function load({ parent, locals }) { const { organization } = await parent(); const result = await loadNotificationSettings(locals, organization.id); if (!result.ok) throw error(result.status, result.error); - return result.data; + const channels = await loadChannelsSection(locals, organizationLocation(organization.id)); + return { ...result.data, channels }; +} + +function organizationLocation(organizationId: string) { + return { scope: 'organization' as const, organizationId, projectId: null }; } export const actions = { + ...channelActions(async ({ params }) => + organizationLocation((await organizationOf(params.org)).id), + ), async domains({ request, locals, params }) { const organization = await organizationOf(params.org); const form = await request.formData(); diff --git a/src/routes/org/[org]/settings/notifications/+page.svelte b/src/routes/org/[org]/settings/notifications/+page.svelte index 8dedef0a..120bb13b 100644 --- a/src/routes/org/[org]/settings/notifications/+page.svelte +++ b/src/routes/org/[org]/settings/notifications/+page.svelte @@ -3,6 +3,8 @@ import { Globe, MailCheck, MailWarning, RefreshCw, Save } from '@lucide/svelte'; import { _ } from '#lib/i18n'; import { statusBadgeClass } from '#lib/notifications/status'; + import ChannelsSection from '#lib/components/notifications/ChannelsSection.svelte'; + import type { ChannelsFormResult } from '#lib/notifications/types'; import type { ActionData, PageData } from './$types'; let { data, form }: { data: PageData; form: ActionData } = $props(); @@ -186,4 +188,8 @@ {/if} {/if} + + {#if data.channels} + + {/if}