From 53b66fc5666e06b07dc21949df5ed74973a0462b Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Wed, 25 Nov 2026 16:40:13 +0100
Subject: [PATCH 1/3] Feat: Add alerts webhooks
---
.env.example | 5 +
.github/copilot-instructions.md | 13 +-
CLAUDE.md | 59 +++-
README.md | 16 +-
docs/webhooks/README.md | 123 ++++++++
docs/webhooks/verify-signature.ts | 36 +++
e2e/global-setup.ts | 2 +
e2e/specs/alerts.spec.ts | 32 ++-
src/env.ts | 2 +
src/lib/components/alerts/AlertEditor.svelte | 2 +-
.../notifications/ChannelsSection.svelte | 264 ++++++++++++++++--
src/lib/database/schemas.ts | 9 +
src/lib/events/catalog/index.ts | 3 +
.../events/catalog/notifications.events.ts | 55 ++++
src/lib/events/catalog/types.ts | 2 +-
src/lib/events/domain-events.ts | 16 ++
src/lib/i18n/locales/en.json | 66 ++++-
src/lib/i18n/locales/es.json | 66 ++++-
src/lib/notifications/types.ts | 9 +
src/lib/server/alerts/operations.ts | 6 +-
.../server/infra/http/guarded-fetch.test.ts | 210 ++++++++++++++
src/lib/server/infra/http/guarded-fetch.ts | 182 ++++++++++++
src/lib/server/infra/http/webhook-request.ts | 72 ++++-
.../infra/notifications/chat-notification.ts | 42 ++-
src/lib/server/infra/notifications/index.ts | 2 +
.../notifications/webhook/webhook-payload.ts | 57 ++++
.../webhook/webhook-signature.test.ts | 77 +++++
.../webhook/webhook-signature.ts | 34 +++
.../webhook/webhook.transport.test.ts | 218 +++++++++++++++
.../webhook/webhook.transport.ts | 67 +++++
src/lib/server/notifications/channels-page.ts | 26 +-
src/lib/server/notifications/channels.ts | 39 ++-
.../alerts/application/alert-engine.test.ts | 22 ++
.../alerts/application/alert.channels.test.ts | 10 +-
.../domain/system-notifications.data.ts | 10 +-
.../infrastructure/alert-channel-message.ts | 17 ++
.../infrastructure/alert-mail.notifier.ts | 21 +-
.../notification-channel.service.test.ts | 255 ++++++++++++++++-
.../notification-channel.service.ts | 243 ++++++++++++++--
.../notifications/application/testing.ts | 44 ++-
.../domain/notification-channel.domain.ts | 49 +++-
src/modules/notifications/index.ts | 39 ++-
.../infrastructure/config/webhook.config.ts | 27 ++
.../infrastructure/crypto/channel-cipher.ts | 24 +-
.../notification-channel.repository.ts | 14 +-
src/routes/api/alerts/server.test.ts | 69 ++++-
.../[id]/rotate-secret/+server.ts | 8 +
.../api/notification-channels/server.test.ts | 60 +++-
.../org/[org]/settings/events/event-view.ts | 1 +
49 files changed, 2553 insertions(+), 172 deletions(-)
create mode 100644 docs/webhooks/README.md
create mode 100644 docs/webhooks/verify-signature.ts
create mode 100644 src/lib/events/catalog/notifications.events.ts
create mode 100644 src/lib/server/infra/http/guarded-fetch.test.ts
create mode 100644 src/lib/server/infra/http/guarded-fetch.ts
create mode 100644 src/lib/server/infra/notifications/webhook/webhook-payload.ts
create mode 100644 src/lib/server/infra/notifications/webhook/webhook-signature.test.ts
create mode 100644 src/lib/server/infra/notifications/webhook/webhook-signature.ts
create mode 100644 src/lib/server/infra/notifications/webhook/webhook.transport.test.ts
create mode 100644 src/lib/server/infra/notifications/webhook/webhook.transport.ts
create mode 100644 src/modules/notifications/infrastructure/config/webhook.config.ts
create mode 100644 src/routes/api/notification-channels/[id]/rotate-secret/+server.ts
diff --git a/.env.example b/.env.example
index 05d93c1..091c431 100644
--- a/.env.example
+++ b/.env.example
@@ -35,6 +35,11 @@ GITDB_SYNC_POLL_SECONDS=60
# NOTIFICATION_SMTP_FROM_NAME=GitOps
# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true # only set false for self-signed test servers
+# Generic webhook channels only reach public https URLs (no private, loopback, link-local, CGNAT,
+# multicast or cloud metadata addresses). Local development only: never enable in production.
+# NOTIFICATIONS_WEBHOOK_ALLOW_HTTP=false
+# NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS=false
+
# Optional cluster-wide Google sign-in (OpenID Connect). Shown on the login page when both the
# client ID and secret are set. Redirect URI to register in GCP: /auth/sso/google/callback
GOOGLE_SSO_CLIENT_ID=
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 1701f9b..78a27b4 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -122,10 +122,15 @@ verificación y desuscripción. En `/org//settings/alerts/settings`, admini
permitidos y canales (`NotificationChannelEntity` en GitDB). Alertas guardan `recipients` (usuarios, roles,
emails externos) y `channelIds` (referencias a canales, no destinatarios individuales). Canales de organización
se usan en alertas de org y proyecto; canales de proyecto solo en sus alertas. URLs de webhook se encriptan
-con `GITDB_ENCRYPTION_KEY` (AES-GCM por channel id). Emails externos: `pending` → `verified` → `unsubscribed`
-o `blocked` si dominio se quita; template reducido sin campos `sensitive` ni links; `List-Unsubscribe` HMAC
-(90 días). Canales: un mensaje por canal en paralelo, fallo de canal nunca afecta email. Rutas públicas
-`/notifications/verify` y `/notifications/unsubscribe` aceptan POST (no GET). Sin `ORIGIN` no se envía nada.
+con `GITDB_ENCRYPTION_KEY`. Emails externos: `pending` → `verified` → `unsubscribed` o `blocked`; template
+sin campos `sensitive` ni links; `List-Unsubscribe` HMAC (90 días). Canales: un mensaje por canal en paralelo,
+fallo de canal nunca afecta email. El tipo `webhook` se firma con HMAC-SHA256 (`X-GitOps-Signature`): secreto
+`whsec_…` se muestra una sola vez al crear o rotar (rotación con 24 h de gracia, ambos secretos validan durante
+el período); resuelve DNS rechazando IPs privadas/loopback/link-local/CGNAT/metadata (antes de guardar y cada
+envío), no sigue redirects, reintentos con backoff (20 fallos consecutivos deshabilitan automáticamente, evento
+`notifications.channel.disabled` con detalles del canal y error). Docs en `docs/webhooks/`. Variables:
+`NOTIFICATIONS_WEBHOOK_ALLOW_HTTP` y `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS` (solo dev/e2e). Rutas
+públicas `/notifications/verify` y `/notifications/unsubscribe` aceptan POST. Sin `ORIGIN` no se envía nada.
Al crear una organización (vía bootstrap o `/gitops-settings`), se llama automáticamente a
`roleService.createDefaultOrganizationRoles()`. Al crear un proyecto, se llama a
diff --git a/CLAUDE.md b/CLAUDE.md
index eb807dd..38ed87d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -248,8 +248,8 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
**anti-escalation** (the author must hold the event's `readPermission`).
- `AlertEngine` subscribes to `'*'` once per process (`registerAlertEngine()` in `hooks.server.ts`,
HMR-safe). Per event: fixed system notifications first (`system-notifications.data.ts`: access
- granted/updated/revoked to the affected user, new personal API keys to their owner, never to the
- actor, invitations skipped), then the enabled alerts of that type (cached 60 s, invalidated by
+ granted/updated/revoked to the affected user, new personal API keys to their owner, a self-disabled
+ notification channel to its creator, never to the actor, invitations skipped), then the enabled alerts of that type (cached 60 s, invalidated by
the service) whose location covers the event and whose conditions match. A per-alert in-memory
throttle (`throttleMinutes`) suppresses repeats and the next email reports how many were skipped.
- Recipients = selected users ∪ members with the selected roles, minus disabled users and users
@@ -281,7 +281,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
`GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test`
(dry runs that never touch the throttle; with `send: true`, `AlertEngine.sendTest()` also emails
the recipients a real event would reach, members filtered by cancan and verified externals only,
- with a `[Test]` subject; needs SMTP and is limited to 5 per caller every 10 minutes, in memory.
+ with a `[Test]` subject, and posts to the alert's channels; needs SMTP unless the alert has
+ channels (then only they get it), test messages never count toward a channel's failure streak,
+ and it is limited to 5 per caller every 10 minutes, in memory.
It also registers the draft's new external addresses, so they get the confirmation email and
receive the next test once confirmed, before the alert is saved).
Project API keys only reach their project.
@@ -324,14 +326,44 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
`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`). This base registers none: each
- transport (webhook, Slack, Google Chat) activates its own, and 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. `enabled` flag can disable delivery without deleting the channel.
+ (`#lib/server/infra/notifications/chat-notification.ts`) in the composition root
+ (`$modules/notifications/index.ts`); today only `webhook` is, and tests use `FakeChatTransport`.
+ A `ChatTransport` implements `send()` and `validateDestination()` (sync or async), the anti-SSRF
+ check run before saving and again before every send: `validateWebhookUrl()` for providers with a
+ fixed host (https, no credentials, no IP literal, default port, allowed host and path),
+ `validateOpenWebhookUrl()` for free URLs (resolves DNS and refuses private, loopback,
+ link-local, CGNAT, multicast and metadata addresses, IPv4-mapped IPv6 included). Send through
+ `createGuardedFetch()` (`#lib/server/infra/http/guarded-fetch.ts`): it connects only to the
+ checked address (no DNS rebinding), never follows redirects and drains at most 64 KB of the
+ answer. The destination (`webhookUrl`) is encrypted with `GITDB_ENCRYPTION_KEY`
+ (`channel-cipher.ts`, AES-GCM bound to the channel id and the value's purpose) and only ever
+ leaves the server masked (`https://hooks.slack.com/…/••••1a2b`); changing it means typing it
+ again. `enabled` flag can disable delivery without deleting the channel; `disabledReason:
+ 'failures'` means the platform disabled it after 20 consecutive failures.
+- Signed channels: webhook is a signed type. The service generates a signing secret on create
+ (`whsec_` + 32 random bytes, encrypted in `signingSecret`) and returns it in clear **only once**
+ from `createChannel()` or `POST /api/notification-channels/[id]/rotate-secret` (never readable
+ again). Rotation keeps the previous secret in `previousSigningSecret` for 24 h
+ (`previousSecretExpiresAt`); both are handed to `send()` in `ChatNotification.signingSecrets`
+ with a stable `deliveryId` per message so receivers can deduplicate retries. The signature is
+ `X-GitOps-Signature: t=,v1=[,v1=]` using `HMAC-SHA256(secret,
+ ".")` on the JSON sent (not encoded).
+- Generic webhook (`#lib/server/infra/notifications/webhook/`): `POST` with the versioned
+ `WebhookPayload` (`version`, `deliveryId`, `test`, `alert`, `event` with the raw non-sensitive
+ catalog `fields` from `ChannelMessage.event.fields`, `link`), headers `X-GitOps-Event`,
+ `X-GitOps-Delivery`, `X-GitOps-Signature` (`HMAC-SHA256` of the timestamp and body) and
+ `User-Agent: GitOps-Webhooks/1`. All webhooks are signed: `createChannel()` and `rotateChannelSecret()`
+ return the secret in `signingSecret` once; the service encrypts it after and never shows it again.
+ Receiver docs and the verification example are in `docs/webhooks/` (the example is unit-tested
+ and must stay identical in the README). `NOTIFICATIONS_WEBHOOK_ALLOW_HTTP` /
+ `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS` relax the rules for local development and e2e only.
+- Failure streaks: every definitive delivery failure of a real message (not tests, not
+ `unavailable` types) increments `consecutiveFailures` (one commit each per channel); a success
+ resets it. At 20 (`MAX_CONSECUTIVE_FAILURES`) the channel disables itself (`enabled: false`,
+ `disabledReason: 'failures'`) and publishes `notifications.channel.disabled` (system actor,
+ organization alertable event with `organization:notifications:read`, payload includes channel
+ name, type, failure count and last error). The channel creator gets emailed the `channel_disabled`
+ system notice. Re-enabling resets the streak.
- Channel delivery: alerts store `channelIds` (references to `NotificationChannelEntity`). Adding
a channel needs `:notifications:update` (`forbidden_channel`), and a channel must be
usable from the alert's location (`unknown_channel`). The engine emails each recipient and
@@ -348,8 +380,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- Channels HTTP: `#lib/server/notifications/channels.ts` (permission-first with
`:notifications:read|create|update|delete`; 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). Form actions for the settings pages live in
+ `GET|PATCH|DELETE /api/notification-channels/[id]`, `POST /api/notification-channels/[id]/test`
+ (posts a test even to a disabled channel) and `POST /api/notification-channels/[id]/rotate-secret`
+ (`update` permission, returns the new secret once). Form actions for the settings pages live in
`#lib/server/notifications/channels-page.ts`; the UI is `ChannelsSection`
(`#lib/components/notifications/`), and the alert editors pick channels from `data.channels`
(the alert's draft has `channelIds: string[]`, not direct recipients by channel type).
diff --git a/README.md b/README.md
index a6a7f56..ffcdd12 100644
--- a/README.md
+++ b/README.md
@@ -139,8 +139,9 @@ vulnerabilities*.
*greater than* `0`.
4. Recipients: the **Project Admin** role. Throttle: one email every **30** minutes at most.
5. **Test alert** shows whether an example event matches and who would get the email, without
- sending anything. **Send test email** also emails those recipients with an example event and a
- `[Test]` subject (external addresses only once confirmed). Then **Create alert**.
+ sending anything. **Send test** also sends the example event to every destination: an email
+ with a `[Test]` subject to those recipients (external addresses only once confirmed) and a
+ message to each selected channel. Then **Create alert**.
The same alert through the API (`gvs_` project keys only manage alerts of their own project):
@@ -198,8 +199,15 @@ emails or the other channels.
Adding channels to an alert needs `organization:notifications:update` or
`project:notifications:update`: people reading a channel may have no access to the resource.
-Messages leave out sensitive fields. Channel types become available as their transports land
-(generic webhooks, Slack and Google Chat); until then the settings say no type is available yet.
+Messages leave out sensitive fields. Channel types become available as their transports land:
+generic webhooks are available; Slack and Google Chat are not yet.
+
+A **webhook** channel posts a versioned JSON body to any public `https` URL, signed with
+HMAC-SHA256 in `X-GitOps-Signature`. Its signing secret is shown once when the channel is created
+(and when it is rotated; the previous secret keeps signing for 24 hours). Private, loopback,
+link-local and cloud metadata addresses are refused, and redirects are never followed. A channel
+that fails 20 deliveries in a row disables itself and its creator is emailed. The request format,
+retries and how to verify the signature are in [docs/webhooks](docs/webhooks/README.md).
### Monitoring
diff --git a/docs/webhooks/README.md b/docs/webhooks/README.md
new file mode 100644
index 0000000..5c8e712
--- /dev/null
+++ b/docs/webhooks/README.md
@@ -0,0 +1,123 @@
+# Generic webhooks
+
+A **webhook** notification channel posts every alert it is attached to as a signed JSON request
+to a URL you choose. It is created from the alert settings ("Settings" in an alert list → Channels)
+of an organization (usable by every project of it) or of a project.
+
+## The request
+
+```http
+POST
+Content-Type: application/json
+User-Agent: GitOps-Webhooks/1
+X-GitOps-Event: code_report.analysis.completed
+X-GitOps-Delivery: 3f0c6c3e-2a0e-4f43-9f87-6a0f1d1c2b55
+X-GitOps-Signature: t=1764000000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
+```
+
+```json
+{
+ "version": 1,
+ "deliveryId": "3f0c6c3e-2a0e-4f43-9f87-6a0f1d1c2b55",
+ "test": false,
+ "alert": { "id": "…", "name": "Critical vulnerabilities" },
+ "event": {
+ "id": "…",
+ "type": "code_report.analysis.completed",
+ "occurredAt": "2026-11-25T10:00:00.000Z",
+ "scope": { "organizationId": "…", "projectId": "…" },
+ "fields": { "serviceId": "…", "tool": "trivy", "summary.critical": 3 }
+ },
+ "link": "https://gitops.example.com/org/acme/projects/web/…"
+}
+```
+
+- `version` only changes when a field is removed or renamed; new fields may appear in version 1,
+ so ignore the ones you don't know.
+- `event.fields` holds the event catalog values (ids, enums, numbers), the same fields alerts can
+ filter on. Fields marked sensitive are never sent; there are no templates nor HTML.
+- `link` is `null` when the server has no `ORIGIN`.
+- "Send test message" posts `event.type: "channel.test"` with `test: true`, no alert and empty
+ `fields`. Alert test sends carry the real event shape with `test: true`.
+- `X-GitOps-Delivery` is the same on every retry of one delivery: use it to deduplicate.
+
+Any `2xx` answer is a success. The answer body is read up to 64 KB and discarded. Redirects are
+never followed (a `3xx` is a failure). Each attempt times out after 5 s.
+
+## Retries and automatic disabling
+
+Network errors, timeouts, `429` (honoring `Retry-After`, up to 60 s) and `5xx` are retried up to 4
+attempts (1 s → 4 s → 16 s, with jitter). Other `4xx` answers are final. After **20 failed
+deliveries in a row** the channel disables itself, its creator gets an email and the
+`notifications.channel.disabled` event is published (organizations can alert on it). Enabling the
+channel again resets the count. Test messages never count.
+
+## Verifying the signature
+
+`X-GitOps-Signature` is `t=,v1=`, where the signature is
+`HMAC-SHA256(secret, ".")` and the secret is the whole `whsec_…` string shown when
+the channel was created. To verify a delivery:
+
+1. Take the body **exactly as received**, before parsing it (re-serialized JSON won't match).
+2. Recompute the HMAC with your secret and compare it with each `v1=` value in constant time.
+3. Reject deliveries whose `t` is more than 5 minutes away from your clock (replays).
+
+```ts
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+/** How far `t` may be from the receiver's clock: older deliveries are replays. */
+export const TOLERANCE_SECONDS = 5 * 60;
+
+/**
+ * Verifies the `X-GitOps-Signature` header of a GitOps webhook delivery.
+ *
+ * @param rawBody the request body exactly as received (before any JSON parsing)
+ * @param header the `X-GitOps-Signature` header (`t=,v1=[,v1=]`)
+ * @param secret the channel's signing secret (`whsec_…`)
+ */
+export function verifyGitOpsSignature(
+ rawBody: string,
+ header: string | null,
+ secret: string,
+ nowSeconds: number = Math.floor(Date.now() / 1000),
+): boolean {
+ if (!header) return false;
+ let timestamp = Number.NaN;
+ const signatures: string[] = [];
+ for (const part of header.split(',')) {
+ const [key, value] = part.trim().split('=', 2);
+ if (key === 't') timestamp = Number(value);
+ else if (key === 'v1' && value) signatures.push(value);
+ }
+ if (!Number.isInteger(timestamp) || signatures.length === 0) return false;
+ if (Math.abs(nowSeconds - timestamp) > TOLERANCE_SECONDS) return false;
+
+ const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
+ // during a secret rotation there are two `v1=`: any of them may match
+ return signatures.some((signature) => {
+ const received = Buffer.from(signature, 'hex');
+ return received.length === expected.length && timingSafeEqual(received, expected);
+ });
+}
+```
+
+`docs/webhooks/verify-signature.ts` holds this same code and is covered by the unit tests.
+
+## Rotating the secret
+
+"Rotate signing secret" shows a new secret once. For the next **24 hours** every delivery is
+signed with both secrets (`t=…,v1=,v1=`), so you can deploy the new secret to the
+receiver without losing deliveries; after that only the new one signs. Rotating again during the
+grace period drops the oldest secret.
+
+## Network rules (anti-SSRF)
+
+The URL must be `https`, without user or password. Its host is resolved when the channel is saved
+and before every delivery, and it is refused when **any** address is private, loopback,
+link-local, CGNAT, multicast, reserved or the cloud metadata one (`169.254.169.254`), IPv4 and IPv6
+(IPv4-mapped forms included). The request then connects only to the address that was checked, so
+DNS rebinding can't redirect it. For local development only, `NOTIFICATIONS_WEBHOOK_ALLOW_HTTP`
+and `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS` lift these rules.
+
+The URL and the secret are stored encrypted (`GITDB_ENCRYPTION_KEY`), never returned by the API
+(the secret only in the create / rotate response) and never logged.
diff --git a/docs/webhooks/verify-signature.ts b/docs/webhooks/verify-signature.ts
new file mode 100644
index 0000000..e187ef9
--- /dev/null
+++ b/docs/webhooks/verify-signature.ts
@@ -0,0 +1,36 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+/** How far `t` may be from the receiver's clock: older deliveries are replays. */
+export const TOLERANCE_SECONDS = 5 * 60;
+
+/**
+ * Verifies the `X-GitOps-Signature` header of a GitOps webhook delivery.
+ *
+ * @param rawBody the request body exactly as received (before any JSON parsing)
+ * @param header the `X-GitOps-Signature` header (`t=,v1=[,v1=]`)
+ * @param secret the channel's signing secret (`whsec_…`)
+ */
+export function verifyGitOpsSignature(
+ rawBody: string,
+ header: string | null,
+ secret: string,
+ nowSeconds: number = Math.floor(Date.now() / 1000),
+): boolean {
+ if (!header) return false;
+ let timestamp = Number.NaN;
+ const signatures: string[] = [];
+ for (const part of header.split(',')) {
+ const [key, value] = part.trim().split('=', 2);
+ if (key === 't') timestamp = Number(value);
+ else if (key === 'v1' && value) signatures.push(value);
+ }
+ if (!Number.isInteger(timestamp) || signatures.length === 0) return false;
+ if (Math.abs(nowSeconds - timestamp) > TOLERANCE_SECONDS) return false;
+
+ const expected = createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest();
+ // during a secret rotation there are two `v1=`: any of them may match
+ return signatures.some((signature) => {
+ const received = Buffer.from(signature, 'hex');
+ return received.length === expected.length && timingSafeEqual(received, expected);
+ });
+}
diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts
index 81464ee..4a9b004 100644
--- a/e2e/global-setup.ts
+++ b/e2e/global-setup.ts
@@ -66,6 +66,8 @@ function buildEnv(): Record {
MONITORING_INTERNAL_HOSTS: '',
MONITORING_EMBEDDED_WORKER: 'true',
MONITORING_ALLOW_PRIVATE_TARGETS: 'true',
+ // webhook channels are created with a URL nobody resolves; no delivery is attempted
+ NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS: 'true',
PORT: String(E2E_PORT),
};
}
diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts
index 1976df0..d3dc590 100644
--- a/e2e/specs/alerts.spec.ts
+++ b/e2e/specs/alerts.spec.ts
@@ -248,9 +248,37 @@ test.describe('organization alerts', () => {
await page.waitForLoadState('networkidle');
await page.getByTestId('alert-settings').click();
const dialog = page.getByRole('dialog', { name: 'Configuración de alertas' });
- await expect(dialog.getByTestId('notification-channels')).toBeVisible();
- await expect(dialog.getByTestId('channel-types-unavailable')).toBeVisible();
+ const channels = dialog.getByTestId('notification-channels');
+ await expect(channels).toBeVisible();
await expect(dialog.getByLabel('Dominios (uno por línea)')).toHaveCount(0);
+
+ // a webhook channel shows its signing secret once, and rotating it asks first
+ const types = channels.getByTestId('channel-type-cards');
+ await expect(types.getByRole('radio', { name: /Slack/ })).toBeDisabled();
+ await expect(types.getByRole('radio', { name: /Google Chat/ })).toBeDisabled();
+ await expect(types.locator('[data-channel-type="slack"]')).toContainText('Próximamente');
+ await expect(types.getByRole('radio', { name: /Webhook/ })).toBeChecked();
+ await channels.getByLabel('Nombre', { exact: true }).fill('SIEM e2e');
+ await channels.getByLabel('URL del webhook').fill('https://receiver.example.com/gitops');
+ await channels.getByRole('button', { name: 'Añadir canal' }).click();
+
+ const secret = page.getByRole('dialog', { name: 'Secreto de firma' });
+ await expect(secret.getByTestId('channel-secret')).toHaveText(/^whsec_[0-9a-f]{64}$/);
+ const first = await secret.getByTestId('channel-secret').textContent();
+ await secret.getByTestId('channel-secret-done').click();
+ await expect(secret).toBeHidden();
+
+ const row = channels.locator('li[data-channel-id]').filter({ hasText: 'SIEM e2e' });
+ await expect(row).toContainText('Firmado');
+ await expect(row).not.toContainText('whsec_');
+
+ await row.getByTestId('channel-rotate').click();
+ const confirm = page.getByRole('alertdialog', { name: '¿Rotar el secreto de firma?' });
+ await confirm.getByTestId('channel-rotate-confirm').click();
+ await expect(secret.getByTestId('channel-secret')).toHaveText(/^whsec_[0-9a-f]{64}$/);
+ await expect(secret.getByTestId('channel-secret')).not.toHaveText(first!);
+ await secret.getByTestId('channel-secret-done').click();
+ await expect(row).toContainText('El secreto anterior es válido hasta');
});
test('a project viewer gets no settings button', async ({ page, loginAs }) => {
diff --git a/src/env.ts b/src/env.ts
index 8394cfa..8a4bf4e 100644
--- a/src/env.ts
+++ b/src/env.ts
@@ -25,6 +25,8 @@ export const variables = defineEnvVars({
NOTIFICATION_SMTP_FROM: optional,
NOTIFICATION_SMTP_FROM_NAME: optional,
NOTIFICATION_SMTP_REJECT_UNAUTHORIZED: optional,
+ NOTIFICATIONS_WEBHOOK_ALLOW_HTTP: optional,
+ NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS: optional,
GOOGLE_SSO_CLIENT_ID: optional,
GOOGLE_SSO_CLIENT_SECRET: optional,
GOOGLE_SSO_ALLOWED_DOMAINS: optional,
diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte
index a196090..192fdb7 100644
--- a/src/lib/components/alerts/AlertEditor.svelte
+++ b/src/lib/components/alerts/AlertEditor.svelte
@@ -629,7 +629,7 @@
name="send"
value="true"
class="k-btn k-btn-secondary"
- disabled={busy !== null || !data.mailConfigured}
+ disabled={busy !== null || (!data.mailConfigured && draft.channelIds.length === 0)}
title={$_('alerts.editor.sendTestHelp')}
data-testid="alert-send-test"
>
diff --git a/src/lib/components/notifications/ChannelsSection.svelte b/src/lib/components/notifications/ChannelsSection.svelte
index cb4cb70..b0a7804 100644
--- a/src/lib/components/notifications/ChannelsSection.svelte
+++ b/src/lib/components/notifications/ChannelsSection.svelte
@@ -3,12 +3,16 @@
import type { SubmitFunction } from '$app/forms';
import { invalidateAll } from '$app/navigation';
import {
+ Check,
+ Copy,
Hash,
+ KeyRound,
LoaderCircle,
MessageSquare,
Pencil,
Plus,
Power,
+ RefreshCw,
Send,
ShieldAlert,
Trash2,
@@ -31,6 +35,14 @@
webhook: Webhook,
};
+ /** Every channel type, available or not: the ones without a transport show as coming soon. */
+ const CHANNEL_TYPES = ['webhook', 'slack', 'google-chat'] as const;
+ const typeDescriptions: Record<(typeof CHANNEL_TYPES)[number], string> = {
+ webhook: 'alerts.wizard.webhookDescription',
+ slack: 'alerts.wizard.slackDescription',
+ 'google-chat': 'alerts.wizard.googleChatDescription',
+ };
+
let busy = $state(null);
let createErrors = $state>({});
let editErrors = $state>({});
@@ -38,6 +50,43 @@
let editOpen = $state(false);
let deleteTarget = $state(null);
let deleteOpen = $state(false);
+ let rotateTarget = $state(null);
+ let rotateOpen = $state(false);
+ /** Secret just issued (create / rotate): shown once, dropped when the modal closes. */
+ let issuedSecret = $state<{ channelId: string; secret: string; rotated?: boolean } | null>(null);
+ let secretOpen = $state(false);
+ let createType = $state('');
+ const selectedType = $derived(
+ createType || (form?.channelDraft?.type ?? data.availableTypes[0] ?? ''),
+ );
+
+ function showSecret(data: Record | undefined) {
+ const issued = data?.channelSecret as typeof issuedSecret;
+ if (!issued?.secret) return;
+ issuedSecret = issued;
+ secretOpen = true;
+ }
+
+ $effect(() => {
+ // nothing of the secret stays in memory once the modal is closed
+ if (!secretOpen) issuedSecret = null;
+ });
+
+ async function copySecret() {
+ if (!issuedSecret) return;
+ try {
+ await navigator.clipboard.writeText(issuedSecret.secret);
+ toast.success($_('notifications.channels.secretCopied'));
+ } catch {
+ toast.error($_('alerts.wizard.failed'));
+ }
+ }
+
+ function openRotate(event: MouseEvent, channel: ChannelView) {
+ event.preventDefault();
+ rotateTarget = channel;
+ rotateOpen = true;
+ }
const formCreateErrors = $derived(
form?.channelForm === 'create' ? (form.channelErrors ?? {}) : {},
@@ -94,9 +143,15 @@
};
};
- const create = submit('create', () => {
+ const create = submit('create', (result) => {
createErrors = {};
toast.success($_('notifications.channels.created'));
+ showSecret(result);
+ });
+ const rotate = submit('rotate', (result) => {
+ rotateOpen = false;
+ toast.success($_('notifications.channels.rotated'));
+ showSecret(result);
});
const edit = submit('edit', () => {
editOpen = false;
@@ -145,6 +200,19 @@
{$_('notifications.channels.privacyNotice')}
+ {#if form?.channelSecret}
+
+
+
+ {$_('notifications.channels.secretTitle')}
+
+
{$_('notifications.channels.secretDescription')}
+
{form.channelSecret.secret}
+
+ {/if}
+
{#if form?.channelTest}
{#if !channel.enabled}
-
+
{$_('notifications.channels.disabled')}
{/if}
+ {#if channel.signed}
+
+ {$_('notifications.channels.signed')}
+
+ {/if}
{#if !channel.available}
{$_('notifications.channels.unavailable')}
@@ -207,6 +284,20 @@
{$_('notifications.channels.lastError', { values: { error: channel.lastError } })}
{/if}
+ {#if !channel.enabled && channel.disabledReason === 'failures'}
+
+ {$_('notifications.channels.autoDisabled', {
+ values: { failures: channel.consecutiveFailures },
+ })}
+
+ {/if}
+ {#if channel.rotationEndsAt}
+
+ {$_('notifications.channels.rotationEndsAt', {
+ values: { date: formatDate(channel.rotationEndsAt) },
+ })}
+
+ {/if}
@@ -243,6 +334,22 @@
+ {#if channel.signed && channel.available}
+
+ {/if}
-
-
{$_('notifications.channels.type')}
-
- {#each data.availableTypes as type (type)}
- {$_(`notifications.channels.types.${type}`)}
+
+
+ {$_('notifications.channels.type')}
+
+ {#each CHANNEL_TYPES as type (type)}
+ {@const Icon = typeIcons[type] ?? Webhook}
+ {@const available = data.availableTypes.includes(type)}
+ {@const on = available && selectedType === type}
+
+ (createType = type)}
+ />
+
+
+ {$_(`notifications.channels.types.${type}`)}
+
+ {$_(typeDescriptions[type])}
+ {#if available}
+ {#if on} {/if}
+ {:else}
+ {$_('notifications.channels.comingSoon')}
+ {/if}
+
{/each}
-
- {#if errors.type}
+
+ {#if errors.type}
{errorText(errors, 'type')}
{/if}
-
-
+
+
{$_('notifications.channels.name')}
{#if errors.destination}
{errorText(errors, 'destination')}
+ {:else if selectedType === 'webhook'}
+
{$_('notifications.channels.webhookHelp')}
{/if}
@@ -479,3 +628,82 @@
{/snippet}
{/if}
+
+{#if data.canUpdate}
+
+ {#snippet icon()}
+
+ {/snippet}
+
+ {#snippet footer()}
+ (rotateOpen = false)}
+ >{$_('common.cancel')}
+
+ {#if busy === 'rotate'} {/if}
+ {$_('notifications.channels.rotate')}
+
+ {/snippet}
+
+{/if}
+
+
+ {#snippet icon()}
+
+ {/snippet}
+ {#if issuedSecret}
+
+ {issuedSecret.secret}
+
+ {$_('notifications.channels.secretCopy')}
+
+
+ {/if}
+ {#snippet footer()}
+ (secretOpen = false)}
+ data-autofocus
+ data-testid="channel-secret-done">{$_('notifications.channels.secretDone')}
+ {/snippet}
+
diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts
index a9e5f5a..1efcad1 100644
--- a/src/lib/database/schemas.ts
+++ b/src/lib/database/schemas.ts
@@ -449,6 +449,15 @@ export const NotificationChannelEntity = entity('notification_channels', {
.$defaultFn(() => new Date().toISOString()),
lastDeliveryAt: timestamp(),
lastError: text(),
+ /** Signing secret of signed types (`webhook`), encrypted like `webhookUrl`. */
+ signingSecret: text(),
+ /** Previous signing secret, still used to sign until `previousSecretExpiresAt` (rotation). */
+ previousSigningSecret: text(),
+ previousSecretExpiresAt: timestamp(),
+ /** Definitive delivery failures in a row; the channel disables itself at the limit. */
+ consecutiveFailures: integer().notNull().default(0),
+ /** Why the platform disabled it (`failures`); `null` when enabled or disabled by a person. */
+ disabledReason: text(),
});
relations.for(ProjectEntity, ({ one, many }) => ({
diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts
index 75ff2c5..9121661 100644
--- a/src/lib/events/catalog/index.ts
+++ b/src/lib/events/catalog/index.ts
@@ -5,6 +5,7 @@ import { projectEvents } from './projects.events';
import { organizationEvents } from './organization.events';
import { accessEvents } from './access.events';
import { monitoringEvents } from './monitoring.events';
+import { notificationEvents } from './notifications.events';
import type {
EventCatalog,
EventDefinition,
@@ -21,6 +22,7 @@ export { PROJECT_CHANGED_FIELDS } from './projects.events';
export { ORGANIZATION_CHANGED_FIELDS } from './organization.events';
export { ACCESS_SCOPES } from './access.events';
export { MONITORING_CAUSES } from './monitoring.events';
+export { CHANNEL_TYPE_OPTIONS } from './notifications.events';
export {
PROJECT_SCOPE_FIELD,
isScopeField,
@@ -53,6 +55,7 @@ export const EVENT_CATALOG: EventCatalog = defineEventCatalog({
...organizationEvents,
...accessEvents,
...monitoringEvents,
+ ...notificationEvents,
});
export function isEventType(value: string): value is EventType {
diff --git a/src/lib/events/catalog/notifications.events.ts b/src/lib/events/catalog/notifications.events.ts
new file mode 100644
index 0000000..1eba8ab
--- /dev/null
+++ b/src/lib/events/catalog/notifications.events.ts
@@ -0,0 +1,55 @@
+import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields';
+import type { EventDefinitions } from './types';
+import { organizationPath, projectPath } from './links';
+
+/** Values of `notification_channels.type` (`#lib/server/infra/notifications/chat-types`). */
+const CHANNEL_TYPES = ['webhook', 'slack', 'google-chat'] as const;
+export const CHANNEL_TYPE_OPTIONS = enumOptions('channelType', CHANNEL_TYPES);
+
+const DISABLED = 'notifications.channel.disabled';
+
+export const notificationEvents: EventDefinitions
= {
+ [DISABLED]: {
+ // where the channel is managed: the alert settings of its project or organization
+ link: (context) =>
+ context.projectSlug
+ ? projectPath(context, '/settings/alerts')
+ : organizationPath(context, '/settings/alerts'),
+ mailSummary: ({ name, failures }) => ({
+ key: 'alerts.email.summary.channelDisabled',
+ values: { name, failures },
+ }),
+ ...eventText(DISABLED),
+ module: 'notifications',
+ scope: 'organization',
+ readPermission: 'organization:notifications:read',
+ alertable: true,
+ fields: [
+ {
+ key: 'type',
+ label: fieldLabel(DISABLED, 'type'),
+ type: 'enum',
+ options: CHANNEL_TYPE_OPTIONS,
+ operators: OPERATORS.enum,
+ },
+ {
+ key: 'name',
+ label: fieldLabel(DISABLED, 'name'),
+ type: 'string',
+ operators: OPERATORS.string,
+ },
+ {
+ key: 'failures',
+ label: fieldLabel(DISABLED, 'failures'),
+ type: 'number',
+ operators: OPERATORS.number,
+ },
+ {
+ key: 'lastError',
+ label: fieldLabel(DISABLED, 'lastError'),
+ type: 'string',
+ operators: OPERATORS.string,
+ },
+ ],
+ },
+};
diff --git a/src/lib/events/catalog/types.ts b/src/lib/events/catalog/types.ts
index 6ba4b9f..10c6b1e 100644
--- a/src/lib/events/catalog/types.ts
+++ b/src/lib/events/catalog/types.ts
@@ -33,7 +33,7 @@ export type FieldReference =
| 'monitor';
export type EventModule =
- 'code_report' | 'vault' | 'projects' | 'organization' | 'access' | 'monitoring';
+ 'code_report' | 'vault' | 'projects' | 'organization' | 'access' | 'monitoring' | 'notifications';
export type EventDefinitionScope = 'organization' | 'project';
diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts
index 7a8b541..ab9bec3 100644
--- a/src/lib/events/domain-events.ts
+++ b/src/lib/events/domain-events.ts
@@ -195,6 +195,21 @@ export type MonitoringMonitorStatusPayload = {
durationSeconds: number | null;
};
+/**
+ * A notification channel disabled itself after too many delivery failures in a row. Never carries
+ * the destination nor any secret: `lastError` is the short reason (`HTTP 410`, `timeout`).
+ */
+export type NotificationChannelDisabledPayload = {
+ channelId: string;
+ name: string;
+ /** `webhook`, `slack`, `google-chat` */
+ type: string;
+ reason: 'failures';
+ failures: number;
+ lastError: string;
+ createdByUserId: string;
+};
+
export interface DomainEventMap {
'code_report.analysis.completed': CodeReportAnalysisCompletedPayload;
'code_report.analysis.failed': CodeReportAnalysisFailedPayload;
@@ -222,6 +237,7 @@ export interface DomainEventMap {
'monitoring.monitor.down': MonitoringMonitorStatusPayload;
'monitoring.monitor.degraded': MonitoringMonitorStatusPayload;
'monitoring.monitor.recovered': MonitoringMonitorStatusPayload;
+ 'notifications.channel.disabled': NotificationChannelDisabledPayload;
}
export type EventType = Extract;
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json
index fb75b7d..e150909 100644
--- a/src/lib/i18n/locales/en.json
+++ b/src/lib/i18n/locales/en.json
@@ -599,7 +599,8 @@
"projects": "Projects",
"organization": "Organization",
"access": "Access",
- "monitoring": "Monitoring"
+ "monitoring": "Monitoring",
+ "notifications": "Notifications"
}
},
"current": "Current",
@@ -1404,6 +1405,11 @@
"too_many_redirects": "Too many redirects",
"invalid_url": "Invalid URL",
"error": "Error"
+ },
+ "channelType": {
+ "webhook": "Webhook",
+ "slack": "Slack",
+ "google-chat": "Google Chat"
}
},
"vault": {
@@ -1621,6 +1627,20 @@
}
}
}
+ },
+ "notifications": {
+ "channel": {
+ "disabled": {
+ "label": "Channel disabled automatically",
+ "description": "A notification channel failed too many deliveries in a row and was disabled.",
+ "fields": {
+ "type": "Channel type",
+ "name": "Channel name",
+ "failures": "Failures in a row",
+ "lastError": "Last error"
+ }
+ }
+ }
}
},
"alerts": {
@@ -1650,7 +1670,12 @@
"body": "The personal API key “{name}” ({prefix}…) was created on your account.",
"warning": "If it wasn’t you, revoke the API key and change your password as soon as possible."
},
- "openProfile": "Open my profile"
+ "openProfile": "Open my profile",
+ "channel_disabled": {
+ "subject": "The channel “{name}” was disabled",
+ "body": "The notification channel “{name}” in {target} failed {failures} deliveries in a row (last error: {error}) and GitOps disabled it. Alerts will not post to it until it is enabled again.",
+ "warning": "Check that the destination still works, then enable the channel again from the alert settings."
+ }
},
"manageAlert": "Manage the alert",
"viewInApp": "View in GitOps",
@@ -1674,7 +1699,8 @@
"policyViolated": "“{policy}” violated ({count})",
"monitorDown": "{name} is down ({cause})",
"monitorDegraded": "{name} is degraded",
- "monitorRecovered": "{name} recovered after {minutes} min"
+ "monitorRecovered": "{name} recovered after {minutes} min",
+ "channelDisabled": "{name} disabled after {failures} failures"
},
"externalFooter": "You receive this email because {organization} added your address to the alert “{alert}”.",
"unsubscribe": "Unsubscribe",
@@ -1723,8 +1749,8 @@
"invalid_url": "Use a valid http(s) URL.",
"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.",
+ "mail_not_configured": "SMTP is not configured and the alert has no channels: there is nowhere to send the test.",
+ "test_rate_limited": "You sent too many tests. 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."
},
@@ -1819,9 +1845,9 @@
"externalDisabled": "The organization does not allow external recipients.",
"externalSettingsLink": "Configure allowed domains",
"externalStatus": "Status of the external emails",
- "sendTest": "Send test email",
+ "sendTest": "Send test",
"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 an example event to every destination of the alert: an email to the recipients that would get it (external ones only once confirmed) and a message to each selected channel.",
"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",
@@ -1835,10 +1861,10 @@
"recipients": "It would be sent to: {names}",
"noRecipients": "It would not be sent to anyone.",
"denied": "{count} recipients would not get it because they cannot view this event.",
- "nothingSent": "This is a test: no email was sent.",
+ "nothingSent": "This is a dry run: nothing was sent.",
"externalDelivers": "would get it",
"externalSkipped": "would not get it ({status})",
- "delivered": "Test email sent: {sent} sent, {failed} failed.",
+ "delivered": "Test sent: {sent} delivered, {failed} failed.",
"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)"
@@ -2143,7 +2169,10 @@
"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."
+ "path_not_allowed": "The URL path does not match this channel type.",
+ "private_address": "The URL points to a private or internal address.",
+ "unresolvable": "The URL host could not be resolved.",
+ "not_signed": "This channel type does not sign its messages."
},
"link": {
"invalid": "This link is not valid or has already been used.",
@@ -2217,7 +2246,22 @@
"deleted": "Channel deleted",
"disabledToast": "Channel disabled",
"enabledToast": "Channel enabled",
- "deleteTitle": "Delete the channel?"
+ "deleteTitle": "Delete the channel?",
+ "autoDisabled": "Disabled after {failures} failed deliveries in a row",
+ "signed": "Signed",
+ "rotate": "Rotate signing secret",
+ "rotateTitle": "Rotate the signing secret?",
+ "confirmRotate": "A new secret will be generated. For the next 24 hours deliveries are signed with both the new and the current secret, so the receiver can switch over; after that only the new one is valid.",
+ "rotated": "Signing secret rotated",
+ "rotationEndsAt": "Previous secret valid until {date}",
+ "secretTitle": "Signing secret",
+ "secretDescription": "Copy it now and configure it in the receiver: it will not be shown again. Each delivery carries an X-GitOps-Signature header made with it.",
+ "secretCopy": "Copy",
+ "secretCopied": "Secret copied",
+ "secretDone": "I have saved it",
+ "secretDocs": "How to verify the signature",
+ "webhookHelp": "Any public https URL. GitOps signs each request with HMAC-SHA256 and never follows redirects.",
+ "comingSoon": "Coming soon"
}
}
}
diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json
index efbca96..833f580 100644
--- a/src/lib/i18n/locales/es.json
+++ b/src/lib/i18n/locales/es.json
@@ -599,7 +599,8 @@
"projects": "Proyectos",
"organization": "Organización",
"access": "Accesos",
- "monitoring": "Monitoring"
+ "monitoring": "Monitoring",
+ "notifications": "Notificaciones"
}
},
"current": "Actual",
@@ -1404,6 +1405,11 @@
"too_many_redirects": "Demasiadas redirecciones",
"invalid_url": "URL no válida",
"error": "Error"
+ },
+ "channelType": {
+ "webhook": "Webhook",
+ "slack": "Slack",
+ "google-chat": "Google Chat"
}
},
"vault": {
@@ -1621,6 +1627,20 @@
}
}
}
+ },
+ "notifications": {
+ "channel": {
+ "disabled": {
+ "label": "Canal deshabilitado automáticamente",
+ "description": "Un canal de notificaciones ha fallado demasiados envíos seguidos y se ha deshabilitado.",
+ "fields": {
+ "type": "Tipo de canal",
+ "name": "Nombre del canal",
+ "failures": "Fallos seguidos",
+ "lastError": "Último error"
+ }
+ }
+ }
}
},
"alerts": {
@@ -1650,7 +1670,12 @@
"body": "Se ha creado la API key personal «{name}» ({prefix}…) en tu cuenta.",
"warning": "Si no has sido tú, revoca la API key y cambia tu contraseña cuanto antes."
},
- "openProfile": "Abrir mi perfil"
+ "openProfile": "Abrir mi perfil",
+ "channel_disabled": {
+ "subject": "Se ha deshabilitado el canal «{name}»",
+ "body": "El canal de notificaciones «{name}» de {target} ha fallado {failures} envíos seguidos (último error: {error}) y GitOps lo ha deshabilitado. Las alertas no publicarán en él hasta que se vuelva a habilitar.",
+ "warning": "Comprueba que el destino sigue funcionando y vuelve a habilitar el canal desde los ajustes de alertas."
+ }
},
"manageAlert": "Gestionar la alerta",
"viewInApp": "Ver en GitOps",
@@ -1674,7 +1699,8 @@
"policyViolated": "«{policy}» incumplida ({count})",
"monitorDown": "{name} está caído ({cause})",
"monitorDegraded": "{name} responde degradado",
- "monitorRecovered": "{name} se ha recuperado tras {minutes} min"
+ "monitorRecovered": "{name} se ha recuperado tras {minutes} min",
+ "channelDisabled": "{name} deshabilitado tras {failures} fallos"
},
"externalFooter": "Recibes este email porque {organization} añadió tu dirección a la alerta “{alert}”.",
"unsubscribe": "Darme de baja",
@@ -1723,8 +1749,8 @@
"invalid_url": "Usa una URL http(s) válida.",
"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.",
+ "mail_not_configured": "El SMTP no está configurado y la alerta no tiene canales: no hay a dónde enviar la prueba.",
+ "test_rate_limited": "Has enviado demasiadas pruebas. 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."
},
@@ -1819,9 +1845,9 @@
"externalDisabled": "La organización no permite destinatarios externos.",
"externalSettingsLink": "Configurar dominios permitidos",
"externalStatus": "Estado de los emails externos",
- "sendTest": "Enviar email de prueba",
+ "sendTest": "Enviar 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 evento de ejemplo a todos los destinos de la alerta: email a los destinatarios que lo recibirían (los externos solo si están confirmados) y un mensaje a cada canal seleccionado.",
"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",
@@ -1835,10 +1861,10 @@
"recipients": "Se enviaría a: {names}",
"noRecipients": "No se enviaría a nadie.",
"denied": "{count} destinatarios no lo recibirían porque no pueden ver este evento.",
- "nothingSent": "Es una prueba: no se ha enviado ningún email.",
+ "nothingSent": "Es una simulación: no se ha enviado nada.",
"externalDelivers": "lo recibiría",
"externalSkipped": "no lo recibiría ({status})",
- "delivered": "Email de prueba enviado: {sent} enviados, {failed} fallidos.",
+ "delivered": "Prueba enviada: {sent} entregadas, {failed} fallidas.",
"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)"
@@ -2143,7 +2169,10 @@
"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."
+ "path_not_allowed": "La ruta de la URL no corresponde a este tipo de canal.",
+ "private_address": "La URL apunta a una dirección privada o interna.",
+ "unresolvable": "No se ha podido resolver el dominio de la URL.",
+ "not_signed": "Este tipo de canal no firma sus mensajes."
},
"link": {
"invalid": "Este enlace no es válido o ya se ha usado.",
@@ -2217,7 +2246,22 @@
"deleted": "Canal eliminado",
"disabledToast": "Canal deshabilitado",
"enabledToast": "Canal habilitado",
- "deleteTitle": "¿Eliminar el canal?"
+ "deleteTitle": "¿Eliminar el canal?",
+ "autoDisabled": "Deshabilitado tras {failures} envíos fallidos seguidos",
+ "signed": "Firmado",
+ "rotate": "Rotar el secreto de firma",
+ "rotateTitle": "¿Rotar el secreto de firma?",
+ "confirmRotate": "Se generará un secreto nuevo. Durante las próximas 24 horas los envíos se firman con el nuevo y con el actual, para que el receptor pueda migrar; después solo vale el nuevo.",
+ "rotated": "Secreto de firma rotado",
+ "rotationEndsAt": "El secreto anterior es válido hasta {date}",
+ "secretTitle": "Secreto de firma",
+ "secretDescription": "Cópialo ahora y configúralo en el receptor: no se volverá a mostrar. Cada envío lleva una cabecera X-GitOps-Signature hecha con él.",
+ "secretCopy": "Copiar",
+ "secretCopied": "Secreto copiado",
+ "secretDone": "Ya lo he guardado",
+ "secretDocs": "Cómo verificar la firma",
+ "webhookHelp": "Cualquier URL https pública. GitOps firma cada petición con HMAC-SHA256 y nunca sigue redirecciones.",
+ "comingSoon": "Próximamente"
}
}
}
diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts
index a3f6c64..6d8dd6a 100644
--- a/src/lib/notifications/types.ts
+++ b/src/lib/notifications/types.ts
@@ -32,6 +32,13 @@ export type ChannelView = {
updatedAt: string;
lastDeliveryAt: string | null;
lastError: string | null;
+ consecutiveFailures: number;
+ /** `failures` when the platform disabled it. */
+ disabledReason: string | null;
+ /** Signs its deliveries (webhook): has a rotatable secret. */
+ signed: boolean;
+ /** End of a rotation's grace period, while the previous secret still signs. */
+ rotationEndsAt: string | null;
};
export type ChannelsSectionData = {
@@ -52,4 +59,6 @@ export type ChannelsFormResult = {
channelSaved?: string;
channelDeleted?: string;
channelTest?: { channelId: string; sent: boolean; error: string | null };
+ /** Signing secret just created or rotated: shown once, never readable again. */
+ channelSecret?: { channelId: string; secret: string; rotated?: boolean };
} | null;
diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts
index 2521869..69e32c0 100644
--- a/src/lib/server/alerts/operations.ts
+++ b/src/lib/server/alerts/operations.ts
@@ -222,8 +222,10 @@ async function dryRun(
if (!isEventType(alert.eventType)) return { ok: false, status: 400, error: 'Unknown event type' };
const send = input.send === true || input.send === 'true';
const actor = actorFor(locals);
+ const mailConfigured = isMailConfigured();
if (send) {
- if (!isMailConfigured()) {
+ // the test goes to every destination of the alert: without SMTP only its channels get it
+ if (!mailConfigured && (alert.channelIds ?? []).length === 0) {
return { ok: false, status: 409, error: 'mail_not_configured' };
}
if (!actor || !testSendLimiter.consume(actor.userId).allowed) {
@@ -260,7 +262,7 @@ async function dryRun(
projectId = sample.projectId;
}
- if (send && actor && alert.recipients.emails.length > 0) {
+ if (send && mailConfigured && actor && alert.recipients.emails.length > 0) {
await alertService.registerExternal(location, alert.recipients.emails, actor);
}
diff --git a/src/lib/server/infra/http/guarded-fetch.test.ts b/src/lib/server/infra/http/guarded-fetch.test.ts
new file mode 100644
index 0000000..3940cbf
--- /dev/null
+++ b/src/lib/server/infra/http/guarded-fetch.test.ts
@@ -0,0 +1,210 @@
+import http from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import {
+ createGuardedFetch,
+ guardedLookup,
+ resolvePublicAddresses,
+ type Resolver,
+} from './guarded-fetch';
+import { postRawJson, validateOpenWebhookUrl, WebhookDeliveryError } from './webhook-request';
+
+/** DNS stub: hostname → addresses. Unknown names fail like NXDOMAIN. */
+function dnsStub(table: Record): Resolver {
+ return async (hostname) => {
+ const addresses = table[hostname];
+ if (!addresses) throw Object.assign(new Error('not found'), { code: 'ENOTFOUND' });
+ return addresses.map((address) => ({ address, family: address.includes(':') ? 6 : 4 }));
+ };
+}
+
+const resolve = dnsStub({
+ 'hooks.example.com': ['93.184.216.34'],
+ 'dual.example.com': ['93.184.216.34', '2606:2800:220:1::1'],
+ 'rebind.example.com': ['93.184.216.34', '10.0.0.7'],
+ 'internal.example.com': ['10.1.2.3'],
+ 'metadata.example.com': ['169.254.169.254'],
+ 'loop6.example.com': ['::1'],
+ 'mapped.example.com': ['::ffff:127.0.0.1'],
+ 'mapped-hex.example.com': ['::ffff:a9fe:a9fe'],
+ 'cgnat.example.com': ['100.64.0.1'],
+ 'multicast.example.com': ['224.0.0.1'],
+ 'ula.example.com': ['fd00::1'],
+});
+
+describe('validateOpenWebhookUrl (free URL anti-SSRF)', () => {
+ it.each(['https://hooks.example.com/in', 'https://dual.example.com:8443/in?x=1'])(
+ 'accepts %s',
+ async (url) => {
+ expect(await validateOpenWebhookUrl(url, { resolve })).toMatchObject({ ok: true });
+ },
+ );
+
+ it.each([
+ ['http://hooks.example.com/in', 'not_https'],
+ ['ftp://hooks.example.com/in', 'not_https'],
+ ['https://user:pass@hooks.example.com/in', 'credentials'],
+ ['https://localhost/in', 'private_address'],
+ ['https://api.localhost/in', 'private_address'],
+ ['https://127.0.0.1/in', 'private_address'],
+ ['https://10.0.0.1/in', 'private_address'],
+ ['https://192.168.1.10/in', 'private_address'],
+ ['https://169.254.169.254/latest/meta-data', 'private_address'],
+ ['https://[::1]/in', 'private_address'],
+ ['https://[::ffff:127.0.0.1]/in', 'private_address'],
+ ['https://[::ffff:169.254.169.254]/in', 'private_address'],
+ ['https://[fe80::1]/in', 'private_address'],
+ ['https://internal.example.com/in', 'private_address'],
+ ['https://metadata.example.com/in', 'private_address'],
+ ['https://rebind.example.com/in', 'private_address'],
+ ['https://loop6.example.com/in', 'private_address'],
+ ['https://mapped.example.com/in', 'private_address'],
+ ['https://mapped-hex.example.com/in', 'private_address'],
+ ['https://cgnat.example.com/in', 'private_address'],
+ ['https://multicast.example.com/in', 'private_address'],
+ ['https://ula.example.com/in', 'private_address'],
+ ['https://nowhere.example.com/in', 'unresolvable'],
+ ['not a url', 'invalid_url'],
+ ['', 'invalid_url'],
+ ])('rejects %s (%s)', async (url, error) => {
+ expect(await validateOpenWebhookUrl(url, { resolve })).toEqual({ ok: false, error });
+ });
+
+ it('only lets http and private targets through with the development flags', async () => {
+ expect(
+ await validateOpenWebhookUrl('http://127.0.0.1:3000/in', {
+ resolve,
+ allowHttp: true,
+ allowPrivateTargets: true,
+ }),
+ ).toMatchObject({ ok: true });
+ expect(
+ await validateOpenWebhookUrl('http://internal.example.com/in', { resolve, allowHttp: true }),
+ ).toEqual({ ok: false, error: 'private_address' });
+ });
+});
+
+describe('guardedLookup (connect to the checked address)', () => {
+ const lookup = (hostname: string, options: object = {}) =>
+ new Promise<{ error: NodeJS.ErrnoException | null; address: unknown }>((done) =>
+ guardedLookup(resolve)(hostname, options, (error, address) => done({ error, address })),
+ );
+
+ it('hands the socket the address that was checked', async () => {
+ expect(await lookup('hooks.example.com')).toEqual({ error: null, address: '93.184.216.34' });
+ expect(await lookup('dual.example.com', { all: true })).toEqual({
+ error: null,
+ address: [
+ { address: '93.184.216.34', family: 4 },
+ { address: '2606:2800:220:1::1', family: 6 },
+ ],
+ });
+ });
+
+ it('refuses a name that resolves to a private address at connection time (DNS rebinding)', async () => {
+ const { error } = await lookup('rebind.example.com');
+ expect(error?.code).toBe('EBLOCKEDTARGET');
+ expect((await lookup('mapped.example.com')).error?.code).toBe('EBLOCKEDTARGET');
+ expect((await lookup('nowhere.example.com')).error?.code).toBe('ENOTFOUND');
+ });
+
+ it('checks every address, not just the first one', async () => {
+ expect(await resolvePublicAddresses('rebind.example.com', resolve)).toEqual({
+ ok: false,
+ error: 'private_address',
+ });
+ });
+});
+
+describe('createGuardedFetch', () => {
+ let server: http.Server;
+ let base: string;
+ const received: Array<{ headers: http.IncomingHttpHeaders; body: string }> = [];
+
+ beforeAll(async () => {
+ server = http.createServer((req, res) => {
+ let body = '';
+ req.on('data', (chunk) => (body += chunk));
+ req.on('end', () => {
+ received.push({ headers: req.headers, body });
+ if (req.url === '/redirect') {
+ res.writeHead(302, { location: 'http://169.254.169.254/latest/meta-data' }).end();
+ } else if (req.url === '/big') {
+ res.writeHead(200, { 'content-type': 'text/plain' });
+ res.end('x'.repeat(512 * 1024));
+ } else if (req.url === '/limited') {
+ res.writeHead(429, { 'retry-after': '3' }).end();
+ } else {
+ res.writeHead(204).end();
+ }
+ });
+ });
+ await new Promise((done) => server.listen(0, '127.0.0.1', done));
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ });
+
+ afterAll(() => new Promise((done) => server.close(() => done())));
+
+ const local = createGuardedFetch({ allowHttp: true, allowPrivateTargets: true });
+
+ it('posts the exact raw body and headers', async () => {
+ received.length = 0;
+ await postRawJson(`${base}/in`, '{"a":1}', { fetch: local, headers: { 'X-Test': 'yes' } });
+ expect(received[0].body).toBe('{"a":1}');
+ expect(received[0].headers['x-test']).toBe('yes');
+ expect(received[0].headers['content-type']).toBe('application/json');
+ });
+
+ it('never follows redirects: a 3xx is a permanent failure', async () => {
+ received.length = 0;
+ const error = await postRawJson(`${base}/redirect`, '{}', { fetch: local }).catch((e) => e);
+ expect(error).toBeInstanceOf(WebhookDeliveryError);
+ expect(error).toMatchObject({ status: 302, retryable: false, reason: 'redirect' });
+ expect(received).toHaveLength(1);
+ });
+
+ it('discards a large answer without failing the delivery', async () => {
+ await expect(
+ postRawJson(`${base}/big`, '{}', {
+ fetch: createGuardedFetch({ ...flags, maxResponseBytes: 1024 }),
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('passes 429 and its Retry-After through', async () => {
+ const error = await postRawJson(`${base}/limited`, '{}', { fetch: local }).catch((e) => e);
+ expect(error).toMatchObject({ status: 429, retryable: true, retryAfterMs: 3000 });
+ });
+
+ it('refuses private targets by default, without retrying', async () => {
+ received.length = 0;
+ const strict = createGuardedFetch({ allowHttp: true });
+ const error = await postRawJson(`${base}/in`, '{}', { fetch: strict }).catch((e) => e);
+ expect(error).toMatchObject({ status: null, retryable: false, reason: 'blocked' });
+ expect(error.summary).toBe('blocked_target');
+ expect(received).toHaveLength(0);
+ });
+
+ it('refuses a public name that resolves to a private address when connecting', async () => {
+ received.length = 0;
+ const port = (server.address() as AddressInfo).port;
+ const rebinding = createGuardedFetch({
+ allowHttp: true,
+ resolve: dnsStub({ 'public.example.com': ['127.0.0.1'] }),
+ });
+ const error = await postRawJson(`http://public.example.com:${port}/in`, '{}', {
+ fetch: rebinding,
+ }).catch((e) => e);
+ expect(error).toMatchObject({ reason: 'blocked', retryable: false });
+ expect(received).toHaveLength(0);
+ });
+
+ it('refuses http unless allowed', async () => {
+ const error = await postRawJson(`${base}/in`, '{}', {
+ fetch: createGuardedFetch({ allowPrivateTargets: true }),
+ }).catch((e) => e);
+ expect(error).toMatchObject({ reason: 'blocked' });
+ });
+});
+
+const flags = { allowHttp: true, allowPrivateTargets: true };
diff --git a/src/lib/server/infra/http/guarded-fetch.ts b/src/lib/server/infra/http/guarded-fetch.ts
new file mode 100644
index 0000000..ed34f48
--- /dev/null
+++ b/src/lib/server/infra/http/guarded-fetch.ts
@@ -0,0 +1,182 @@
+import dns from 'node:dns';
+import http from 'node:http';
+import https from 'node:https';
+import { isIP, type LookupFunction } from 'node:net';
+import { isBlockedAddress, isBlockedHostname } from '#lib/monitoring/target-guard';
+
+/**
+ * Outgoing HTTP for notification channels with anti-SSRF guarantees that `fetch` can't give:
+ * every address a hostname resolves to is checked (private, loopback, link-local, CGNAT,
+ * multicast, cloud metadata, IPv4-mapped IPv6…) and the socket connects to that already checked
+ * address, so DNS rebinding can't swap it afterwards. Redirects are never followed and the
+ * answer's body is read up to a limit and thrown away.
+ */
+
+/** `fetch`-shaped function: what `postJson` sends through. */
+export type FetchLike = (url: string, init: RequestInit) => Promise;
+
+/** Resolves every address of a hostname (injectable so tests don't touch DNS). */
+export type Resolver = (hostname: string) => Promise>;
+
+export const systemResolver: Resolver = (hostname) =>
+ dns.promises.lookup(hostname, { all: true, verbatim: true });
+
+/** The destination is (or resolves to) an address channels may not reach. */
+export class BlockedTargetError extends Error {
+ readonly code = 'EBLOCKEDTARGET';
+ constructor() {
+ super('target resolves to a blocked address');
+ this.name = 'BlockedTargetError';
+ }
+}
+
+export type AddressCheck =
+ | { ok: true; addresses: Array<{ address: string; family: number }> }
+ | { ok: false; error: 'private_address' | 'unresolvable' };
+
+/** Resolves `hostname` and accepts it only when **every** address is public. */
+export async function resolvePublicAddresses(
+ hostname: string,
+ resolve: Resolver = systemResolver,
+): Promise {
+ const host = hostname.replace(/^\[|\]$/g, '');
+ if (isBlockedHostname(host)) return { ok: false, error: 'private_address' };
+ if (isIP(host)) return { ok: true, addresses: [{ address: host, family: isIP(host) }] };
+ let addresses: Array<{ address: string; family: number }>;
+ try {
+ addresses = await resolve(host);
+ } catch {
+ return { ok: false, error: 'unresolvable' };
+ }
+ if (addresses.length === 0) return { ok: false, error: 'unresolvable' };
+ if (addresses.some((entry) => isBlockedAddress(entry.address))) {
+ return { ok: false, error: 'private_address' };
+ }
+ return { ok: true, addresses };
+}
+
+/**
+ * `lookup` hook for `http(s).request`: the socket only gets addresses that passed
+ * `isBlockedAddress`, so what was checked is what it connects to.
+ */
+export function guardedLookup(resolve: Resolver = systemResolver): LookupFunction {
+ return (hostname, options, callback) => {
+ resolvePublicAddresses(hostname, resolve).then(
+ (checked) => {
+ if (!checked.ok) {
+ const error = Object.assign(
+ checked.error === 'private_address'
+ ? new BlockedTargetError()
+ : new Error('dns lookup failed'),
+ { code: checked.error === 'private_address' ? 'EBLOCKEDTARGET' : 'ENOTFOUND' },
+ );
+ return callback(error as NodeJS.ErrnoException, '', 4);
+ }
+ const family = (options as { family?: number }).family;
+ const list = family
+ ? checked.addresses.filter((entry) => entry.family === family)
+ : checked.addresses;
+ if (list.length === 0) {
+ const error = Object.assign(new Error('dns lookup failed'), { code: 'ENOTFOUND' });
+ return callback(error as NodeJS.ErrnoException, '', 4);
+ }
+ if ((options as { all?: boolean }).all) {
+ return (callback as unknown as (e: null, a: typeof list) => void)(null, list);
+ }
+ callback(null, list[0].address, list[0].family);
+ },
+ (error) => callback(error as NodeJS.ErrnoException, '', 4),
+ );
+ };
+}
+
+export type GuardedFetchOptions = {
+ /** Lifts the address checks (local development and e2e only). */
+ allowPrivateTargets?: boolean;
+ /** Accepts `http:` URLs (local development only). */
+ allowHttp?: boolean;
+ /** Bytes of the answer read before the connection is dropped; nothing is kept. */
+ maxResponseBytes?: number;
+ resolve?: Resolver;
+};
+
+export const MAX_RESPONSE_BYTES = 64 * 1024;
+/** How long the discarded answer may keep the socket open after its headers. */
+const DRAIN_TIMEOUT_MS = 2_000;
+
+function toHeaders(raw: http.IncomingHttpHeaders): Headers {
+ const headers = new Headers();
+ for (const [name, value] of Object.entries(raw)) {
+ if (value === undefined) continue;
+ try {
+ headers.set(name, Array.isArray(value) ? value.join(', ') : value);
+ } catch {
+ // a header the Fetch API refuses is not one we need
+ }
+ }
+ return headers;
+}
+
+/**
+ * A `fetch` replacement built on `node:http(s)` with the guarded lookup. It resolves as soon as
+ * the status arrives, with an empty body; the real body is drained up to `maxResponseBytes`.
+ */
+export function createGuardedFetch(options: GuardedFetchOptions = {}): FetchLike {
+ const maxBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES;
+ const lookup = options.allowPrivateTargets ? undefined : guardedLookup(options.resolve);
+
+ return (input, init) =>
+ new Promise((resolve, reject) => {
+ let url: URL;
+ try {
+ url = new URL(input);
+ } catch {
+ return reject(new TypeError('invalid url'));
+ }
+ const allowed = url.protocol === 'https:' || (options.allowHttp && url.protocol === 'http:');
+ if (!allowed || url.username || url.password) return reject(new BlockedTargetError());
+ if (!options.allowPrivateTargets && isBlockedHostname(url.hostname)) {
+ return reject(new BlockedTargetError());
+ }
+
+ const body = typeof init.body === 'string' ? init.body : '';
+ const headers: Record = {};
+ new Headers(init.headers).forEach((value, name) => {
+ headers[name] = value;
+ });
+ headers['content-length'] = String(Buffer.byteLength(body));
+
+ const client = url.protocol === 'https:' ? https : http;
+ const request = client.request(
+ url,
+ {
+ method: init.method ?? 'POST',
+ headers,
+ signal: init.signal ?? undefined,
+ lookup,
+ // a fresh connection per delivery: a pooled socket would skip the lookup check
+ agent: false,
+ },
+ (response) => {
+ let read = 0;
+ const drain = setTimeout(() => response.destroy(), DRAIN_TIMEOUT_MS);
+ drain.unref?.();
+ response.on('data', (chunk: Buffer) => {
+ read += chunk.length;
+ if (read > maxBytes) response.destroy();
+ });
+ response.on('close', () => clearTimeout(drain));
+ response.on('error', () => {});
+
+ const status = response.statusCode ?? 0;
+ if (status < 200 || status > 599) {
+ response.destroy();
+ return reject(new Error('invalid http status'));
+ }
+ resolve(new Response(null, { status, headers: toHeaders(response.headers) }));
+ },
+ );
+ request.on('error', reject);
+ request.end(body);
+ });
+}
diff --git a/src/lib/server/infra/http/webhook-request.ts b/src/lib/server/infra/http/webhook-request.ts
index 66292d4..0216731 100644
--- a/src/lib/server/infra/http/webhook-request.ts
+++ b/src/lib/server/infra/http/webhook-request.ts
@@ -1,4 +1,5 @@
import { isIP } from 'node:net';
+import { resolvePublicAddresses, type FetchLike, type Resolver } from './guarded-fetch';
/** Why a webhook URL is refused; the UI maps them to `notifications.errors.`. */
export type WebhookUrlError =
@@ -8,7 +9,9 @@ export type WebhookUrlError =
| 'ip_address'
| 'port'
| 'host_not_allowed'
- | 'path_not_allowed';
+ | 'path_not_allowed'
+ | 'private_address'
+ | 'unresolvable';
export type WebhookUrlRule = {
/** Exact host names the URL may point at (`hooks.slack.com`). */
@@ -49,6 +52,43 @@ export function validateWebhookUrl(
return { ok: true, url };
}
+export type OpenWebhookUrlOptions = {
+ /** Accepts `http:` (local development only). */
+ allowHttp?: boolean;
+ /** Skips the address checks (local development and e2e only). */
+ allowPrivateTargets?: boolean;
+ resolve?: Resolver;
+};
+
+/**
+ * Anti-SSRF check of a URL anyone can type (generic webhooks): there is no host allow-list, so the
+ * hostname is resolved and refused when **any** of its addresses is private, loopback, link-local,
+ * CGNAT, multicast or the cloud metadata one (IPv4 and IPv6, mapped forms included). `https` only
+ * and no credentials. Run before saving and before every send; the request itself then connects
+ * only to checked addresses (`createGuardedFetch`), which closes the DNS rebinding window.
+ */
+export async function validateOpenWebhookUrl(
+ raw: unknown,
+ options: OpenWebhookUrlOptions = {},
+): Promise<{ 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' };
+ }
+ const httpAllowed = options.allowHttp && url.protocol === 'http:';
+ if (url.protocol !== 'https:' && !httpAllowed) return { ok: false, error: 'not_https' };
+ if (url.username || url.password) return { ok: false, error: 'credentials' };
+ if (!url.hostname) return { ok: false, error: 'invalid_url' };
+ if (options.allowPrivateTargets) return { ok: true, url };
+ const checked = await resolvePublicAddresses(url.hostname, options.resolve);
+ return checked.ok ? { ok: true, url } : { ok: false, error: checked.error };
+}
+
/** A webhook delivery that failed; `retryable` tells whether trying again may help. */
export class WebhookDeliveryError extends Error {
constructor(
@@ -57,7 +97,7 @@ export class WebhookDeliveryError extends Error {
readonly retryable: boolean,
/** `Retry-After` of a 429, in ms. */
readonly retryAfterMs: number | null = null,
- readonly reason: 'timeout' | 'network' | 'redirect' | 'http' = 'http',
+ readonly reason: 'timeout' | 'network' | 'redirect' | 'blocked' | 'http' = 'http',
) {
super(
status === null ? `Webhook delivery failed (${reason})` : `Webhook answered HTTP ${status}`,
@@ -68,7 +108,7 @@ export class WebhookDeliveryError extends Error {
/** 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;
+ return this.reason === 'blocked' ? 'blocked_target' : this.reason;
}
}
@@ -87,21 +127,30 @@ function parseRetryAfter(value: string | null, now: number): number | null {
export type PostJsonOptions = {
timeoutMs?: number;
headers?: Record;
- fetch?: typeof fetch;
+ /** `createGuardedFetch()` for anti-SSRF delivery; global `fetch` by default. */
+ fetch?: FetchLike;
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.
+ * errors, timeouts, 429 (with its `Retry-After`) and 5xx; permanent for 3xx, other 4xx and blocked
+ * destinations.
*/
-export async function postJson(
+export function postJson(url: string, body: unknown, options: PostJsonOptions = {}): Promise {
+ return postRawJson(url, JSON.stringify(body), options);
+}
+
+/**
+ * `postJson` with an already serialized body: what is signed must be byte for byte what is sent.
+ */
+export async function postRawJson(
url: string,
- body: unknown,
+ rawBody: string,
options: PostJsonOptions = {},
): Promise {
- const send = options.fetch ?? fetch;
+ const send: FetchLike = options.fetch ?? fetch;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? WEBHOOK_TIMEOUT_MS);
let response: Response;
@@ -109,11 +158,14 @@ export async function postJson(
response = await send(url, {
method: 'POST',
headers: { 'content-type': 'application/json', ...options.headers },
- body: JSON.stringify(body),
+ body: rawBody,
redirect: 'manual',
signal: controller.signal,
});
- } catch {
+ } catch (error) {
+ if ((error as { code?: unknown })?.code === 'EBLOCKEDTARGET') {
+ throw new WebhookDeliveryError(null, false, null, 'blocked');
+ }
throw new WebhookDeliveryError(
null,
true,
diff --git a/src/lib/server/infra/notifications/chat-notification.ts b/src/lib/server/infra/notifications/chat-notification.ts
index 9a82ab7..771b0f2 100644
--- a/src/lib/server/infra/notifications/chat-notification.ts
+++ b/src/lib/server/infra/notifications/chat-notification.ts
@@ -30,7 +30,14 @@ export type ChannelMessage = {
/** 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 };
+ event?: {
+ id: string;
+ type: string;
+ occurredAt: string;
+ scope: Record;
+ /** Catalog field values by key, sensitive ones left out (no labels, no formatting). */
+ fields?: Record;
+ };
alert?: { id: string; name: string };
};
@@ -39,18 +46,29 @@ export type ChatNotificationInput = {
/** Destination URL in clear: only ever held in memory, right before sending. */
destination: string;
message: ChannelMessage;
+ /** Same for every attempt of one delivery, so receivers can deduplicate retries. */
+ deliveryId?: string;
+ /**
+ * Signing secrets in clear, newest first (two during a rotation's grace period). Only for
+ * transports with `signed: true`; only ever held in memory, right before sending.
+ */
+ signingSecrets?: string[];
};
export class ChatNotification extends Notification {
readonly channel: ChatChannelType;
readonly destination: string;
readonly message: ChannelMessage;
+ readonly deliveryId: string;
+ readonly signingSecrets: readonly string[];
constructor(input: ChatNotificationInput) {
super();
this.channel = input.channel;
this.destination = input.destination;
this.message = input.message;
+ this.deliveryId = input.deliveryId ?? crypto.randomUUID();
+ this.signingSecrets = input.signingSecrets ?? [];
}
validate(): void {
@@ -59,12 +77,28 @@ export class ChatNotification extends Notification {
}
}
+export type DestinationCheck = { ok: true; url: URL } | { ok: false; error: WebhookUrlError };
+
/**
- * 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.
+ * Transport of one chat channel type; registering it is all a new provider needs (the entity,
+ * cipher, queue, retries, permissions, UI and test message are shared).
+ *
+ * - `validateDestination` is the anti-SSRF check of the URL, run before saving a channel and
+ * again before every send. It may be async (free URLs resolve DNS).
+ * - `signed: true` makes the service generate a signing secret per channel (shown once, rotatable
+ * with a grace period) and hand the active ones to `send()` in `signingSecrets`.
*/
export interface ChatTransport extends NotificationTransport {
- validateDestination(raw: unknown): { ok: true; url: URL } | { ok: false; error: WebhookUrlError };
+ validateDestination(raw: unknown): DestinationCheck | Promise;
+ readonly signed?: boolean;
+}
+
+/** No transport is registered for a channel type (recorded as the channel's `lastError`). */
+export class ChatTransportUnavailableError extends Error {
+ constructor(type: ChatChannelType) {
+ super(`No transport registered for channel type ${type}`);
+ this.name = 'TransportUnavailable';
+ }
}
const CHAT_TRANSPORTS_KEY = Symbol.for('gitops.notifications.chat-transports');
diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts
index cbd16c7..b160c98 100644
--- a/src/lib/server/infra/notifications/index.ts
+++ b/src/lib/server/infra/notifications/index.ts
@@ -27,6 +27,7 @@ export { emailButton, emailNote } from './email-parts';
export {
CHAT_CHANNEL_TYPES,
ChatNotification,
+ ChatTransportUnavailableError,
availableChatTypes,
getChatTransport,
isChatChannelType,
@@ -36,6 +37,7 @@ export {
type ChatChannelType,
type ChatNotificationInput,
type ChatTransport,
+ type DestinationCheck,
} from './chat-notification';
export { DeliveryQueue, defaultErrorCode, type DeliveryQueueOptions } from './delivery-queue';
export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue';
diff --git a/src/lib/server/infra/notifications/webhook/webhook-payload.ts b/src/lib/server/infra/notifications/webhook/webhook-payload.ts
new file mode 100644
index 0000000..f1f905b
--- /dev/null
+++ b/src/lib/server/infra/notifications/webhook/webhook-payload.ts
@@ -0,0 +1,57 @@
+import type { ChannelMessage } from '../chat-notification';
+
+/** Event type of the "Send test message" delivery (no real event behind it). */
+export const WEBHOOK_TEST_EVENT = 'channel.test';
+export const WEBHOOK_PAYLOAD_VERSION = 1;
+
+/**
+ * Body of a generic webhook delivery. Versioned: fields may be added within a version, never
+ * removed or renamed. Values are the catalog's raw ones (no labels, templates nor HTML), and
+ * fields marked `sensitive` are never included.
+ */
+export type WebhookPayload = {
+ version: typeof WEBHOOK_PAYLOAD_VERSION;
+ deliveryId: string;
+ /** `true` for "Send test message" and alert test sends. */
+ test: boolean;
+ alert: { id: string; name: string } | null;
+ event: {
+ id: string | null;
+ type: string;
+ occurredAt: string;
+ scope: Record;
+ fields: Record;
+ };
+ /** Absolute link to the resource in GitOps, `null` without `ORIGIN`. */
+ link: string | null;
+};
+
+export function buildWebhookPayload(
+ message: ChannelMessage,
+ deliveryId: string,
+ now: () => Date = () => new Date(),
+): WebhookPayload {
+ const event = message.event;
+ return {
+ version: WEBHOOK_PAYLOAD_VERSION,
+ deliveryId,
+ test: message.test,
+ alert: message.alert ? { id: message.alert.id, name: message.alert.name } : null,
+ event: event
+ ? {
+ id: event.id,
+ type: event.type,
+ occurredAt: event.occurredAt,
+ scope: { ...event.scope },
+ fields: { ...event.fields },
+ }
+ : {
+ id: null,
+ type: WEBHOOK_TEST_EVENT,
+ occurredAt: now().toISOString(),
+ scope: {},
+ fields: {},
+ },
+ link: message.link?.url ?? null,
+ };
+}
diff --git a/src/lib/server/infra/notifications/webhook/webhook-signature.test.ts b/src/lib/server/infra/notifications/webhook/webhook-signature.test.ts
new file mode 100644
index 0000000..14500cc
--- /dev/null
+++ b/src/lib/server/infra/notifications/webhook/webhook-signature.test.ts
@@ -0,0 +1,77 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { describe, expect, it } from 'vitest';
+import {
+ TOLERANCE_SECONDS,
+ verifyGitOpsSignature,
+} from '../../../../../../docs/webhooks/verify-signature';
+import {
+ computeSignature,
+ generateSigningSecret,
+ signatureHeader,
+ SIGNING_SECRET_PREFIX,
+} from './webhook-signature';
+
+const BODY = '{"hello":"world"}';
+const T = 1_700_000_000;
+// HMAC-SHA256 computed outside this code (Python's hmac module) for these inputs
+const KNOWN = 'f592bbf3951cfc94e560eecfb5d9dd4da6b0fff2e626235f8ab4b54860925d0b';
+const KNOWN_OLD = 'd30afec711349560803be4b024ef1aa59709bddff9b640379e8656024fe3b10c';
+
+describe('webhook signature', () => {
+ it('matches a known HMAC-SHA256 vector of "."', () => {
+ expect(computeSignature('whsec_test', T, BODY)).toBe(KNOWN);
+ expect(signatureHeader(['whsec_test'], T, BODY)).toBe(`t=${T},v1=${KNOWN}`);
+ });
+
+ it('repeats v1= for every active secret, newest first (rotation grace period)', () => {
+ expect(signatureHeader(['whsec_test', 'whsec_old'], T, BODY)).toBe(
+ `t=${T},v1=${KNOWN},v1=${KNOWN_OLD}`,
+ );
+ });
+
+ it('refuses to sign without a secret', () => {
+ expect(() => signatureHeader([], T, BODY)).toThrow();
+ });
+
+ it('generates 32 random bytes per secret', () => {
+ const secret = generateSigningSecret();
+ expect(secret).toMatch(new RegExp(`^${SIGNING_SECRET_PREFIX}[0-9a-f]{64}$`));
+ expect(generateSigningSecret()).not.toBe(secret);
+ });
+});
+
+describe('documented verification example (docs/webhooks/verify-signature.ts)', () => {
+ const header = signatureHeader(['whsec_test'], T, BODY);
+
+ it('accepts what GitOps signs', () => {
+ expect(verifyGitOpsSignature(BODY, header, 'whsec_test', T)).toBe(true);
+ expect(verifyGitOpsSignature(BODY, header, 'whsec_test', T + TOLERANCE_SECONDS)).toBe(true);
+ });
+
+ it('accepts either secret while a rotation signs with both', () => {
+ const both = signatureHeader(['whsec_test', 'whsec_old'], T, BODY);
+ expect(verifyGitOpsSignature(BODY, both, 'whsec_old', T)).toBe(true);
+ expect(verifyGitOpsSignature(BODY, both, 'whsec_test', T)).toBe(true);
+ });
+
+ it.each([
+ ['another secret', BODY, header, 'whsec_other', T],
+ ['a modified body', '{"hello":"World"}', header, 'whsec_test', T],
+ ['an old timestamp (replay)', BODY, header, 'whsec_test', T + TOLERANCE_SECONDS + 1],
+ ['a timestamp from the future', BODY, header, 'whsec_test', T - TOLERANCE_SECONDS - 1],
+ ['a missing header', BODY, null, 'whsec_test', T],
+ ['a header without v1', BODY, `t=${T}`, 'whsec_test', T],
+ ['a truncated signature', BODY, `t=${T},v1=${KNOWN.slice(0, 10)}`, 'whsec_test', T],
+ ['a changed timestamp', BODY, header.replace(`t=${T}`, `t=${T + 1}`), 'whsec_test', T],
+ ])('rejects %s', (_case, body, value, secret, now) => {
+ expect(verifyGitOpsSignature(body, value, secret, now)).toBe(false);
+ });
+
+ it('is the code the documentation shows', () => {
+ const docs = path.resolve(import.meta.dirname, '../../../../../../docs/webhooks');
+ const code = readFileSync(path.join(docs, 'verify-signature.ts'), 'utf8');
+ const readme = readFileSync(path.join(docs, 'README.md'), 'utf8');
+ expect(readme).toContain(code);
+ });
+});
diff --git a/src/lib/server/infra/notifications/webhook/webhook-signature.ts b/src/lib/server/infra/notifications/webhook/webhook-signature.ts
new file mode 100644
index 0000000..12ea8c8
--- /dev/null
+++ b/src/lib/server/infra/notifications/webhook/webhook-signature.ts
@@ -0,0 +1,34 @@
+import crypto from 'node:crypto';
+
+export const SIGNATURE_HEADER = 'X-GitOps-Signature';
+export const SIGNATURE_VERSION = 'v1';
+/** Prefix of signing secrets, so a leaked one is easy to recognize (and to scan for). */
+export const SIGNING_SECRET_PREFIX = 'whsec_';
+const SECRET_BYTES = 32;
+
+/** A new signing secret: `whsec_` + 32 random bytes in hex. The whole string is the HMAC key. */
+export function generateSigningSecret(): string {
+ return `${SIGNING_SECRET_PREFIX}${crypto.randomBytes(SECRET_BYTES).toString('hex')}`;
+}
+
+/** `HMAC-SHA256(secret, ".")` in hex. */
+export function computeSignature(secret: string, timestamp: number, rawBody: string): string {
+ return crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex');
+}
+
+/**
+ * Value of `X-GitOps-Signature`: `t=,v1=`, with one `v1=` per secret (newest
+ * first). During a rotation's grace period both the new and the previous secret sign, so a
+ * receiver still configured with the old one keeps accepting deliveries.
+ */
+export function signatureHeader(
+ secrets: readonly string[],
+ timestamp: number,
+ rawBody: string,
+): string {
+ if (secrets.length === 0) throw new Error('A signed webhook needs at least one secret');
+ const signatures = secrets.map(
+ (secret) => `${SIGNATURE_VERSION}=${computeSignature(secret, timestamp, rawBody)}`,
+ );
+ return [`t=${timestamp}`, ...signatures].join(',');
+}
diff --git a/src/lib/server/infra/notifications/webhook/webhook.transport.test.ts b/src/lib/server/infra/notifications/webhook/webhook.transport.test.ts
new file mode 100644
index 0000000..164e1aa
--- /dev/null
+++ b/src/lib/server/infra/notifications/webhook/webhook.transport.test.ts
@@ -0,0 +1,218 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { verifyGitOpsSignature } from '../../../../../../docs/webhooks/verify-signature';
+import { isRetryableWebhookError, webhookRetryAfter } from '../../http/webhook-request';
+import type { FetchLike } from '../../http/guarded-fetch';
+import { ChatNotification, type ChannelMessage } from '../chat-notification';
+import { DeliveryQueue } from '../delivery-queue';
+import { createWebhookTransport, MissingSigningSecretError } from './webhook.transport';
+
+const NOW = new Date('2026-11-25T10:00:00.000Z');
+const URL_ = 'https://hooks.example.com/in/abc';
+
+const message: ChannelMessage = {
+ title: 'Críticas',
+ summary: '3 critical',
+ eventLabel: 'Analysis completed',
+ fields: [{ label: 'Tool', value: 'Trivy' }],
+ link: { url: 'https://gitops.example.com/org/acme/x', label: 'View in GitOps' },
+ suppressed: 0,
+ text: '[GitOps] Críticas: 3 critical',
+ test: false,
+ event: {
+ id: 'event-1',
+ type: 'code_report.analysis.completed',
+ occurredAt: '2026-11-25T09:59:00.000Z',
+ scope: { organizationId: 'org-1', projectId: 'p1' },
+ fields: { tool: 'trivy', 'summary.critical': 3 },
+ },
+ alert: { id: 'alert-1', name: 'Críticas' },
+};
+
+type Captured = { url: string; headers: Record; body: string };
+
+function recordingFetch(statuses: Array = []) {
+ const calls: Captured[] = [];
+ const fetch: FetchLike = async (url, init) => {
+ calls.push({
+ url,
+ headers: Object.fromEntries(new Headers(init.headers).entries()),
+ body: String(init.body),
+ });
+ const next = statuses.shift() ?? 204;
+ if (next === 'network') throw new Error('ECONNRESET');
+ return new Response(null, { status: next, headers: { 'retry-after': '2' } });
+ };
+ return { fetch, calls };
+}
+
+function notification(secrets: string[] = ['whsec_new']) {
+ return new ChatNotification({
+ channel: 'webhook',
+ destination: URL_,
+ message,
+ deliveryId: 'delivery-1',
+ signingSecrets: secrets,
+ });
+}
+
+describe('webhook transport', () => {
+ it('posts the versioned body with the event headers and a verifiable signature', async () => {
+ const { fetch, calls } = recordingFetch();
+ const transport = createWebhookTransport({ fetch, now: () => NOW });
+ await transport.send(notification());
+
+ const [call] = calls;
+ expect(call.url).toBe(URL_);
+ expect(call.headers).toMatchObject({
+ 'content-type': 'application/json',
+ 'user-agent': 'GitOps-Webhooks/1',
+ 'x-gitops-event': 'code_report.analysis.completed',
+ 'x-gitops-delivery': 'delivery-1',
+ });
+ expect(JSON.parse(call.body)).toEqual({
+ version: 1,
+ deliveryId: 'delivery-1',
+ test: false,
+ alert: { id: 'alert-1', name: 'Críticas' },
+ event: {
+ id: 'event-1',
+ type: 'code_report.analysis.completed',
+ occurredAt: '2026-11-25T09:59:00.000Z',
+ scope: { organizationId: 'org-1', projectId: 'p1' },
+ fields: { tool: 'trivy', 'summary.critical': 3 },
+ },
+ link: 'https://gitops.example.com/org/acme/x',
+ });
+ // no templates nor translated text
+ expect(call.body).not.toContain('View in GitOps');
+ expect(call.body).not.toContain('Trivy');
+
+ const t = NOW.getTime() / 1000;
+ expect(call.headers['x-gitops-signature']).toMatch(new RegExp(`^t=${t},v1=[0-9a-f]{64}$`));
+ expect(
+ verifyGitOpsSignature(call.body, call.headers['x-gitops-signature'], 'whsec_new', t),
+ ).toBe(true);
+ });
+
+ it('signs with both secrets during a rotation', async () => {
+ const { fetch, calls } = recordingFetch();
+ await createWebhookTransport({ fetch, now: () => NOW }).send(
+ notification(['whsec_new', 'whsec_old']),
+ );
+ const header = calls[0].headers['x-gitops-signature'];
+ expect(header.match(/v1=/g)).toHaveLength(2);
+ const t = NOW.getTime() / 1000;
+ expect(verifyGitOpsSignature(calls[0].body, header, 'whsec_old', t)).toBe(true);
+ expect(verifyGitOpsSignature(calls[0].body, header, 'whsec_new', t)).toBe(true);
+ });
+
+ it('describes a test message as channel.test', async () => {
+ const { fetch, calls } = recordingFetch();
+ const test = new ChatNotification({
+ channel: 'webhook',
+ destination: URL_,
+ message: { ...message, test: true, event: undefined, alert: undefined, link: null },
+ deliveryId: 'delivery-2',
+ signingSecrets: ['whsec_new'],
+ });
+ await createWebhookTransport({ fetch, now: () => NOW }).send(test);
+ expect(calls[0].headers['x-gitops-event']).toBe('channel.test');
+ expect(JSON.parse(calls[0].body)).toMatchObject({
+ test: true,
+ alert: null,
+ link: null,
+ event: { id: null, type: 'channel.test', occurredAt: NOW.toISOString(), fields: {} },
+ });
+ });
+
+ it('refuses to send unsigned', async () => {
+ const { fetch, calls } = recordingFetch();
+ await expect(createWebhookTransport({ fetch }).send(notification([]))).rejects.toBeInstanceOf(
+ MissingSigningSecretError,
+ );
+ expect(calls).toHaveLength(0);
+ });
+
+ it('validates destinations as free URLs (DNS + private ranges)', async () => {
+ const transport = createWebhookTransport({
+ resolve: async (host) =>
+ host === 'hooks.example.com' ? [{ address: '93.184.216.34', family: 4 }] : [],
+ });
+ expect(await transport.validateDestination(URL_)).toMatchObject({ ok: true });
+ expect(await transport.validateDestination('https://169.254.169.254/x')).toEqual({
+ ok: false,
+ error: 'private_address',
+ });
+ expect(transport.signed).toBe(true);
+ });
+});
+
+describe('webhook delivery retries (DeliveryQueue + withRetry)', () => {
+ beforeEach(() => vi.useFakeTimers({ now: NOW }));
+ afterEach(() => vi.useRealTimers());
+
+ function queueFor(fetch: FetchLike) {
+ const transport = createWebhookTransport({ fetch });
+ const outcomes: Array<{ sent: boolean }> = [];
+ const queue = new DeliveryQueue({
+ send: (item) => transport.send(item),
+ retry: { isRetryable: isRetryableWebhookError, retryAfterMs: webhookRetryAfter, jitter: 0 },
+ logger: { warn: () => {}, error: () => {}, debug: () => {} },
+ label: { prefix: '[channels]', noun: 'message', plural: 'messages' },
+ onSettled: (_item, outcome) => outcomes.push(outcome),
+ });
+ return { queue, outcomes };
+ }
+
+ it('retries network errors and 5xx with backoff, keeping the delivery id', async () => {
+ const { fetch, calls } = recordingFetch(['network', 503, 204]);
+ const { queue } = queueFor(fetch);
+ const sent = queue.enqueue(notification());
+
+ await vi.advanceTimersByTimeAsync(0);
+ expect(calls).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(calls).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(3_999);
+ expect(calls).toHaveLength(2);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(calls).toHaveLength(3);
+
+ await expect(sent).resolves.toBe(true);
+ expect(new Set(calls.map((call) => call.headers['x-gitops-delivery']))).toEqual(
+ new Set(['delivery-1']),
+ );
+ // every attempt is signed at its own time, so a late retry is still within the tolerance
+ expect(calls[2].headers['x-gitops-signature']).toContain(`t=${NOW.getTime() / 1000 + 5}`);
+ });
+
+ it('honors Retry-After on 429', async () => {
+ const { fetch, calls } = recordingFetch([429, 204]);
+ const { queue } = queueFor(fetch);
+ const sent = queue.enqueue(notification());
+ await vi.advanceTimersByTimeAsync(1_999);
+ expect(calls).toHaveLength(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(calls).toHaveLength(2);
+ await expect(sent).resolves.toBe(true);
+ });
+
+ it.each([400, 401, 404, 410, 301])('does not retry HTTP %s', async (status) => {
+ const { fetch, calls } = recordingFetch([status, 204]);
+ const { queue, outcomes } = queueFor(fetch);
+ const sent = queue.enqueue(notification());
+ await vi.advanceTimersByTimeAsync(60_000);
+ await expect(sent).resolves.toBe(false);
+ expect(calls).toHaveLength(1);
+ expect(outcomes).toEqual([{ sent: false, error: expect.objectContaining({ status }) }]);
+ });
+
+ it('gives up after 4 attempts', async () => {
+ const { fetch, calls } = recordingFetch([500, 500, 500, 500, 204]);
+ const { queue } = queueFor(fetch);
+ const sent = queue.enqueue(notification());
+ await vi.advanceTimersByTimeAsync(1_000 + 4_000 + 16_000);
+ await expect(sent).resolves.toBe(false);
+ expect(calls).toHaveLength(4);
+ });
+});
diff --git a/src/lib/server/infra/notifications/webhook/webhook.transport.ts b/src/lib/server/infra/notifications/webhook/webhook.transport.ts
new file mode 100644
index 0000000..2d4b1e6
--- /dev/null
+++ b/src/lib/server/infra/notifications/webhook/webhook.transport.ts
@@ -0,0 +1,67 @@
+import {
+ postRawJson,
+ validateOpenWebhookUrl,
+ type OpenWebhookUrlOptions,
+} from '../../http/webhook-request';
+import { createGuardedFetch, type FetchLike } from '../../http/guarded-fetch';
+import type { ChatNotification, ChatTransport } from '../chat-notification';
+import { buildWebhookPayload } from './webhook-payload';
+import { SIGNATURE_HEADER, signatureHeader } from './webhook-signature';
+
+export const WEBHOOK_USER_AGENT = 'GitOps-Webhooks/1';
+export const EVENT_HEADER = 'X-GitOps-Event';
+export const DELIVERY_HEADER = 'X-GitOps-Delivery';
+
+export type WebhookTransportOptions = OpenWebhookUrlOptions & {
+ /** Defaults to `createGuardedFetch` with the same address rules. */
+ fetch?: FetchLike;
+ now?: () => Date;
+};
+
+/** A signed transport was asked to send without a secret (a channel created before #96). */
+export class MissingSigningSecretError extends Error {
+ constructor() {
+ super('Webhook channel has no signing secret');
+ this.name = 'MissingSigningSecret';
+ }
+}
+
+/**
+ * Generic webhook: a signed JSON `POST` to any public `https` URL.
+ *
+ * - Body: `WebhookPayload` (versioned, catalog values only).
+ * - Headers: `X-GitOps-Event`, `X-GitOps-Delivery` (same on retries), `X-GitOps-Signature`
+ * (`t=,v1=`, one `v1` per active secret) and `User-Agent: GitOps-Webhooks/1`.
+ * - Anti-SSRF: the URL is resolved and checked when saved and before every send, and the request
+ * connects only to checked addresses (`createGuardedFetch`). No redirects.
+ */
+export function createWebhookTransport(options: WebhookTransportOptions = {}): ChatTransport {
+ const now = options.now ?? (() => new Date());
+ const fetch =
+ options.fetch ??
+ createGuardedFetch({
+ allowHttp: options.allowHttp,
+ allowPrivateTargets: options.allowPrivateTargets,
+ resolve: options.resolve,
+ });
+
+ return {
+ signed: true,
+ validateDestination: (raw) => validateOpenWebhookUrl(raw, options),
+ async send(notification: ChatNotification) {
+ if (notification.signingSecrets.length === 0) throw new MissingSigningSecretError();
+ const payload = buildWebhookPayload(notification.message, notification.deliveryId, now);
+ const rawBody = JSON.stringify(payload);
+ const timestamp = Math.floor(now().getTime() / 1000);
+ await postRawJson(notification.destination, rawBody, {
+ fetch,
+ headers: {
+ 'User-Agent': WEBHOOK_USER_AGENT,
+ [EVENT_HEADER]: payload.event.type,
+ [DELIVERY_HEADER]: notification.deliveryId,
+ [SIGNATURE_HEADER]: signatureHeader(notification.signingSecrets, timestamp, rawBody),
+ },
+ });
+ },
+ };
+}
diff --git a/src/lib/server/notifications/channels-page.ts b/src/lib/server/notifications/channels-page.ts
index 4dea086..a916c57 100644
--- a/src/lib/server/notifications/channels-page.ts
+++ b/src/lib/server/notifications/channels-page.ts
@@ -7,6 +7,7 @@ import {
createChannel,
deleteChannel,
listChannels,
+ rotateChannelSecret,
testChannel,
updateChannel,
} from './channels';
@@ -50,7 +51,30 @@ export function channelActions(resolve: (event: ActionEvent) => Promise> {
+): 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) };
+ const issued = await notificationChannelService.create(location, input, actor.userId);
+ return { ok: true, status: 201, data: withSecret(issued) };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+/**
+ * Generates a new signing secret (the previous one keeps signing for 24 h) and returns it, this
+ * one time, in clear. Needs `:notifications:update`.
+ */
+export async function rotateChannelSecret(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'update');
+ if (!loaded.ok) return loaded;
+ try {
+ return {
+ ok: true,
+ status: 200,
+ data: withSecret(await notificationChannelService.rotateSecret(id)),
+ };
} catch (error) {
return failure(error);
}
diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts
index c60eaff..5ce50be 100644
--- a/src/modules/alerts/application/alert-engine.test.ts
+++ b/src/modules/alerts/application/alert-engine.test.ts
@@ -503,6 +503,28 @@ describe('AlertEngine', () => {
]);
});
+ it('tells the creator of a channel that disabled itself', async () => {
+ await engine.handle({
+ id: 'event-channel',
+ type: 'notifications.channel.disabled',
+ occurredAt: TIMESTAMP,
+ actor: { kind: 'system' },
+ scope: { organizationId: 'org-1', projectId: null },
+ payload: {
+ channelId: 'c1',
+ name: 'SIEM',
+ type: 'webhook',
+ reason: 'failures',
+ failures: 20,
+ lastError: 'HTTP 410',
+ createdByUserId: 'ana',
+ },
+ });
+ expect(notifier.system).toMatchObject([
+ { kind: 'channel_disabled', recipient: { userId: 'ana' } },
+ ]);
+ });
+
it('runs before the alerts of the same event', async () => {
const order: string[] = [];
notifier.sendSystemNotification = async () => void order.push('system');
diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts
index a85d4ee..8aa53c7 100644
--- a/src/modules/alerts/application/alert.channels.test.ts
+++ b/src/modules/alerts/application/alert.channels.test.ts
@@ -108,17 +108,17 @@ describe('alerts with notification channels', () => {
{ type: 'slack', name: '#org', destination: HOOK },
'a',
)
- ).id;
+ ).channel.id;
p1Channel = (
await channels.service.create(p1, { type: 'slack', name: '#p1', destination: HOOK }, 'a')
- ).id;
+ ).channel.id;
p2Channel = (
await channels.service.create(
{ ...p1, projectId: 'p2' },
{ type: 'slack', name: '#p2', destination: HOOK },
'a',
)
- ).id;
+ ).channel.id;
repository = new InMemoryAlertRepository();
directory = new FakeAlertDirectory();
@@ -349,6 +349,10 @@ describe('alerts with notification channels', () => {
expect(text).not.toContain('DB_PASSWORD');
expect(text).not.toContain('/pay');
expect(text).toContain('Production');
+ // raw catalog values for data formats (generic webhooks), sensitive ones left out too
+ expect(message.event?.fields).toMatchObject({ environmentIds: ['e'] });
+ expect(message.event?.fields).not.toHaveProperty('key');
+ expect(message.event?.fields).not.toHaveProperty('folderPath');
expect(message.suppressed).toBe(3);
expect(message.link).toEqual({
url: 'https://gitops.example.com/org/kettu/projects/web/vault',
diff --git a/src/modules/alerts/domain/system-notifications.data.ts b/src/modules/alerts/domain/system-notifications.data.ts
index 42fa670..3a5f372 100644
--- a/src/modules/alerts/domain/system-notifications.data.ts
+++ b/src/modules/alerts/domain/system-notifications.data.ts
@@ -2,7 +2,7 @@ import type { DomainEventMap, EventType } from '#lib/events/domain-events';
/** Fixed notification kinds; the notifier turns each into a subject and a message. */
export type SystemNotificationKind =
- 'access_granted' | 'access_updated' | 'access_revoked' | 'api_key_created';
+ 'access_granted' | 'access_updated' | 'access_revoked' | 'api_key_created' | 'channel_disabled';
export type SystemNotificationRule = {
eventType: K;
@@ -15,7 +15,8 @@ type Rules = { [K in EventType]?: SystemNotificationRule };
/**
* Notifications nobody configures: people hear about changes to their own access and about new
- * personal API keys. They never go to the user who caused the event (the engine skips the actor).
+ * personal API keys, and whoever created a notification channel hears when it disables itself
+ * after repeated failures. They never go to the user who caused the event (the engine skips the actor).
*
* Invitations (`status: 'invited'`) are skipped: the invitation email already tells the user.
*/
@@ -44,6 +45,11 @@ export const SYSTEM_NOTIFICATIONS: Rules = {
// project keys belong to a project, not to a person
recipient: (payload) => (payload.projectId ? null : payload.userId),
},
+ 'notifications.channel.disabled': {
+ eventType: 'notifications.channel.disabled',
+ kind: 'channel_disabled',
+ recipient: (payload) => payload.createdByUserId,
+ },
};
export function getSystemNotification(
diff --git a/src/modules/alerts/infrastructure/alert-channel-message.ts b/src/modules/alerts/infrastructure/alert-channel-message.ts
index b8a5e80..ba27d6f 100644
--- a/src/modules/alerts/infrastructure/alert-channel-message.ts
+++ b/src/modules/alerts/infrastructure/alert-channel-message.ts
@@ -1,6 +1,8 @@
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 type { EventFieldDefinition } from '#lib/events/catalog';
+import { readAlertField } from '../domain/condition-evaluator';
import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary';
/** What a channel message is built from: an alert email without its recipient. */
@@ -46,7 +48,22 @@ export function buildAlertChannelMessage(input: AlertMessageInput): ChannelMessa
type: event.type,
occurredAt: event.occurredAt,
scope: { ...event.scope },
+ fields: rawEventFields(input),
},
alert: { id: alert.id, name: alert.name },
};
}
+
+/**
+ * Catalog field values by key, as the event carries them (ids, enums, numbers), for formats that
+ * want data rather than text (generic webhooks). Sensitive fields are left out, as in the text.
+ */
+function rawEventFields({ event, definition }: AlertMessageInput): Record {
+ const fields: Record = {};
+ for (const field of definition.fields) {
+ if (field.sensitive) continue;
+ const value = readAlertField(event, field as EventFieldDefinition);
+ if (value !== undefined) fields[field.key as string] = value;
+ }
+ return fields;
+}
diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
index 1ad39c9..f6b9430 100644
--- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts
+++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
@@ -157,33 +157,46 @@ export class AlertMailNotifier implements AlertNotifierPort {
organization: names.organization ?? '',
})
: (names.organization ?? 'GitOps');
- const payload = email.event.payload as { name?: string; keyPrefix?: string };
+ const payload = email.event.payload as {
+ name?: string;
+ keyPrefix?: string;
+ failures?: number;
+ lastError?: string;
+ };
const values = {
target,
role: names.role ?? '',
name: payload.name ?? '',
prefix: payload.keyPrefix ?? '',
+ failures: payload.failures ?? 0,
+ error: payload.lastError ?? '',
};
const base = `alerts.email.system.${email.kind}`;
const subject = t(`${base}.subject`, values);
const isApiKey = email.kind === 'api_key_created';
+ const isChannel = email.kind === 'channel_disabled';
+ const isNotice = isApiKey || isChannel;
// a revoked user has nothing left to open
let path: string | null = null;
if (isApiKey) path = '/profile';
- else if (email.kind !== 'access_revoked' && names.organizationSlug) {
+ else if (isChannel && names.organizationSlug) {
+ path = names.projectSlug
+ ? `/org/${names.organizationSlug}/projects/${names.projectSlug}/settings/alerts`
+ : `/org/${names.organizationSlug}/settings/alerts`;
+ } else if (email.kind !== 'access_revoked' && names.organizationSlug) {
path = names.projectSlug
? `/org/${names.organizationSlug}/projects/${names.projectSlug}/overview`
: `/org/${names.organizationSlug}/overview`;
}
const content = await renderEmail(
- isApiKey ? 'system-security-notice' : 'system-access-changed',
+ isNotice ? 'system-security-notice' : 'system-access-changed',
{
title: subject,
greeting: t('alerts.email.greeting', { name: email.recipient.username }),
message: t(`${base}.body`, values),
- warning: isApiKey ? t(`${base}.warning`) : '',
+ warning: isNotice ? t(`${base}.warning`, values) : '',
actionButton: button(
absoluteUrl(path),
t(isApiKey ? 'alerts.email.system.openProfile' : 'alerts.email.viewInApp'),
diff --git a/src/modules/notifications/application/notification-channel.service.test.ts b/src/modules/notifications/application/notification-channel.service.test.ts
index 9350812..16599ea 100644
--- a/src/modules/notifications/application/notification-channel.service.test.ts
+++ b/src/modules/notifications/application/notification-channel.service.test.ts
@@ -1,7 +1,9 @@
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';
+import { RecordingEventBus } from '#lib/server/events/testing';
+import { createChannelCipher } from '../infrastructure/crypto/channel-cipher';
+import { createChannelsFixture, FakeChatTransport } from './testing';
const ORG = 'org-1';
const orgLocation = { scope: 'organization' as const, organizationId: ORG, projectId: null };
@@ -32,9 +34,13 @@ describe('NotificationChannelService', () => {
f = createChannelsFixture();
});
+ /** Creates a channel and returns it (without the issued secret). */
+ const create = (...args: Parameters) =>
+ f.service.create(...args).then((issued) => issued.channel);
+
describe('create and storage', () => {
it('stores the destination encrypted and only ever shows it masked', async () => {
- const channel = await f.service.create(
+ const channel = await create(
orgLocation,
{ type: 'slack', name: ' #alertas ', destination: HOOK },
'admin',
@@ -92,7 +98,7 @@ describe('NotificationChannelService', () => {
});
it('keeps the destination when an update leaves it empty, and re-encrypts a new one', async () => {
- const channel = await f.service.create(
+ const channel = await create(
orgLocation,
{ type: 'slack', name: 'a', destination: HOOK },
'x',
@@ -110,13 +116,9 @@ describe('NotificationChannelService', () => {
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(
+ const org = await create(orgLocation, { type: 'slack', name: 'org', destination: HOOK }, 'a');
+ const own = await create(p1, { type: 'slack', name: 'p1', destination: HOOK }, 'a');
+ await create(
{ ...p1, projectId: 'p2' },
{ type: 'slack', name: 'p2', destination: HOOK },
'a',
@@ -136,9 +138,8 @@ describe('NotificationChannelService', () => {
let channelId: string;
beforeEach(async () => {
- channelId = (
- await f.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x')
- ).id;
+ channelId = (await create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x'))
+ .id;
});
it('sends to the decrypted destination', async () => {
@@ -207,7 +208,7 @@ describe('NotificationChannelService', () => {
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;
+ ).channel.id;
g.transport.failWith = [503, 503, 503, 503];
await g.service.deliver(id, message, { alertId: 'alert-1' });
@@ -238,3 +239,229 @@ describe('NotificationChannelService', () => {
});
});
});
+
+describe('NotificationChannelService: signed channels and failure streaks', () => {
+ const webhook = (overrides: Partial[0]> = {}) => {
+ const signed = new FakeChatTransport(true);
+ const events = new RecordingEventBus();
+ const lines: unknown[] = [];
+ const record = (...args: unknown[]) => void lines.push(args);
+ const fixture = createChannelsFixture({
+ transports: { webhook: signed },
+ events,
+ logger: { warn: record, error: record, debug: record },
+ ...overrides,
+ });
+ return { ...fixture, signed, events, lines };
+ };
+
+ it('issues a signing secret once, stores it encrypted and never shows it again', async () => {
+ const f = webhook();
+ const issued = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'admin',
+ );
+ expect(issued.signingSecret).toBe('whsec_test1');
+
+ const [row] = f.repository.rows;
+ expect(row.signingSecret).toBeTruthy();
+ expect(row.signingSecret).not.toContain('whsec_test1');
+ const view = f.service.toView(await f.service.get(issued.channel.id));
+ expect(view.signed).toBe(true);
+ expect(JSON.stringify(view)).not.toContain('whsec_');
+ expect(view).not.toHaveProperty('signingSecret');
+ expect(view).not.toHaveProperty('previousSigningSecret');
+
+ // unsigned types get none
+ const slack = await f.service.create(
+ orgLocation,
+ { type: 'slack', name: '#a', destination: HOOK },
+ 'admin',
+ );
+ expect(slack.signingSecret).toBeNull();
+ await expect(f.service.rotateSecret(slack.channel.id)).rejects.toBeInstanceOf(
+ NotificationChannelValidationError,
+ );
+ });
+
+ it('signs each delivery with a delivery id and the active secret', async () => {
+ const f = webhook();
+ const { channel } = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'admin',
+ );
+ await f.service.deliver(channel.id, message);
+ await f.service.deliver(channel.id, message);
+ expect(f.signed.sent.map((sent) => sent.signingSecrets)).toEqual([
+ ['whsec_test1'],
+ ['whsec_test1'],
+ ]);
+ expect(f.signed.sent.map((sent) => sent.deliveryId)).toEqual(['delivery-1', 'delivery-2']);
+ });
+
+ it('keeps the previous secret signing for 24 h after a rotation', async () => {
+ const f = webhook();
+ const { channel } = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'admin',
+ );
+ const rotated = await f.service.rotateSecret(channel.id);
+ expect(rotated.signingSecret).toBe('whsec_test2');
+ expect(f.service.toView(rotated.channel).rotationEndsAt).toBe('2026-11-25T10:00:00.000Z');
+
+ await f.service.deliver(channel.id, message);
+ expect(f.signed.sent.at(-1)!.signingSecrets).toEqual(['whsec_test2', 'whsec_test1']);
+
+ f.advance(24 * 60 * 60 * 1000);
+ await f.service.deliver(channel.id, message);
+ expect(f.signed.sent.at(-1)!.signingSecrets).toEqual(['whsec_test2']);
+ expect(f.service.toView(await f.service.get(channel.id)).rotationEndsAt).toBeNull();
+
+ // a second rotation drops the oldest secret
+ await f.service.rotateSecret(channel.id);
+ await f.service.rotateSecret(channel.id);
+ await f.service.deliver(channel.id, message);
+ expect(f.signed.sent.at(-1)!.signingSecrets).toEqual(['whsec_test4', 'whsec_test3']);
+ });
+
+ it('refuses to deliver a signed channel without a secret', async () => {
+ const f = webhook();
+ const { channel } = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'admin',
+ );
+ await f.repository.update(channel.id, { signingSecret: null });
+ expect(await f.service.deliver(channel.id, message)).toBe(false);
+ expect(f.signed.attempts).toHaveLength(0);
+ expect((await f.service.get(channel.id)).lastError).toBe('missing_secret');
+ });
+
+ it('disables a channel after N definitive failures in a row and announces it once', async () => {
+ const f = webhook({ maxConsecutiveFailures: 3 });
+ const { channel } = await f.service.create(
+ p1,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'creator',
+ );
+ f.signed.failWith = [410, 410];
+ await f.service.deliver(channel.id, message);
+ await f.service.deliver(channel.id, message);
+ expect(await f.service.get(channel.id)).toMatchObject({
+ enabled: true,
+ consecutiveFailures: 2,
+ });
+
+ // a success ends the streak
+ await f.service.deliver(channel.id, message);
+ expect((await f.service.get(channel.id)).consecutiveFailures).toBe(0);
+
+ f.signed.failWith = [404, 404, 404];
+ for (let i = 0; i < 3; i += 1) await f.service.deliver(channel.id, message);
+ const disabled = await f.service.get(channel.id);
+ expect(disabled).toMatchObject({
+ enabled: false,
+ disabledReason: 'failures',
+ consecutiveFailures: 3,
+ lastError: 'HTTP 404',
+ });
+
+ const announced = f.events.ofType('notifications.channel.disabled');
+ expect(announced).toHaveLength(1);
+ expect(announced[0]).toMatchObject({
+ actor: { kind: 'system' },
+ scope: { organizationId: ORG, projectId: 'p1' },
+ payload: {
+ channelId: channel.id,
+ name: 'SIEM',
+ type: 'webhook',
+ reason: 'failures',
+ failures: 3,
+ lastError: 'HTTP 404',
+ createdByUserId: 'creator',
+ },
+ });
+ expect(JSON.stringify(announced)).not.toContain('hooks.example.com');
+
+ // a disabled channel gets nothing else, and doesn't announce again
+ expect(await f.service.deliver(channel.id, message)).toBe(false);
+ expect(f.events.ofType('notifications.channel.disabled')).toHaveLength(1);
+
+ // enabling it again starts a new streak
+ await f.service.update(channel.id, { enabled: true });
+ expect(await f.service.get(channel.id)).toMatchObject({
+ enabled: true,
+ disabledReason: null,
+ consecutiveFailures: 0,
+ });
+ });
+
+ it('counts a destination that became invalid, but never test messages', async () => {
+ const f = webhook({ maxConsecutiveFailures: 2 });
+ const { channel } = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'creator',
+ );
+ f.signed.failWith = [500, 500, 500, 500, 500, 500, 500, 500];
+ await f.service.test(channel.id, { ...message, test: true });
+ await f.service.test(channel.id, { ...message, test: true });
+ expect(await f.service.get(channel.id)).toMatchObject({
+ enabled: true,
+ consecutiveFailures: 0,
+ });
+
+ await f.repository.update(channel.id, {
+ webhookUrl: createChannelCipher(() => 'test-encryption-key').encrypt(
+ channel.id,
+ 'https://169.254.169.254/hook/x',
+ ),
+ });
+ await f.service.deliver(channel.id, message);
+ await f.service.deliver(channel.id, message);
+ expect(await f.service.get(channel.id)).toMatchObject({
+ enabled: false,
+ lastError: 'invalid_destination',
+ });
+ });
+
+ it('never counts alert test sends toward disabling the channel', async () => {
+ const f = webhook({ maxConsecutiveFailures: 1 });
+ const { channel } = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'creator',
+ );
+ f.signed.failWith = [410, 410];
+ // what AlertEngine.sendTest delivers: a real-looking message flagged as a test
+ expect(
+ await f.service.deliver(channel.id, { ...message, test: true }, { kind: 'alert_test' }),
+ ).toBe(false);
+ expect(await f.service.get(channel.id)).toMatchObject({
+ enabled: true,
+ consecutiveFailures: 0,
+ lastError: 'HTTP 410',
+ });
+ expect(f.events.ofType('notifications.channel.disabled')).toHaveLength(0);
+ });
+
+ it('never logs the secret nor the destination', async () => {
+ const f = webhook({ maxConsecutiveFailures: 1 });
+ const { channel } = await f.service.create(
+ orgLocation,
+ { type: 'webhook', name: 'SIEM', destination: HOOK },
+ 'creator',
+ );
+ await f.service.rotateSecret(channel.id);
+ f.signed.failWith = [503, 503, 503, 503];
+ await f.service.deliver(channel.id, message);
+ expect(f.lines.length).toBeGreaterThan(0);
+ const logged = JSON.stringify(f.lines);
+ expect(logged).toContain(channel.id);
+ expect(logged).not.toContain('whsec_');
+ expect(logged).not.toContain('hooks.example.com');
+ });
+});
diff --git a/src/modules/notifications/application/notification-channel.service.ts b/src/modules/notifications/application/notification-channel.service.ts
index ef98c6a..7a24b23 100644
--- a/src/modules/notifications/application/notification-channel.service.ts
+++ b/src/modules/notifications/application/notification-channel.service.ts
@@ -8,8 +8,12 @@ import type {
ChatTransport,
} from '#lib/server/infra/notifications/chat-notification';
import { WebhookDeliveryError } from '#lib/server/infra/http/webhook-request';
+import { generateSigningSecret } from '#lib/server/infra/notifications/webhook/webhook-signature';
+import type { EventPublisher } from '#lib/server/events';
import {
MAX_CHANNEL_NAME_LENGTH,
+ MAX_CONSECUTIVE_FAILURES,
+ SECRET_ROTATION_GRACE_MS,
NotificationChannelDomain,
NotificationChannelNotFoundError,
NotificationChannelValidationError,
@@ -29,6 +33,10 @@ export type ChannelDelivery = {
type: ChatChannelType;
destination: string;
message: ChannelMessage;
+ /** Same for every retry of this delivery (`X-GitOps-Delivery`). */
+ deliveryId: string;
+ /** Active signing secrets in clear, newest first (signed types only). */
+ signingSecrets: string[];
/** Called by the queue once the delivery succeeded or definitively failed. */
report: (outcome: { sent: true } | { sent: false; error: unknown }) => void;
};
@@ -51,26 +59,55 @@ export type ChannelInput = {
enabled?: unknown;
};
+/**
+ * A channel just created or with a rotated secret. `signingSecret` is in clear and is returned
+ * this one time only (signed types; `null` otherwise): it is never readable again.
+ */
+export type IssuedChannel = {
+ channel: NotificationChannelDomain;
+ signingSecret: string | null;
+};
+
export type NotificationChannelServiceOptions = {
now?: () => Date;
generateId?: () => string;
+ generateDeliveryId?: () => string;
+ generateSecret?: () => string;
+ /** Publishes `notifications.channel.disabled` when a channel disables itself. */
+ events?: EventPublisher;
+ /** Definitive failures in a row before a channel disables itself (default 20). */
+ maxConsecutiveFailures?: number;
+ /** How long the previous secret keeps signing after a rotation (default 24 h). */
+ rotationGraceMs?: number;
/** How often a healthy channel records `lastDeliveryAt` (each record is a GitDB commit). */
deliveryStampIntervalMs?: number;
- logger?: { warn: (object: object, message: string) => void };
+ logger?: {
+ warn: (object: object, message: string) => void;
+ error?: (object: object, message: string) => void;
+ };
};
+/** Failures that say nothing about the destination: they never count toward auto-disabling. */
+const UNCOUNTED_FAILURES = new Set(['unavailable']);
+
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`.
+ * send, stored encrypted and only ever shown masked. Signed types also get a signing secret,
+ * shown once and rotatable with a grace period. Deliveries go through a queue with retries; a
+ * definitive failure is recorded in `lastError`, and after `maxConsecutiveFailures` of them in a
+ * row the channel disables itself and `notifications.channel.disabled` is published.
*/
export class NotificationChannelService {
private readonly now: () => Date;
private readonly generateId: () => string;
private readonly stampIntervalMs: number;
+ private readonly generateDeliveryId: () => string;
+ private readonly generateSecret: () => string;
+ private readonly maxFailures: number;
+ private readonly rotationGraceMs: number;
constructor(
private readonly repository: NotificationChannelRepositoryPort,
@@ -82,6 +119,10 @@ export class NotificationChannelService {
this.now = options.now ?? (() => new Date());
this.generateId = options.generateId ?? (() => crypto.randomUUID());
this.stampIntervalMs = options.deliveryStampIntervalMs ?? DEFAULT_STAMP_INTERVAL_MS;
+ this.generateDeliveryId = options.generateDeliveryId ?? (() => crypto.randomUUID());
+ this.generateSecret = options.generateSecret ?? generateSigningSecret;
+ this.maxFailures = Math.max(1, options.maxConsecutiveFailures ?? MAX_CONSECUTIVE_FAILURES);
+ this.rotationGraceMs = options.rotationGraceMs ?? SECRET_ROTATION_GRACE_MS;
}
/** Channel types that can be created now (a transport is registered for them). */
@@ -112,18 +153,30 @@ export class NotificationChannelService {
}
toView(channel: NotificationChannelDomain): NotificationChannelView {
- const { webhookUrl: _secret, ...rest } = channel.toJson();
+ const {
+ webhookUrl: _destination,
+ signingSecret: _secret,
+ previousSigningSecret: _previous,
+ ...rest
+ } = channel.toJson();
+ void _destination;
void _secret;
+ void _previous;
let destinationMasked = '••••';
try {
destinationMasked = maskDestination(this.cipher.decrypt(channel.id, channel.webhookUrl));
} catch {
// an undecryptable destination (rotated key) shows as fully masked
}
+ const transport = this.transports.get(channel.type);
return {
...rest,
destinationMasked,
- available: this.transports.get(channel.type) !== null,
+ available: transport !== null,
+ signed: transport?.signed === true || channel.signingSecret !== null,
+ rotationEndsAt: channel.previousSecretActive(this.now())
+ ? channel.previousSecretExpiresAt
+ : null,
};
}
@@ -131,17 +184,20 @@ export class NotificationChannelService {
location: ChannelLocation,
input: ChannelInput,
actorUserId: string,
- ): Promise {
+ ): 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;
+ const destination = type
+ ? await 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 signingSecret = this.transports.get(type)?.signed ? this.generateSecret() : null;
const row = new NotificationChannelDomain({
id,
type,
@@ -156,9 +212,41 @@ export class NotificationChannelService {
updatedAt: timestamp,
lastDeliveryAt: null,
lastError: null,
+ signingSecret: signingSecret
+ ? this.cipher.encrypt(id, signingSecret, 'signing-secret')
+ : null,
+ previousSigningSecret: null,
+ previousSecretExpiresAt: null,
+ consecutiveFailures: 0,
+ disabledReason: null,
}).toJson();
await this.repository.create(row);
- return new NotificationChannelDomain(row);
+ return { channel: new NotificationChannelDomain(row), signingSecret };
+ }
+
+ /**
+ * Replaces the signing secret of a signed channel. The previous one keeps signing next to the
+ * new one (`v1=` twice) for `rotationGraceMs`, so receivers can switch without losing
+ * deliveries. Rotating again during the grace period drops the oldest secret.
+ */
+ async rotateSecret(id: string): Promise {
+ const channel = await this.get(id);
+ if (!this.transports.get(channel.type)?.signed) {
+ throw new NotificationChannelValidationError({ type: 'not_signed' });
+ }
+ const signingSecret = this.generateSecret();
+ const changes: NotificationChannelChanges = {
+ signingSecret: this.cipher.encrypt(channel.id, signingSecret, 'signing-secret'),
+ previousSigningSecret: channel.signingSecret,
+ previousSecretExpiresAt: channel.signingSecret
+ ? new Date(this.now().getTime() + this.rotationGraceMs).toISOString()
+ : null,
+ };
+ await this.repository.update(id, changes);
+ return {
+ channel: new NotificationChannelDomain({ ...channel.toJson(), ...changes }),
+ signingSecret,
+ };
}
/** Name, enabled and destination; the type can't change. An empty destination keeps it. */
@@ -169,13 +257,19 @@ export class NotificationChannelService {
if (input.name !== undefined) changes.name = this.validateName(input.name, errors);
if (input.enabled !== undefined) {
changes.enabled = input.enabled === true || input.enabled === 'true';
+ // enabled again by a person (or disabled on purpose): the failure streak is over
+ if (changes.enabled !== channel.enabled) {
+ changes.disabledReason = null;
+ changes.consecutiveFailures = 0;
+ }
}
if (typeof input.destination === 'string' && input.destination.trim()) {
- const destination = this.validateDestination(channel.type, input.destination, errors);
+ const destination = await 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;
+ changes.consecutiveFailures = 0;
}
}
if (Object.keys(errors).length > 0) throw new NotificationChannelValidationError(errors);
@@ -218,23 +312,28 @@ export class NotificationChannelService {
message: ChannelMessage,
context: Record,
): Promise {
- const transport = this.transports.get(channel.type);
- if (!transport) {
- await this.recordFailure(channel, 'unavailable');
+ // a test (channel or alert "Send test") never counts toward disabling the channel
+ const counts = !message.test;
+ const fail = async (reason: string) => {
+ await this.recordFailure(channel, reason, counts);
return false;
- }
+ };
+ const transport = this.transports.get(channel.type);
+ if (!transport) return fail('unavailable');
let destination: string;
+ let signingSecrets: string[] = [];
try {
destination = this.cipher.decrypt(channel.id, channel.webhookUrl);
+ if (transport.signed) signingSecrets = this.activeSecrets(channel);
} 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;
+ return fail('undecryptable');
}
+ if (transport.signed && signingSecrets.length === 0) return fail('missing_secret');
+ // the stored value is checked again: GitDB can be edited outside the app, and DNS changes
+ const checked = await Promise.resolve(transport.validateDestination(destination)).catch(() => ({
+ ok: false as const,
+ }));
+ if (!checked.ok) return fail('invalid_destination');
let outcome: { sent: true } | { sent: false; error: unknown } = { sent: false, error: null };
const sent = await this.sender.enqueue(
@@ -243,6 +342,8 @@ export class NotificationChannelService {
type: channel.type,
destination,
message,
+ deliveryId: this.generateDeliveryId(),
+ signingSecrets,
report: (result) => {
outcome = result;
},
@@ -259,26 +360,106 @@ export class NotificationChannelService {
: error instanceof Error
? error.name
: 'failed',
+ counts,
);
}
return sent;
}
+ /** Signing secrets in clear, newest first; the previous one only during its grace period. */
+ private activeSecrets(channel: NotificationChannelDomain): string[] {
+ if (!channel.signingSecret) return [];
+ const secrets = [this.cipher.decrypt(channel.id, channel.signingSecret, 'signing-secret')];
+ if (channel.previousSecretActive(this.now())) {
+ try {
+ secrets.push(
+ this.cipher.decrypt(channel.id, channel.previousSigningSecret!, 'signing-secret'),
+ );
+ } catch {
+ // the old secret is only a courtesy to receivers: the new one still signs
+ }
+ }
+ return secrets;
+ }
+
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;
+ // each write is a commit: only when the error clears, a streak ends or the stamp got old
+ if (!channel.lastError && channel.consecutiveFailures === 0 && !stale) return;
await this.repository
- .update(channel.id, { lastDeliveryAt: this.now().toISOString(), lastError: null })
+ .update(channel.id, {
+ lastDeliveryAt: this.now().toISOString(),
+ lastError: null,
+ consecutiveFailures: 0,
+ })
.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));
+ /**
+ * Records a failed delivery. Real deliveries (`counts`) extend the failure streak, and the one
+ * that reaches the limit disables an enabled channel and announces it. Test messages (from the
+ * channel or from an alert's "Send test") only record the reason: a person is watching them.
+ */
+ private async recordFailure(channel: NotificationChannelDomain, reason: string, counts = true) {
+ if (!counts || UNCOUNTED_FAILURES.has(reason)) {
+ if (channel.lastError === reason) return;
+ await this.repository
+ .update(channel.id, { lastError: reason })
+ .catch((error) => this.logWriteFailure(channel, error));
+ return;
+ }
+
+ const failures = channel.consecutiveFailures + 1;
+ const disable = channel.enabled && failures >= this.maxFailures;
+ const changes: NotificationChannelChanges = {
+ lastError: reason,
+ consecutiveFailures: failures,
+ };
+ if (disable) {
+ changes.enabled = false;
+ changes.disabledReason = 'failures';
+ }
+ try {
+ await this.repository.update(channel.id, changes);
+ } catch (error) {
+ this.logWriteFailure(channel, error);
+ return;
+ }
+ // the row read before sending is stale now: keep the in-memory copy in step for callers
+ Object.assign(channel, changes);
+ if (disable) this.announceDisabled(channel, failures, reason);
+ }
+
+ private announceDisabled(channel: NotificationChannelDomain, failures: number, reason: string) {
+ this.options.logger?.warn(
+ { channelId: channel.id, type: channel.type, failures, reason },
+ '[channels] channel disabled after repeated delivery failures',
+ );
+ try {
+ this.options.events?.publish(
+ 'notifications.channel.disabled',
+ {
+ channelId: channel.id,
+ name: channel.name,
+ type: channel.type,
+ reason: 'failures',
+ failures,
+ lastError: reason,
+ createdByUserId: channel.createdByUserId,
+ },
+ {
+ scope: { organizationId: channel.organizationId, projectId: channel.projectId },
+ // the platform did it, not whoever caused the event that failed to deliver
+ actor: { kind: 'system' },
+ },
+ );
+ } catch (error) {
+ this.options.logger?.error?.(
+ { channelId: channel.id, err: error instanceof Error ? error.name : 'unknown' },
+ '[channels] failed to publish notifications.channel.disabled',
+ );
+ }
}
private logWriteFailure(channel: NotificationChannelDomain, error: unknown) {
@@ -307,11 +488,11 @@ export class NotificationChannelService {
return name;
}
- private validateDestination(
+ private async validateDestination(
type: ChatChannelType,
value: unknown,
errors: Record,
- ): string | null {
+ ): Promise {
if (typeof value !== 'string' || !value.trim()) {
errors.destination = 'required';
return null;
@@ -321,7 +502,7 @@ export class NotificationChannelService {
errors.type = 'type_unavailable';
return null;
}
- const checked = transport.validateDestination(value.trim());
+ const checked = await transport.validateDestination(value.trim());
if (!checked.ok) {
errors.destination = checked.error;
return null;
diff --git a/src/modules/notifications/application/testing.ts b/src/modules/notifications/application/testing.ts
index de32189..779698a 100644
--- a/src/modules/notifications/application/testing.ts
+++ b/src/modules/notifications/application/testing.ts
@@ -1,9 +1,10 @@
import {
+ ChatNotification,
DeliveryQueue,
type ChatChannelType,
- type ChatNotification,
type ChatTransport,
} from '#lib/server/infra/notifications';
+import type { EventPublisher } from '#lib/server/events';
import {
isRetryableWebhookError,
validateWebhookUrl,
@@ -81,12 +82,17 @@ export function createNotificationsFixture(options: { origin?: string | null } =
export class FakeChatTransport implements ChatTransport {
sent: ChatNotification[] = [];
failWith: Array = [];
+ /** Every attempt, failed ones included (retries share their `deliveryId`). */
+ attempts: ChatNotification[] = [];
+
+ constructor(readonly signed = false) {}
validateDestination(raw: unknown) {
return validateWebhookUrl(raw, { hosts: ['hooks.example.com'], pathPrefix: '/hook/' });
}
async send(notification: ChatNotification) {
+ this.attempts.push(notification);
const failure = this.failWith.shift();
if (failure === 'network') throw new WebhookDeliveryError(null, true, null, 'network');
if (typeof failure === 'number') {
@@ -99,21 +105,32 @@ export class FakeChatTransport implements ChatTransport {
export function createChannelsFixture(
options: {
types?: ChatChannelType[];
+ /** Transports by type instead of the shared fake (a real webhook transport, a signed fake). */
+ transports?: Partial>;
+ events?: EventPublisher;
+ maxConsecutiveFailures?: number;
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 types =
+ options.types ?? (['slack', ...Object.keys(options.transports ?? {})] as ChatChannelType[]);
+ const transportFor = (type: ChatChannelType): ChatTransport | null =>
+ options.transports?.[type] ?? (types.includes(type) ? transport : null);
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),
+ transportFor(delivery.type)!.send(
+ new ChatNotification({
+ channel: delivery.type,
+ destination: delivery.destination,
+ message: delivery.message,
+ deliveryId: delivery.deliveryId,
+ signingSecrets: delivery.signingSecrets,
+ }),
+ ),
retry: {
isRetryable: isRetryableWebhookError,
retryAfterMs: webhookRetryAfter,
@@ -125,15 +142,24 @@ export function createChannelsFixture(
onSettled: (delivery, outcome) => delivery.report(outcome),
});
let id = 0;
+ let delivery = 0;
+ let secret = 0;
const service = new NotificationChannelService(
repository,
createChannelCipher(() => 'test-encryption-key'),
{
- get: (type) => (types.includes(type) ? transport : null),
+ get: (type) => (types.includes(type) ? transportFor(type) : null),
available: () => [...types],
},
queue,
- { now: () => clock.now, generateId: () => `channel-${++id}` },
+ {
+ now: () => clock.now,
+ generateId: () => `channel-${++id}`,
+ generateDeliveryId: () => `delivery-${++delivery}`,
+ generateSecret: () => `whsec_test${++secret}`,
+ events: options.events,
+ maxConsecutiveFailures: options.maxConsecutiveFailures,
+ },
);
return {
clock,
diff --git a/src/modules/notifications/domain/notification-channel.domain.ts b/src/modules/notifications/domain/notification-channel.domain.ts
index b55f107..9a5762c 100644
--- a/src/modules/notifications/domain/notification-channel.domain.ts
+++ b/src/modules/notifications/domain/notification-channel.domain.ts
@@ -25,16 +25,39 @@ export type NotificationChannelRow = ChannelLocation & {
lastDeliveryAt: string | null;
/** Short reason of the last failed delivery (`HTTP 404`, `timeout`), cleared on success. */
lastError: string | null;
+ /** Signing secret (signed types only), encrypted: never returned nor logged. */
+ signingSecret: string | null;
+ /** Secret being replaced, encrypted; still signs until `previousSecretExpiresAt`. */
+ previousSigningSecret: string | null;
+ previousSecretExpiresAt: string | null;
+ /** Definitive delivery failures in a row (tests don't count); reset by a success. */
+ consecutiveFailures: number;
+ /** `failures` when the platform disabled the channel; `null` otherwise. */
+ disabledReason: ChannelDisabledReason | null;
};
-/** What the API and the pages may show: the destination only masked. */
-export type NotificationChannelView = Omit & {
+export type ChannelDisabledReason = 'failures';
+
+/** Encrypted fields: none of them ever leaves the server. */
+type SecretFields = 'webhookUrl' | 'signingSecret' | 'previousSigningSecret';
+
+/** What the API and the pages may show: the destination only masked, secrets never. */
+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;
+ /** Its type signs deliveries (`webhook`): it has a secret that can be rotated. */
+ signed: boolean;
+ /** A rotation is in its grace period: the previous secret still signs until this date. */
+ rotationEndsAt: string | null;
};
+/** Definitive failures in a row after which a channel disables itself. */
+export const MAX_CONSECUTIVE_FAILURES = 20;
+/** How long the previous secret keeps signing after a rotation. */
+export const SECRET_ROTATION_GRACE_MS = 24 * 60 * 60 * 1000;
+
export const MAX_CHANNEL_NAME_LENGTH = 80;
function toIso(value: unknown): string | null {
@@ -56,6 +79,11 @@ export class NotificationChannelDomain implements NotificationChannelRow {
updatedAt: string;
lastDeliveryAt: string | null;
lastError: string | null;
+ signingSecret: string | null;
+ previousSigningSecret: string | null;
+ previousSecretExpiresAt: string | null;
+ consecutiveFailures: number;
+ disabledReason: ChannelDisabledReason | null;
constructor(row: Record) {
this.id = row.id;
@@ -71,6 +99,18 @@ export class NotificationChannelDomain implements NotificationChannelRow {
this.updatedAt = toIso(row.updatedAt) ?? this.createdAt;
this.lastDeliveryAt = toIso(row.lastDeliveryAt);
this.lastError = row.lastError ?? null;
+ this.signingSecret = row.signingSecret || null;
+ this.previousSigningSecret = row.previousSigningSecret || null;
+ this.previousSecretExpiresAt = toIso(row.previousSecretExpiresAt);
+ const failures = Number(row.consecutiveFailures);
+ this.consecutiveFailures = Number.isInteger(failures) && failures > 0 ? failures : 0;
+ this.disabledReason = row.disabledReason === 'failures' ? 'failures' : null;
+ }
+
+ /** Whether the previous secret still signs at `now` (rotation grace period). */
+ previousSecretActive(now: Date): boolean {
+ if (!this.previousSigningSecret || !this.previousSecretExpiresAt) return false;
+ return Date.parse(this.previousSecretExpiresAt) > now.getTime();
}
get location(): ChannelLocation {
@@ -101,6 +141,11 @@ export class NotificationChannelDomain implements NotificationChannelRow {
updatedAt: this.updatedAt,
lastDeliveryAt: this.lastDeliveryAt,
lastError: this.lastError,
+ signingSecret: this.signingSecret,
+ previousSigningSecret: this.previousSigningSecret,
+ previousSecretExpiresAt: this.previousSecretExpiresAt,
+ consecutiveFailures: this.consecutiveFailures,
+ disabledReason: this.disabledReason,
};
}
}
diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts
index 912319c..24ba7f9 100644
--- a/src/modules/notifications/index.ts
+++ b/src/modules/notifications/index.ts
@@ -1,12 +1,15 @@
import {
ChatNotification,
+ ChatTransportUnavailableError,
DeliveryQueue,
absoluteUrl,
availableChatTypes,
getChatTransport,
notify,
- sendWithLatestNotify,
+ registerChatTransport,
} from '#lib/server/infra/notifications';
+import { createWebhookTransport } from '#lib/server/infra/notifications/webhook/webhook.transport';
+import { eventBus } from '#lib/server/events';
import { isRetryableWebhookError, webhookRetryAfter } from '#lib/server/infra/http/webhook-request';
import { RateLimiter } from '#lib/server/infra/rate-limit';
import { createLogger } from '#lib/server/logger';
@@ -19,6 +22,7 @@ import {
type ChannelDelivery,
} from './application/notification-channel.service';
import { createChannelCipher } from './infrastructure/crypto/channel-cipher';
+import { readWebhookChannelConfig } from './infrastructure/config/webhook.config';
import { NotificationChannelRepository } from './infrastructure/repositories/notification-channel.repository';
import { ExternalRecipientMailNotifier } from './infrastructure/external-recipient-mail.notifier';
import { ExternalRecipientRepository } from './infrastructure/repositories/external-recipient.repository';
@@ -61,6 +65,10 @@ export const notificationSettingsService = new NotificationSettingsService(
externalRecipientService,
);
+// transports of the channel types this build supports; Slack (#97) and Google Chat (#98) add
+// theirs here. Registering again on HMR just replaces the previous one
+registerChatTransport('webhook', createWebhookTransport(readWebhookChannelConfig()));
+
const CHANNEL_QUEUE_KEY = Symbol.for('gitops.notifications.channel-queue');
const CHANNEL_SHUTDOWN_KEY = Symbol.for('gitops.notifications.channel-shutdown');
type GlobalWithChannelQueue = typeof globalThis & {
@@ -71,14 +79,22 @@ type GlobalWithChannelQueue = typeof globalThis & {
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,
- }),
- ),
+ // the transport comes from the process-wide registry, not from `notify()`: in dev the server code
+ // runs in more than one Vite module runner (and HMR reloads it), and each copy of `notify` has
+ // its own transport map, where the chat transports may be missing
+ send: async (delivery) => {
+ const transport = getChatTransport(delivery.type);
+ if (!transport) throw new ChatTransportUnavailableError(delivery.type);
+ const notification = new ChatNotification({
+ channel: delivery.type,
+ destination: delivery.destination,
+ message: delivery.message,
+ deliveryId: delivery.deliveryId,
+ signingSecrets: delivery.signingSecrets,
+ });
+ notification.validate();
+ await transport.send(notification);
+ },
concurrency: 3,
retry: { isRetryable: isRetryableWebhookError, retryAfterMs: webhookRetryAfter },
logger: createLogger('channels'),
@@ -92,7 +108,7 @@ export const notificationChannelService = new NotificationChannelService(
createChannelCipher(() => passwordService.ensureEncryptionKey()),
{ get: (type) => getChatTransport(type), available: () => availableChatTypes() },
channelQueue,
- { logger: log },
+ { logger: log, events: eventBus },
);
export function registerChannelShutdown(): void {
@@ -127,9 +143,10 @@ export type { NotificationSettings } from './domain/notification-settings.domain
export {
NotificationChannelNotFoundError,
NotificationChannelValidationError,
+ MAX_CONSECUTIVE_FAILURES,
type ChannelLocation,
type NotificationChannelView,
} from './domain/notification-channel.domain';
-export type { ChannelInput } from './application/notification-channel.service';
+export type { ChannelInput, IssuedChannel } 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/config/webhook.config.ts b/src/modules/notifications/infrastructure/config/webhook.config.ts
new file mode 100644
index 0000000..c64ecc4
--- /dev/null
+++ b/src/modules/notifications/infrastructure/config/webhook.config.ts
@@ -0,0 +1,27 @@
+import * as env from '$app/env/private';
+
+/**
+ * Development-only relaxations of the generic webhook's anti-SSRF rules. Both default to `false`
+ * and must stay so in production: a free URL is otherwise a way into the internal network.
+ */
+export type WebhookChannelConfig = {
+ /** `NOTIFICATIONS_WEBHOOK_ALLOW_HTTP`: accept `http:` URLs. */
+ allowHttp: boolean;
+ /** `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS`: let URLs reach private addresses. */
+ allowPrivateTargets: boolean;
+};
+
+function flag(value: string | undefined): boolean {
+ const raw = value
+ ?.trim()
+ .replace(/^["']|["']$/g, '')
+ .toLowerCase();
+ return raw === 'true' || raw === '1' || raw === 'yes';
+}
+
+export function readWebhookChannelConfig(): WebhookChannelConfig {
+ return {
+ allowHttp: flag(env.NOTIFICATIONS_WEBHOOK_ALLOW_HTTP),
+ allowPrivateTargets: flag(env.NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS),
+ };
+}
diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts
index 5ab63ec..769fb77 100644
--- a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts
+++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts
@@ -6,9 +6,12 @@ const KEY_SALT = 'gitops:notifications:channel-destination:v1';
const IV_BYTES = 12;
const AUTH_TAG_BYTES = 16;
+/** What an encrypted value is: a ciphertext of one purpose doesn't decrypt as another. */
+export type ChannelSecretPurpose = 'destination' | 'signing-secret';
+
export interface ChannelCipher {
- encrypt(channelId: string, value: string): string;
- decrypt(channelId: string, stored: string): string;
+ encrypt(channelId: string, value: string, purpose?: ChannelSecretPurpose): string;
+ decrypt(channelId: string, stored: string, purpose?: ChannelSecretPurpose): string;
}
/**
@@ -26,15 +29,22 @@ export function createChannelCipher(secret: () => string): ChannelCipher {
}
return cached.key;
};
- const aad = (channelId: string) => Buffer.from(`${VERSION}:channel:${channelId}`, 'utf8');
+ // the destination keeps the original AAD, so channels stored before purposes existed decrypt
+ const aad = (channelId: string, purpose: ChannelSecretPurpose = 'destination') =>
+ Buffer.from(
+ purpose === 'destination'
+ ? `${VERSION}:channel:${channelId}`
+ : `${VERSION}:channel:${channelId}:${purpose}`,
+ 'utf8',
+ );
return {
- encrypt(channelId, value) {
+ encrypt(channelId, value, purpose) {
const iv = crypto.randomBytes(IV_BYTES);
const cipher = crypto.createCipheriv(ALGORITHM, key(), iv, {
authTagLength: AUTH_TAG_BYTES,
});
- cipher.setAAD(aad(channelId));
+ cipher.setAAD(aad(channelId, purpose));
const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
return [
VERSION,
@@ -43,7 +53,7 @@ export function createChannelCipher(secret: () => string): ChannelCipher {
ciphertext.toString('base64'),
].join(':');
},
- decrypt(channelId, stored) {
+ decrypt(channelId, stored, purpose) {
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`);
@@ -52,7 +62,7 @@ export function createChannelCipher(secret: () => string): ChannelCipher {
const decipher = crypto.createDecipheriv(ALGORITHM, key(), Buffer.from(iv, 'base64'), {
authTagLength: AUTH_TAG_BYTES,
});
- decipher.setAAD(aad(channelId));
+ decipher.setAAD(aad(channelId, purpose));
decipher.setAuthTag(Buffer.from(authTag, 'base64'));
return Buffer.concat([
decipher.update(Buffer.from(ciphertext, 'base64')),
diff --git a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts
index 8f11637..bbda750 100644
--- a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts
+++ b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts
@@ -6,7 +6,19 @@ import {
} from '../../domain/notification-channel.domain';
export type NotificationChannelChanges = Partial<
- Pick
+ Pick<
+ NotificationChannelRow,
+ | 'name'
+ | 'webhookUrl'
+ | 'enabled'
+ | 'lastDeliveryAt'
+ | 'lastError'
+ | 'signingSecret'
+ | 'previousSigningSecret'
+ | 'previousSecretExpiresAt'
+ | 'consecutiveFailures'
+ | 'disabledReason'
+ >
>;
/** Persistence port; `InMemoryNotificationChannelRepository` implements it in tests. */
diff --git a/src/routes/api/alerts/server.test.ts b/src/routes/api/alerts/server.test.ts
index 0620fe2..aae44d4 100644
--- a/src/routes/api/alerts/server.test.ts
+++ b/src/routes/api/alerts/server.test.ts
@@ -61,8 +61,24 @@ vi.mock('#modules/alerts', async () => {
const { InMemoryAlertRepository } =
await import('#modules/alerts/infrastructure/repositories/in-memory-alert.repository');
const { buildSampleEvent } = await import('#modules/alerts/domain/sample-event');
- const { createNotificationsFixture } = await import('#modules/notifications/application/testing');
+ const { createNotificationsFixture, createChannelsFixture } =
+ await import('#modules/notifications/application/testing');
+ const { buildAlertChannelMessage } =
+ await import('#modules/alerts/infrastructure/alert-channel-message');
const notifications = createNotificationsFixture();
+ const channels = createChannelsFixture();
+ const channelPort = {
+ listUsable: async (location: { organizationId: string; projectId: string | null }) =>
+ (await channels.service.listUsable(location)).map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ type: channel.type,
+ scope: channel.scope,
+ enabled: channel.enabled,
+ })),
+ deliver: (id: string, message: never, context?: Record) =>
+ channels.service.deliver(id, message, context),
+ };
await notifications.settings.setAllowedDomains('org-1', ['partner.com']);
const repository = new InMemoryAlertRepository();
@@ -85,6 +101,7 @@ vi.mock('#modules/alerts', async () => {
const alertService = new AlertService(repository, directory, {
generateId: () => `alert-${++id}`,
externalRecipients: notifications.recipients,
+ channels: channelPort,
});
const alertEngine = new AlertEngine({
repository,
@@ -97,6 +114,9 @@ vi.mock('#modules/alerts', async () => {
},
sendSystemNotification: async () => {},
},
+ channels: channelPort,
+ channelMessage: buildAlertChannelMessage,
+ deliveryEnabled: () => mail.configured,
logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
});
return {
@@ -107,6 +127,7 @@ vi.mock('#modules/alerts', async () => {
buildSampleEvent,
repository,
notifications,
+ channels,
isMailConfigured: () => mail.configured,
};
});
@@ -125,6 +146,10 @@ const notifications = (
}
).notifications;
+type ChannelsFixture = ReturnType<
+ typeof import('#modules/notifications/application/testing').createChannelsFixture
+>;
+
const ADMIN_GRANTS = [
'project:alerts:read',
'project:alerts:create',
@@ -267,6 +292,48 @@ describe('/api/alerts', () => {
expect(statuses).toEqual([200, 200, 200, 200, 200, 429]);
});
+ it('sends the test to the selected channels too, and without SMTP only to them', async () => {
+ const fixture = (alerts as unknown as { channels: ChannelsFixture }).channels;
+ fixture.transport.sent = [];
+ const { channel } = await fixture.service.create(
+ { scope: 'project', organizationId: 'org-1', projectId: 'p1' },
+ { type: 'slack', name: '#ops', destination: 'https://hooks.example.com/hook/T0/B0/x' },
+ 'admin',
+ );
+ const caller = { user: { id: 'channels' } };
+ grants.users.channels = {
+ 'project:p1': [...ADMIN_GRANTS, 'project:notifications:update'],
+ };
+ const created = await call(collection.POST, {
+ locals: caller,
+ body: { ...guided, channelIds: [channel.id] },
+ });
+ expect(created.status).toBe(201);
+ const { id } = (await created.json()) as { id: string };
+
+ sentEmails.length = 0;
+ const both = await call(test.POST, { locals: caller, params: { id }, body: { send: true } });
+ await expect(both.json()).resolves.toMatchObject({ delivery: { sent: 2, failed: 0 } });
+ expect(sentEmails).toHaveLength(1);
+ expect(fixture.transport.sent).toHaveLength(1);
+ expect(fixture.transport.sent[0].message.test).toBe(true);
+
+ mail.configured = false;
+ sentEmails.length = 0;
+ const channelsOnly = await call(test.POST, {
+ locals: caller,
+ params: { id },
+ body: { send: true },
+ });
+ expect(channelsOnly.status).toBe(200);
+ await expect(channelsOnly.json()).resolves.toMatchObject({
+ delivery: { sent: 1, failed: 0 },
+ });
+ expect(sentEmails).toHaveLength(0);
+ expect(fixture.transport.sent).toHaveLength(2);
+ mail.configured = true;
+ });
+
it('asks new external addresses of a draft to confirm, then sends them the test', async () => {
grants.users.admin['project:p1'].push('project:notifications:update');
const body = {
diff --git a/src/routes/api/notification-channels/[id]/rotate-secret/+server.ts b/src/routes/api/notification-channels/[id]/rotate-secret/+server.ts
new file mode 100644
index 0000000..0bde825
--- /dev/null
+++ b/src/routes/api/notification-channels/[id]/rotate-secret/+server.ts
@@ -0,0 +1,8 @@
+import { toResponse } from '#lib/server/alerts/http';
+import { rotateChannelSecret } from '#lib/server/notifications/channels';
+
+// POST /api/notification-channels//rotate-secret: new signing secret, returned this one time
+// (`signingSecret`); the previous one keeps signing next to it for 24 h
+export async function POST({ params, locals }) {
+ return toResponse(await rotateChannelSecret(locals, params.id));
+}
diff --git a/src/routes/api/notification-channels/server.test.ts b/src/routes/api/notification-channels/server.test.ts
index a355990..10235e3 100644
--- a/src/routes/api/notification-channels/server.test.ts
+++ b/src/routes/api/notification-channels/server.test.ts
@@ -49,11 +49,12 @@ vi.mock('#modules/organization', () => ({
}));
vi.mock('#modules/notifications', async () => {
- const { createChannelsFixture } = await import('#modules/notifications/application/testing');
+ const { createChannelsFixture, FakeChatTransport } =
+ 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();
+ const fixture = createChannelsFixture({ transports: { webhook: new FakeChatTransport(true) } });
return {
...domain,
buildChannelTestMessage,
@@ -70,6 +71,7 @@ const notifications = (await import('#modules/notifications')) as unknown as {
const collection = await import('./+server');
const item = await import('./[id]/+server');
const test = await import('./[id]/test/+server');
+const rotate = await import('./[id]/rotate-secret/+server');
const HOOK = 'https://hooks.example.com/hook/T0/B0/topsecret1a2b';
const ORG_ADMIN = ['read', 'create', 'update', 'delete'].map(
@@ -257,4 +259,58 @@ describe('/api/notification-channels', () => {
).toBe(200);
expect(notifications.fixture.repository.rows).toHaveLength(0);
});
+
+ it('returns a webhook signing secret only when creating or rotating it', async () => {
+ const created = await call(collection.POST, {
+ locals: as('orgAdmin'),
+ body: { organizationId: 'org-1', type: 'webhook', name: 'SIEM', destination: HOOK },
+ });
+ expect(created.status).toBe(201);
+ const body = (await created.json()) as { id: string; signingSecret: string; signed: boolean };
+ expect(body.signingSecret).toMatch(/^whsec_/);
+ expect(body.signed).toBe(true);
+ const first = body.signingSecret;
+
+ const listed = await call(collection.GET, {
+ locals: as('orgAdmin'),
+ url: 'http://localhost/api/notification-channels?organizationId=org-1',
+ });
+ const fetched = await call(item.GET, { locals: as('orgAdmin'), params: { id: body.id } });
+ const patched = await call(item.PATCH, {
+ locals: as('orgAdmin'),
+ params: { id: body.id },
+ body: { name: 'SIEM 2' },
+ });
+ for (const response of [listed, fetched, patched]) {
+ expect(response.status).toBe(200);
+ const text = await response.text();
+ expect(text).not.toContain('whsec_');
+ expect(text).not.toContain('signingSecret');
+ expect(text).not.toContain('topsecret');
+ }
+
+ // rotating needs update
+ expect(
+ (await call(rotate.POST, { locals: as('orgReader'), params: { id: body.id } })).status,
+ ).toBe(403);
+ const rotated = await call(rotate.POST, { locals: as('orgAdmin'), params: { id: body.id } });
+ expect(rotated.status).toBe(200);
+ const next = (await rotated.json()) as { signingSecret: string; rotationEndsAt: string };
+ expect(next.signingSecret).toMatch(/^whsec_/);
+ expect(next.signingSecret).not.toBe(first);
+ expect(next.rotationEndsAt).toBeTruthy();
+ });
+
+ it('cannot rotate a channel type that does not sign', async () => {
+ const created = await createOrgChannel();
+ const response = await call(rotate.POST, {
+ locals: as('orgAdmin'),
+ params: { id: created.id },
+ });
+ expect(response.status).toBe(400);
+ expect(await response.json()).toMatchObject({ errors: { type: 'not_signed' } });
+ expect(
+ (await call(rotate.POST, { locals: as('orgAdmin'), params: { id: 'missing' } })).status,
+ ).toBe(404);
+ });
});
diff --git a/src/routes/org/[org]/settings/events/event-view.ts b/src/routes/org/[org]/settings/events/event-view.ts
index d1d7cdf..e4b543d 100644
--- a/src/routes/org/[org]/settings/events/event-view.ts
+++ b/src/routes/org/[org]/settings/events/event-view.ts
@@ -13,6 +13,7 @@ export const EVENT_MODULES: readonly EventModule[] = [
'projects',
'organization',
'access',
+ 'notifications',
];
export type EventStatusFilter = 'all' | 'pending' | 'acked';
From b5a2845f9cc322784835aa7406883243d20c43f0 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Wed, 25 Nov 2026 16:45:51 +0100
Subject: [PATCH 2/3] Feat: Add alerts webhooks
---
e2e/specs/alerts.spec.ts | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts
index d3dc590..882a056 100644
--- a/e2e/specs/alerts.spec.ts
+++ b/e2e/specs/alerts.spec.ts
@@ -79,7 +79,7 @@ test.describe('project alerts', () => {
await expect(result).toContainText(seed.personas.projectAdmin.username);
await expect(result).toContainText('oncall@example.com');
await expect(result).toContainText('Sin añadir');
- await expect(result).toContainText('no se ha enviado ningún email');
+ await expect(result).toContainText('no se ha enviado nada');
await wizard.getByRole('button', { name: 'Crear alerta' }).click();
await expect(wizard).toBeHidden();
From 39f6a7272c4d41d190b8be5b705b5481d1b765e0 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Thu, 26 Nov 2026 08:31:10 +0100
Subject: [PATCH 3/3] Chore: retrigger CI
Co-Authored-By: Claude Opus 5.5