diff --git a/.env.example b/.env.example index ecdbc7e1..fae85049 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,22 @@ GITDB_SYNC_POLL_SECONDS=60 # NOTIFICATIONS_WEBHOOK_ALLOW_HTTP=false # NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS=false +# Optional "Add to Slack" for Slack alert channels: users pick the workspace and channel in Slack +# instead of pasting an Incoming Webhook URL. Create the app from GitOps Settings → Slack (prefilled +# manifest, incoming-webhook scope only). Redirect URL: /notifications/slack/callback (https) +# SLACK_CLIENT_ID= +# SLACK_CLIENT_SECRET= +# The /gitops command of the same app (install the app, link users, connect channels from Slack) +# also needs the app's Signing Secret (Basic Information → App Credentials). Slack sends commands +# to /api/slack/commands, so the server must be reachable from the internet (locally: a +# tunnel such as cloudflared or ngrok, with ORIGIN set to the tunnel's https URL) +# SLACK_SIGNING_SECRET= +# To try it locally serve the dev server over https (Slack refuses http redirect URLs): +# mkdir -p .certs && openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=localhost \ +# -addext subjectAltName=DNS:localhost -keyout .certs/localhost-key.pem -out .certs/localhost.pem +# then open https://localhost:5173 and register https://localhost:5173/notifications/slack/callback +# DEV_HTTPS=true + # 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 78a27b44..bb0f61b8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -34,7 +34,9 @@ ejecución. SAML es configuración solo. - Vitest, ESLint y Prettier - Playwright para tests e2e de RBAC (`e2e/`) -Las variables de entorno se declaran en `src/env.ts` y se documentan en `.env.example`; Google SSO usa las `GOOGLE_SSO_*` descritas arriba. +Las variables de entorno se declaran en `src/env.ts` y se documentan en `.env.example`; Google SSO usa las +`GOOGLE_SSO_*` descritas arriba, "Add to Slack" usa `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` y el comando +`/gitops` también necesita `SLACK_SIGNING_SECRET` (opcionales). Comandos: @@ -121,16 +123,41 @@ y `project:notifications:update` gestionan destinatarios externos y canales. El verificación y desuscripción. En `/org//settings/alerts/settings`, administradores configuran dominios 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`. 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. +se usan en alertas de org y proyecto; canales de proyecto solo en sus alertas. Cada canal tiene un idioma +(`locale`: es | en, por defecto en), que determina el idioma de etiquetas y eventos en sus mensajes. +URLs de webhook se encriptan 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. **Webhook** se firma con HMAC-SHA256 +(`X-GitOps-Signature`): secreto `whsec_…` se muestra una sola vez al crear o rotar (24 h gracia, ambos secretos +validan); resuelve DNS rechazando IPs privadas/loopback; no sigue redirects; reintentos con backoff (20 fallos += auto-deshabilita). Docs en `docs/webhooks/`. **Slack**: Incoming Webhook (solo URLs `https://hooks.slack.com/services/…`, +sin firma), formatea como Block Kit en el idioma del canal (nombre de alerta, resumen, campos, cambios de campos +con before/after, fecha en zona horaria del lector, nota de contexto y botón "Ver en GitOps" si hay link), escapa +caracteres Slack (`&<>`) en datos de usuario/evento. Un canal GitOps por webhook Slack. Los errores 4xx no se reintentan +y se muestran como último error. **Add to Slack** (`SlackConnectService`): cuando `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` están configurados, +los settings de canales muestran "Añadir a Slack"; usuario elige workspace y canal, GitOps crea el canal con webhook. +Admin abre `GitOps Settings → Slack`, crea la app Slack (manifest con scope `incoming-webhook` y redirect +`/notifications/slack/callback`, requiere https), copia credenciales al entorno y reinicia. En dev, usar +`DEV_HTTPS=true` con certificados en `.certs/` (ver `.env.example`). + +**Comando `/gitops`** (`SlackAppService`, requiere `SLACK_SIGNING_SECRET`): organización instala el app desde la +página de canales (`installSlack` action, scope `commands`), guardando el bot token en `slack_workspaces` +(GitDB, una fila por team, vinculada a organización). Los endpoints `/api/slack/commands` y +`/api/slack/interactions` verifican la firma Slack (5 min window, `verifySlackSignature`) y actúan como el +usuario Slack vinculado (`authProviders` entry `slack` = `:`) con permiso `organization:notifications:create`. +Luego en Slack: (1) `/gitops login` → link firmado a `/notifications/slack/link` para vincular usuario a su +cuenta GitOps (10 min, una vez; `hooks.server.ts` preserva la URL en `gitops_return_to`); (2) `/gitops channel` +pide nombre e idioma → link firmado a `/notifications/slack/connect` que abre selector de canales Slack, crea el +canal en GitOps con webhook y posea test → `/notifications/slack/callback` → `/notifications/slack/done`; +(3) `/gitops status` muestra organización vinculada y canales conectados. Las rutas de Slack bypass CSRF porque +Slack envía requests sin `Origin` header; solo los endpoints firmados (`CSRF_EXEMPT_PATHS`) están excluidos. + +Configuración: webhook Slack (URL: `https://hooks.slack.com/services/…`), canales tienen idioma (`locale: es|en`), +URLs de webhook encriptadas, emails externos: `pending` → `verified` o `blocked`; template sin campos `sensitive` ni +links internos; unsubscribe HMAC (90 días). **Webhook** se firma: secreto `whsec_…` (mostrado una sola vez), resuelve +DNS rechazando IPs privadas, 20 fallos consecutivos = auto-deshabilita. Variantes de desarrollo: +`NOTIFICATIONS_WEBHOOK_ALLOW_HTTP`, `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS`. Rutas públicas +`/notifications/verify` y `/notifications/unsubscribe` aceptan POST sin sesión. 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/.gitignore b/.gitignore index 755c4bbf..60e3fff1 100644 --- a/.gitignore +++ b/.gitignore @@ -18,4 +18,6 @@ test-results/ playwright-report/ blob-report/ creport-cloud.sh -creport-local.sh \ No newline at end of file +creport-local.sh +# local https certificates (DEV_HTTPS) +.certs/ diff --git a/CLAUDE.md b/CLAUDE.md index bff02b32..da1c4be9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,7 +53,9 @@ The roadmap is in `IDEAS.md`. Do not describe roadmap items as implemented featu - Vitest, ESLint, and Prettier - Playwright for RBAC end-to-end tests (`e2e/`) -Environment variables are declared in `src/env.ts` and documented in `.env.example`; Google SSO uses the `GOOGLE_SSO_*` variables described above. +Environment variables are declared in `src/env.ts` and documented in `.env.example`; Google SSO uses the +`GOOGLE_SSO_*` variables described above, "Add to Slack" uses `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`, +and the `/gitops` Slack command also needs `SLACK_SIGNING_SECRET`. Email notification templates (`src/notifications/`) are read from disk at runtime; the Docker image copies them so emails can be sent from the container. @@ -359,7 +361,11 @@ in `docs/adr/0001-event-bus-and-alerts.md`. 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`) in the composition root - (`$modules/notifications/index.ts`); today only `webhook` is, and tests use `FakeChatTransport`. + (`$modules/notifications/index.ts`); today `webhook` and `slack` are, and tests use + `FakeChatTransport`. Providers with incoming webhooks on a fixed host (Slack, Google Chat) only + write a formatter: `createFixedHostChatTransport({ rule, format })` + (`chat-webhook.transport.ts`) does the URL rule, guarded fetch and `postJson`; `truncateText` + (`chat-format.ts`) is shared for provider length limits. 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), @@ -372,6 +378,10 @@ in `docs/adr/0001-event-bus-and-alerts.md`. 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. +- Channel language: `NotificationChannelEntity.locale` (`es` | `en`, rows without it read as `en`, + `CHANNEL_LOCALES` in `chat-types.ts`), set in the channel forms and the API (`locale`, invalid → + `invalid_locale`). The engine passes `deliver()` a builder `(locale) => ChannelMessage` + (`ChannelMessageSource`) so each channel gets its own language; the test message uses it too. - 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 @@ -380,6 +390,81 @@ in `docs/adr/0001-event-bus-and-alerts.md`. 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). +- Slack (`#lib/server/infra/notifications/slack/`): Incoming Webhook, URL limited to + `https://hooks.slack.com/services/` only (`SLACK_WEBHOOK_RULE`), unsigned. `buildSlackPayload()` turns + the `ChannelMessage` into Block Kit in the channel's language only: header (alert name, `plain_text`), the + summary only when it differs from the event label, a fields section with `location` + (`Project`/`Organization`: name) and the date (`slackDate()`, ``, reader's time zone), + a divider and a `*Changes*` title (`labels.changes`), then one section per change (`*Label*` / + `Before: …` / `New: …`, `labels.empty` for a `null` side, + only the label when both are `null`), remaining field sections of 10, "View in GitOps" button, + and `note` as context. Every `mrkdwn` value goes through `escapeSlackText()` + (`&`, `<`, `>`) so event or user data can't mention or link. Texts are cut to Block Kit limits. + The Slack channel is fixed by the webhook: one GitOps channel per Slack webhook. 4xx responses + (revoked webhook, archived or deleted channel) are not retried and show as the channel's last error. +- Add to Slack (`slackConnectService` in `$modules/notifications`, `#97`): OAuth v2 install + (`SlackConnectService`, `SlackOAuthClient`) with only the `incoming-webhook` scope, so Slack asks for + the workspace and channel and returns its webhook URL, saved as a normal `slack` channel (same transport, + same `SLACK_WEBHOOK_RULE`). Enabled when `SLACK_CLIENT_ID` and `SLACK_CLIENT_SECRET` are both set + (`readSlackAppConfig()`; half set counts as disabled). Picking the Slack card in the create-channel + form shows an "Add to Slack" button (`formaction` to the `connectSlack` action, `channels-page.ts`; + the enhanced submit follows the redirect with `window.location`; Enter keeps creating the manual channel) + next to the manual URL fields, and GitOps admins get a link to `/gitops-settings/slack` while it is not + configured. The action needs `:notifications:create` and a session, not an API key; it sets + the `gitops_slack_flow` cookie (`signToken`, 10 min, bound to the user, location, locale and a return + path) and redirects to Slack; `/notifications/slack/callback` (fixed: it is the app's redirect URL, + needs the same session) checks the state, exchanges the code (Basic auth), creates the channel through + `createChannel()` (permission checked again) and goes back with `?slack=connected|` + (`notifications.errors.slack_*`). Self-hosted admins create the app from `/gitops-settings/slack` + (prefilled manifest link, redirect URL, status); a hosted GitOps uses the official app's credentials + the same way. Pasting a webhook URL keeps working. A central OAuth broker for self-hosted installations + is not implemented. +- `/gitops` (`slackAppService` in `$modules/notifications`): the same Slack app with the `commands` + scope, enabled when `SLACK_SIGNING_SECRET` is also set (`slackConnectService.commandsEnabled()`). + An organization installs it from its channels page (`installSlack` action, OAuth with only + `commands`, flow `kind: 'install'`): `slack_workspaces` (GitDB) keeps one row per Slack team, linked + to that organization (another organization gets `slack_workspace_taken`), with the bot token + encrypted (`ChannelCipher` purpose `slack-bot-token`; only used to open forms, `views.open`). + `/api/slack/commands` and `/api/slack/interactions` have no session or API key: they verify + `X-Slack-Signature` (`verifySlackSignature`, 5 min window) on the raw body and act as the GitOps + user linked to the Slack user (`authProviders` entry `slack` = `:`, `findByExternalIdentity`), + refusing disabled users and checking `organization:notifications:create` every time. + `/gitops login` answers with a signed 10-minute link to `/notifications/slack/link` (needs a session: + `hooks.server.ts` remembers it in `gitops_return_to` and the password and Google logins come back to + it, `#lib/server/return-to`; the user must see the workspace's organization). `/gitops channel` opens a + modal (name, locale); its submission answers with a signed link to `/notifications/slack/connect` + (no session), which starts Slack's channel picker (flow `kind: 'command'`, bound to the Slack team + and user: the callback refuses another one with `slack_wrong_workspace`). `/notifications/slack/callback` + then accepts requests without a session (only `command` flows can finish without one), creates the + channel through `createChannel()` as the linked user (`runWithActor`), posts a test message and ends + on `/notifications/slack/done`. Replies use the workspace's locale (picked at install). +- CSRF: SvelteKit's origin check is disabled in the framework (`csrf.trustedOrigins: ['*']`) and done + by `csrfGuard` in `hooks.server.ts` with the same rule (`#lib/server/csrf`), because Slack posts + forms without an `Origin` header. Only `CSRF_EXEMPT_PATHS` (the two signed Slack endpoints) skip it; + never add a path there that does not authenticate its requests by other means. + + Local development of Slack OAuth flows requires HTTPS (Slack refuses `http://` redirect URLs). + Set `DEV_HTTPS=true` and create a self-signed certificate: + ```bash + mkdir -p .certs && openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=localhost \ + -addext subjectAltName=DNS:localhost -keyout .certs/localhost-key.pem -out .certs/localhost.pem + ``` + Then open `https://localhost:5173` and register `https://localhost:5173/notifications/slack/callback` + in the test Slack app. See `.env.example` for details. +- `ChannelMessage` (built by `buildAlertChannelMessage(input, locale)`): `fields` leave out what + the message says elsewhere: `occurredAt`, `location` (project or organization, and any field with + that name), and `changedFields` when `changes` (translated label + before/after) exists. + `labels` carries the translated `Date`/`Changes`/`Before`/`New`/`empty`, and `text` only adds the summary + when it differs from the event label, so nothing is said twice in two languages. + `note` is the translated side note (test send, throttled count); the raw `suppressed` count is + still there. `occurredAt` and `location` are always present; `changes` only for update events; + `labels` only when any of `occurredAt`, `location` or `changes` is used by the transport. +- Update events carry `changes?: FieldChange[]` (`{ field, before, after }`, plain text cut to 200 + chars by `fieldChange()` in `#lib/events/field-changes.ts`, `null` when empty or not shown): + `project.updated` (modules as the enabled list, organization by name, settings without values) + and `organization.updated`. Never put secrets in them; `vault.secret.updated` has none. `FieldChange` + is defined in `src/lib/events/domain-events.ts` with the type parameter for field names and is + used by channels (Slack shows before/after) and by the update events in payloads. - 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`, diff --git a/README.md b/README.md index ffcdd12d..808167bb 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ 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 are available; Slack and Google Chat are not yet. +generic webhooks and Slack are available; Google Chat is 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 @@ -209,6 +209,59 @@ link-local and cloud metadata addresses are refused, and redirects are never fol 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). +Each channel has a **message language** (Spanish or English, chosen when it is created or edited; +channels created before the setting existed use English): the event, field labels and button of +its messages are written in it. + +A **Slack** channel posts a Block Kit message, in the channel's language only, to a Slack Incoming +Webhook: the alert name, a summary when the event has one (`3 critical, 5 high`), where it +happened (**Project** or **Organization**) and the date (in each reader's time zone), for update +events a **Changes** section with each changed field and its **Before** and **New** values (`empty` when there was none), +the remaining event fields and a **View in GitOps** button when `ORIGIN` is set. The webhook decides +the Slack channel, so each GitOps channel posts to one Slack channel. + +**Add to Slack (one click).** When the installation has a Slack app configured +(`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`), the channel settings show **Add to Slack**: the user +picks the workspace and the channel in Slack and GitOps creates the channel with its webhook, with +nothing to copy. Any workspace can be connected, so each organization uses its own Slack. To set it +up, a GitOps admin opens **GitOps Settings → Slack**, clicks **Create Slack app** (Slack opens with a +prefilled manifest: the `incoming-webhook` and `commands` scopes, the `/gitops` command and this installation's redirect URL, +`/notifications/slack/callback`, which must be https), copies the app's **Client ID** and +**Client Secret** into the environment and restarts GitOps. To let workspaces other than the one +that owns the app install it, enable **Public Distribution** in the app's **Manage Distribution**. + +**From Slack (`/gitops`).** With the app's **Signing Secret** also set (`SLACK_SIGNING_SECRET`), an +organization admin clicks **Install in Slack** in the organization's channel settings, once per +workspace. Then, in Slack: + +1. `/gitops login`: a private link opens GitOps (sign in with your password or Google) to link your + Slack user to your account. Once per person. +2. `/gitops channel`: a form asks for the configuration's name and message language; **Pick the + channel in Slack** opens Slack's own channel picker in the browser (the only way Slack issues a + webhook). GitOps saves the channel in the organization, with its webhook, and posts a test message + to it. Repeat for every channel (`#devops_ES`, `#devops_FR`…). +3. `/gitops status`: the linked organization, your account and the connected channels. + +Alerts are still created in GitOps, where the new channels show up like any other. Every action runs +as the linked GitOps user with the usual permissions (`organization:notifications:create`). Slack +sends the commands to `/api/slack/commands` and `/api/slack/interactions`, so the +installation must be reachable from the internet (locally: a tunnel such as cloudflared or ngrok). + +**Manually**, without a Slack app in GitOps, create one webhook per Slack channel: + +1. In Slack, open [api.slack.com/apps](https://api.slack.com/apps) → **Create New App** → **From + scratch**, and pick the workspace (or open an app your workspace already uses for this). +2. In the app, go to **Incoming Webhooks**, turn **Activate Incoming Webhooks** on and click **Add + New Webhook to Workspace**. Choose the channel and allow it. +3. Copy the URL (`https://hooks.slack.com/services/T…/B…/…`) and, in GitOps, add a channel of type + **Slack** with that URL and a name (usually the Slack channel's, `#security-alerts`). Repeat for + every Slack channel. +4. When you create or edit an alert, pick **Slack** in **Destinations** and tick the channels that + should get it (one or several). + +Only `https://hooks.slack.com/services/…` URLs are accepted. Slack's 4xx answers (revoked webhook, +archived or deleted channel) are not retried and show as the channel's last error. + ### Monitoring HTTP monitors check a URL (method, headers and body of your choice) every 60 seconds by default and diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts index 882a0560..dc96d09f 100644 --- a/e2e/specs/alerts.spec.ts +++ b/e2e/specs/alerts.spec.ts @@ -254,9 +254,9 @@ test.describe('organization alerts', () => { // 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: /Slack/ })).toBeEnabled(); await expect(types.getByRole('radio', { name: /Google Chat/ })).toBeDisabled(); - await expect(types.locator('[data-channel-type="slack"]')).toContainText('Próximamente'); + await expect(types.locator('[data-channel-type="google-chat"]')).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'); @@ -279,6 +279,65 @@ test.describe('organization alerts', () => { 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'); + + await types.locator('[data-channel-type="slack"]').click(); + await expect(types.getByRole('radio', { name: /Slack/ })).toBeChecked(); + for (const [name, hook, locale, language] of [ + ['#seguridad-e2e', 'https://hooks.slack.com/services/T000/B001/aaaa', 'es', 'Español'], + ['#incidencias-e2e', 'https://hooks.slack.com/services/T000/B002/bbbb', 'en', 'Inglés'], + ]) { + await channels.getByLabel('Nombre', { exact: true }).fill(name); + await channels.getByLabel('URL del webhook').fill(hook); + await channels.getByLabel('Idioma de los mensajes').selectOption(locale); + await channels.getByRole('button', { name: 'Añadir canal' }).click(); + const slackRow = channels.locator('li[data-channel-id]').filter({ hasText: name }); + await expect(slackRow).toContainText('Slack'); + await expect(slackRow.getByTestId('channel-locale')).toHaveText(language); + await expect(slackRow).not.toContainText('Firmado'); + await expect(slackRow).not.toContainText(hook); + } + + await channels.getByLabel('Nombre', { exact: true }).fill('#otro'); + await channels + .getByLabel('URL del webhook') + .fill('https://hooks.slack.com.evil.example/services/x'); + await channels.getByRole('button', { name: 'Añadir canal' }).click(); + await expect( + channels.getByText('Ese dominio no está permitido para este tipo de canal.'), + ).toBeVisible(); + }); + + test('an alert posts to the Slack channels picked in the wizard', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await page.goto(alertsUrl); + await page.waitForLoadState('networkidle'); + const row = page.getByTestId('alert-row').filter({ hasText: GUIDED_NAME }); + await row.getByRole('link', { name: 'Editar' }).click(); + const wizard = page.getByRole('dialog', { name: 'Editar alerta' }); + await wizard.getByRole('button', { name: /Destinos/ }).click(); + + const channels = wizard.getByTestId('alert-channels'); + const slackCard = channels.locator('[data-channel-type="slack"]'); + await expect(slackCard).not.toContainText('No configurado'); + await slackCard.getByRole('checkbox').click(); + await expect(slackCard.getByRole('checkbox')).toHaveAttribute('aria-checked', 'true'); + + const seguridad = wizard.getByRole('checkbox', { name: /#seguridad-e2e/ }); + const incidencias = wizard.getByRole('checkbox', { name: /#incidencias-e2e/ }); + await expect(seguridad).toBeChecked(); + await expect(incidencias).toBeChecked(); + await incidencias.uncheck(); + + await wizard.getByRole('button', { name: 'Siguiente' }).click(); + await expect(wizard).toContainText('#seguridad-e2e'); + await expect(wizard).not.toContainText('#incidencias-e2e'); + await wizard.getByRole('button', { name: 'Guardar cambios' }).click(); + await expect(wizard).toBeHidden(); + + await row.getByRole('link', { name: 'Editar' }).click(); + await wizard.getByRole('button', { name: /Destinos/ }).click(); + await expect(wizard.getByRole('checkbox', { name: /#seguridad-e2e/ })).toBeChecked(); + await expect(wizard.getByRole('checkbox', { name: /#incidencias-e2e/ })).not.toBeChecked(); }); test('a project viewer gets no settings button', async ({ page, loginAs }) => { diff --git a/src/env.ts b/src/env.ts index 87cd2de9..e5a9634f 100644 --- a/src/env.ts +++ b/src/env.ts @@ -27,6 +27,9 @@ export const variables = defineEnvVars({ NOTIFICATION_SMTP_REJECT_UNAUTHORIZED: optional, NOTIFICATIONS_WEBHOOK_ALLOW_HTTP: optional, NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS: optional, + SLACK_CLIENT_ID: optional, + SLACK_CLIENT_SECRET: optional, + SLACK_SIGNING_SECRET: optional, GOOGLE_SSO_CLIENT_ID: optional, GOOGLE_SSO_CLIENT_SECRET: optional, GOOGLE_SSO_ALLOWED_DOMAINS: optional, diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 8b841e22..4836016b 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -15,6 +15,16 @@ import { startGitDb } from '#lib/server/gitdb'; import { getServerReadyState, markServerFailed, markServerReady } from '#lib/server/server-ready'; import { renderStartingPage } from '#lib/server/starting-page'; import { runWithActor } from '#lib/server/request-context'; +import { csrfForbiddenResponse, isCsrfForbidden } from '#lib/server/csrf'; +import { returnToCookie } from '#lib/server/return-to'; +import { + SLACK_CALLBACK_PATH, + SLACK_COMMANDS_PATH, + SLACK_CONNECT_PATH, + SLACK_DONE_PATH, + SLACK_INTERACTIONS_PATH, + SLACK_LINK_PATH, +} from '#modules/notifications'; import { rememberDevOrigin } from '#lib/server/infra/notifications'; import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger'; @@ -67,6 +77,15 @@ const requestLogger: Handle = async ({ event, resolve }) => { return response; }; +// SvelteKit's CSRF origin check (disabled in the framework, see `#lib/server/csrf`): like the +// framework, it only applies in production +const csrfGuard: Handle = async ({ event, resolve }) => { + if (!import.meta.env.DEV && isCsrfForbidden(event.request, event.url)) { + return csrfForbiddenResponse(event.request); + } + return resolve(event); +}; + const authGuard: Handle = async ({ event, resolve }) => { const pathname = event.url.pathname; if (import.meta.env.DEV) rememberDevOrigin(event.url.origin); @@ -136,6 +155,12 @@ const authGuard: Handle = async ({ event, resolve }) => { if ( pathname === '/notifications/verify' || pathname === '/notifications/unsubscribe' || + // Slack's requests: authenticated by their signature in the handlers + pathname === SLACK_COMMANDS_PATH || + pathname === SLACK_INTERACTIONS_PATH || + // a channel connected from Slack: the signed link and the Slack user identify the caller + pathname === SLACK_CONNECT_PATH || + pathname === SLACK_DONE_PATH || pathname === '/auth/login' || pathname === '/auth/sso/google/start' || pathname === '/auth/sso/google/callback' || @@ -188,7 +213,18 @@ const authGuard: Handle = async ({ event, resolve }) => { if (isApiRequest) { return unauthorized('Authentication required'); } - return new Response(null, { status: 302, headers: { location: '/auth/login' } }); + // the Slack app's redirect URL serves flows that need this session ("Add to Slack", the app + // install: they fail without it) and channels connected from Slack (no session needed) + if (pathname === SLACK_CALLBACK_PATH) { + return resolve(event); + } + const headers = new Headers({ location: '/auth/login' }); + // `/gitops login`: come back to the link once signed in + if (pathname === SLACK_LINK_PATH) { + const cookie = returnToCookie(event.cookies, `${pathname}${event.url.search}`); + if (cookie) headers.append('set-cookie', cookie); + } + return new Response(null, { status: 302, headers }); } const projectSettingsMatch = event.url.pathname.match( @@ -226,7 +262,7 @@ const authGuard: Handle = async ({ event, resolve }) => { return runWithActor(actor, () => resolve(event)); }; -export const handle = sequence(requestLogger, authGuard); +export const handle = sequence(requestLogger, csrfGuard, authGuard); // unexpected errors from load/actions/endpoints land here: log with the request's // trace-aware logger so the entry is correlated with the failed httpRequest diff --git a/src/lib/components/notifications/ChannelsSection.svelte b/src/lib/components/notifications/ChannelsSection.svelte index b0a78047..7826286d 100644 --- a/src/lib/components/notifications/ChannelsSection.svelte +++ b/src/lib/components/notifications/ChannelsSection.svelte @@ -1,7 +1,9 @@ + + + {$_('clusterSettings.slack.title')} - {$_('clusterSettings.title')} + + +
+
+

+ {$_('clusterSettings.slack.title')} +

+

{$_('clusterSettings.slack.description')}

+
+ +
+
+ +
+
+

{$_('clusterSettings.slack.statusTitle')}

+ {#if data.status.configured} + + {$_('clusterSettings.slack.configured')} + + {:else if data.status.reason === 'invalid'} + + {$_('clusterSettings.slack.invalid')} + + {:else} + + {$_('clusterSettings.slack.notConfigured')} + + {/if} +
+

+ {data.status.configured + ? $_('clusterSettings.slack.configuredHelp') + : $_('clusterSettings.slack.notConfiguredHelp')} +

+ {#if data.status.configured} +
+ {$_('clusterSettings.slack.commandsTitle')} + {#if data.status.commands} + + {$_('clusterSettings.slack.commandsOn')} + + {:else} + + {$_('clusterSettings.slack.commandsOff')} + + {/if} +
+

{$_('clusterSettings.slack.commandsHelp')}

+ {/if} +
+
+
+ +
+

{$_('clusterSettings.slack.setupTitle')}

+ +
    +
  1. +

    {$_('clusterSettings.slack.step1')}

    + + {$_('clusterSettings.slack.createApp')} + +
    + + {$_('clusterSettings.slack.showManifest')} + +
    +
    {data.manifest}
    + +
    +
    +
  2. +
  3. +

    {$_('clusterSettings.slack.step2')}

    +
    + {data.redirectUri} + +
    + {#if !data.https} +

    + {$_( + 'clusterSettings.slack.httpsWarning', + )} +

    + {/if} +
  4. +
  5. +

    {$_('clusterSettings.slack.step3')}

    +
    SLACK_CLIENT_ID=…
    +SLACK_CLIENT_SECRET=…
    +
  6. +
  7. +

    {$_('clusterSettings.slack.step4')}

    +
    SLACK_SIGNING_SECRET=…
    + {#each [data.commandsUrl, data.interactionsUrl] as endpoint (endpoint)} +
    + {endpoint} + +
    + {/each} +
  8. +
+ +

+ {$_('clusterSettings.slack.manualNote')} +

+
+
diff --git a/src/routes/notifications/slack/callback/+server.ts b/src/routes/notifications/slack/callback/+server.ts new file mode 100644 index 00000000..0476677f --- /dev/null +++ b/src/routes/notifications/slack/callback/+server.ts @@ -0,0 +1,27 @@ +import { redirect } from '@sveltejs/kit'; +import { SLACK_FLOW_COOKIE, SLACK_FLOW_COOKIE_PATH } from '#modules/notifications'; +import { completeSlackFlow } from '#lib/server/notifications/channels'; + +/** + * Redirect URL of the GitOps Slack app (registered in the app). Finishes "Add to Slack" and the + * app install (both need the session that started them) and channels connected from `/gitops` + * (bound to the Slack user instead: reachable without a session, see `hooks.server.ts`). The + * result travels back as `?slack=`. + */ +export async function GET({ url, cookies, locals }) { + const flowCookie = cookies.get(SLACK_FLOW_COOKIE); + // the flow is single-use whatever the outcome + cookies.delete(SLACK_FLOW_COOKIE, { path: SLACK_FLOW_COOKIE_PATH }); + + const outcome = await completeSlackFlow(locals, { + flowCookie, + searchParams: url.searchParams, + origin: url.origin, + }); + + if (outcome.error) { + // never log the query: it carries the authorization code + locals.logger.warn({ code: outcome.error }, '[slack] flow failed'); + } + throw redirect(303, outcome.location); +} diff --git a/src/routes/notifications/slack/connect/+server.ts b/src/routes/notifications/slack/connect/+server.ts new file mode 100644 index 00000000..5c6d2ab8 --- /dev/null +++ b/src/routes/notifications/slack/connect/+server.ts @@ -0,0 +1,50 @@ +import { redirect } from '@sveltejs/kit'; +import { + SLACK_DONE_PATH, + SLACK_FLOW_COOKIE, + SLACK_FLOW_COOKIE_PATH, + SLACK_FLOW_TTL_MS, + SlackConnectError, + slackAppService, + slackConnectService, +} from '#modules/notifications'; +import { slackRedirectUri } from '#lib/server/notifications/channels'; + +/** + * Opened from the "Pick the channel in Slack" button of `/gitops channel`: no GitOps session, the + * signed link carries who asked (and expires in 10 minutes). Sends the browser to Slack's channel + * picker; the callback checks that the same Slack workspace and user finish it. + */ +export async function GET({ url, cookies }) { + const request = slackAppService.readChannelRequest(url.searchParams.get('token')); + if (!request) { + throw redirect( + 303, + `${SLACK_DONE_PATH}?${new URLSearchParams({ slack: 'slack_invalid_state' })}`, + ); + } + let started; + try { + started = slackConnectService.startFromSlack({ + userId: request.userId, + organizationId: request.organizationId, + name: request.name, + locale: request.locale, + slackTeamId: request.teamId, + slackUserId: request.slackUserId, + redirectUri: slackRedirectUri(url.origin), + }); + } catch (error) { + const code = error instanceof SlackConnectError ? error.code : 'slack_exchange_failed'; + throw redirect(303, `${SLACK_DONE_PATH}?${new URLSearchParams({ slack: code })}`); + } + // sameSite lax: Slack's redirect back is a top-level GET navigation, so the cookie travels + cookies.set(SLACK_FLOW_COOKIE, started.flowCookie, { + path: SLACK_FLOW_COOKIE_PATH, + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + maxAge: SLACK_FLOW_TTL_MS / 1000, + }); + throw redirect(303, started.authorizationUrl, { external: ['https://slack.com'] }); +} diff --git a/src/routes/notifications/slack/done/+page.server.ts b/src/routes/notifications/slack/done/+page.server.ts new file mode 100644 index 00000000..82934205 --- /dev/null +++ b/src/routes/notifications/slack/done/+page.server.ts @@ -0,0 +1,28 @@ +import { LINK_PAGE_HEADERS } from '#lib/server/notifications/links'; + +/** End of a channel connected from `/gitops channel`: no session, only the outcome to show. */ +export function load({ url, setHeaders }) { + setHeaders(LINK_PAGE_HEADERS); + const status = url.searchParams.get('slack') ?? 'slack_invalid_state'; + const team = url.searchParams.get('team') ?? ''; + const channel = url.searchParams.get('channel') ?? ''; + const valid = (value: string) => /^[A-Z0-9]{1,32}$/.test(value); + return { + connected: status === 'connected', + // only a code shape from our own list reaches the i18n lookup + error: + status === 'connected' + ? null + : /^[A-Za-z_]{1,64}$/.test(status) + ? status + : 'slack_invalid_state', + name: (url.searchParams.get('name') ?? '').slice(0, 80), + // deep link back to the channel in the Slack app, when Slack said which one + slackUrl: + valid(team) && valid(channel) + ? `slack://channel?${new URLSearchParams({ team, id: channel })}` + : valid(team) + ? `slack://open?${new URLSearchParams({ team })}` + : null, + }; +} diff --git a/src/routes/notifications/slack/done/+page.svelte b/src/routes/notifications/slack/done/+page.svelte new file mode 100644 index 00000000..45aa99fb --- /dev/null +++ b/src/routes/notifications/slack/done/+page.svelte @@ -0,0 +1,33 @@ + + + + {$_('notifications.slackDone.title')} - GitOps + + + + {#if data.connected} + + {$_('notifications.slackDone.connected', { values: { name: data.name } })} + +

{$_('notifications.slackDone.next')}

+ {:else} + + {$_(errorKey) === errorKey ? $_('notifications.errors.slack_exchange_failed') : $_(errorKey)} + +

{$_('notifications.slackDone.retry')}

+ {/if} + {#if data.slackUrl} + + {$_('notifications.slackDone.back')} + + {/if} +
diff --git a/src/routes/notifications/slack/link/+page.server.ts b/src/routes/notifications/slack/link/+page.server.ts new file mode 100644 index 00000000..71c06525 --- /dev/null +++ b/src/routes/notifications/slack/link/+page.server.ts @@ -0,0 +1,42 @@ +import { fail, redirect } from '@sveltejs/kit'; +import { organizationService } from '#modules/organization'; +import { slackAppService } from '#modules/notifications'; +import { LINK_PAGE_HEADERS } from '#lib/server/notifications/links'; + +/** + * Links the Slack user of `/gitops login` to the GitOps account signed in. Needs a session: + * `hooks.server.ts` sends signed-out browsers to the login and back here afterwards. + */ +export async function load({ url, locals, setHeaders }) { + setHeaders(LINK_PAGE_HEADERS); + if (!locals.user) throw redirect(303, '/auth/login'); + const token = url.searchParams.get('token') ?? ''; + const request = await slackAppService.readLinkRequest(token); + if (!request) return { token, link: { state: 'invalid' as const } }; + const organization = await organizationService + .getOrganization(request.workspace.organizationId) + .catch(() => null); + return { + token, + link: { + state: 'ready' as const, + teamName: request.workspace.teamName, + slackUserName: request.slackUserName, + organization: organization?.name ?? request.workspace.teamName, + username: locals.user.username as string, + }, + }; +} + +export const actions = { + async default({ request, locals }) { + if (!locals.user) throw redirect(303, '/auth/login'); + const form = await request.formData(); + const result = await slackAppService.confirmLink( + String(form.get('token') ?? ''), + locals.user.id, + ); + if (result !== 'linked') return fail(400, { result }); + return { result }; + }, +}; diff --git a/src/routes/notifications/slack/link/+page.svelte b/src/routes/notifications/slack/link/+page.svelte new file mode 100644 index 00000000..2c6d20e0 --- /dev/null +++ b/src/routes/notifications/slack/link/+page.svelte @@ -0,0 +1,57 @@ + + + + {$_('notifications.slackLink.title')} - GitOps + + + + {#if result === 'linked'} + {$_('notifications.slackLink.done')} + {:else if result} + {$_(`notifications.slackLink.errors.${result}`)} + {:else if data.link.state === 'ready'} +

+ {$_('notifications.slackLink.question', { + values: { + slackUser: data.link.slackUserName ?? 'Slack', + team: data.link.teamName, + username: data.link.username, + organization: data.link.organization, + }, + })} +

+
{ + submitting = true; + return async ({ update }) => { + await update(); + submitting = false; + }; + }} + > + + +
+ {:else} + {$_('notifications.slackLink.errors.invalid')} + {/if} +
diff --git a/vite.config.ts b/vite.config.ts index 518e2e04..84553da3 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -3,6 +3,8 @@ import adapter from '@sveltejs/adapter-node'; import { sveltekit } from '@sveltejs/kit/vite'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; import tailwindcss from '@tailwindcss/vite'; +import fs from 'node:fs'; +import { loadEnv } from 'vite'; import { defineConfig, type Plugin } from 'vitest/config'; // Vite only transforms hooks.server.ts lazily on the first request; warm it up eagerly in dev. @@ -20,7 +22,21 @@ function warmupHooksPlugin(): Plugin { }; } -export default defineConfig({ +// Local https for flows whose provider only accepts https redirect URLs (Add to Slack). Opt-in with +// DEV_HTTPS=true and a certificate in .certs/ (see .env.example); off for everyone else and for e2e. +function devHttps(mode: string) { + const env = loadEnv(mode, process.cwd(), ''); + if (env.DEV_HTTPS !== 'true') return undefined; + const key = env.DEV_HTTPS_KEY || '.certs/localhost-key.pem'; + const cert = env.DEV_HTTPS_CERT || '.certs/localhost.pem'; + if (!fs.existsSync(key) || !fs.existsSync(cert)) { + throw new Error(`DEV_HTTPS=true but ${key} / ${cert} are missing (see .env.example)`); + } + return { key: fs.readFileSync(key), cert: fs.readFileSync(cert) }; +} + +export default defineConfig(({ mode }) => ({ + server: { https: devHttps(mode) }, plugins: [ tailwindcss(), paraglideVitePlugin({ @@ -31,6 +47,9 @@ export default defineConfig({ sveltekit({ adapter: adapter(), preprocess: vitePreprocess(), + // the CSRF origin check runs in hooks.server.ts (`csrfGuard`), with the same rule, so the + // Slack endpoints (signed requests without an Origin header) can be exempt + csrf: { trustedOrigins: ['*'] }, }), warmupHooksPlugin(), ], @@ -38,4 +57,4 @@ export default defineConfig({ environment: 'node', include: ['src/**/*.{test,spec}.ts'], }, -}); +}));