Skip to content
Closed
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
15 changes: 12 additions & 3 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,14 @@ con dominio permitido (configurado en `/org/<org>/settings/notifications`). Las
campos sensibles y links al app para externals. Rutas públicas sin sesión: `/notifications/verify`
y `/notifications/unsubscribe` aceptan POST con tokens HMAC.

**Canales de notificación:** Alertas también posean a canales (webhooks genéricos, Slack, Google
Chat): un mensaje por canal, además de emails. Los canales se gestionan en Settings → Notifications
de org o proyecto, con permisos `organization:notifications:*` o `project:notifications:*`. Las
URLs se cifran (AES-GCM, nunca mostradas nuevamente) y solo se aceptan URLs `https` del host del
proveedor (validadas al guardar y antes de cada envío). Los mensajes omiten campos sensibles y
nunca van a canales (acceso diferente). Los reintentos solo aplican a errores de red, 429 y 5xx.
Un error permanente (4xx, URL inválida) se muestra en el canal como `lastError`.

Las rutas deben importar desde el `index.ts` publico.

GitDB es la unica fuente de verdad para usuarios, roles, API keys, organizaciones, proyectos,
Expand All @@ -102,12 +110,13 @@ con scope `cluster`, `organization` o `project`. Usar siempre `can()` o `isAdmin
**Permisos de org:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`,
`organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`,
`organization:audit:read`, `organization:events:read`, `organization:alerts:read`,
`organization:notifications:read` (leer destinatarios externos y dominios permitidos),
`organization:notifications:update` (añadir direcciones externas, cambiar dominios).
`organization:notifications:read` (leer destinatarios externos, dominios, canales),
`organization:notifications:update` (añadir direcciones, canales, cambiar dominios).

**Permisos de proyecto:** `project:project:read`, `project:users:read`, `project:roles:read`,
`project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`
(leer destinatarios externos de alertas), `project:notifications:update` (añadir direcciones).
(leer destinatarios externos y canales de alertas), `project:notifications:update` (añadir
direcciones y canales).

**Gating de permisos en UI:** En loaders de rutas, usar `cancanService.canSessionUser()` para verificar
permisos específicos y pasarlos a componentes como props (`canCreate`, `canUpdate`, `canDelete`) para
Expand Down
50 changes: 45 additions & 5 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
recipient hash, never the content or the address. `registerMailShutdown()` drains it on
`sveltekit:shutdown` (10 s). Invitations and password resets call `notify()` directly: their
tokens must not travel through the bus or the queue. Without SMTP (`isMailConfigured()`), the
engine skips events (debug log), warns once at startup and the alert pages show a banner.
engine skips emails and system notifications (debug log) but still posts to channels, warns once
at startup and the alert pages show a banner. `MailQueue` is a `DeliveryQueue`
(`#lib/server/infra/notifications/delivery-queue.ts`), the generic queue channels reuse.
- HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by
the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`,
`GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test`
Expand Down Expand Up @@ -235,7 +237,45 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
(read with `organization:settings:read` or `organization:notifications:read`, changed with
`organization:settings:update` or `organization:notifications:update`) and the external recipients
status (`organization:notifications:read`, resend confirmation with `organization:notifications:update`).
Notification channels (#95) will live on this page too.
Its channels section is described below.
- Notification channels (`$modules/notifications`, #95): `NotificationChannelEntity` (GitDB
`notification_channels`), owned by an organization (usable by alerts of the organization and of
all its projects) or a project (only its alerts). `type` is `webhook`, `slack` or `google-chat`;
a type is available only once its transport is registered with `registerChatTransport()`
(`#lib/server/infra/notifications/chat-notification.ts`, it also calls `registerTransport`).
This base registers none: each transport sub-task (#96 webhook, #97 Slack, #98 Google Chat)
activates its own, and the tests use `FakeChatTransport`. A `ChatTransport` implements `send()`
and `validateDestination()`, the anti-SSRF check (`validateWebhookUrl()`: https, no credentials,
no IP literal, default port, allowed host and path) run before saving and again before every
send. The destination (`webhookUrl`) is encrypted with `GITDB_ENCRYPTION_KEY`
(`channel-cipher.ts`, AES-GCM bound to the channel id) and only ever leaves the server masked
(`https://hooks.slack.com/…/••••1a2b`); changing it means typing it again.
- Channel delivery: alerts store `channelIds` (`ALERT_CHANNELS` is derived on save: `mail` when
there are email recipients, plus the channel types). Adding a channel needs
`<scope>:notifications:update` (`forbidden_channel`), and a channel must be usable from the
alert's location (`unknown_channel`). The engine's `deliver()` emails each recipient and posts
**one message per channel** in parallel; a failing channel never affects the emails or the other
channels, and system notifications never go to channels. The message is a provider-neutral
`ChannelMessage` (`buildAlertChannelMessage()`: default language, no `sensitive` fields, "View in
GitOps" link, throttled count); transports format it. Deliveries go through the process-wide
`channelQueue` (concurrency 3; `postJson()` from `#lib/server/infra/http/webhook-request.ts` with
a 5 s timeout and no redirects; `withRetry` only on network errors, 429 honoring `Retry-After`,
and 5xx). A permanent failure (4xx, invalid or undecryptable destination, type without transport)
sets `lastError`; a success clears it. `lastDeliveryAt` is only refreshed hourly, since each
write is a commit. Logs carry the channel id and type, never the URL nor the message.
- Channels HTTP: `#lib/server/notifications/channels.ts` (permission-first, a channel the caller
can't read is a 404). Routes: `GET|POST /api/notification-channels` (`organizationId` or
`projectId`), `GET|PATCH|DELETE /api/notification-channels/[id]` and
`POST /api/notification-channels/[id]/test` (posts a test even to a disabled channel). UI: the
`ChannelsSection` component (`#lib/components/notifications/`) on
`/org/<org>/settings/notifications` and `/org/<org>/projects/<slug>/settings/notifications`
(form actions in `src/lib/server/notifications/channels-page.ts`, no JavaScript needed; project
pages list the inherited organization channels read-only), and a channel picker in the alert editor
that shows the alert's `channelIds`, loading channel options from the page loader's `data.channels`.
- Dev reloads: the alert engine, the mail and channel queues and the verification limiters live on
`globalThis`. Their collaborators are resolved on every call (`latest()` and the engine slot's
`dependencies` in `alerts/index.ts`, `sendWithLatestNotify()` for the queues), and the engine is
rebuilt when its class or `ENGINE_WIRING` changes: bump it when the engine's wiring changes.
- UI: `/org/<org>/settings/alerts` and `/org/<org>/projects/<slug>/settings/alerts` (list, `new`,
`[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`,
`test`, `toggle`, `delete`; everything works without JavaScript). Components live in
Expand Down Expand Up @@ -292,8 +332,8 @@ return { roles, canCreate };

The root layout (`+layout.server.ts`) calculates granular read permissions for each settings section and
passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions:
- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`, `organization:notifications:read`
- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`, `project:notifications:update`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`, `organization:notifications:read`, `organization:notifications:update`

This ensures the UI only displays navigation items for sections the user has permission to view.

Expand All @@ -308,7 +348,7 @@ Permissions always include their scope as a prefix (e.g., `organization:projects
- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access; reads alerts
- **Project Viewer** — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history

`organization:notifications:read` and `organization:notifications:update` gate external email recipient management at the organization level. At the project level, `project:notifications:read` and `project:notifications:update` control external recipients of project alerts (externals of alerts that scope to a project).
`organization:notifications:read` and `organization:notifications:update` gate external email recipients and notification channels at the organization level. At the project level, `project:notifications:read` and `project:notifications:update` control external recipients and channels for project alerts.

Module resources have granular sub-permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. These allow fine-grained access control within each module.

Expand Down
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,28 @@ sensitive fields and links into the app. Removing a domain blocks its addresses
them, and allowing it again restores them. `ORIGIN` must be set: without it, confirmation and
unsubscribe links can't be built and nothing is sent to external addresses.

#### Notification channels

Alerts can also post to chat channels and webhooks: one message per channel, next to the emails.
Channels are managed in **Settings → Notifications** of the organization (usable by the alerts of
the organization and all its projects) or of a project (only that project's alerts), with
`organization:notifications:*` or `project:notifications:*`. Each channel has a **Send test
message** button, and the alert editor lists the channels the alert can use.

- The channel URL is stored encrypted and never shown again in full. To change it, type it again.
- Only `https` URLs of the provider's own host are accepted, checked when saving and before every
message.
- A message never includes fields marked sensitive, since people reading the channel may not be
allowed to see the event. Access and role notices never go to channels.
- Failed messages are retried on network errors, rate limits and server errors. A permanent error,
such as a deleted webhook, shows on the channel as its last error.

The channel types (generic webhooks, Slack and Google Chat) become available as their transports
are added; until then the page says that no type is available. Each one will need an incoming
webhook created on the provider side: in Slack, an app with **Incoming Webhooks** enabled and a
webhook for the target channel (`https://hooks.slack.com/services/...`); in Google Chat, the space's
**Apps & integrations → Webhooks** (`https://chat.googleapis.com/v1/spaces/.../messages?...`).

### Email

Invitations, password resets, alerts and access notices are sent by SMTP:
Expand Down
6 changes: 6 additions & 0 deletions src/lib/alerts/summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,17 @@ export function summarizeRecipients(
users: AlertOption[],
roles: AlertOption[],
t: Translate,
/** Channels of the alert, by id, with their names. */
channels: { ids: string[]; options: Array<{ id: string; name: string }> } = {
ids: [],
options: [],
},
): string {
const names = [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id),
...(recipients.externalEmails ?? []),
...channels.ids.map((id) => channels.options.find((option) => option.id === id)?.name ?? id),
];
return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients');
}
13 changes: 13 additions & 0 deletions src/lib/alerts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,19 @@ export type AlertDraft = {
match: 'all' | 'any';
conditions: DraftCondition[];
recipients: { userIds: string[]; roleIds: string[]; externalEmails: string[] };
channelIds: string[];
throttleMinutes: number;
};

/** A notification channel the alert can post to (its project's or its organization's). */
export type AlertChannelOption = {
id: string;
name: string;
type: string;
scope: 'organization' | 'project';
enabled: boolean;
};

/** External email recipients as the editor needs them. */
export type ExternalRecipientsEditorData = {
/** `<scope>:notifications:update`: needed to add addresses. */
Expand All @@ -57,6 +67,8 @@ type Shared = {
referenceOptions: Record<string, AlertOption[]>;
users: AlertOption[];
roles: AlertOption[];
/** Channels alerts of the location can post to. */
channels: AlertChannelOption[];
/** `false` when SMTP is not configured: alerts are saved but nothing is sent. */
mailConfigured: boolean;
};
Expand All @@ -83,6 +95,7 @@ export type AlertTestView = {
recipients: Array<{ userId: string; username: string }>;
deniedCount: number;
external: Array<{ email: string; status: string; delivers: boolean }>;
channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
/** Present when a real test email was sent. */
delivery?: { sent: number; failed: number };
event: { type: string; payload: Record<string, unknown>; projectId: string | null };
Expand Down
7 changes: 7 additions & 0 deletions src/lib/components/AppSidebar.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
export let canReadProjectServerKeys = false;
export let canReadProjectAudit = false;
export let canReadProjectAlerts = false;
export let canReadProjectNotifications = false;
export let canReadProjectVault = false;
export let canReadProjectCodeReport = false;
export let canReadProjectStateIac = false;
Expand Down Expand Up @@ -240,6 +241,12 @@
icon: BellRing,
visible: canReadProjectAlerts,
},
{
label: $_('sidebar.items.notifications'),
href: `${projectBase}/settings/notifications`,
icon: Mail,
visible: canReadProjectNotifications,
},
{
label: $_('sidebar.items.serverKeys'),
href: `${projectBase}/settings/server-access-keys`,
Expand Down
Loading
Loading