From 69d911fa9bdfbcd2443bf958db08479f32928f7c Mon Sep 17 00:00:00 2001 From: "Liam Verdejo (ES)" Date: Fri, 27 Nov 2026 11:22:52 +0100 Subject: [PATCH] Feat: Add config slack app --- .env.example | 5 + .github/copilot-instructions.md | 34 +- CLAUDE.md | 26 +- README.md | 19 +- src/env.ts | 1 + src/hooks.server.ts | 40 +- .../notifications/ChannelsSection.svelte | 211 +++++++- src/lib/database/schemas.ts | 22 + src/lib/i18n/locales/en.json | 93 +++- src/lib/i18n/locales/es.json | 93 +++- src/lib/notifications/types.ts | 23 + src/lib/server/csrf.test.ts | 55 ++ src/lib/server/csrf.ts | 42 ++ src/lib/server/notifications/channels-page.ts | 90 +++- src/lib/server/notifications/channels.ts | 170 ++++-- .../server/notifications/slack-requests.ts | 26 + src/lib/server/return-to.test.ts | 18 + src/lib/server/return-to.ts | 49 ++ src/modules/auth/application/auth.service.ts | 44 +- .../application/slack-app.service.test.ts | 317 +++++++++++ .../application/slack-app.service.ts | 508 ++++++++++++++++++ .../application/slack-connect.service.test.ts | 191 ++++++- .../application/slack-connect.service.ts | 334 ++++++++++-- .../domain/slack-workspace.domain.ts | 30 ++ src/modules/notifications/index.ts | 62 ++- .../infrastructure/config/slack-app.config.ts | 13 +- .../infrastructure/crypto/channel-cipher.ts | 2 +- .../slack-workspace.repository.ts | 94 ++++ .../infrastructure/slack/slack-api.client.ts | 36 ++ .../slack/slack-oauth.client.test.ts | 41 +- .../slack/slack-oauth.client.ts | 55 +- .../infrastructure/slack/slack-signature.ts | 39 ++ src/routes/api/slack/commands/+server.ts | 18 + src/routes/api/slack/interactions/+server.ts | 24 + src/routes/auth/login/+page.server.ts | 5 +- .../auth/sso/google/callback/+server.ts | 6 +- .../gitops-settings/slack/+page.server.ts | 8 +- src/routes/gitops-settings/slack/+page.svelte | 37 ++ .../notifications/slack/callback/+server.ts | 17 +- .../notifications/slack/connect/+server.ts | 50 ++ .../notifications/slack/done/+page.server.ts | 28 + .../notifications/slack/done/+page.svelte | 33 ++ .../notifications/slack/link/+page.server.ts | 42 ++ .../notifications/slack/link/+page.svelte | 57 ++ vite.config.ts | 3 + 45 files changed, 2933 insertions(+), 178 deletions(-) create mode 100644 src/lib/server/csrf.test.ts create mode 100644 src/lib/server/csrf.ts create mode 100644 src/lib/server/notifications/slack-requests.ts create mode 100644 src/lib/server/return-to.test.ts create mode 100644 src/lib/server/return-to.ts create mode 100644 src/modules/notifications/application/slack-app.service.test.ts create mode 100644 src/modules/notifications/application/slack-app.service.ts create mode 100644 src/modules/notifications/domain/slack-workspace.domain.ts create mode 100644 src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts create mode 100644 src/modules/notifications/infrastructure/slack/slack-api.client.ts create mode 100644 src/modules/notifications/infrastructure/slack/slack-signature.ts create mode 100644 src/routes/api/slack/commands/+server.ts create mode 100644 src/routes/api/slack/interactions/+server.ts create mode 100644 src/routes/notifications/slack/connect/+server.ts create mode 100644 src/routes/notifications/slack/done/+page.server.ts create mode 100644 src/routes/notifications/slack/done/+page.svelte create mode 100644 src/routes/notifications/slack/link/+page.server.ts create mode 100644 src/routes/notifications/slack/link/+page.svelte diff --git a/.env.example b/.env.example index ed53d373..4de888ab 100644 --- a/.env.example +++ b/.env.example @@ -45,6 +45,11 @@ GITDB_SYNC_POLL_SECONDS=60 # 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 diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index e0ea46da..bb0f61b8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -35,7 +35,8 @@ ejecución. SAML es configuración solo. - 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, y "Add to Slack" usa `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` (opcionales). +`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: @@ -133,13 +134,30 @@ validan); resuelve DNS rechazando IPs privadas/loopback; no sigue redirects; rei 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**: cuando `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` están configurados, -los settings de canales muestran "Añadir a Slack": usuario elige workspace y canal en Slack, GitOps crea el canal con su webhook -(`SlackConnectService` y `SlackOAuthClient`). Admin abre `GitOps Settings → Slack`, crea la app Slack (manifest prefilled con -solo scope `incoming-webhook` y redirect URL `/notifications/slack/callback`, requiere https), copia Client ID y Secret -al entorno y reinicia. En dev, Slack OAuth requiere HTTPS: usar `DEV_HTTPS=true` con certificados en `.certs/` (ver `.env.example`). Variables: -`NOTIFICATIONS_WEBHOOK_ALLOW_HTTP` y `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS` (dev/e2e). Rutas públicas -`/notifications/verify` y `/notifications/unsubscribe` aceptan POST. Sin `ORIGIN` no se envía nada. +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/CLAUDE.md b/CLAUDE.md index c11e7c41..f107cf15 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,7 +55,8 @@ The roadmap is in `IDEAS.md`. Do not describe roadmap items as implemented featu - 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, and "Add to Slack" uses `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`. +`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. @@ -386,6 +387,29 @@ in `docs/adr/0001-event-bus-and-alerts.md`. (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: diff --git a/README.md b/README.md index cc4a714d..808167bb 100644 --- a/README.md +++ b/README.md @@ -225,11 +225,28 @@ the Slack channel, so each GitOps channel posts to one Slack channel. 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: only the `incoming-webhook` scope and this installation's redirect URL, +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 diff --git a/src/env.ts b/src/env.ts index 0a03d233..9a0bbfef 100644 --- a/src/env.ts +++ b/src/env.ts @@ -29,6 +29,7 @@ export const variables = defineEnvVars({ 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 668d0697..5ef3765d 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -14,6 +14,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'; @@ -64,6 +74,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); @@ -133,6 +152,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' || @@ -185,7 +210,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( @@ -223,7 +259,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 17b2ab68..7826286d 100644 --- a/src/lib/components/notifications/ChannelsSection.svelte +++ b/src/lib/components/notifications/ChannelsSection.svelte @@ -26,6 +26,7 @@ ChannelView, ChannelsFormResult, ChannelsSectionData, + AppProvider, } from '#lib/notifications/types'; type Props = { data: ChannelsSectionData; action: string; form?: ChannelsFormResult }; @@ -119,6 +120,8 @@ const outcome = page.url.searchParams.get('slack'); if (!outcome) return; if (outcome === 'connected') toast.success($_('notifications.channels.slackConnected')); + else if (outcome === 'installed') + toast.success($_('notifications.channels.slackAppInstalledToast')); else toast.error(errorMessage(outcome)); // a reload must not repeat the toast const url = new URL(page.url.href); @@ -182,6 +185,43 @@ }; }; + /** Form actions of each app (`channels-page.ts`); `null` while the provider has none. */ + const APP_INSTALL_ACTIONS: Record = { + slack: 'installSlack', + 'google-chat': null, + }; + const APP_REMOVE_ACTIONS: Record = { + slack: 'removeSlackWorkspace', + 'google-chat': null, + }; + + /** "Install": the action answers with the provider's URL (Slack's OAuth page). */ + const installApp: SubmitFunction = () => { + busy = 'app-install'; + return async ({ result }) => { + if (result.type === 'redirect') { + window.location.assign(result.location); + return; + } + busy = null; + toast.error( + result.type === 'failure' ? failureMessage(result.data) : $_('alerts.wizard.failed'), + ); + }; + }; + + let removeWorkspaceTarget = $state<{ id: string; name: string } | null>(null); + let removeWorkspaceOpen = $state(false); + function openRemoveWorkspace(event: MouseEvent, workspace: { id: string; name: string }) { + event.preventDefault(); + removeWorkspaceTarget = workspace; + removeWorkspaceOpen = true; + } + const removeWorkspace = submit('slack-app-remove', () => { + removeWorkspaceOpen = false; + toast.success($_('notifications.channels.slackAppRemovedToast')); + }); + /** Slack picked and "Add to Slack" configured: the Slack app gives the name and the URL. */ const slackConnectMode = $derived(data.slackConnect && selectedType === 'slack'); const rotate = submit('rotate', (result) => { @@ -252,14 +292,137 @@ {#if slackOutcome} {/if} + {#if data.apps} +
+
+

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

+

{$_('notifications.apps.description')}

+
+
+ {#each data.apps as app (app.provider)} + {@const Icon = typeIcons[app.provider] ?? Webhook} + {@const installed = app.installations.length > 0} + {@const installAction = APP_INSTALL_ACTIONS[app.provider]} +
+ + + {$_(`notifications.channels.types.${app.provider}`)} + + + {$_(`notifications.apps.descriptions.${app.provider}`)} + + {#if app.comingSoon} + {$_('notifications.channels.comingSoon')} + {:else if installed} + {$_('notifications.apps.installed')} + {:else} + {$_('notifications.apps.notInstalled')} + {/if} + + {#if installed} + +
    + {#each app.installations as installation (installation.id)} +
  • + + + {$_('notifications.apps.connectedTo', { + values: { name: installation.name }, + })} + + {#if app.canRemove && APP_REMOVE_ACTIONS[app.provider]} + +
    + + +
    + {/if} +
  • + {/each} +
+ {:else if !app.comingSoon} + {#if app.canInstall && installAction} +
+ + + +
+ {:else if app.setupPath} +

+ {$_('notifications.apps.setupHint')} + {$_('notifications.channels.slackSetupLink')} +

+ {/if} + {/if} +
+ {/each} +
+
+ {/if} + {#if form?.channelTest}

{/if} +{#if data.apps?.some((app) => app.canRemove)} + + {#snippet icon()} + + {/snippet} +

+ +
+ {#snippet footer()} + + + {/snippet} + +{/if} + {#if data.canUpdate} new Date().toISOString()), + updatedAt: timestamp() + .notNull() + .$defaultFn(() => new Date().toISOString()), +}); + relations.for(ProjectEntity, ({ one, many }) => ({ roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }), organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }), diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index edfcad60..3028e448 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -411,7 +411,7 @@ "configuredHelp": "Channel settings show an Add to Slack button. Users pick the workspace and channel in Slack.", "notConfiguredHelp": "Slack channels are created by pasting an Incoming Webhook URL. Create the Slack app below to enable Add to Slack.", "setupTitle": "Set up the Slack app", - "step1": "Create the Slack app for this installation from its manifest (incoming-webhook scope only, with this installation's redirect URL).", + "step1": "Create the Slack app for this installation from its manifest (incoming-webhook and commands scopes, the /gitops command and this installation's redirect URL).", "createApp": "Create Slack app", "showManifest": "Show manifest", "step2": "Check that the app's redirect URL (OAuth & Permissions) is this one:", @@ -419,7 +419,12 @@ "step3": "In Basic Information, copy the Client ID and Client Secret into the environment and restart GitOps. To let other workspaces install it, enable Public Distribution in Manage Distribution.", "manualNote": "Pasting a webhook URL keeps working with or without the Slack app.", "copy": "Copy", - "copied": "Copied" + "copied": "Copied", + "commandsTitle": "/gitops command", + "commandsOn": "Active", + "commandsOff": "SLACK_SIGNING_SECRET missing", + "commandsHelp": "With the Signing Secret, each organization installs the app from its channel settings and connects channels from Slack with /gitops. Slack sends the commands to this installation, which must be reachable from the internet.", + "step4": "For /gitops, also copy the Signing Secret (Basic Information → App Credentials) to SLACK_SIGNING_SECRET. The manifest already registers the command and the interactivity URL:" } }, "org": { @@ -2206,7 +2211,9 @@ "slack_cancelled": "The Slack connection was cancelled.", "slack_invalid_state": "The Slack connection expired or was started by another session. Try again.", "slack_exchange_failed": "Slack did not complete the connection. Try again.", - "slack_no_webhook": "Slack did not return a channel webhook: the Slack app needs the incoming-webhook scope." + "slack_no_webhook": "Slack did not return a channel webhook: the Slack app needs the incoming-webhook scope.", + "slack_wrong_workspace": "The connection was finished in another workspace or by another Slack user. Use the account that typed /gitops channel.", + "slack_workspace_taken": "This Slack workspace is already connected to another GitOps organization." }, "link": { "invalid": "This link is not valid or has already been used.", @@ -2309,7 +2316,85 @@ "slackConnected": "Slack channel added", "slackManual": "or paste an Incoming Webhook URL", "slackSetupHint": "Add to Slack (pick the channel in Slack, no URL to copy) is not set up yet.", - "slackSetupLink": "Set it up" + "slackSetupLink": "Set it up", + "slackAppRemove": "Disconnect", + "slackAppRemoveTitle": "Disconnect {team}?", + "slackAppRemoveConfirm": "/gitops stops working in that workspace until it is installed again. Channels already connected keep posting; to revoke them, remove the app in Slack.", + "slackAppInstalledToast": "Slack app installed", + "slackAppRemovedToast": "Workspace disconnected" + }, + "slackApp": { + "notInstalled": "This Slack workspace is not connected to GitOps. An organization admin has to click *Install in Slack* in GitOps (Settings → Alerts → Settings → Channels).", + "help": "*GitOps commands*\n• `/gitops login`: link your Slack user to your GitOps account (once).\n• `/gitops channel`: connect a Slack channel to the organization's alerts.\n• `/gitops status`: linked organization, your account and the connected channels.", + "notLinked": "Link your GitOps account first with `/gitops login`.", + "disabled": "Your GitOps account is disabled.", + "forbidden": "Your GitOps account is not allowed to create channels in this organization.", + "failed": "GitOps could not complete the action ({code}).", + "linkExpires": "This link is only for you and expires in 10 minutes.", + "login": { + "prompt": "Open GitOps to link your Slack user to your account (sign in with your password or with Google).", + "button": "Link with GitOps" + }, + "status": { + "organization": "Organization: *{organization}*", + "linked": "Your account: *{username}*", + "notLinked": "Your account: not linked (`/gitops login`)", + "channels": "Slack channels: {channels}", + "noChannels": "No Slack channels connected yet (`/gitops channel`).", + "disabled": "disabled" + }, + "locale": { + "es": "Spanish", + "en": "English" + }, + "channel": { + "title": "Connect a channel", + "next": "Next", + "cancel": "Cancel", + "close": "Close", + "intro": "The channel is added to *{organization}*, where its alerts can use it.", + "name": "Name", + "nameHint": "How the configuration shows in GitOps.", + "namePlaceholder": "DevOps ES", + "locale": "Message language", + "nameRequired": "Type a name.", + "nameTooLong": "The name is too long (80 characters at most).", + "pick": "Last step: pick the Slack channel for *{name}*. Slack opens in the browser with your channels; once you allow it, GitOps saves the configuration and posts a test message to the channel.", + "pickButton": "Pick the channel in Slack" + } + }, + "slackLink": { + "title": "Link Slack", + "question": "Link the Slack user {slackUser} (workspace {team}) to your account {username}? You will be able to connect {organization} channels from Slack with /gitops.", + "confirm": "Link", + "done": "Done. Go back to Slack and use /gitops channel to connect a channel.", + "errors": { + "invalid": "The link is invalid or has expired. Type /gitops login in Slack again.", + "taken": "This Slack user is already linked to another GitOps account.", + "forbidden": "Your account does not belong to the organization of this Slack workspace.", + "not_installed": "The Slack workspace is no longer connected to GitOps." + } + }, + "slackDone": { + "title": "Slack", + "connected": "Channel “{name}” connected. We posted a test message to it.", + "next": "You can now pick it in GitOps alerts. You can close this tab.", + "retry": "Go back to Slack and try again with /gitops channel.", + "back": "Back to Slack" + }, + "apps": { + "title": "Apps", + "description": "Integrations installed in the organization. A connected app lets people manage channels from the tool itself.", + "installed": "Connected", + "notInstalled": "Not installed", + "connectedTo": "Connected to {name}", + "install": "Install", + "remove": "Disconnect", + "setupHint": "The app is not set up in this installation yet.", + "descriptions": { + "slack": "Connect channels from Slack with /gitops login and /gitops channel.", + "google-chat": "Connect Google Chat spaces to alerts." + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index be596d7f..1d5337a5 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -411,7 +411,7 @@ "configuredHelp": "Los ajustes de canales muestran el botón Añadir a Slack. El usuario elige el workspace y el canal en Slack.", "notConfiguredHelp": "Los canales de Slack se crean pegando una URL de Incoming Webhook. Crea la app de Slack abajo para activar Añadir a Slack.", "setupTitle": "Configurar la app de Slack", - "step1": "Crea la app de Slack de esta instalación desde su manifest (solo el scope incoming-webhook, con la redirect URL de esta instalación).", + "step1": "Crea la app de Slack de esta instalación desde su manifest (scopes incoming-webhook y commands, el comando /gitops y la redirect URL de esta instalación).", "createApp": "Crear app de Slack", "showManifest": "Ver manifest", "step2": "Comprueba que la redirect URL de la app (OAuth & Permissions) es esta:", @@ -419,7 +419,12 @@ "step3": "En Basic Information, copia el Client ID y el Client Secret al entorno y reinicia GitOps. Para que otros workspaces la instalen, activa Public Distribution en Manage Distribution.", "manualNote": "Pegar una webhook URL sigue funcionando, con o sin app de Slack.", "copy": "Copiar", - "copied": "Copiado" + "copied": "Copiado", + "commandsTitle": "Comando /gitops", + "commandsOn": "Activo", + "commandsOff": "Falta SLACK_SIGNING_SECRET", + "commandsHelp": "Con el Signing Secret, cada organización instala la app desde sus ajustes de canales y conecta canales desde Slack con /gitops. Slack envía los comandos a esta instalación, que tiene que ser accesible desde internet.", + "step4": "Para /gitops, copia también el Signing Secret (Basic Information → App Credentials) a SLACK_SIGNING_SECRET. El manifest ya registra el comando y la URL de interactividad:" } }, "org": { @@ -2206,7 +2211,9 @@ "slack_cancelled": "Se canceló la conexión con Slack.", "slack_invalid_state": "La conexión con Slack caducó o la inició otra sesión. Vuelve a intentarlo.", "slack_exchange_failed": "Slack no completó la conexión. Vuelve a intentarlo.", - "slack_no_webhook": "Slack no devolvió el webhook del canal: la app de Slack necesita el scope incoming-webhook." + "slack_no_webhook": "Slack no devolvió el webhook del canal: la app de Slack necesita el scope incoming-webhook.", + "slack_wrong_workspace": "La conexión se completó en otro workspace o con otro usuario de Slack. Hazlo con la cuenta que escribió /gitops channel.", + "slack_workspace_taken": "Este workspace de Slack ya está conectado a otra organización de GitOps." }, "link": { "invalid": "Este enlace no es válido o ya se ha usado.", @@ -2309,7 +2316,85 @@ "slackConnected": "Canal de Slack añadido", "slackManual": "o pega una URL de Incoming Webhook", "slackSetupHint": "Añadir a Slack (elegir el canal en Slack, sin copiar URLs) aún no está configurado.", - "slackSetupLink": "Configurarlo" + "slackSetupLink": "Configurarlo", + "slackAppRemove": "Desconectar", + "slackAppRemoveTitle": "¿Desconectar {team}?", + "slackAppRemoveConfirm": "/gitops dejará de funcionar en ese workspace hasta que se instale de nuevo. Los canales ya conectados siguen publicando; para revocarlos, quita la app en Slack.", + "slackAppInstalledToast": "App de Slack instalada", + "slackAppRemovedToast": "Workspace desconectado" + }, + "slackApp": { + "notInstalled": "Este workspace de Slack no está conectado a GitOps. Un administrador de la organización tiene que pulsar *Instalar en Slack* en GitOps (Ajustes → Alertas → Ajustes → Canales).", + "help": "*Comandos de GitOps*\n• `/gitops login`: vincula tu usuario de Slack con tu cuenta de GitOps (una vez).\n• `/gitops channel`: conecta un canal de Slack a las alertas de la organización.\n• `/gitops status`: organización vinculada, tu cuenta y los canales conectados.", + "notLinked": "Primero vincula tu cuenta de GitOps con `/gitops login`.", + "disabled": "Tu cuenta de GitOps está deshabilitada.", + "forbidden": "Tu cuenta de GitOps no tiene permiso para crear canales en esta organización.", + "failed": "GitOps no ha podido completar la acción ({code}).", + "linkExpires": "El enlace es solo para ti y caduca en 10 minutos.", + "login": { + "prompt": "Abre GitOps para vincular tu usuario de Slack con tu cuenta (puedes entrar con contraseña o con Google).", + "button": "Vincular con GitOps" + }, + "status": { + "organization": "Organización: *{organization}*", + "linked": "Tu cuenta: *{username}*", + "notLinked": "Tu cuenta: sin vincular (`/gitops login`)", + "channels": "Canales de Slack: {channels}", + "noChannels": "Todavía no hay canales de Slack conectados (`/gitops channel`).", + "disabled": "deshabilitado" + }, + "locale": { + "es": "Español", + "en": "Inglés" + }, + "channel": { + "title": "Conectar canal", + "next": "Siguiente", + "cancel": "Cancelar", + "close": "Cerrar", + "intro": "El canal se añadirá a *{organization}* y lo podrán usar sus alertas.", + "name": "Nombre", + "nameHint": "Así se verá la configuración en GitOps.", + "namePlaceholder": "DevOps ES", + "locale": "Idioma de los mensajes", + "nameRequired": "Escribe un nombre.", + "nameTooLong": "El nombre es demasiado largo (máximo 80 caracteres).", + "pick": "Último paso: elige el canal de Slack para *{name}*. Se abrirá Slack en el navegador con tus canales; al permitirlo, GitOps guarda la configuración y publica un mensaje de prueba en el canal.", + "pickButton": "Elegir canal en Slack" + } + }, + "slackLink": { + "title": "Vincular Slack", + "question": "¿Vincular el usuario de Slack {slackUser} (workspace {team}) con tu cuenta {username}? Podrás conectar canales de {organization} desde Slack con /gitops.", + "confirm": "Vincular", + "done": "Listo. Vuelve a Slack y usa /gitops channel para conectar un canal.", + "errors": { + "invalid": "El enlace no es válido o ha caducado. Vuelve a escribir /gitops login en Slack.", + "taken": "Este usuario de Slack ya está vinculado a otra cuenta de GitOps.", + "forbidden": "Tu cuenta no pertenece a la organización de este workspace de Slack.", + "not_installed": "El workspace de Slack ya no está conectado a GitOps." + } + }, + "slackDone": { + "title": "Slack", + "connected": "Canal «{name}» conectado. Hemos publicado un mensaje de prueba en él.", + "next": "Ya puedes elegirlo en las alertas de GitOps. Puedes cerrar esta pestaña.", + "retry": "Vuelve a Slack y prueba de nuevo con /gitops channel.", + "back": "Volver a Slack" + }, + "apps": { + "title": "Apps", + "description": "Integraciones instaladas en la organización. Una app conectada permite gestionar canales desde la propia herramienta.", + "installed": "Conectada", + "notInstalled": "No instalada", + "connectedTo": "Conectada a {name}", + "install": "Instalar", + "remove": "Desconectar", + "setupHint": "La app aún no está configurada en esta instalación.", + "descriptions": { + "slack": "Conecta canales desde Slack con /gitops login y /gitops channel.", + "google-chat": "Conecta espacios de Google Chat a las alertas." + } } } } diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts index 323f1d1c..64900746 100644 --- a/src/lib/notifications/types.ts +++ b/src/lib/notifications/types.ts @@ -54,6 +54,29 @@ export type ChannelsSectionData = { slackConnect: boolean; /** Where a GitOps admin sets up "Add to Slack" while it is not configured; `null` otherwise. */ slackSetupPath: string | null; + /** + * Apps installed in the organization (the GitOps Slack app and, later, other providers): one card + * each. `null` on project pages: apps belong to organizations. + */ + apps: AppCardData[] | null; +}; + +/** Providers with an app card; the ones without an implementation show as coming soon. */ +export const APP_PROVIDERS = ['slack', 'google-chat'] as const; +export type AppProvider = (typeof APP_PROVIDERS)[number]; + +export type AppCardData = { + provider: AppProvider; + /** Not built yet: the card only says "coming soon". */ + comingSoon: boolean; + /** The installation has the app configured (credentials set by a GitOps admin). */ + configured: boolean; + canInstall: boolean; + canRemove: boolean; + /** Where it is installed (Slack workspaces); empty = not installed. */ + installations: { id: string; name: string }[]; + /** Shown to GitOps admins while the app is not configured. */ + setupPath: string | null; }; export type ChannelsFormResult = { diff --git a/src/lib/server/csrf.test.ts b/src/lib/server/csrf.test.ts new file mode 100644 index 00000000..ec946245 --- /dev/null +++ b/src/lib/server/csrf.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; +import { isCsrfForbidden } from './csrf'; + +const ORIGIN = 'https://gitops.example.com'; + +function request( + path: string, + init: { method?: string; origin?: string | null; type?: string | null }, +) { + const headers = new Headers(); + if (init.origin) headers.set('origin', init.origin); + if (init.type) headers.set('content-type', init.type); + return { + request: new Request(`${ORIGIN}${path}`, { method: init.method ?? 'POST', headers }), + url: new URL(`${ORIGIN}${path}`), + }; +} + +describe('isCsrfForbidden', () => { + it.each([ + [ + 'a form from another site', + { origin: 'https://evil.example', type: 'application/x-www-form-urlencoded' }, + true, + ], + ['a form without Origin', { origin: null, type: 'multipart/form-data; boundary=x' }, true], + [ + 'an enhanced form with files', + { origin: 'https://evil.example', type: 'application/x-sveltekit-formdata' }, + true, + ], + ['a POST without content type', { origin: null, type: null }, true], + ['a same-origin form', { origin: ORIGIN, type: 'application/x-www-form-urlencoded' }, false], + [ + 'JSON from another site (CORS applies)', + { origin: 'https://evil.example', type: 'application/json' }, + false, + ], + ['a GET', { method: 'GET', origin: 'https://evil.example', type: null }, false], + ])('%s → %s', (_label, init, forbidden) => { + const { request: req, url } = request('/org/acme/settings', init); + expect(isCsrfForbidden(req, url)).toBe(forbidden); + }); + + it('lets only the signed Slack endpoints through without Origin', () => { + for (const path of ['/api/slack/commands', '/api/slack/interactions']) { + const { request: req, url } = request(path, { type: 'application/x-www-form-urlencoded' }); + expect(isCsrfForbidden(req, url)).toBe(false); + } + const { request: req, url } = request('/api/slack/commands/x', { + type: 'application/x-www-form-urlencoded', + }); + expect(isCsrfForbidden(req, url)).toBe(true); + }); +}); diff --git a/src/lib/server/csrf.ts b/src/lib/server/csrf.ts new file mode 100644 index 00000000..10fe3aad --- /dev/null +++ b/src/lib/server/csrf.ts @@ -0,0 +1,42 @@ +/** + * SvelteKit's CSRF origin check, done here instead of by the framework (`csrf.trustedOrigins: + * ['*']` in `vite.config.ts`) so a few routes can be exempt: Slack posts its commands and forms + * as `application/x-www-form-urlencoded` without an `Origin` header, which SvelteKit would refuse + * in production. Those routes authenticate every request with Slack's HMAC signature instead. + */ + +const FORM_CONTENT_TYPES = [ + 'application/x-www-form-urlencoded', + 'multipart/form-data', + 'text/plain', + // what `enhance` sends for forms with files + 'application/x-sveltekit-formdata', +]; +const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']); + +/** Routes that verify their own signed requests (`X-Slack-Signature`), and nothing else. */ +export const CSRF_EXEMPT_PATHS = new Set(['/api/slack/commands', '/api/slack/interactions']); + +function isFormContentType(header: string | null): boolean { + const type = header?.split(';', 1)[0].trim().toLowerCase() ?? ''; + return FORM_CONTENT_TYPES.includes(type); +} + +/** Same rule as SvelteKit's `is_csrf_forbidden` (no trusted origins), plus the exempt paths. */ +export function isCsrfForbidden(request: Request, url: URL): boolean { + if (CSRF_EXEMPT_PATHS.has(url.pathname)) return false; + const contentType = request.headers.get('content-type'); + return ( + (!contentType || isFormContentType(contentType)) && + MUTATING_METHODS.has(request.method) && + request.headers.get('origin') !== url.origin + ); +} + +export function csrfForbiddenResponse(request: Request): Response { + const message = `Cross-site ${request.method} form submissions are forbidden`; + if (request.headers.get('accept') === 'application/json') { + return Response.json({ message }, { status: 403 }); + } + return new Response(message, { status: 403, headers: { 'content-type': 'text/plain' } }); +} diff --git a/src/lib/server/notifications/channels-page.ts b/src/lib/server/notifications/channels-page.ts index 22ce190b..6bf8ce6c 100644 --- a/src/lib/server/notifications/channels-page.ts +++ b/src/lib/server/notifications/channels-page.ts @@ -4,18 +4,21 @@ import { SLACK_FLOW_COOKIE, SLACK_FLOW_COOKIE_PATH, SLACK_FLOW_TTL_MS, + slackAppService, slackConnectService, type ChannelLocation, } from '#modules/notifications'; import type { AlertLocals } from '#lib/server/alerts/access'; -import type { ChannelsSectionData } from '#lib/notifications/types'; +import type { AppCardData, ChannelsSectionData } from '#lib/notifications/types'; import { canManageChannels, createChannel, deleteChannel, listChannels, + removeSlackWorkspace, rotateChannelSecret, startSlackConnection, + startSlackInstall, testChannel, updateChannel, } from './channels'; @@ -39,9 +42,31 @@ export async function loadChannelsSection( cancanService.canAccessAdminArea( locals.user as Parameters[0], ); + // apps belong to organizations: projects use the organization's channels + const apps: AppCardData[] | null = + location.scope === 'organization' + ? [ + await slackAppCard(locals, location.organizationId, { + canCreate, + canDelete, + isAdmin, + available: slackAvailable, + }), + { + provider: 'google-chat', + comingSoon: true, + configured: false, + canInstall: false, + canRemove: false, + installations: [], + setupPath: null, + }, + ] + : null; return { ...listed.data, scope: location.scope, + apps, canCreate, canUpdate, canDelete, @@ -53,6 +78,28 @@ export async function loadChannelsSection( }; } +/** The GitOps Slack app (`/gitops`): needs the app configured with its signing secret. */ +async function slackAppCard( + locals: AlertLocals, + organizationId: string, + input: { canCreate: boolean; canDelete: boolean; isAdmin: boolean; available: boolean }, +): Promise { + const configured = input.available && slackConnectService.commandsEnabled(); + const installations = (await slackAppService.workspacesOf(organizationId)).map((workspace) => ({ + id: workspace.id, + name: workspace.teamName, + })); + return { + provider: 'slack', + comingSoon: false, + configured, + canInstall: configured && input.canCreate && !locals.apiKey, + canRemove: input.canDelete, + installations, + setupPath: !configured && input.isAdmin ? '/gitops-settings/slack' : null, + }; +} + type ActionEvent = { request: Request; params: Record; @@ -123,6 +170,47 @@ export function channelActions(resolve: (event: ActionEvent) => Promise> { + const location: ChannelLocation = { scope: 'organization', organizationId, projectId: null }; + const userId = locals.apiKey ? null : locals.user?.id; + if (!userId || !(await canManageChannels(locals, location, 'create'))) return forbidden; + if (!slackConnectService.commandsEnabled()) { + return { ok: false, status: 400, error: 'slack_not_configured' }; + } + try { + return { + ok: true, + status: 303, + data: slackConnectService.startInstall({ + userId, + organizationId, + locale: input.locale, + returnTo: input.returnTo, + redirectUri: slackRedirectUri(input.origin), + }), + }; + } catch (error) { + if (error instanceof SlackConnectError) return { ok: false, status: 400, error: error.code }; + throw error; + } +} + +/** Forgets a Slack workspace of the organization (`organization:notifications:delete`). */ +export async function removeSlackWorkspace( + locals: AlertLocals, + organizationId: string, + workspaceId: string, +): Promise> { + const location: ChannelLocation = { scope: 'organization', organizationId, projectId: null }; + if (!(await canManageChannels(locals, location, 'delete'))) return forbidden; + const removed = await slackAppService.removeWorkspace(organizationId, workspaceId); + return removed + ? { ok: true, status: 200, data: { id: workspaceId } } + : { ok: false, status: 404, error: 'Workspace not found' }; +} + +/** Where the callback sends the browser, and the error code to log when it failed. */ +export type SlackFlowOutcome = { location: string; error: string | null }; + +function withStatus(path: string, status: string, extra: Record = {}) { + return `${path}?${new URLSearchParams({ slack: status, ...extra })}`; +} + +/** The first validation error of a failed create, as a `notifications.errors.*` code. */ +function createError(result: { status: number; errors?: Record }): string { + return result.status === 403 + ? 'Forbidden' + : (Object.values(result.errors ?? {})[0] ?? 'slack_exchange_failed'); +} /** - * Finishes "Add to Slack": validates the flow (same user, state), trades the code for the - * channel's webhook and creates the channel, checking `:notifications:create` again. + * Finishes a Slack OAuth flow, whichever started it: + * - "Add to Slack" on a channels page: creates the channel (same session, permission again); + * - the app install: saves the workspace for the organization (same session, permission again); + * - `/gitops channel`: creates the channel named in Slack as the linked user (no session needed, + * the flow is bound to the Slack workspace and user), posts a test message to it, and ends on + * the "go back to Slack" page. */ -export async function completeSlackConnection( +export async function completeSlackFlow( locals: AlertLocals, - input: { - flowCookie: string | undefined; - searchParams: URLSearchParams; - origin: string; - }, -): Promise { - const userId = locals.apiKey ? '' : (locals.user?.id ?? ''); - let connection; + input: { flowCookie: string | undefined; searchParams: URLSearchParams; origin: string }, +): Promise { + const sessionUserId = locals.apiKey ? null : (locals.user?.id ?? null); + let result: SlackFlowResult; try { - connection = await slackConnectService.complete({ + result = await slackConnectService.complete({ flowCookie: input.flowCookie, - userId, + sessionUserId, state: input.searchParams.get('state'), code: input.searchParams.get('code'), error: input.searchParams.get('error'), @@ -273,25 +334,70 @@ export async function completeSlackConnection( }); } catch (error) { if (error instanceof SlackConnectError) { - return { ok: false, returnTo: error.returnTo, error: error.code }; + return { location: withStatus(error.returnTo, error.code), error: error.code }; } throw error; } - const created = await createChannel(locals, connection.location, { - type: 'slack', - name: connection.name, - destination: connection.webhookUrl, - locale: connection.locale, - enabled: true, - }); - if (!created.ok) { - // codes of `notifications.errors.*`: the first validation error says enough - const code = - created.status === 403 - ? 'Forbidden' - : (Object.values(created.errors ?? {})[0] ?? 'slack_exchange_failed'); - return { ok: false, returnTo: connection.returnTo, error: code }; + if (result.kind === 'install') { + const location: ChannelLocation = { + scope: 'organization', + organizationId: result.organizationId, + projectId: null, + }; + if (!(await canManageChannels(locals, location, 'create'))) { + return { location: withStatus(result.returnTo, 'Forbidden'), error: 'Forbidden' }; + } + const installed = await slackAppService.installWorkspace(result); + const status = installed === 'installed' ? 'installed' : 'slack_workspace_taken'; + return { + location: withStatus(result.returnTo, status), + error: installed === 'installed' ? null : status, + }; + } + + if (result.kind === 'channel') { + const created = await createChannel(locals, result.location, { + type: 'slack', + name: result.name, + destination: result.webhookUrl, + locale: result.locale, + enabled: true, + }); + if (!created.ok) { + const code = createError(created); + return { location: withStatus(result.returnTo, code), error: code }; + } + return { location: withStatus(result.returnTo, 'connected'), error: null }; } - return { ok: true, returnTo: connection.returnTo, channel: created.data }; + + // from Slack: act as the linked user, who must still exist, be enabled and hold the permission + const user = await authService.sessionUserById(result.userId); + if (!user || user.disabled) { + return { location: withStatus(result.returnTo, 'Forbidden'), error: 'Forbidden' }; + } + const userLocals: AlertLocals = { user }; + const actor = { + name: user.username, + email: user.email || `${user.username}@gitops.local`, + userId: user.id, + }; + return runWithActor(actor, async () => { + const created = await createChannel(userLocals, result.location, { + type: 'slack', + name: result.name, + destination: result.webhookUrl, + locale: result.locale, + enabled: true, + }); + if (!created.ok) { + const code = createError(created); + return { location: withStatus(result.returnTo, code), error: code }; + } + // the channel says hello: the user sees in Slack that it works + await testChannel(userLocals, created.data.id).catch(() => undefined); + const extra: Record = { team: result.teamId, name: result.name }; + if (result.channelId) extra.channel = result.channelId; + return { location: withStatus(result.returnTo, 'connected', extra), error: null }; + }); } diff --git a/src/lib/server/notifications/slack-requests.ts b/src/lib/server/notifications/slack-requests.ts new file mode 100644 index 00000000..b000159e --- /dev/null +++ b/src/lib/server/notifications/slack-requests.ts @@ -0,0 +1,26 @@ +import { json } from '@sveltejs/kit'; +import { slackAppService } from '#modules/notifications'; + +/** + * Reads and authenticates a request from Slack (`/gitops` and its forms). Slack signs the raw + * body with the app's signing secret; nothing else authenticates these routes (no session, no + * API key), so an unsigned or stale request is refused before anything is parsed. + */ +export async function readSlackRequest(request: Request): Promise { + const body = await request.text(); + const verified = slackAppService.verifyRequest({ + timestamp: request.headers.get('x-slack-request-timestamp'), + signature: request.headers.get('x-slack-signature'), + body, + }); + return verified ? new URLSearchParams(body) : null; +} + +export function slackUnauthorized() { + return json({ error: 'Invalid Slack signature' }, { status: 401 }); +} + +/** Slack wants a 200 within 3 s; an empty body acknowledges without replying. */ +export function slackReply(reply: Record | null) { + return reply ? json(reply) : new Response(null, { status: 200 }); +} diff --git a/src/lib/server/return-to.test.ts b/src/lib/server/return-to.test.ts new file mode 100644 index 00000000..1b62fa70 --- /dev/null +++ b/src/lib/server/return-to.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from 'vitest'; +import { safeReturnPath } from './return-to'; + +describe('safeReturnPath', () => { + it.each([ + ['/notifications/slack/link?token=abc', '/notifications/slack/link?token=abc'], + ['/notifications/slack/link', '/notifications/slack/link'], + ['/org/acme', null], + ['//evil.example.com/notifications/slack/link', null], + ['/\\evil.example.com', null], + ['https://evil.example.com/notifications/slack/link', null], + ['/notifications/slack/link/../../auth/logout', null], + ['', null], + [null, null], + ])('%s → %s', (input, expected) => { + expect(safeReturnPath(input)).toBe(expected); + }); +}); diff --git a/src/lib/server/return-to.ts b/src/lib/server/return-to.ts new file mode 100644 index 00000000..8bba2917 --- /dev/null +++ b/src/lib/server/return-to.ts @@ -0,0 +1,49 @@ +import type { Cookies } from '@sveltejs/kit'; + +/** Where to land after signing in, for links that need a session (`/gitops login`). */ +export const RETURN_TO_COOKIE = 'gitops_return_to'; +const RETURN_TO_TTL_SECONDS = 10 * 60; +/** Only these pages ask to come back after the login; everything else lands on `/` as always. */ +const RETURNABLE_PATHS = ['/notifications/slack/link']; + +/** A same-origin path of `RETURNABLE_PATHS` (with its query), or `null`. */ +export function safeReturnPath(value: string | undefined | null): string | null { + if (!value || !value.startsWith('/') || value.startsWith('//') || value.includes('\\')) { + return null; + } + let url: URL; + try { + url = new URL(value, 'http://gitops.invalid'); + } catch { + return null; + } + if (url.origin !== 'http://gitops.invalid' || !RETURNABLE_PATHS.includes(url.pathname)) { + return null; + } + return `${url.pathname}${url.search}`; +} + +/** + * `Set-Cookie` value that remembers `path`, or `null` when it is not returnable. A header, not + * `cookies.set()`: the hook returns its own redirect, and SvelteKit only adds the cookies of + * `cookies.set()` to responses that went through `resolve()`. + */ +export function returnToCookie(cookies: Cookies, path: string): string | null { + const safe = safeReturnPath(path); + if (!safe) return null; + return cookies.serialize(RETURN_TO_COOKIE, safe, { + path: '/', + httpOnly: true, + secure: process.env.NODE_ENV === 'production', + sameSite: 'lax', + maxAge: RETURN_TO_TTL_SECONDS, + }); +} + +/** The remembered page (once), or `fallback`. */ +export function consumeReturnTo(cookies: Cookies, fallback = '/'): string { + const value = cookies.get(RETURN_TO_COOKIE); + if (value === undefined) return fallback; + cookies.delete(RETURN_TO_COOKIE, { path: '/' }); + return safeReturnPath(value) ?? fallback; +} diff --git a/src/modules/auth/application/auth.service.ts b/src/modules/auth/application/auth.service.ts index 86f80c86..8ca07719 100644 --- a/src/modules/auth/application/auth.service.ts +++ b/src/modules/auth/application/auth.service.ts @@ -3,7 +3,10 @@ import { PasswordService } from './password.service'; import { SessionService } from './session.service'; import { UserRepository } from '../infrastructure/repositories/user.repository'; import { RoleRepository } from '../infrastructure/repositories/role.repository'; -import { CLUSTER_ADMIN_PERMISSIONS, CLUSTER_USER_PERMISSIONS } from '../domain/role-permissions.data'; +import { + CLUSTER_ADMIN_PERMISSIONS, + CLUSTER_USER_PERMISSIONS, +} from '../domain/role-permissions.data'; export class AuthService { constructor( @@ -159,7 +162,45 @@ export class AuthService { if (!userId) { return null; } + return this.sessionUserById(userId); + } + + /** + * The user linked to an external identity (`provider` + `providerId`, e.g. a Slack + * `:`), or `null`. Callers acting for it must refuse a `disabled` user. + */ + async findByExternalIdentity( + provider: string, + providerId: string, + ): Promise<{ id: string; username: string; email: string | null; disabled: boolean } | null> { + const user = await this.userRepository.findByAuthProvider(provider, providerId); + if (!user) return null; + return { id: user.id, username: user.username, email: user.email, disabled: user.disabled }; + } + + /** + * Links an external identity to `userId`. `taken` when another user already has it: an identity + * belongs to one GitOps user, and moving it must be an explicit unlink first. + */ + async linkExternalIdentity( + userId: string, + provider: string, + providerId: string, + ): Promise<'linked' | 'taken' | 'not_found'> { + const owner = await this.userRepository.findByAuthProvider(provider, providerId); + if (owner && owner.id !== userId) return 'taken'; + if (owner) return 'linked'; + const user = await this.userRepository.findById(userId); + if (!user) return 'not_found'; + await this.userRepository.updateAuthProviders(userId, [ + ...user.authProviders, + { provider, providerId }, + ]); + return 'linked'; + } + /** The same shape as a session's `locals.user`, for requests that act as a user by other means. */ + async sessionUserById(userId: string): Promise { const user = await this.userRepository.findById(userId); if (!user) { return null; @@ -169,6 +210,7 @@ export class AuthService { id: user.id, username: user.username, email: user.email, + disabled: user.disabled, role: user.role ? { id: user.role.id, diff --git a/src/modules/notifications/application/slack-app.service.test.ts b/src/modules/notifications/application/slack-app.service.test.ts new file mode 100644 index 00000000..7bc7c8c5 --- /dev/null +++ b/src/modules/notifications/application/slack-app.service.test.ts @@ -0,0 +1,317 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createChannelCipher } from '../infrastructure/crypto/channel-cipher'; +import { InMemorySlackWorkspaceRepository } from '../infrastructure/repositories/slack-workspace.repository'; +import { signSlackRequest } from '../infrastructure/slack/slack-signature'; +import type { SlackAppConfig } from '../infrastructure/config/slack-app.config'; +import { SLACK_CONNECT_PATH, SLACK_LINK_PATH, SlackAppService } from './slack-app.service'; +import type { SlackInstall } from './slack-connect.service'; + +const NOW = Date.UTC(2026, 10, 27, 12); +const ORIGIN = 'https://gitops.example.com'; +const CONFIG: SlackAppConfig = { + clientId: '123.456', + clientSecret: 'shh', + signingSecret: 'signing-secret', +}; +const INSTALL: SlackInstall = { + kind: 'install', + userId: 'admin-1', + organizationId: 'org-1', + locale: 'es', + returnTo: '/org/acme/settings/alerts/settings', + teamId: 'T1', + teamName: 'Acme', + botToken: 'xoxb-secret', +}; + +type User = { id: string; username: string; disabled: boolean }; + +function setup(options: { config?: SlackAppConfig | null; canCreate?: boolean } = {}) { + const workspaces = new InMemorySlackWorkspaceRepository(); + const cipher = createChannelCipher(() => 'encryption-key'); + const identities = new Map(); + const users: Record = { + 'user-1': { id: 'user-1', username: 'ana', disabled: false }, + 'user-2': { id: 'user-2', username: 'bob', disabled: false }, + }; + const openView = vi.fn(async () => ({ ok: true as const })); + const members = new Set(['user-1', 'admin-1']); + const service = new SlackAppService({ + readConfig: () => (options.config === undefined ? CONFIG : options.config), + workspaces, + cipher, + api: { openView }, + identities: { + async find(provider, providerId) { + return identities.get(`${provider}/${providerId}`) ?? null; + }, + async link(userId, provider, providerId) { + const key = `${provider}/${providerId}`; + const owner = identities.get(key); + if (owner && owner.id !== userId) return 'taken'; + if (!users[userId]) return 'not_found'; + identities.set(key, users[userId]); + return 'linked'; + }, + }, + access: { + canCreateChannels: async () => options.canCreate ?? true, + canViewOrganization: async (userId) => members.has(userId), + organizationName: async () => 'Acme Corp', + }, + channels: { + listSlack: async () => [ + { name: 'DevOps ES', enabled: true }, + { name: '', enabled: false }, + ], + }, + secret: () => 'token-secret', + now: () => NOW, + }); + const command = (text: string, extra: Record = {}) => + service.handleCommand( + new URLSearchParams({ + team_id: 'T1', + user_id: 'U1', + user_name: 'ana.slack', + trigger_id: 'trigger-1', + text, + ...extra, + }), + ORIGIN, + ); + const link = async (userId = 'user-1') => { + const reply = (await command('login')) as { blocks: any[] }; + const url = new URL(reply.blocks[1].elements[0].url); + return { + token: url.searchParams.get('token'), + result: await service.confirmLink(url.searchParams.get('token'), userId), + }; + }; + const submit = (name: string, locale = 'en', ids = { team: 'T1', user: 'U1' }) => + service.handleInteraction( + { + type: 'view_submission', + team: { id: ids.team }, + user: { id: ids.user }, + view: { + callback_id: 'gitops_channel', + state: { + values: { + name: { value: { type: 'plain_text_input', value: name } }, + locale: { value: { selected_option: { value: locale } } }, + }, + }, + }, + }, + ORIGIN, + ); + return { service, workspaces, cipher, openView, command, link, submit, members }; +} + +describe('SlackAppService', () => { + describe('request signatures', () => { + it('accepts what Slack signs and refuses the rest', () => { + const { service } = setup(); + const timestamp = String(Math.floor(NOW / 1000)); + const body = 'command=%2Fgitops&text=status'; + const signature = signSlackRequest('signing-secret', timestamp, body); + expect(service.verifyRequest({ timestamp, signature, body })).toBe(true); + expect(service.verifyRequest({ timestamp, signature, body: `${body}x` })).toBe(false); + expect(service.verifyRequest({ timestamp, signature: 'v0=00', body })).toBe(false); + // a replay after 5 minutes + const old = String(Math.floor(NOW / 1000) - 301); + expect( + service.verifyRequest({ + timestamp: old, + signature: signSlackRequest('signing-secret', old, body), + body, + }), + ).toBe(false); + }); + + it('refuses everything without a signing secret', () => { + const { service } = setup({ config: { ...CONFIG, signingSecret: null } }); + const timestamp = String(Math.floor(NOW / 1000)); + const signature = signSlackRequest('', timestamp, 'x'); + expect(service.verifyRequest({ timestamp, signature, body: 'x' })).toBe(false); + }); + }); + + describe('workspaces', () => { + it('stores the workspace with its token encrypted and never shows it', async () => { + const { service, workspaces, cipher } = setup(); + expect(await service.installWorkspace(INSTALL)).toBe('installed'); + const [stored] = [...workspaces.rows.values()]; + expect(stored.botToken).not.toContain('xoxb'); + expect(cipher.decrypt(stored.id, stored.botToken, 'slack-bot-token')).toBe('xoxb-secret'); + const [view] = await service.workspacesOf('org-1'); + expect(view).toMatchObject({ teamId: 'T1', teamName: 'Acme', locale: 'es' }); + expect(view).not.toHaveProperty('botToken'); + }); + + it('reinstalls in place, but never moves a workspace to another organization', async () => { + const { service, workspaces } = setup(); + await service.installWorkspace(INSTALL); + expect(await service.installWorkspace({ ...INSTALL, teamName: 'Acme Inc' })).toBe( + 'installed', + ); + expect(workspaces.rows.size).toBe(1); + expect([...workspaces.rows.values()][0].teamName).toBe('Acme Inc'); + expect(await service.installWorkspace({ ...INSTALL, organizationId: 'org-2' })).toBe('taken'); + }); + + it('removes a workspace of the organization only', async () => { + const { service } = setup(); + await service.installWorkspace(INSTALL); + const [view] = await service.workspacesOf('org-1'); + expect(await service.removeWorkspace('org-2', view.id)).toBe(false); + expect(await service.removeWorkspace('org-1', view.id)).toBe(true); + expect(await service.workspacesOf('org-1')).toEqual([]); + }); + }); + + describe('/gitops', () => { + it('says the workspace is not connected before the app is installed from GitOps', async () => { + const { command } = setup(); + const reply = (await command('login')) as { text: string }; + expect(reply.text).toMatch(/GitOps/); + expect(reply).toMatchObject({ response_type: 'ephemeral' }); + }); + + it('answers with help for an unknown action', async () => { + const { service, command } = setup(); + await service.installWorkspace(INSTALL); + const reply = (await command('what')) as { text: string }; + expect(reply.text).toContain('/gitops login'); + }); + + it('login: a private link that expires, then links the GitOps account', async () => { + const { service, link } = setup(); + await service.installWorkspace(INSTALL); + const { token, result } = await link(); + expect(result).toBe('linked'); + const request = await service.readLinkRequest(token); + expect(request).toMatchObject({ + teamId: 'T1', + slackUserId: 'U1', + slackUserName: 'ana.slack', + }); + expect(request?.workspace.teamName).toBe('Acme'); + }); + + it('login: the link points at the link page of this origin', async () => { + const { service, command } = setup(); + await service.installWorkspace(INSTALL); + const reply = (await command('login')) as { blocks: any[]; response_type: string }; + expect(reply.response_type).toBe('ephemeral'); + const url = new URL(reply.blocks[1].elements[0].url); + expect(url.origin + url.pathname).toBe(`${ORIGIN}${SLACK_LINK_PATH}`); + }); + + it('login: refuses an account outside the organization, or a Slack user already linked', async () => { + const { service, link } = setup(); + await service.installWorkspace(INSTALL); + expect((await link('user-2')).result).toBe('forbidden'); + expect((await link('user-1')).result).toBe('linked'); + // user-2 joins the organization: the Slack user is still someone else's + const other = setup(); + await other.service.installWorkspace(INSTALL); + other.members.add('user-2'); + await other.link('user-1'); + expect((await other.link('user-2')).result).toBe('taken'); + }); + + it('login: refuses an invalid or expired token', async () => { + const { service } = setup(); + await service.installWorkspace(INSTALL); + expect(await service.confirmLink('v1.x.y', 'user-1')).toBe('invalid'); + expect(await service.confirmLink(null, 'user-1')).toBe('invalid'); + }); + + it('channel: asks to log in first, then opens the form with the bot token', async () => { + const { service, command, link, openView } = setup(); + await service.installWorkspace(INSTALL); + expect(((await command('channel')) as { text: string }).text).toContain('/gitops login'); + expect(openView).not.toHaveBeenCalled(); + + await link(); + expect(await command('channel')).toBeNull(); + expect(openView).toHaveBeenCalledWith( + 'xoxb-secret', + 'trigger-1', + expect.objectContaining({ type: 'modal', callback_id: 'gitops_channel' }), + ); + }); + + it('channel: needs notifications:create in the organization', async () => { + const { service, command, link, openView } = setup({ canCreate: false }); + await service.installWorkspace(INSTALL); + await link(); + expect(((await command('channel')) as { text: string }).text).toBeTruthy(); + expect(openView).not.toHaveBeenCalled(); + }); + + it('status: the organization, the account and the Slack channels, escaped', async () => { + const { service, command, link } = setup(); + await service.installWorkspace(INSTALL); + await link(); + const { text } = (await command('status')) as { text: string }; + expect(text).toContain('Acme Corp'); + expect(text).toContain('ana'); + expect(text).toContain('DevOps ES'); + expect(text).toContain('<!here>'); + expect(text).not.toContain(''); + }); + }); + + describe('channel form', () => { + it('turns a valid name into the link that opens the channel picker', async () => { + const { service, link, submit } = setup(); + await service.installWorkspace(INSTALL); + await link(); + const reply = (await submit(' DevOps ES ')) as { response_action: string; view: any }; + expect(reply.response_action).toBe('update'); + const button = reply.view.blocks[1].elements[0]; + const url = new URL(button.url); + expect(url.origin + url.pathname).toBe(`${ORIGIN}${SLACK_CONNECT_PATH}`); + expect(service.readChannelRequest(url.searchParams.get('token'))).toEqual({ + userId: 'user-1', + organizationId: 'org-1', + teamId: 'T1', + slackUserId: 'U1', + name: 'DevOps ES', + locale: 'en', + }); + }); + + it('reports field errors: empty or long names, unlinked users, no permission', async () => { + const { service, link, submit } = setup(); + await service.installWorkspace(INSTALL); + expect(await submit('DevOps')).toMatchObject({ response_action: 'errors' }); + await link(); + expect(await submit(' ')).toMatchObject({ response_action: 'errors' }); + expect(await submit('x'.repeat(81))).toMatchObject({ response_action: 'errors' }); + + const denied = setup({ canCreate: false }); + await denied.service.installWorkspace(INSTALL); + await denied.link(); + expect(await denied.submit('DevOps')).toMatchObject({ + response_action: 'errors', + errors: { name: expect.any(String) }, + }); + }); + + it('acknowledges button clicks and other interactions without a reply', async () => { + const { service } = setup(); + expect(await service.handleInteraction({ type: 'block_actions' }, ORIGIN)).toBeNull(); + expect(await service.handleInteraction(null, ORIGIN)).toBeNull(); + }); + + it('refuses forged or expired channel links', () => { + const { service } = setup(); + expect(service.readChannelRequest(null)).toBeNull(); + expect(service.readChannelRequest('v1.e30.AAAA')).toBeNull(); + }); + }); +}); diff --git a/src/modules/notifications/application/slack-app.service.ts b/src/modules/notifications/application/slack-app.service.ts new file mode 100644 index 00000000..90a388da --- /dev/null +++ b/src/modules/notifications/application/slack-app.service.ts @@ -0,0 +1,508 @@ +import crypto from 'node:crypto'; +import { signToken, verifySignedToken } from '#lib/server/infra/tokens'; +import { + DEFAULT_CHANNEL_LOCALE, + isChannelLocale, + type ChannelLocale, +} from '#lib/server/infra/notifications/chat-types'; +import { translator, type Translate } from '#lib/server/infra/notifications/i18n'; +import { MAX_CHANNEL_NAME_LENGTH } from '../domain/notification-channel.domain'; +import { + SLACK_IDENTITY_PROVIDER, + slackIdentity, + toSlackWorkspaceView, + type SlackWorkspace, + type SlackWorkspaceView, +} from '../domain/slack-workspace.domain'; +import type { SlackAppConfig } from '../infrastructure/config/slack-app.config'; +import type { ChannelCipher } from '../infrastructure/crypto/channel-cipher'; +import type { SlackWorkspaceRepositoryPort } from '../infrastructure/repositories/slack-workspace.repository'; +import type { SlackApiResult } from '../infrastructure/slack/slack-api.client'; +import { verifySlackSignature } from '../infrastructure/slack/slack-signature'; +import type { SlackInstall } from './slack-connect.service'; + +/** Page that links a Slack user to the GitOps account signed in (needs a session). */ +export const SLACK_LINK_PATH = '/notifications/slack/link'; +/** Starts the channel picker of a channel named in Slack (no session needed). */ +export const SLACK_CONNECT_PATH = '/notifications/slack/connect'; +/** Links from Slack replies live this long. */ +export const SLACK_LINK_TTL_MS = 10 * 60 * 1000; + +const LINK_PURPOSE = 'slack-link'; +const CHANNEL_PURPOSE = 'slack-channel'; +const CHANNEL_VIEW = 'gitops_channel'; +const BOT_TOKEN_PURPOSE = 'slack-bot-token'; + +/** JSON body answered to Slack (an ephemeral message or a `response_action`). */ +export type SlackReply = Record; + +type SlackUser = { id: string; username: string; disabled: boolean }; + +export type SlackLinkRequest = { + teamId: string; + slackUserId: string; + slackUserName: string | null; +}; + +/** What `/notifications/slack/connect` needs to start the channel picker. */ +export type SlackChannelRequest = { + userId: string; + organizationId: string; + teamId: string; + slackUserId: string; + name: string; + locale: ChannelLocale; +}; + +export type SlackLinkResult = 'linked' | 'taken' | 'invalid' | 'not_installed' | 'forbidden'; + +type Dependencies = { + readConfig: () => SlackAppConfig | null; + workspaces: SlackWorkspaceRepositoryPort; + cipher: ChannelCipher; + api: { openView(token: string, triggerId: string, view: unknown): Promise }; + identities: { + find(provider: string, providerId: string): Promise; + link( + userId: string, + provider: string, + providerId: string, + ): Promise<'linked' | 'taken' | 'not_found'>; + }; + access: { + /** `organization:notifications:create` in the organization. */ + canCreateChannels(userId: string, organizationId: string): Promise; + /** Whether the user can see the organization at all (member of it or of one of its projects). */ + canViewOrganization(userId: string, organizationId: string): Promise; + organizationName(organizationId: string): Promise; + }; + channels: { listSlack(organizationId: string): Promise<{ name: string; enabled: boolean }[]> }; + secret: () => string; + now?: () => number; +}; + +/** + * The GitOps Slack app: workspaces installed per organization, and the `/gitops` command that + * links Slack users to their GitOps accounts and connects channels. A channel connected from Slack + * still goes through Slack's own channel picker (the only way to get its webhook): the form here + * only names it, then hands a short-lived link to `/notifications/slack/connect`. + */ +export class SlackAppService { + private readonly now: () => number; + + constructor(private readonly deps: Dependencies) { + this.now = deps.now ?? (() => Date.now()); + } + + /** Checks `X-Slack-Signature` with the app's signing secret; `false` while it is not set. */ + verifyRequest(input: { timestamp: string | null; signature: string | null; body: string }) { + let config: SlackAppConfig | null; + try { + config = this.deps.readConfig(); + } catch { + config = null; + } + if (!config?.signingSecret) return false; + return verifySlackSignature({ ...input, signingSecret: config.signingSecret, now: this.now() }); + } + + // --- workspaces ------------------------------------------------------------------------- + + /** + * Saves the workspace of an install for its organization (the caller checked the permission). + * A workspace belongs to one organization: installing it from another one is refused. + */ + async installWorkspace(install: SlackInstall): Promise<'installed' | 'taken'> { + const existing = await this.deps.workspaces.findByTeamId(install.teamId); + if (existing && existing.organizationId !== install.organizationId) return 'taken'; + if (existing) { + await this.deps.workspaces.update(existing.id, { + teamName: install.teamName, + botToken: this.deps.cipher.encrypt(existing.id, install.botToken, BOT_TOKEN_PURPOSE), + locale: install.locale, + installedByUserId: install.userId, + }); + return 'installed'; + } + const id = crypto.randomUUID(); + const timestamp = new Date(this.now()).toISOString(); + await this.deps.workspaces.insert({ + id, + teamId: install.teamId, + teamName: install.teamName, + organizationId: install.organizationId, + botToken: this.deps.cipher.encrypt(id, install.botToken, BOT_TOKEN_PURPOSE), + locale: install.locale, + installedByUserId: install.userId, + createdAt: timestamp, + updatedAt: timestamp, + }); + return 'installed'; + } + + async workspacesOf(organizationId: string): Promise { + return (await this.deps.workspaces.listByOrganization(organizationId)).map( + toSlackWorkspaceView, + ); + } + + /** + * Forgets a workspace of the organization: `/gitops` stops working there until it is installed + * again. Its channels keep their webhooks (remove the app in Slack to revoke them). + */ + async removeWorkspace(organizationId: string, workspaceId: string): Promise { + const workspace = (await this.deps.workspaces.listByOrganization(organizationId)).find( + (item) => item.id === workspaceId, + ); + if (!workspace) return false; + await this.deps.workspaces.delete(workspace.id); + return true; + } + + // --- /gitops ---------------------------------------------------------------------------- + + /** Answers a slash command (already verified). `null` = an empty 200 (a form was opened). */ + async handleCommand(params: URLSearchParams, origin: string): Promise { + const teamId = params.get('team_id') ?? ''; + const slackUserId = params.get('user_id') ?? ''; + const [action = ''] = (params.get('text') ?? '').trim().toLowerCase().split(/\s+/); + + const workspace = teamId ? await this.deps.workspaces.findByTeamId(teamId) : null; + const t = translator(workspace?.locale ?? DEFAULT_CHANNEL_LOCALE); + if (!workspace) return ephemeral(t('notifications.slackApp.notInstalled')); + + switch (action) { + case 'login': + case 'link': + return this.login(workspace, slackUserId, params.get('user_name'), origin, t); + case 'channel': + case 'canal': + return this.openChannelForm(workspace, slackUserId, params.get('trigger_id'), t); + case 'status': + case 'estado': + return this.status(workspace, slackUserId, t); + default: + return ephemeral(t('notifications.slackApp.help')); + } + } + + /** Answers a form submission or a button click (already verified). */ + async handleInteraction(payload: unknown, origin: string): Promise { + const data = payload as { + type?: string; + team?: { id?: string }; + user?: { id?: string }; + view?: { callback_id?: string; state?: { values?: Record } }; + }; + // link buttons also report their click: nothing to do but acknowledge it + if (data?.type !== 'view_submission' || data.view?.callback_id !== CHANNEL_VIEW) return null; + + const teamId = data.team?.id ?? ''; + const slackUserId = data.user?.id ?? ''; + const values = data.view.state?.values ?? {}; + const workspace = teamId ? await this.deps.workspaces.findByTeamId(teamId) : null; + const t = translator(workspace?.locale ?? DEFAULT_CHANNEL_LOCALE); + if (!workspace) return fieldError('name', t('notifications.slackApp.notInstalled')); + + const name = String(values.name?.value?.value ?? '').trim(); + const selected = values.locale?.value?.selected_option?.value; + const locale: ChannelLocale = isChannelLocale(selected) ? selected : workspace.locale; + if (!name) return fieldError('name', t('notifications.slackApp.channel.nameRequired')); + if (name.length > MAX_CHANNEL_NAME_LENGTH) { + return fieldError('name', t('notifications.slackApp.channel.nameTooLong')); + } + + // checked again: the account could have changed since the form was opened + const user = await this.linkedUser(teamId, slackUserId); + if (!user || user.disabled) return fieldError('name', t('notifications.slackApp.notLinked')); + if (!(await this.deps.access.canCreateChannels(user.id, workspace.organizationId))) { + return fieldError('name', t('notifications.slackApp.forbidden')); + } + + const token = signToken( + CHANNEL_PURPOSE, + { + userId: user.id, + organizationId: workspace.organizationId, + teamId, + slackUserId, + name, + locale, + }, + { secret: this.deps.secret(), ttlMs: SLACK_LINK_TTL_MS, now: this.now() }, + ); + const url = `${origin}${SLACK_CONNECT_PATH}?${new URLSearchParams({ token })}`; + return { response_action: 'update', view: pickChannelView(t, name, url) }; + } + + /** The channel request behind a `/notifications/slack/connect` link, or `null`. */ + readChannelRequest(token: string | null): SlackChannelRequest | null { + if (!token) return null; + const data = verifySignedToken(CHANNEL_PURPOSE, token, { + secret: this.deps.secret(), + now: this.now(), + }); + if ( + !data || + typeof data.userId !== 'string' || + typeof data.organizationId !== 'string' || + typeof data.teamId !== 'string' || + typeof data.slackUserId !== 'string' || + typeof data.name !== 'string' || + !data.name.trim() + ) { + return null; + } + return { + userId: data.userId, + organizationId: data.organizationId, + teamId: data.teamId, + slackUserId: data.slackUserId, + name: data.name.trim().slice(0, MAX_CHANNEL_NAME_LENGTH), + locale: isChannelLocale(data.locale) ? data.locale : DEFAULT_CHANNEL_LOCALE, + }; + } + + // --- linking accounts ------------------------------------------------------------------- + + /** The Slack user behind a `/notifications/slack/link` token, with its workspace, or `null`. */ + async readLinkRequest( + token: string | null, + ): Promise<(SlackLinkRequest & { workspace: SlackWorkspaceView }) | null> { + if (!token) return null; + const data = verifySignedToken(LINK_PURPOSE, token, { + secret: this.deps.secret(), + now: this.now(), + }); + if (!data || typeof data.teamId !== 'string' || typeof data.slackUserId !== 'string') { + return null; + } + const workspace = await this.deps.workspaces.findByTeamId(data.teamId); + if (!workspace) return null; + return { + teamId: data.teamId, + slackUserId: data.slackUserId, + slackUserName: typeof data.slackUserName === 'string' ? data.slackUserName : null, + workspace: toSlackWorkspaceView(workspace), + }; + } + + /** + * Links the Slack user of `token` to the signed-in `userId`. The user must belong to the + * workspace's organization: a link never gives access to another organization. + */ + async confirmLink(token: string | null, userId: string): Promise { + const request = await this.readLinkRequest(token); + if (!request) return 'invalid'; + if (!(await this.deps.access.canViewOrganization(userId, request.workspace.organizationId))) { + return 'forbidden'; + } + const result = await this.deps.identities.link( + userId, + SLACK_IDENTITY_PROVIDER, + slackIdentity(request.teamId, request.slackUserId), + ); + return result === 'not_found' ? 'invalid' : result; + } + + // --- commands --------------------------------------------------------------------------- + + private linkedUser(teamId: string, slackUserId: string) { + return this.deps.identities.find(SLACK_IDENTITY_PROVIDER, slackIdentity(teamId, slackUserId)); + } + + private login( + workspace: SlackWorkspace, + slackUserId: string, + slackUserName: string | null, + origin: string, + t: Translate, + ): SlackReply { + const token = signToken( + LINK_PURPOSE, + { teamId: workspace.teamId, slackUserId, slackUserName }, + { secret: this.deps.secret(), ttlMs: SLACK_LINK_TTL_MS, now: this.now() }, + ); + const url = `${origin}${SLACK_LINK_PATH}?${new URLSearchParams({ token })}`; + return { + response_type: 'ephemeral', + text: t('notifications.slackApp.login.prompt'), + blocks: [ + section(t('notifications.slackApp.login.prompt')), + { + type: 'actions', + elements: [ + { + type: 'button', + action_id: 'login', + style: 'primary', + text: plain(t('notifications.slackApp.login.button')), + url, + }, + ], + }, + context(t('notifications.slackApp.linkExpires')), + ], + }; + } + + private async openChannelForm( + workspace: SlackWorkspace, + slackUserId: string, + triggerId: string | null, + t: Translate, + ): Promise { + const user = await this.linkedUser(workspace.teamId, slackUserId); + if (!user) return ephemeral(t('notifications.slackApp.notLinked')); + if (user.disabled) return ephemeral(t('notifications.slackApp.disabled')); + if (!(await this.deps.access.canCreateChannels(user.id, workspace.organizationId))) { + return ephemeral(t('notifications.slackApp.forbidden')); + } + if (!triggerId) return ephemeral(t('notifications.slackApp.failed', { code: 'no_trigger' })); + + const organization = + (await this.deps.access.organizationName(workspace.organizationId)) ?? workspace.teamName; + let botToken: string; + try { + botToken = this.deps.cipher.decrypt(workspace.id, workspace.botToken, BOT_TOKEN_PURPOSE); + } catch { + return ephemeral(t('notifications.slackApp.failed', { code: 'token' })); + } + const opened = await this.deps.api.openView( + botToken, + triggerId, + channelFormView(t, organization, workspace.locale), + ); + return opened.ok ? null : ephemeral(t('notifications.slackApp.failed', { code: opened.error })); + } + + private async status( + workspace: SlackWorkspace, + slackUserId: string, + t: Translate, + ): Promise { + const [user, organization, channels] = await Promise.all([ + this.linkedUser(workspace.teamId, slackUserId), + this.deps.access.organizationName(workspace.organizationId), + this.deps.channels.listSlack(workspace.organizationId), + ]); + const lines = [ + t('notifications.slackApp.status.organization', { + organization: escapeSlack(organization ?? workspace.organizationId), + }), + user + ? t('notifications.slackApp.status.linked', { username: escapeSlack(user.username) }) + : t('notifications.slackApp.status.notLinked'), + channels.length + ? t('notifications.slackApp.status.channels', { + channels: channels + .map((channel) => + channel.enabled + ? escapeSlack(channel.name) + : `${escapeSlack(channel.name)} (${t('notifications.slackApp.status.disabled')})`, + ) + .join(', '), + }) + : t('notifications.slackApp.status.noChannels'), + ]; + return ephemeral(lines.join('\n')); + } +} + +// --- Block Kit ------------------------------------------------------------------------------ + +function plain(text: string) { + return { type: 'plain_text', text, emoji: true }; +} + +function section(text: string) { + return { type: 'section', text: { type: 'mrkdwn', text } }; +} + +function context(text: string) { + return { type: 'context', elements: [{ type: 'mrkdwn', text }] }; +} + +function ephemeral(text: string): SlackReply { + return { response_type: 'ephemeral', text }; +} + +function fieldError(block: string, message: string): SlackReply { + return { response_action: 'errors', errors: { [block]: message } }; +} + +/** `&`, `<` and `>` are Slack's control characters: names never mention or link anyone. */ +export function escapeSlack(value: string): string { + return value.replace(/&/g, '&').replace(//g, '>'); +} + +/** Slack caps modal titles at 24 characters. */ +function title(text: string) { + return plain(text.length > 24 ? `${text.slice(0, 23)}…` : text); +} + +function channelFormView(t: Translate, organization: string, locale: ChannelLocale) { + const option = (value: ChannelLocale) => ({ + text: plain(t(`notifications.slackApp.locale.${value}`)), + value, + }); + return { + type: 'modal', + callback_id: CHANNEL_VIEW, + title: title(t('notifications.slackApp.channel.title')), + submit: plain(t('notifications.slackApp.channel.next')), + close: plain(t('notifications.slackApp.channel.cancel')), + blocks: [ + section( + t('notifications.slackApp.channel.intro', { organization: escapeSlack(organization) }), + ), + { + type: 'input', + block_id: 'name', + label: plain(t('notifications.slackApp.channel.name')), + hint: plain(t('notifications.slackApp.channel.nameHint')), + element: { + type: 'plain_text_input', + action_id: 'value', + max_length: MAX_CHANNEL_NAME_LENGTH, + placeholder: plain(t('notifications.slackApp.channel.namePlaceholder')), + }, + }, + { + type: 'input', + block_id: 'locale', + label: plain(t('notifications.slackApp.channel.locale')), + element: { + type: 'static_select', + action_id: 'value', + initial_option: option(locale), + options: [option('es'), option('en')], + }, + }, + ], + }; +} + +function pickChannelView(t: Translate, name: string, url: string) { + return { + type: 'modal', + title: title(t('notifications.slackApp.channel.title')), + close: plain(t('notifications.slackApp.channel.close')), + blocks: [ + section(t('notifications.slackApp.channel.pick', { name: escapeSlack(name) })), + { + type: 'actions', + elements: [ + { + type: 'button', + action_id: 'pick_channel', + style: 'primary', + text: plain(t('notifications.slackApp.channel.pickButton')), + url, + }, + ], + }, + context(t('notifications.slackApp.linkExpires')), + ], + }; +} diff --git a/src/modules/notifications/application/slack-connect.service.test.ts b/src/modules/notifications/application/slack-connect.service.test.ts index ab21d6e7..cbb37af0 100644 --- a/src/modules/notifications/application/slack-connect.service.test.ts +++ b/src/modules/notifications/application/slack-connect.service.test.ts @@ -2,34 +2,50 @@ import { describe, expect, it, vi } from 'vitest'; import { SlackOAuthClient, SlackOAuthError, - type SlackIncomingWebhook, + type SlackInstallation, } from '../infrastructure/slack/slack-oauth.client'; -import { SlackAppConfigError } from '../infrastructure/config/slack-app.config'; -import { SlackConnectError, SlackConnectService, safeReturnTo } from './slack-connect.service'; +import { + SlackAppConfigError, + type SlackAppConfig, +} from '../infrastructure/config/slack-app.config'; +import { + SLACK_DONE_PATH, + SlackConnectError, + SlackConnectService, + safeReturnTo, + type SlackFlowResult, +} from './slack-connect.service'; const NOW = Date.UTC(2026, 10, 26); const SECRET = 'test-encryption-key'; const REDIRECT = 'https://gitops.example.com/notifications/slack/callback'; const LOCATION = { scope: 'project' as const, organizationId: 'org-1', projectId: 'prj-1' }; -const WEBHOOK: SlackIncomingWebhook = { - url: 'https://hooks.slack.com/services/T1/B1/xyz', - channel: '#alerts', +const INSTALLATION: SlackInstallation = { + teamId: 'T1', teamName: 'Acme', + authedUserId: 'U1', + botToken: 'xoxb-secret', + webhook: { + url: 'https://hooks.slack.com/services/T1/B1/xyz', + channel: '#alerts', + channelId: 'C1', + }, }; +const CONFIG: SlackAppConfig = { clientId: '123.456', clientSecret: 'shh', signingSecret: null }; function setup( options: { - config?: () => { clientId: string; clientSecret: string } | null; - exchange?: () => Promise; + config?: () => SlackAppConfig | null; + exchange?: () => Promise; } = {}, ) { let now = NOW; const client = new SlackOAuthClient(); const exchangeCode = vi .spyOn(client, 'exchangeCode') - .mockImplementation(options.exchange ?? (async () => WEBHOOK)); + .mockImplementation(options.exchange ?? (async () => INSTALLATION)); const service = new SlackConnectService({ - readConfig: options.config ?? (() => ({ clientId: '123.456', clientSecret: 'shh' })), + readConfig: options.config ?? (() => CONFIG), client, secret: () => SECRET, now: () => now, @@ -46,7 +62,7 @@ function setup( const complete = ( flowCookie: string | undefined, overrides: Partial<{ - userId: string; + sessionUserId: string | null; state: string | null; code: string | null; error: string | null; @@ -54,7 +70,7 @@ function setup( ) => service.complete({ flowCookie, - userId: 'user-1', + sessionUserId: 'user-1', state: 'state-1', code: 'code-1', error: null, @@ -64,19 +80,32 @@ function setup( return { service, exchangeCode, started, complete, advance: (ms: number) => (now += ms) }; } +function as(result: SlackFlowResult, kind: K) { + expect(result.kind).toBe(kind); + return result as Extract; +} + describe('SlackConnectService', () => { - it('reports whether the Slack app is configured', () => { - expect(setup().service.status()).toEqual({ configured: true }); + it('reports whether the Slack app and its command are configured', () => { + expect(setup().service.status()).toEqual({ configured: true, commands: false }); + const withCommands = setup({ config: () => ({ ...CONFIG, signingSecret: 'sign' }) }); + expect(withCommands.service.status()).toEqual({ configured: true, commands: true }); + expect(withCommands.service.commandsEnabled()).toBe(true); expect(setup({ config: () => null }).service.status()).toEqual({ configured: false, reason: 'missing', + commands: false, }); const invalid = setup({ config: () => { throw new SlackAppConfigError('half set'); }, }); - expect(invalid.service.status()).toEqual({ configured: false, reason: 'invalid' }); + expect(invalid.service.status()).toEqual({ + configured: false, + reason: 'invalid', + commands: false, + }); expect(invalid.service.isConfigured()).toBe(false); }); @@ -87,6 +116,7 @@ describe('SlackConnectService', () => { expect(url.searchParams.get('state')).toBe('state-1'); expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT); expect(url.searchParams.get('client_id')).toBe('123.456'); + expect(url.searchParams.get('scope')).toBe('incoming-webhook'); // nothing secret in the cookie: it only carries the flow expect(flowCookie).not.toContain('shh'); }); @@ -101,11 +131,13 @@ describe('SlackConnectService', () => { const connection = await complete(started().flowCookie); expect(connection).toEqual({ + kind: 'channel', + userId: 'user-1', location: LOCATION, locale: 'es', returnTo: '/org/acme/projects/web/settings/alerts/settings', name: '#alerts (Acme)', - webhookUrl: WEBHOOK.url, + webhookUrl: INSTALLATION.webhook?.url, }); expect(exchangeCode).toHaveBeenCalledWith({ clientId: '123.456', @@ -124,7 +156,7 @@ describe('SlackConnectService', () => { returnTo: 'https://evil.example.com', redirectUri: REDIRECT, }); - const connection = await complete(flowCookie); + const connection = as(await complete(flowCookie), 'channel'); expect(connection.location).toEqual({ scope: 'organization', organizationId: 'org-1', @@ -136,7 +168,8 @@ describe('SlackConnectService', () => { it.each([ ['no cookie', undefined, {}], - ['another user', 'cookie', { userId: 'user-2' }], + ['another user', 'cookie', { sessionUserId: 'user-2' }], + ['no session', 'cookie', { sessionUserId: null }], ['a different state', 'cookie', { state: 'state-2' }], ['no state', 'cookie', { state: null }], ])('rejects %s as an invalid state', async (_label, cookie, overrides) => { @@ -168,7 +201,7 @@ describe('SlackConnectService', () => { expect(exchangeCode).not.toHaveBeenCalled(); }); - it('maps exchange failures', async () => { + it('maps exchange failures and installs without a webhook', async () => { const failing = setup({ exchange: async () => { throw new SlackOAuthError('invalid_code'); @@ -178,11 +211,7 @@ describe('SlackConnectService', () => { code: 'slack_exchange_failed', }); - const noWebhook = setup({ - exchange: async () => { - throw new SlackOAuthError('no_webhook'); - }, - }); + const noWebhook = setup({ exchange: async () => ({ ...INSTALLATION, webhook: null }) }); await expect(noWebhook.complete(noWebhook.started().flowCookie)).rejects.toMatchObject({ code: 'slack_no_webhook', }); @@ -190,19 +219,127 @@ describe('SlackConnectService', () => { it('cuts long channel names', async () => { const { started, complete } = setup({ - exchange: async () => ({ ...WEBHOOK, channel: `#${'a'.repeat(90)}`, teamName: null }), + exchange: async () => ({ + ...INSTALLATION, + teamName: null, + webhook: { + url: 'https://hooks.slack.com/x', + channel: `#${'a'.repeat(90)}`, + channelId: null, + }, + }), }); - const { name } = await complete(started().flowCookie); + const { name } = as(await complete(started().flowCookie), 'channel'); expect(name).toHaveLength(80); expect(name.endsWith('…')).toBe(true); }); + describe('app install', () => { + const startInstall = (service: SlackConnectService) => + service.startInstall({ + userId: 'user-1', + organizationId: 'org-1', + locale: 'es', + returnTo: '/org/acme/settings/alerts/settings', + redirectUri: REDIRECT, + }); + + it('asks for the commands scope only (no channel picker)', () => { + const { service } = setup(); + const url = new URL(startInstall(service).authorizationUrl); + expect(url.searchParams.get('scope')).toBe('commands'); + }); + + it('completes into the workspace and its bot token, in the same session', async () => { + const { service, complete } = setup({ + exchange: async () => ({ ...INSTALLATION, webhook: null }), + }); + const { flowCookie } = startInstall(service); + expect(as(await complete(flowCookie), 'install')).toEqual({ + kind: 'install', + userId: 'user-1', + organizationId: 'org-1', + locale: 'es', + returnTo: '/org/acme/settings/alerts/settings', + teamId: 'T1', + teamName: 'Acme', + botToken: 'xoxb-secret', + }); + await expect(complete(flowCookie, { sessionUserId: null })).rejects.toMatchObject({ + code: 'slack_invalid_state', + }); + }); + + it('fails when Slack returns no bot token', async () => { + const { service, complete } = setup({ + exchange: async () => ({ ...INSTALLATION, botToken: null }), + }); + await expect(complete(startInstall(service).flowCookie)).rejects.toMatchObject({ + code: 'slack_exchange_failed', + }); + }); + }); + + describe('channels connected from Slack', () => { + const startFromSlack = (service: SlackConnectService) => + service.startFromSlack({ + userId: 'user-1', + organizationId: 'org-1', + name: 'DevOps ES', + locale: 'es', + slackTeamId: 'T1', + slackUserId: 'U1', + redirectUri: REDIRECT, + }); + + it('needs no GitOps session and keeps the name typed in Slack', async () => { + const { service, complete } = setup(); + const result = as( + await complete(startFromSlack(service).flowCookie, { sessionUserId: null }), + 'command', + ); + expect(result).toEqual({ + kind: 'command', + userId: 'user-1', + location: { scope: 'organization', organizationId: 'org-1', projectId: null }, + locale: 'es', + returnTo: SLACK_DONE_PATH, + name: 'DevOps ES', + webhookUrl: INSTALLATION.webhook?.url, + teamId: 'T1', + channelId: 'C1', + }); + }); + + it.each([ + ['another workspace', { teamId: 'T2' }], + ['another Slack user', { authedUserId: 'U2' }], + ])('refuses a flow finished in %s', async (_label, overrides) => { + const { service, complete } = setup({ + exchange: async () => ({ ...INSTALLATION, ...overrides }), + }); + await expect( + complete(startFromSlack(service).flowCookie, { sessionUserId: null }), + ).rejects.toMatchObject({ code: 'slack_wrong_workspace', returnTo: SLACK_DONE_PATH }); + }); + }); + it('builds a manifest and creation link for the installation', () => { const { service } = setup(); const manifest = service.manifest('https://gitops.example.com/'); expect(manifest.oauth_config).toEqual({ redirect_urls: [REDIRECT], - scopes: { bot: ['incoming-webhook'] }, + scopes: { bot: ['incoming-webhook', 'commands'] }, + }); + expect(manifest.features.slash_commands).toEqual([ + expect.objectContaining({ + command: '/gitops', + url: 'https://gitops.example.com/api/slack/commands', + }), + ]); + expect(manifest.settings.interactivity).toEqual({ + is_enabled: true, + request_url: 'https://gitops.example.com/api/slack/interactions', }); expect(manifest.display_information.name.length).toBeLessThanOrEqual(35); diff --git a/src/modules/notifications/application/slack-connect.service.ts b/src/modules/notifications/application/slack-connect.service.ts index 142fd3e3..738197a3 100644 --- a/src/modules/notifications/application/slack-connect.service.ts +++ b/src/modules/notifications/application/slack-connect.service.ts @@ -11,17 +11,24 @@ import { } from '../domain/notification-channel.domain'; import type { SlackAppConfig } from '../infrastructure/config/slack-app.config'; import { + SLACK_APP_SCOPES, SLACK_CONNECT_SCOPE, + SLACK_INSTALL_SCOPE, SlackOAuthError, type SlackOAuthClient, } from '../infrastructure/slack/slack-oauth.client'; /** Fixed path of the OAuth callback: it is the redirect URL registered in the Slack app. */ export const SLACK_CALLBACK_PATH = '/notifications/slack/callback'; -/** Path of the flow cookie: only the callback needs it. */ +/** Path of the flow cookie: only the callback (and the start from Slack) need it. */ export const SLACK_FLOW_COOKIE_PATH = '/notifications/slack'; export const SLACK_FLOW_COOKIE = 'gitops_slack_flow'; export const SLACK_FLOW_TTL_MS = 10 * 60 * 1000; +/** Request URLs of the `/gitops` command and its forms (manifest). */ +export const SLACK_COMMANDS_PATH = '/api/slack/commands'; +export const SLACK_INTERACTIONS_PATH = '/api/slack/interactions'; +/** Page a channel connected from Slack ends on: "go back to Slack". */ +export const SLACK_DONE_PATH = '/notifications/slack/done'; const FLOW_PURPOSE = 'slack-connect'; const DEFAULT_RETURN = '/org'; @@ -36,7 +43,9 @@ export type SlackConnectErrorCode = /** Slack refused the code or could not be reached. */ | 'slack_exchange_failed' /** The install did not return a webhook (the app lacks the `incoming-webhook` scope). */ - | 'slack_no_webhook'; + | 'slack_no_webhook' + /** A flow started from Slack was finished in another workspace or by another Slack user. */ + | 'slack_wrong_workspace'; export class SlackConnectError extends Error { constructor( @@ -50,16 +59,31 @@ export class SlackConnectError extends Error { } } +/** + * - `channel`: "Add to Slack" from a channels page (needs the same GitOps session at the end). + * - `install`: installs the app in a workspace for the `/gitops` command (same session). + * - `command`: a channel connected from `/gitops channel` in Slack; no GitOps session, the flow + * is bound to the linked GitOps user and to the Slack workspace and user who started it. + */ +export type SlackFlowKind = 'channel' | 'install' | 'command'; + type SlackFlow = { + kind: SlackFlowKind; state: string; userId: string; organizationId: string; projectId: string | null; locale: ChannelLocale; returnTo: string; + name: string | null; + slackTeamId: string | null; + slackUserId: string | null; }; +/** A channel from "Add to Slack" on a channels page. */ export type SlackConnection = { + kind: 'channel'; + userId: string; location: ChannelLocation; locale: ChannelLocale; returnTo: string; @@ -69,14 +93,53 @@ export type SlackConnection = { webhookUrl: string; }; +/** The app installed in a workspace, from an organization's channels page. */ +export type SlackInstall = { + kind: 'install'; + userId: string; + organizationId: string; + locale: ChannelLocale; + returnTo: string; + teamId: string; + teamName: string; + /** Secret: encrypted when the workspace is saved. */ + botToken: string; +}; + +/** A channel connected from Slack (`/gitops channel`), named by the user in Slack. */ +export type SlackCommandConnection = { + kind: 'command'; + userId: string; + location: ChannelLocation; + locale: ChannelLocale; + returnTo: string; + name: string; + webhookUrl: string; + teamId: string; + channelId: string | null; +}; + +export type SlackFlowResult = SlackConnection | SlackInstall | SlackCommandConnection; + export type SlackConnectStatus = - { configured: true } | { configured: false; reason: 'missing' | 'invalid' }; + | { configured: true; commands: boolean } + | { configured: false; reason: 'missing' | 'invalid'; commands: false }; export type SlackAppManifest = { display_information: { name: string; description: string; background_color: string }; - features: { bot_user: { display_name: string; always_online: boolean } }; + features: { + bot_user: { display_name: string; always_online: boolean }; + slash_commands: { + command: string; + url: string; + description: string; + usage_hint: string; + should_escape: boolean; + }[]; + }; oauth_config: { redirect_urls: string[]; scopes: { bot: string[] } }; settings: { + interactivity: { is_enabled: boolean; request_url: string }; org_deploy_enabled: boolean; socket_mode_enabled: boolean; token_rotation_enabled: boolean; @@ -93,10 +156,10 @@ type Dependencies = { }; /** - * "Add to Slack": runs the OAuth v2 install with the `incoming-webhook` scope, so Slack asks the - * user for a channel and returns its webhook URL. Nothing is stored here: the flow lives in a - * signed, short-lived cookie bound to the user, and the caller saves the channel (with the usual - * permission check) from the returned connection. + * Slack OAuth v2 for the GitOps app: "Add to Slack" (the `incoming-webhook` scope, so Slack asks + * for a channel and returns its webhook) and the app install for `/gitops` (the `commands` + * scope). Nothing is stored here: the flow lives in a signed, short-lived cookie, and the caller + * saves the channel or the workspace (with the usual permission checks) from the result. */ export class SlackConnectService { private readonly now: () => number; @@ -109,11 +172,12 @@ export class SlackConnectService { status(): SlackConnectStatus { try { - return this.deps.readConfig() - ? { configured: true } - : { configured: false, reason: 'missing' }; + const config = this.deps.readConfig(); + return config + ? { configured: true, commands: !!config.signingSecret } + : { configured: false, reason: 'missing', commands: false }; } catch { - return { configured: false, reason: 'invalid' }; + return { configured: false, reason: 'invalid', commands: false }; } } @@ -121,6 +185,12 @@ export class SlackConnectService { return this.status().configured; } + /** The `/gitops` command works: the app is configured and has its signing secret. */ + commandsEnabled(): boolean { + return this.status().commands; + } + + /** "Add to Slack" from a channels page. */ start(input: { userId: string; location: ChannelLocation; @@ -128,26 +198,67 @@ export class SlackConnectService { returnTo: unknown; redirectUri: string; }): { authorizationUrl: string; flowCookie: string } { - const config = this.requireConfig(); - const flow: SlackFlow = { - state: this.random(), - userId: input.userId, - organizationId: input.location.organizationId, - projectId: input.location.projectId, - locale: isChannelLocale(input.locale) ? input.locale : DEFAULT_CHANNEL_LOCALE, - returnTo: safeReturnTo(input.returnTo), - }; - const flowCookie = signToken(FLOW_PURPOSE, flow, { - secret: this.deps.secret(), - ttlMs: SLACK_FLOW_TTL_MS, - now: this.now(), - }); - const authorizationUrl = this.deps.client.buildAuthorizationUrl({ - clientId: config.clientId, - redirectUri: input.redirectUri, - state: flow.state, - }); - return { authorizationUrl, flowCookie }; + return this.begin( + { + kind: 'channel', + userId: input.userId, + organizationId: input.location.organizationId, + projectId: input.location.projectId, + locale: input.locale, + returnTo: safeReturnTo(input.returnTo), + }, + SLACK_CONNECT_SCOPE, + input.redirectUri, + ); + } + + /** Installs the app in a workspace (picked in Slack) for `organizationId`. */ + startInstall(input: { + userId: string; + organizationId: string; + locale: unknown; + returnTo: unknown; + redirectUri: string; + }): { authorizationUrl: string; flowCookie: string } { + return this.begin( + { + kind: 'install', + userId: input.userId, + organizationId: input.organizationId, + projectId: null, + locale: input.locale, + returnTo: safeReturnTo(input.returnTo), + }, + SLACK_INSTALL_SCOPE, + input.redirectUri, + ); + } + + /** A channel connected from `/gitops channel`: bound to the Slack workspace and user. */ + startFromSlack(input: { + userId: string; + organizationId: string; + name: string; + locale: unknown; + slackTeamId: string; + slackUserId: string; + redirectUri: string; + }): { authorizationUrl: string; flowCookie: string } { + return this.begin( + { + kind: 'command', + userId: input.userId, + organizationId: input.organizationId, + projectId: null, + locale: input.locale, + returnTo: SLACK_DONE_PATH, + name: input.name, + slackTeamId: input.slackTeamId, + slackUserId: input.slackUserId, + }, + SLACK_CONNECT_SCOPE, + input.redirectUri, + ); } /** Where the callback goes back to, even on failure (when the flow cookie is still valid). */ @@ -157,15 +268,18 @@ export class SlackConnectService { async complete(input: { flowCookie: string | undefined; - userId: string; + /** The GitOps session's user; `null` without one (enough for flows started from Slack). */ + sessionUserId: string | null; state: string | null; code: string | null; /** Slack's `error` query parameter (`access_denied` when the user cancels). */ error: string | null; redirectUri: string; - }): Promise { + }): Promise { const flow = this.readFlow(input.flowCookie); - if (!flow || flow.userId !== input.userId) { + // flows started in GitOps finish in the same session; flows from Slack are checked against + // the Slack identity below instead (the browser may have no GitOps session at all) + if (!flow || (flow.kind !== 'command' && flow.userId !== input.sessionUserId)) { throw new SlackConnectError('slack_invalid_state', flow?.returnTo); } if (input.error) throw new SlackConnectError('slack_cancelled', flow.returnTo); @@ -184,53 +298,115 @@ export class SlackConnectService { throw error; } + let installation; try { - const webhook = await this.deps.client.exchangeCode({ + installation = await this.deps.client.exchangeCode({ clientId: config.clientId, clientSecret: config.clientSecret, code: input.code, redirectUri: input.redirectUri, }); - return { - location: { - scope: flow.projectId ? 'project' : 'organization', - organizationId: flow.organizationId, - projectId: flow.projectId, - }, - locale: flow.locale, - returnTo: flow.returnTo, - name: channelName(webhook.channel, webhook.teamName), - webhookUrl: webhook.url, - }; } catch (error) { if (error instanceof SlackOAuthError) { throw new SlackConnectError( - error.code === 'no_webhook' ? 'slack_no_webhook' : 'slack_exchange_failed', + 'slack_exchange_failed', flow.returnTo, `Slack OAuth: ${error.code}`, ); } throw error; } + + const location: ChannelLocation = { + scope: flow.projectId ? 'project' : 'organization', + organizationId: flow.organizationId, + projectId: flow.projectId, + }; + + if (flow.kind === 'install') { + if (!installation.teamId || !installation.botToken) { + throw new SlackConnectError('slack_exchange_failed', flow.returnTo, 'Slack OAuth: no bot'); + } + return { + kind: 'install', + userId: flow.userId, + organizationId: flow.organizationId, + locale: flow.locale, + returnTo: flow.returnTo, + teamId: installation.teamId, + teamName: installation.teamName ?? installation.teamId, + botToken: installation.botToken, + }; + } + + if (flow.kind === 'command') { + // the link from Slack could have been forwarded: only the workspace and the Slack user that + // ran the command may finish it + if ( + installation.teamId !== flow.slackTeamId || + installation.authedUserId !== flow.slackUserId + ) { + throw new SlackConnectError('slack_wrong_workspace', flow.returnTo); + } + } + + if (!installation.webhook) throw new SlackConnectError('slack_no_webhook', flow.returnTo); + + if (flow.kind === 'command') { + return { + kind: 'command', + userId: flow.userId, + location, + locale: flow.locale, + returnTo: flow.returnTo, + name: flow.name ?? channelName(installation.webhook.channel, installation.teamName), + webhookUrl: installation.webhook.url, + teamId: installation.teamId ?? '', + channelId: installation.webhook.channelId, + }; + } + return { + kind: 'channel', + userId: flow.userId, + location, + locale: flow.locale, + returnTo: flow.returnTo, + name: channelName(installation.webhook.channel, installation.teamName), + webhookUrl: installation.webhook.url, + }; } /** - * Manifest of a Slack app for this installation: only `incoming-webhook`, with the callback of - * `origin` as redirect URL. Self-hosted admins create their app from it in one click. + * Manifest of the Slack app for this installation: `incoming-webhook` and `commands`, the + * callback of `origin` as redirect URL, and `/gitops` with its form endpoint. Admins create + * their app from it in one click. */ manifest(origin: string): SlackAppManifest { + const base = origin.replace(/\/+$/, ''); return { display_information: { name: 'GitOps', description: 'GitOps alerts in your Slack channels.', background_color: '#0b0b0f', }, - features: { bot_user: { display_name: 'GitOps', always_online: false } }, + features: { + bot_user: { display_name: 'GitOps', always_online: false }, + slash_commands: [ + { + command: '/gitops', + url: `${base}${SLACK_COMMANDS_PATH}`, + description: 'Connect Slack channels to GitOps alerts', + usage_hint: 'login | channel | status | help', + should_escape: false, + }, + ], + }, oauth_config: { - redirect_urls: [`${origin.replace(/\/+$/, '')}${SLACK_CALLBACK_PATH}`], - scopes: { bot: [SLACK_CONNECT_SCOPE] }, + redirect_urls: [`${base}${SLACK_CALLBACK_PATH}`], + scopes: { bot: [...SLACK_APP_SCOPES] }, }, settings: { + interactivity: { is_enabled: true, request_url: `${base}${SLACK_INTERACTIONS_PATH}` }, org_deploy_enabled: false, socket_mode_enabled: false, token_rotation_enabled: false, @@ -246,6 +422,43 @@ export class SlackConnectService { return url.toString(); } + private begin( + input: Omit & { + locale: unknown; + name?: string; + slackTeamId?: string; + slackUserId?: string; + }, + scope: string, + redirectUri: string, + ): { authorizationUrl: string; flowCookie: string } { + const config = this.requireConfig(); + const flow: SlackFlow = { + kind: input.kind, + state: this.random(), + userId: input.userId, + organizationId: input.organizationId, + projectId: input.projectId, + locale: isChannelLocale(input.locale) ? input.locale : DEFAULT_CHANNEL_LOCALE, + returnTo: input.returnTo, + name: input.name ?? null, + slackTeamId: input.slackTeamId ?? null, + slackUserId: input.slackUserId ?? null, + }; + const flowCookie = signToken(FLOW_PURPOSE, flow, { + secret: this.deps.secret(), + ttlMs: SLACK_FLOW_TTL_MS, + now: this.now(), + }); + const authorizationUrl = this.deps.client.buildAuthorizationUrl({ + clientId: config.clientId, + redirectUri, + state: flow.state, + scope, + }); + return { authorizationUrl, flowCookie }; + } + private requireConfig(): SlackAppConfig { let config: SlackAppConfig | null; try { @@ -272,10 +485,21 @@ export class SlackConnectService { ) { return null; } + // cookies issued before flows had a kind were "Add to Slack" ones + const kind: SlackFlowKind = + flow.kind === 'install' || flow.kind === 'command' ? flow.kind : 'channel'; + if (kind === 'command' && (!flow.slackTeamId || !flow.slackUserId)) return null; return { - ...flow, + kind, + state: flow.state, + userId: flow.userId, + organizationId: flow.organizationId, + projectId: flow.projectId, locale: isChannelLocale(flow.locale) ? flow.locale : DEFAULT_CHANNEL_LOCALE, - returnTo: safeReturnTo(flow.returnTo), + returnTo: kind === 'command' ? SLACK_DONE_PATH : safeReturnTo(flow.returnTo), + name: typeof flow.name === 'string' ? flow.name : null, + slackTeamId: typeof flow.slackTeamId === 'string' ? flow.slackTeamId : null, + slackUserId: typeof flow.slackUserId === 'string' ? flow.slackUserId : null, }; } } diff --git a/src/modules/notifications/domain/slack-workspace.domain.ts b/src/modules/notifications/domain/slack-workspace.domain.ts new file mode 100644 index 00000000..b8af341a --- /dev/null +++ b/src/modules/notifications/domain/slack-workspace.domain.ts @@ -0,0 +1,30 @@ +import type { ChannelLocale } from '#lib/server/infra/notifications/chat-types'; + +/** A Slack workspace with the GitOps app installed, linked to one organization. */ +export type SlackWorkspace = { + id: string; + teamId: string; + teamName: string; + organizationId: string; + /** Encrypted bot token (`ChannelCipher`, purpose `slack-bot-token`, AAD = this id). */ + botToken: string; + locale: ChannelLocale; + installedByUserId: string; + createdAt: string; + updatedAt: string; +}; + +/** What the UI may see of a workspace: never the token. */ +export type SlackWorkspaceView = Omit; + +export function toSlackWorkspaceView(workspace: SlackWorkspace): SlackWorkspaceView { + const { botToken: _token, ...view } = workspace; + return view; +} + +/** Provider of the Slack identities in `user.authProviders` (`providerId` = `:`). */ +export const SLACK_IDENTITY_PROVIDER = 'slack'; + +export function slackIdentity(teamId: string, slackUserId: string): string { + return `${teamId}:${slackUserId}`; +} diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts index 5d90dacb..b35cc70f 100644 --- a/src/modules/notifications/index.ts +++ b/src/modules/notifications/index.ts @@ -14,7 +14,7 @@ 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'; -import { passwordService } from '../auth'; +import { authService, cancanService, passwordService } from '../auth'; import { organizationService } from '../organization'; import { ExternalRecipientService } from './application/external-recipient.service'; import { NotificationSettingsService } from './application/notification-settings.service'; @@ -27,6 +27,9 @@ import { readWebhookChannelConfig } from './infrastructure/config/webhook.config import { readSlackAppConfig } from './infrastructure/config/slack-app.config'; import { SlackOAuthClient } from './infrastructure/slack/slack-oauth.client'; import { SlackConnectService } from './application/slack-connect.service'; +import { SlackAppService } from './application/slack-app.service'; +import { SlackApiClient } from './infrastructure/slack/slack-api.client'; +import { SlackWorkspaceRepository } from './infrastructure/repositories/slack-workspace.repository'; import { NotificationChannelRepository } from './infrastructure/repositories/notification-channel.repository'; import { ExternalRecipientMailNotifier } from './infrastructure/external-recipient-mail.notifier'; import { ExternalRecipientRepository } from './infrastructure/repositories/external-recipient.repository'; @@ -123,6 +126,46 @@ export const slackConnectService = new SlackConnectService({ secret: () => passwordService.ensureEncryptionKey(), }); +/** + * The GitOps Slack app (`/gitops`): workspaces installed per organization, Slack users linked to + * their GitOps accounts, and channels named in Slack and connected through Slack's channel picker. + */ +export const slackAppService = new SlackAppService({ + readConfig: () => readSlackAppConfig(), + workspaces: new SlackWorkspaceRepository(), + cipher: createChannelCipher(() => passwordService.ensureEncryptionKey()), + api: new SlackApiClient(), + identities: { + find: (provider, providerId) => authService.findByExternalIdentity(provider, providerId), + link: (userId, provider, providerId) => + authService.linkExternalIdentity(userId, provider, providerId), + }, + access: { + async canCreateChannels(userId, organizationId) { + const user = await authService.sessionUserById(userId); + return cancanService.canSessionUser(user, 'organization:notifications:create', { + scope: 'organization', + organizationId, + }); + }, + async canViewOrganization(userId, organizationId) { + const user = await authService.sessionUserById(userId); + return cancanService.canViewOrganization(user, organizationId); + }, + organizationName: async (id) => + (await organizationService.getOrganization(id).catch(() => null))?.name ?? null, + }, + channels: { + async listSlack(organizationId) { + const channels = await notificationChannelService.list({ organizationId, projectId: null }); + return channels + .filter((channel) => channel.type === 'slack') + .map((channel) => ({ name: channel.name, enabled: channel.enabled })); + }, + }, + secret: () => passwordService.ensureEncryptionKey(), +}); + export function registerChannelShutdown(): void { const scope = globalThis as GlobalWithChannelQueue; if (scope[CHANNEL_SHUTDOWN_KEY]) return; @@ -164,16 +207,33 @@ export type { ChannelMessageSource, IssuedChannel, } from './application/notification-channel.service'; +export { + SLACK_CONNECT_PATH, + SLACK_LINK_PATH, + SLACK_LINK_TTL_MS, + SlackAppService, + escapeSlack, + type SlackChannelRequest, + type SlackLinkResult, + type SlackReply, +} from './application/slack-app.service'; +export { SLACK_IDENTITY_PROVIDER, type SlackWorkspaceView } from './domain/slack-workspace.domain'; export { SLACK_CALLBACK_PATH, + SLACK_COMMANDS_PATH, + SLACK_DONE_PATH, + SLACK_INTERACTIONS_PATH, SLACK_FLOW_COOKIE, SLACK_FLOW_COOKIE_PATH, SLACK_FLOW_TTL_MS, SlackConnectError, SlackConnectService, type SlackConnectErrorCode, + type SlackCommandConnection, type SlackConnectStatus, type SlackConnection, + type SlackFlowResult, + type SlackInstall, } from './application/slack-connect.service'; export { buildChannelTestMessage } from './infrastructure/channel-test-message'; export { normalizeEmail } from './domain/email-address'; diff --git a/src/modules/notifications/infrastructure/config/slack-app.config.ts b/src/modules/notifications/infrastructure/config/slack-app.config.ts index eafdc68d..21c14af6 100644 --- a/src/modules/notifications/infrastructure/config/slack-app.config.ts +++ b/src/modules/notifications/infrastructure/config/slack-app.config.ts @@ -1,7 +1,14 @@ import * as env from '$app/env/private'; -/** Credentials of the Slack app behind "Add to Slack" (`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`). */ -export type SlackAppConfig = { clientId: string; clientSecret: string }; +/** + * Credentials of the GitOps Slack app: `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` for "Add to + * Slack", and `SLACK_SIGNING_SECRET` for the `/gitops` command (`null` while it is not set). + */ +export type SlackAppConfig = { + clientId: string; + clientSecret: string; + signingSecret: string | null; +}; export class SlackAppConfigError extends Error {} @@ -26,5 +33,5 @@ export function readSlackAppConfig(): SlackAppConfig | null { if (!clientId || !clientSecret) { throw new SlackAppConfigError('SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set together'); } - return { clientId, clientSecret }; + return { clientId, clientSecret, signingSecret: value(env.SLACK_SIGNING_SECRET) }; } diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts index 769fb776..26efd6d2 100644 --- a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts +++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts @@ -7,7 +7,7 @@ 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 type ChannelSecretPurpose = 'destination' | 'signing-secret' | 'slack-bot-token'; export interface ChannelCipher { encrypt(channelId: string, value: string, purpose?: ChannelSecretPurpose): string; diff --git a/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts b/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts new file mode 100644 index 00000000..0a01b5d0 --- /dev/null +++ b/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts @@ -0,0 +1,94 @@ +import { SlackWorkspaceEntity } from '#lib/database/schemas'; +import { Repository } from '#lib/server/infra/repository'; +import { + DEFAULT_CHANNEL_LOCALE, + isChannelLocale, +} from '#lib/server/infra/notifications/chat-types'; +import type { SlackWorkspace } from '../../domain/slack-workspace.domain'; + +export interface SlackWorkspaceRepositoryPort { + findByTeamId(teamId: string): Promise; + listByOrganization(organizationId: string): Promise; + insert(workspace: SlackWorkspace): Promise; + update( + id: string, + changes: Partial< + Pick + >, + ): Promise; + delete(id: string): Promise; +} + +function iso(value: unknown): string { + return value instanceof Date ? value.toISOString() : String(value ?? ''); +} + +function toWorkspace(row: Record): SlackWorkspace { + return { + id: row.id, + teamId: row.teamId, + teamName: row.teamName, + organizationId: row.organizationId, + botToken: row.botToken, + locale: isChannelLocale(row.locale) ? row.locale : DEFAULT_CHANNEL_LOCALE, + installedByUserId: row.installedByUserId, + createdAt: iso(row.createdAt), + updatedAt: iso(row.updatedAt), + }; +} + +export class SlackWorkspaceRepository extends Repository implements SlackWorkspaceRepositoryPort { + async findByTeamId(teamId: string) { + const result = await this.db.select().from(SlackWorkspaceEntity).where({ teamId }).limit(1); + return result.rows[0] ? toWorkspace(result.rows[0]) : null; + } + + async listByOrganization(organizationId: string) { + const result = await this.db.select().from(SlackWorkspaceEntity).where({ organizationId }); + return result.rows.map(toWorkspace); + } + + async insert(workspace: SlackWorkspace) { + await this.db.insert(SlackWorkspaceEntity).values({ ...workspace }); + } + + async update(id: string, changes: Parameters[1]) { + await this.db + .update(SlackWorkspaceEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async delete(id: string) { + await this.db.delete(SlackWorkspaceEntity).where({ id }); + } +} + +/** In-memory fake for unit tests. */ +export class InMemorySlackWorkspaceRepository implements SlackWorkspaceRepositoryPort { + rows = new Map(); + + async findByTeamId(teamId: string) { + const row = [...this.rows.values()].find((item) => item.teamId === teamId); + return row ? structuredClone(row) : null; + } + + async listByOrganization(organizationId: string) { + return [...this.rows.values()] + .filter((item) => item.organizationId === organizationId) + .map((item) => structuredClone(item)); + } + + async insert(workspace: SlackWorkspace) { + this.rows.set(workspace.id, structuredClone(workspace)); + } + + async update(id: string, changes: Parameters[1]) { + const row = this.rows.get(id); + if (row) this.rows.set(id, { ...row, ...changes, updatedAt: new Date().toISOString() }); + } + + async delete(id: string) { + this.rows.delete(id); + } +} diff --git a/src/modules/notifications/infrastructure/slack/slack-api.client.ts b/src/modules/notifications/infrastructure/slack/slack-api.client.ts new file mode 100644 index 00000000..2999e5b3 --- /dev/null +++ b/src/modules/notifications/infrastructure/slack/slack-api.client.ts @@ -0,0 +1,36 @@ +import { safeCode } from './slack-oauth.client'; + +const VIEWS_OPEN_ENDPOINT = 'https://slack.com/api/views.open'; +// Slack's trigger_id expires 3 s after the command: there is no time for a long wait +const TIMEOUT_MS = 2_500; + +type FetchLike = (input: string, init?: Parameters[1]) => Promise; + +export type SlackApiResult = { ok: true } | { ok: false; error: string }; + +/** The few Slack Web API calls GitOps makes with a workspace's bot token. */ +export class SlackApiClient { + constructor(private readonly fetchFn: FetchLike = (input, init) => fetch(input, init)) {} + + /** Opens a modal for the user who ran the command (`trigger_id`). */ + async openView(token: string, triggerId: string, view: unknown): Promise { + let response: Response; + try { + response = await this.fetchFn(VIEWS_OPEN_ENDPOINT, { + method: 'POST', + headers: { + authorization: `Bearer ${token}`, + 'content-type': 'application/json; charset=utf-8', + }, + body: JSON.stringify({ trigger_id: triggerId, view }), + redirect: 'error', + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + } catch { + return { ok: false, error: 'network_error' }; + } + if (!response.ok) return { ok: false, error: `http_${response.status}` }; + const body = (await response.json().catch(() => null)) as { ok?: boolean; error?: unknown }; + return body?.ok ? { ok: true } : { ok: false, error: safeCode(body?.error) }; + } +} diff --git a/src/modules/notifications/infrastructure/slack/slack-oauth.client.test.ts b/src/modules/notifications/infrastructure/slack/slack-oauth.client.test.ts index 7b406a51..4bd3e437 100644 --- a/src/modules/notifications/infrastructure/slack/slack-oauth.client.test.ts +++ b/src/modules/notifications/infrastructure/slack/slack-oauth.client.test.ts @@ -30,11 +30,25 @@ describe('SlackOAuthClient', () => { }); }); - it('exchanges the code with Basic credentials and returns the webhook', async () => { + it('asks for another scope when told to', () => { + const url = new URL( + new SlackOAuthClient().buildAuthorizationUrl({ + clientId: '123.456', + redirectUri: EXCHANGE.redirectUri, + state: 'state-1', + scope: 'commands', + }), + ); + expect(url.searchParams.get('scope')).toBe('commands'); + }); + + it('exchanges the code with Basic credentials and returns the installation', async () => { const fetchFn = reply({ ok: true, access_token: 'xoxb-secret', + token_type: 'bot', team: { id: 'T1', name: 'Acme' }, + authed_user: { id: 'U1' }, incoming_webhook: { channel: '#alerts', channel_id: 'C1', @@ -42,12 +56,18 @@ describe('SlackOAuthClient', () => { url: 'https://hooks.slack.com/services/T1/B1/xyz', }, }); - const webhook = await new SlackOAuthClient(fetchFn).exchangeCode(EXCHANGE); + const installation = await new SlackOAuthClient(fetchFn).exchangeCode(EXCHANGE); - expect(webhook).toEqual({ - url: 'https://hooks.slack.com/services/T1/B1/xyz', - channel: '#alerts', + expect(installation).toEqual({ + teamId: 'T1', teamName: 'Acme', + authedUserId: 'U1', + botToken: 'xoxb-secret', + webhook: { + url: 'https://hooks.slack.com/services/T1/B1/xyz', + channel: '#alerts', + channelId: 'C1', + }, }); const [endpoint, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit]; expect(endpoint).toBe('https://slack.com/api/oauth.v2.access'); @@ -72,9 +92,14 @@ describe('SlackOAuthClient', () => { await expect(client.exchangeCode(EXCHANGE)).rejects.toMatchObject({ code: 'unknown_error' }); }); - it('fails when the install returned no webhook', async () => { - const client = new SlackOAuthClient(reply({ ok: true, access_token: 'xoxb' })); - await expect(client.exchangeCode(EXCHANGE)).rejects.toMatchObject({ code: 'no_webhook' }); + it('returns no webhook for an install without the incoming-webhook scope', async () => { + const client = new SlackOAuthClient( + reply({ ok: true, access_token: 'xoxb', token_type: 'bot', team: { id: 'T1' } }), + ); + await expect(client.exchangeCode(EXCHANGE)).resolves.toMatchObject({ + webhook: null, + botToken: 'xoxb', + }); }); it('maps HTTP and network failures', async () => { diff --git a/src/modules/notifications/infrastructure/slack/slack-oauth.client.ts b/src/modules/notifications/infrastructure/slack/slack-oauth.client.ts index 488a3606..101ccb1d 100644 --- a/src/modules/notifications/infrastructure/slack/slack-oauth.client.ts +++ b/src/modules/notifications/infrastructure/slack/slack-oauth.client.ts @@ -2,13 +2,19 @@ const AUTHORIZE_ENDPOINT = 'https://slack.com/oauth/v2/authorize'; const ACCESS_ENDPOINT = 'https://slack.com/api/oauth.v2.access'; const EXCHANGE_TIMEOUT_MS = 10_000; -/** The only scope GitOps asks for: Slack shows a channel picker and returns a webhook for it. */ +/** "Add to Slack" for a channel: Slack shows a channel picker and returns a webhook for it. */ export const SLACK_CONNECT_SCOPE = 'incoming-webhook'; +/** Installing the app for the `/gitops` command: no channel picker. */ +export const SLACK_INSTALL_SCOPE = 'commands'; +/** Bot scopes of the GitOps app (manifest). Slack adds scopes up, so each install keeps both. */ +export const SLACK_APP_SCOPES = [SLACK_CONNECT_SCOPE, SLACK_INSTALL_SCOPE]; export type SlackAuthorizationRequest = { clientId: string; redirectUri: string; state: string; + /** Defaults to `incoming-webhook`. */ + scope?: string; }; export type SlackCodeExchange = { @@ -18,12 +24,23 @@ export type SlackCodeExchange = { redirectUri: string; }; -/** What an `incoming-webhook` install returns: the webhook of the channel the user picked. */ +/** The webhook of the channel the user picked (only with the `incoming-webhook` scope). */ export type SlackIncomingWebhook = { url: string; /** `#channel` as Slack names it, when it says. */ channel: string | null; + channelId: string | null; +}; + +/** What an install returns. Holds a token: never log or echo it. */ +export type SlackInstallation = { + teamId: string | null; teamName: string | null; + /** The Slack user who authorized the install. */ + authedUserId: string | null; + /** Bot token of the workspace (`xoxb-…`). */ + botToken: string | null; + webhook: SlackIncomingWebhook | null; }; type FetchLike = (input: string, init?: Parameters[1]) => Promise; @@ -38,20 +55,24 @@ export class SlackOAuthError extends Error { } } +function text(value: unknown): string | null { + return typeof value === 'string' && value ? value : null; +} + export class SlackOAuthClient { constructor(private readonly fetchFn: FetchLike = (input, init) => fetch(input, init)) {} buildAuthorizationUrl(request: SlackAuthorizationRequest): string { const url = new URL(AUTHORIZE_ENDPOINT); url.searchParams.set('client_id', request.clientId); - url.searchParams.set('scope', SLACK_CONNECT_SCOPE); + url.searchParams.set('scope', request.scope ?? SLACK_CONNECT_SCOPE); url.searchParams.set('redirect_uri', request.redirectUri); url.searchParams.set('state', request.state); return url.toString(); } - /** Trades the code for the webhook; never logs or echoes the response (it holds a token). */ - async exchangeCode(exchange: SlackCodeExchange): Promise { + /** Trades the code for the installation; never logs or echoes the response (it holds a token). */ + async exchangeCode(exchange: SlackCodeExchange): Promise { // Slack recommends HTTP Basic for the client credentials (RFC 6749 §2.3.1) const credentials = Buffer.from( `${encodeURIComponent(exchange.clientId)}:${encodeURIComponent(exchange.clientSecret)}`, @@ -76,24 +97,30 @@ export class SlackOAuthClient { const body = (await response.json().catch(() => null)) as { ok?: boolean; error?: string; - incoming_webhook?: { url?: unknown; channel?: unknown }; - team?: { name?: unknown } | null; + access_token?: unknown; + token_type?: unknown; + incoming_webhook?: { url?: unknown; channel?: unknown; channel_id?: unknown }; + team?: { id?: unknown; name?: unknown } | null; + authed_user?: { id?: unknown } | null; } | null; if (!body?.ok) throw new SlackOAuthError(safeCode(body?.error)); const webhook = body.incoming_webhook; - if (!webhook || typeof webhook.url !== 'string' || !webhook.url) { - throw new SlackOAuthError('no_webhook'); - } + const url = text(webhook?.url); return { - url: webhook.url, - channel: typeof webhook.channel === 'string' && webhook.channel ? webhook.channel : null, - teamName: typeof body.team?.name === 'string' && body.team.name ? body.team.name : null, + teamId: text(body.team?.id), + teamName: text(body.team?.name), + authedUserId: text(body.authed_user?.id), + botToken: + body.token_type === 'bot' || body.token_type === undefined ? text(body.access_token) : null, + webhook: url + ? { url, channel: text(webhook?.channel), channelId: text(webhook?.channel_id) } + : null, }; } } /** Slack error codes are snake_case words; anything else is not echoed into logs. */ -function safeCode(value: unknown): string { +export function safeCode(value: unknown): string { return typeof value === 'string' && /^[a-z0-9_]{1,64}$/.test(value) ? value : 'unknown_error'; } diff --git a/src/modules/notifications/infrastructure/slack/slack-signature.ts b/src/modules/notifications/infrastructure/slack/slack-signature.ts new file mode 100644 index 00000000..9c9be57f --- /dev/null +++ b/src/modules/notifications/infrastructure/slack/slack-signature.ts @@ -0,0 +1,39 @@ +import crypto from 'node:crypto'; + +/** Requests older than this are refused, so a captured request can't be replayed later. */ +export const SLACK_SIGNATURE_MAX_AGE_SECONDS = 5 * 60; + +/** + * Checks a request from Slack (slash command, interaction): `X-Slack-Signature` is + * `v0=` + HMAC-SHA256(signing secret, `v0::`). + * `body` must be the raw body exactly as received, before any parsing. + */ +export function verifySlackSignature(input: { + signingSecret: string; + timestamp: string | null; + signature: string | null; + body: string; + now?: number; +}): boolean { + const { timestamp, signature } = input; + if (!timestamp || !signature || !/^\d{1,12}$/.test(timestamp)) return false; + const nowSeconds = Math.floor((input.now ?? Date.now()) / 1000); + if (Math.abs(nowSeconds - Number(timestamp)) > SLACK_SIGNATURE_MAX_AGE_SECONDS) return false; + + const expected = Buffer.from( + `v0=${crypto + .createHmac('sha256', input.signingSecret) + .update(`v0:${timestamp}:${input.body}`) + .digest('hex')}`, + ); + const received = Buffer.from(signature); + return expected.length === received.length && crypto.timingSafeEqual(expected, received); +} + +/** Signs like Slack does: for tests and local tooling. */ +export function signSlackRequest(signingSecret: string, timestamp: string, body: string): string { + return `v0=${crypto + .createHmac('sha256', signingSecret) + .update(`v0:${timestamp}:${body}`) + .digest('hex')}`; +} diff --git a/src/routes/api/slack/commands/+server.ts b/src/routes/api/slack/commands/+server.ts new file mode 100644 index 00000000..d7f3b576 --- /dev/null +++ b/src/routes/api/slack/commands/+server.ts @@ -0,0 +1,18 @@ +import { slackAppService } from '#modules/notifications'; +import { + readSlackRequest, + slackReply, + slackUnauthorized, +} from '#lib/server/notifications/slack-requests'; + +/** The `/gitops` slash command (Request URL of the command in the Slack app). */ +export async function POST({ request, url, locals }) { + const params = await readSlackRequest(request); + if (!params) return slackUnauthorized(); + try { + return slackReply(await slackAppService.handleCommand(params, url.origin)); + } catch (error) { + locals.logger.error(error, '[slack] command failed'); + return slackReply({ response_type: 'ephemeral', text: 'GitOps: something went wrong.' }); + } +} diff --git a/src/routes/api/slack/interactions/+server.ts b/src/routes/api/slack/interactions/+server.ts new file mode 100644 index 00000000..04616e13 --- /dev/null +++ b/src/routes/api/slack/interactions/+server.ts @@ -0,0 +1,24 @@ +import { slackAppService } from '#modules/notifications'; +import { + readSlackRequest, + slackReply, + slackUnauthorized, +} from '#lib/server/notifications/slack-requests'; + +/** Forms and buttons of the `/gitops` command (Interactivity Request URL in the Slack app). */ +export async function POST({ request, url, locals }) { + const params = await readSlackRequest(request); + if (!params) return slackUnauthorized(); + let payload: unknown; + try { + payload = JSON.parse(params.get('payload') ?? ''); + } catch { + return slackReply(null); + } + try { + return slackReply(await slackAppService.handleInteraction(payload, url.origin)); + } catch (error) { + locals.logger.error(error, '[slack] interaction failed'); + return slackReply(null); + } +} diff --git a/src/routes/auth/login/+page.server.ts b/src/routes/auth/login/+page.server.ts index d218f938..46da19bb 100644 --- a/src/routes/auth/login/+page.server.ts +++ b/src/routes/auth/login/+page.server.ts @@ -1,6 +1,7 @@ import { fail, redirect } from '@sveltejs/kit'; import { authService, ssoService } from '#modules/auth'; import { clusterSettingsService } from '#modules/config'; +import { consumeReturnTo } from '#lib/server/return-to'; const SESSION_COOKIE = 'pos_session'; const SESSION_MAX_AGE = 60 * 60 * 24 * 30; @@ -8,7 +9,7 @@ const SESSION_MAX_AGE = 60 * 60 * 24 * 30; export async function load({ cookies, url }) { const currentUser = await authService.resolveAuthenticatedUser(cookies.get(SESSION_COOKIE)); if (currentUser) { - throw redirect(303, '/'); + throw redirect(303, consumeReturnTo(cookies)); } const registrationEnabled = await clusterSettingsService.isRegistrationEnabled(); return { @@ -44,6 +45,6 @@ export const actions = { maxAge: SESSION_MAX_AGE, }); - throw redirect(303, '/'); + throw redirect(303, consumeReturnTo(cookies)); }, }; diff --git a/src/routes/auth/sso/google/callback/+server.ts b/src/routes/auth/sso/google/callback/+server.ts index 74da999e..ab8eb428 100644 --- a/src/routes/auth/sso/google/callback/+server.ts +++ b/src/routes/auth/sso/google/callback/+server.ts @@ -1,5 +1,6 @@ import { redirect } from '@sveltejs/kit'; import { authService, SsoError, ssoService } from '#modules/auth'; +import { consumeReturnTo } from '#lib/server/return-to'; const SESSION_COOKIE = 'pos_session'; const SESSION_MAX_AGE = 60 * 60 * 24 * 30; @@ -39,6 +40,7 @@ export async function GET({ url, cookies, locals }) { maxAge: SESSION_MAX_AGE, }); - // same landing as the password form: the root sends the user to their organizations - throw redirect(303, '/'); + // same landing as the password form: the root sends the user to their organizations, unless + // they came from a link that asked to come back (`/gitops login`) + throw redirect(303, consumeReturnTo(cookies)); } diff --git a/src/routes/gitops-settings/slack/+page.server.ts b/src/routes/gitops-settings/slack/+page.server.ts index 9cb22871..69b278c8 100644 --- a/src/routes/gitops-settings/slack/+page.server.ts +++ b/src/routes/gitops-settings/slack/+page.server.ts @@ -1,4 +1,8 @@ -import { slackConnectService } from '#modules/notifications'; +import { + SLACK_COMMANDS_PATH, + SLACK_INTERACTIONS_PATH, + slackConnectService, +} from '#modules/notifications'; import { slackRedirectUri } from '#lib/server/notifications/channels'; // the admin area is guarded by hooks.server.ts (cluster admins only) @@ -6,6 +10,8 @@ export function load({ url }) { return { status: slackConnectService.status(), redirectUri: slackRedirectUri(url.origin), + commandsUrl: `${url.origin}${SLACK_COMMANDS_PATH}`, + interactionsUrl: `${url.origin}${SLACK_INTERACTIONS_PATH}`, manifestUrl: slackConnectService.manifestUrl(url.origin), manifest: JSON.stringify(slackConnectService.manifest(url.origin), null, 2), https: url.protocol === 'https:', diff --git a/src/routes/gitops-settings/slack/+page.svelte b/src/routes/gitops-settings/slack/+page.svelte index 5b840b0c..e0079bb7 100644 --- a/src/routes/gitops-settings/slack/+page.svelte +++ b/src/routes/gitops-settings/slack/+page.svelte @@ -56,6 +56,23 @@ ? $_('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} @@ -121,6 +138,26 @@ class="overflow-auto rounded-lg bg-ink-900 p-3 font-mono text-xs text-white">SLACK_CLIENT_ID=… SLACK_CLIENT_SECRET=… +
  • +

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

    +
    SLACK_SIGNING_SECRET=…
    + {#each [data.commandsUrl, data.interactionsUrl] as endpoint (endpoint)} +
    + {endpoint} + +
    + {/each} +
  • diff --git a/src/routes/notifications/slack/callback/+server.ts b/src/routes/notifications/slack/callback/+server.ts index 6be97958..0476677f 100644 --- a/src/routes/notifications/slack/callback/+server.ts +++ b/src/routes/notifications/slack/callback/+server.ts @@ -1,26 +1,27 @@ import { redirect } from '@sveltejs/kit'; import { SLACK_FLOW_COOKIE, SLACK_FLOW_COOKIE_PATH } from '#modules/notifications'; -import { completeSlackConnection } from '#lib/server/notifications/channels'; +import { completeSlackFlow } from '#lib/server/notifications/channels'; /** - * Redirect URL of "Add to Slack" (registered in the Slack app). Needs the session of the user who - * started the flow; the result travels back as `?slack=connected` or `?slack=`. + * 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 completeSlackConnection(locals, { + const outcome = await completeSlackFlow(locals, { flowCookie, searchParams: url.searchParams, origin: url.origin, }); - if (!outcome.ok) { + if (outcome.error) { // never log the query: it carries the authorization code - locals.logger.warn({ code: outcome.error }, '[slack] connection failed'); + locals.logger.warn({ code: outcome.error }, '[slack] flow failed'); } - const status = outcome.ok ? 'connected' : outcome.error; - throw redirect(303, `${outcome.returnTo}?${new URLSearchParams({ slack: status })}`); + 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 14f4d4c3..84553da3 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -47,6 +47,9 @@ export default defineConfig(({ mode }) => ({ 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(), ],