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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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: <ORIGIN>/auth/sso/google/callback
GOOGLE_SSO_CLIENT_ID=
Expand Down
13 changes: 9 additions & 4 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,15 @@ verificación y desuscripción. En `/org/<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
Expand Down
59 changes: 46 additions & 13 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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=<unix>,v1=<hash>[,v1=<old-hash>]` using `HMAC-SHA256(secret,
"<timestamp>.<raw body>")` 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 `<scope>:notifications:update` (`forbidden_channel`), and a channel must be
usable from the alert's location (`unknown_channel`). The engine emails each recipient and
Expand All @@ -348,8 +380,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- Channels HTTP: `#lib/server/notifications/channels.ts` (permission-first with
`<scope>: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).
Expand Down
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down Expand Up @@ -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

Expand Down
123 changes: 123 additions & 0 deletions docs/webhooks/README.md
Original file line number Diff line number Diff line change
@@ -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 <your URL>
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=<unix seconds>,v1=<hex>`, where the signature is
`HMAC-SHA256(secret, "<t>.<raw body>")` 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=<unix>,v1=<hex>[,v1=<hex>]`)
* @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=<new>,v1=<previous>`), 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.
36 changes: 36 additions & 0 deletions docs/webhooks/verify-signature.ts
Original file line number Diff line number Diff line change
@@ -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=<unix>,v1=<hex>[,v1=<hex>]`)
* @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);
});
}
2 changes: 2 additions & 0 deletions e2e/global-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ function buildEnv(): Record<string, string | undefined> {
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),
};
}
Expand Down
Loading
Loading