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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ GITDB_SYNC_POLL_SECONDS=60
# manifest, incoming-webhook scope only). Redirect URL: <ORIGIN>/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 <ORIGIN>/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
Expand Down
34 changes: 26 additions & 8 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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 `<ORIGIN>/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
`<ORIGIN>/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` = `<team>:<user>`) 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
Expand Down
26 changes: 25 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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` = `<team>:<user>`, `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:
Expand Down
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
`<ORIGIN>/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 `<ORIGIN>/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
Expand Down
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
40 changes: 38 additions & 2 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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' ||
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading