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
21 changes: 20 additions & 1 deletion .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ La logica vive en `src/modules/<module>/` con `domain/`, `application/`, `infras
`index.ts` como composition root. El `domain/` contiene entidades (`*.domain.ts`) y datos
centralizados (`*.data.ts`) para constantes: permisos de roles, defaults de proyecto, pesos de
riesgo y mapeos de herramientas. Los modulos actuales son `auth`, `config`, `organization`,
`projects`, `storage` y `code-report`. Las rutas deben importar desde el `index.ts` publico.
`projects`, `storage`, `code-report`, `vault`, `audit`, `alerts`, `monitoring` y `notifications`. Las rutas deben importar desde el `index.ts` publico.

GitDB es la unica fuente de verdad para usuarios, roles, API keys, organizaciones, proyectos,
metadata de storage y code reports. Se configura con `GITDB_REPOSITORY_URL` (URLs HTTPS o SSH
Expand Down Expand Up @@ -114,6 +114,19 @@ aplican (regla most-specific-wins). Permite delegación de autoridad granular co
`canManageOrganization()` controla acceso al area `/settings`, mientras que `canViewOrganization()` incluye
tambien usuarios con acceso solo a proyectos bajo la organización (ven el overview pero no pueden acciones de org-scope).

**Alertas, destinatarios externos y canales de notificación:** `organization:alerts:read|update` y
`project:alerts:read|update` gestionan alertas por eventos; `organization:notifications:read|update`
y `project:notifications:update` gestionan destinatarios externos y canales. El módulo
`$modules/notifications` maneja dominios permitidos, canales de notificación (webhook, Slack, Google Chat),
verificación y desuscripción. En `/org/<org>/settings/alerts/settings`, administradores configuran dominios
permitidos y canales (`NotificationChannelEntity` en GitDB). Alertas guardan `recipients` (usuarios, roles,
emails externos) y `channelIds` (referencias a canales, no destinatarios individuales). Canales de organización
se usan en alertas de org y proyecto; canales de proyecto solo en sus alertas. URLs de webhook se encriptan
con `GITDB_ENCRYPTION_KEY` (AES-GCM por channel id). Emails externos: `pending` → `verified` → `unsubscribed`
o `blocked` si dominio se quita; template reducido sin campos `sensitive` ni links; `List-Unsubscribe` HMAC
(90 días). Canales: un mensaje por canal en paralelo, fallo de canal nunca afecta email. Rutas públicas
`/notifications/verify` y `/notifications/unsubscribe` aceptan POST (no GET). Sin `ORIGIN` no se envía nada.

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
`roleService.createDefaultProjectRoles()`. Ambas operaciones inicializan sus roles por defecto.
Expand All @@ -133,6 +146,12 @@ normalizan errores. Ejecutar `bun run check`, `bun run lint`, `bun run test` y

## Comportamiento conocido

**i18n imports from notifications:** `#lib/server/infra/notifications/index.ts` no re-exporta
los helpers i18n de email (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`…) porque cargan Paraglide
(requiere Vite), y el index de notifications lo importan módulos que corren fuera de Vite (como `$modules/auth`
en tests e2e). Importar estos helpers desde `#lib/server/infra/notifications/i18n`. Por la misma razón,
`e2e/fixtures/seed.ts` siembra dominios permitidos vía `NotificationSettingsRepository`, no desde `$modules/notifications`.

**Startup y readiness del servidor:** El auth guard en `hooks.server.ts` verifica readiness via
`getServerReadyState()` antes de procesar cualquier request. Durante startup, los navegadores
reciben una página de landing "GitOps is starting" que se recarga automáticamente, mientras que
Expand Down
128 changes: 112 additions & 16 deletions CLAUDE.md

Large diffs are not rendered by default.

38 changes: 37 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ vulnerabilities*.
*greater than* `0`.
4. Recipients: the **Project Admin** role. Throttle: one email every **30** minutes at most.
5. **Test alert** shows whether an example event matches and who would get the email, without
sending anything. Then **Create alert**.
sending anything. **Send test email** also emails those recipients with an example event and a
`[Test]` subject (external addresses only once confirmed). Then **Create alert**.

The same alert through the API (`gvs_` project keys only manage alerts of their own project):

Expand All @@ -165,6 +166,41 @@ fields. Only recipients allowed to view the event get the email, and you can onl
events you can view yourself. Some notifications are always on: users are told when their access to
an organization or project changes and when a personal API key is created on their account.

#### External email recipients

Alerts can also email people without a GitOps account (a vendor, an on-call mailbox):

1. In **Settings → Alerts**, click **Settings** and list the organization's allowed domains (needs
`organization:settings:update`). `partner.com` matches only that domain; use `*.partner.com`
for its subdomains. The list is empty by default, which means no external recipients.
2. In the alert, add the addresses next to users and roles (needs
`organization:notifications:update` or `project:notifications:update`). The API takes them in
`recipients.emails`.
3. Each new address gets a confirmation email and receives nothing until its owner confirms. Every
alert email carries an unsubscribe link. An address added by mistake can be removed from
**Settings** while it is still pending: its confirmation link stops working and it is taken out
of every alert.

External recipients are not checked against GitOps permissions, so their emails leave out
sensitive fields and links into the app. Removing a domain blocks its addresses without deleting
them, and allowing it again restores them. `ORIGIN` must be set: without it, confirmation and
unsubscribe links can't be built and nothing is sent to external addresses.

#### Notification channels

Alerts can also post to chat channels and webhooks. In **Settings → Alerts**, click **Settings** to
manage the channels of the organization (usable by every alert of the organization and its
projects) or of a project (only its alerts). Each channel has a name and the webhook URL its
provider gives you; the URL is stored encrypted and only ever shown masked. **Send test message**
posts an example to check it works. Then pick the channels in the alert, next to its email
recipients: each firing sends one message per channel, and a failing channel never stops the
emails or the other channels.

Adding channels to an alert needs `organization:notifications:update` or
`project:notifications:update`: people reading a channel may have no access to the resource.
Messages leave out sensitive fields. Channel types become available as their transports land
(generic webhooks, Slack and Google Chat); until then the settings say no type is available yet.

### Monitoring

HTTP monitors check a URL (method, headers and body of your choice) every 60 seconds by default and
Expand Down
14 changes: 12 additions & 2 deletions e2e/fixtures/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { apiKeysService, roleService, userAccessService } from '#modules/auth';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import { codeReportService } from '#modules/code-report';
import { NotificationSettingsRepository } from '#modules/notifications/infrastructure/repositories/notification-settings.repository';

export const E2E_PASSWORD = 'E2ePassword!123';

Expand Down Expand Up @@ -110,6 +111,7 @@ export async function seedAll(): Promise<SeedOutput> {
slug: 'e2e-primary',
});
await roleService.createDefaultOrganizationRoles(primaryOrg.id);
await new NotificationSettingsRepository().setAllowedDomains(primaryOrg.id, ['example.com']);
const primaryOrgRoles = await roleService.listRoles('organization', primaryOrg.id);
const orgAdminRoleId = roleIdBySlug(primaryOrgRoles, 'org-admin');
const orgDeveloperRoleId = roleIdBySlug(primaryOrgRoles, 'org-developer');
Expand Down Expand Up @@ -192,7 +194,11 @@ export async function seedAll(): Promise<SeedOutput> {
],
});
const serverKeysNoDeleteUser = await bareUser('e2e-server-keys-no-delete');
await assignProjectRole(primaryProject.id, serverKeysNoDeleteUser.userId, serverKeysNoDeleteRole.id);
await assignProjectRole(
primaryProject.id,
serverKeysNoDeleteUser.userId,
serverKeysNoDeleteRole.id,
);

const serverKeysNoUpdateRole = await roleService.createRole({
name: 'E2E Server Keys No Update',
Expand All @@ -202,7 +208,11 @@ export async function seedAll(): Promise<SeedOutput> {
permissions: ['project:project:read', 'project:server-keys:read', 'project:server-keys:create'],
});
const serverKeysNoUpdateUser = await bareUser('e2e-server-keys-no-update');
await assignProjectRole(primaryProject.id, serverKeysNoUpdateUser.userId, serverKeysNoUpdateRole.id);
await assignProjectRole(
primaryProject.id,
serverKeysNoUpdateUser.userId,
serverKeysNoUpdateRole.id,
);

await apiKeysService.createProjectApiKey({
projectId: primaryProject.id,
Expand Down
66 changes: 59 additions & 7 deletions e2e/specs/alerts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ test.describe('project alerts', () => {
await page.getByRole('option', { name: 'Project Admin', exact: true }).click();
await targets.fill('oncall@example.com');
await targets.press('Enter');
await targets.press('Escape');
await wizard.getByRole('radio', { name: '1 hora' }).click();
await wizard.getByRole('button', { name: 'Siguiente' }).click();

Expand All @@ -77,6 +78,7 @@ test.describe('project alerts', () => {
await expect(result).toContainText('El evento de ejemplo cumple las condiciones.');
await expect(result).toContainText(seed.personas.projectAdmin.username);
await expect(result).toContainText('oncall@example.com');
await expect(result).toContainText('Sin añadir');
await expect(result).toContainText('no se ha enviado ningún email');

await wizard.getByRole('button', { name: 'Crear alerta' }).click();
Expand All @@ -93,7 +95,7 @@ test.describe('project alerts', () => {
await expect(row.getByRole('switch')).toHaveAttribute('aria-checked', 'true');
});

test('only email can be enabled and the alert is edited in the same wizard', async ({
test('without channels only email can be picked and the alert is edited in the same wizard', async ({
page,
loginAs,
}) => {
Expand All @@ -106,12 +108,13 @@ test.describe('project alerts', () => {
await expect(wizard.getByLabel('Nombre', { exact: true })).toHaveValue(GUIDED_NAME);

await wizard.getByRole('button', { name: /Destinos/ }).click();
// Slack, Google Chat and Webhook have no notifier yet: shown as "soon" and not selectable
for (const channel of [/^Slack/, /^Google Chat/, /^Webhook/]) {
const card = wizard.getByRole('checkbox', { name: channel });
await expect(card).toBeDisabled();
await expect(card).toContainText('Próximamente');
await expect(card).toHaveAttribute('aria-checked', 'false');
const channels = wizard.getByTestId('alert-channels');
await expect(channels.getByRole('checkbox', { name: /^Email/ })).toBeEnabled();
for (const type of ['slack', 'google-chat', 'webhook']) {
const card = channels.locator(`[data-channel-type="${type}"]`);
await expect(card.getByRole('checkbox')).toBeDisabled();
await expect(card).toContainText('No configurado');
await expect(card.getByRole('link', { name: 'Configurar' })).toBeVisible();
}

const targets = wizard.getByLabel('Destinatarios');
Expand Down Expand Up @@ -215,11 +218,60 @@ test.describe('organization alerts', () => {
await expect(inherited.getByRole('link', { name: 'Editar' })).toHaveCount(0);
await expect(inherited.getByRole('switch')).toHaveCount(0);
});

test('the alert settings open in a modal from the list and save the allowed domains', async ({
page,
loginAs,
}) => {
await loginAs('orgAdmin');
await page.goto(orgAlertsUrl);
await page.waitForLoadState('networkidle');
await page.getByTestId('alert-settings').click();
const dialog = page.getByRole('dialog', { name: 'Configuración de alertas' });
await expect(dialog).toBeVisible();
await expect(page).toHaveURL(new RegExp(`${orgAlertsUrl}$`));

const domains = dialog.getByLabel('Dominios (uno por línea)');
await expect(domains).toHaveValue('example.com');
await domains.fill('example.com\npartner.com');
await dialog.getByRole('button', { name: 'Guardar dominios' }).click();
await expect(page.getByRole('status').filter({ hasText: 'Dominios guardados' })).toBeVisible();
await expect(domains).toHaveValue('example.com\npartner.com');
});

test('project admins manage the project channels, not the organization domains', async ({
page,
loginAs,
}) => {
await loginAs('projectAdmin');
await page.goto(alertsUrl);
await page.waitForLoadState('networkidle');
await page.getByTestId('alert-settings').click();
const dialog = page.getByRole('dialog', { name: 'Configuración de alertas' });
await expect(dialog.getByTestId('notification-channels')).toBeVisible();
await expect(dialog.getByTestId('channel-types-unavailable')).toBeVisible();
await expect(dialog.getByLabel('Dominios (uno por línea)')).toHaveCount(0);
});

test('a project viewer gets no settings button', async ({ page, loginAs }) => {
await loginAs('projectViewer');
await page.goto(alertsUrl);
await expect(page.getByTestId('alert-settings')).toHaveCount(0);
});
});

test.describe('without JavaScript', () => {
test.use({ javaScriptEnabled: false });

test('the alert settings button opens the settings page', async ({ page, loginAs }) => {
await loginAs('orgAdmin');
await page.goto(orgAlertsUrl);
await page.getByTestId('alert-settings').click();
await expect(page).toHaveURL(new RegExp(`${orgAlertsUrl}/settings$`));
await expect(page.getByRole('heading', { name: 'Configuración de alertas' })).toBeVisible();
await expect(page.getByLabel('Dominios (uno por línea)')).toHaveValue(/example\.com/);
});

test('the editor still creates an alert through form actions', async ({ page, loginAs }) => {
await loginAs('projectAdmin');
await page.goto(`${alertsUrl}/new`);
Expand Down
21 changes: 12 additions & 9 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import { registerAlertEngine } from '#modules/alerts';
import { getMonitoringConfig, startMonitoring } from '#modules/monitoring';
import { isInternalMonitoringRequest, verifyWorkerRequest } from '#lib/server/monitoring/internal-auth';
import {
isInternalMonitoringRequest,
verifyWorkerRequest,
} from '#lib/server/monitoring/internal-auth';
import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstrap';
import { startGitDb } from '#lib/server/gitdb';
import {
getServerReadyState,
markServerFailed,
markServerReady,
} from '#lib/server/server-ready';
import { getServerReadyState, markServerFailed, markServerReady } from '#lib/server/server-ready';
import { renderStartingPage } from '#lib/server/starting-page';
import { runWithActor } from '#lib/server/request-context';
import { rememberDevOrigin } from '#lib/server/infra/notifications';
import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger';

const startupLog = createLogger('startup');
Expand All @@ -28,7 +28,9 @@ const serverReady = (async () => {
await refreshBootstrapState();
markServerReady();
// monitoring needs GitDB; if its repository or runtime can't start, the rest of the app still does
startMonitoring().catch((error) => startupLog.error(error, '[startup] monitoring failed to start'));
startMonitoring().catch((error) =>
startupLog.error(error, '[startup] monitoring failed to start'),
);
})();

serverReady.catch((error) => {
Expand Down Expand Up @@ -64,6 +66,7 @@ const requestLogger: Handle = async ({ event, resolve }) => {

const authGuard: Handle = async ({ event, resolve }) => {
const pathname = event.url.pathname;
if (import.meta.env.DEV) rememberDevOrigin(event.url.origin);
const isApiRequest = pathname.startsWith('/api/');

if (pathname === '/health') {
Expand Down Expand Up @@ -127,9 +130,9 @@ const authGuard: Handle = async ({ event, resolve }) => {
return resolve(event);
}

// sign-in, sign-out, self-registration, password recovery, invitation acceptance and the Google
// SSO round trip must work without (or with a broken) session; each route re-checks what it needs
if (
pathname === '/notifications/verify' ||
pathname === '/notifications/unsubscribe' ||
pathname === '/auth/login' ||
pathname === '/auth/sso/google/start' ||
pathname === '/auth/sso/google/callback' ||
Expand Down
9 changes: 3 additions & 6 deletions src/lib/alerts/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export function emptyDraft(): AlertDraft {
eventType: '',
match: 'all',
conditions: [],
channels: ['mail'],
recipients: emptyRecipients(),
channelIds: [],
throttleMinutes: 0,
};
}
Expand All @@ -36,14 +36,14 @@ export function draftFromAlert(alert: AlertRow): AlertDraft {
? [...condition.value]
: condition.value,
})),
channels: [...alert.channels],
// copia de cada lista: `alert` puede ser un proxy reactivo (no admite structuredClone)
recipients: Object.fromEntries(
Object.entries({ ...emptyRecipients(), ...alert.recipients }).map(([key, list]) => [
key,
[...list],
]),
) as AlertDraft['recipients'],
channelIds: [...(alert.channelIds ?? [])],
throttleMinutes: alert.throttleMinutes,
};
}
Expand All @@ -60,14 +60,11 @@ export function draftToFormData(
form.set('eventType', draft.eventType);
form.set('match', draft.match);
form.set('throttleMinutes', String(draft.throttleMinutes));
for (const channel of draft.channels) form.append('channels', channel);
const lists = {
userIds: draft.recipients.userIds,
roleIds: draft.recipients.roleIds,
emails: draft.recipients.emails,
slackChannels: draft.recipients.slackChannels,
googleChatSpaces: draft.recipients.googleChatSpaces,
webhookUrls: draft.recipients.webhookUrls,
channelIds: draft.channelIds,
};
for (const [name, values] of Object.entries(lists)) {
for (const value of values) form.append(name, value);
Expand Down
26 changes: 14 additions & 12 deletions src/lib/alerts/summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,38 +67,40 @@ export function summarizeRecipients(
users: AlertOption[],
roles: AlertOption[],
t: Translate,
channels: { ids: string[]; options: Array<{ id: string; name: string }> } = {
ids: [],
options: [],
},
): string {
const names = [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id),
...(recipients.emails ?? []),
...channels.ids.map((id) => channels.options.find((option) => option.id === id)?.name ?? id),
];
return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients');
}

/** Targets of one channel, ready to print: names for mail, `#canal` for Slack, spaces, URLs. */
export function channelTargets(
channel: string,
recipients: {
userIds: string[];
roleIds: string[];
emails?: string[];
slackChannels?: string[];
googleChatSpaces?: string[];
webhookUrls?: string[];
alert: {
recipients: { userIds: string[]; roleIds: string[]; emails?: string[] };
channelIds?: string[];
},
users: AlertOption[],
roles: AlertOption[],
channels: Array<{ id: string; name: string; type: string }> = [],
): string[] {
const { recipients } = alert;
if (channel === 'mail') {
return [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id),
...(recipients.emails ?? []),
];
}
if (channel === 'slack') return recipients.slackChannels ?? [];
if (channel === 'google_chat') return recipients.googleChatSpaces ?? [];
if (channel === 'webhook') return recipients.webhookUrls ?? [];
return [];
return (alert.channelIds ?? [])
.map((id) => channels.find((option) => option.id === id))
.filter((option) => option?.type === channel)
.map((option) => option!.name);
}
Loading
Loading