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
15 changes: 10 additions & 5 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
GITDB_REPOSITORY_URL=https://github.com/your-org/your-gitdb-repository.git
GITDB_ENCRYPTION_KEY=replace-with-a-long-random-secret

# Public URL of the app: SvelteKit's CSRF check and the absolute links in emails
ORIGIN=http://localhost:3000

# Optional GitDB configuration
Expand All @@ -20,15 +21,19 @@ GITDB_SYNC_POLL_SECONDS=60
# GITDB_USERNAME=
# GITDB_PASSWORD=

# Optional SMTP notifications
# Optional SMTP notifications: invitations, password resets, alerts and access notices.
# Without HOST and FROM no email is sent (alerts are kept, the UI shows a warning).
# Links in emails are built from ORIGIN above; without it emails go out without links.
# For local testing: `docker compose --profile mail up mailpit`, HOST=localhost, PORT=1025,
# then read the emails at http://localhost:8025
# NOTIFICATION_SMTP_HOST=smtp.example.com
# NOTIFICATION_SMTP_PORT=587
# NOTIFICATION_SMTP_SECURE=false
# NOTIFICATION_SMTP_USER=
# NOTIFICATION_SMTP_PORT=587 # 465 turns TLS on by default
# NOTIFICATION_SMTP_SECURE=false # force TLS on/off
# NOTIFICATION_SMTP_USER= # USER and PASSWORD go together
# NOTIFICATION_SMTP_PASSWORD=
# NOTIFICATION_SMTP_FROM=noreply@example.com
# NOTIFICATION_SMTP_FROM_NAME=GitOps
# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true
# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true # only set false for self-signed test servers

# Optional cluster-wide Google sign-in (OpenID Connect). Shown on the login page when both the
# client ID and secret are set. Redirect URI to register in GCP: <ORIGIN>/auth/sso/google/callback
Expand Down
22 changes: 20 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,26 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
throttle (`throttleMinutes`) suppresses repeats and the next email reports how many were skipped.
- Recipients = selected users ∪ members with the selected roles, minus disabled users and users
without an email, then **filtered with `cancanService.can(userId, readPermission, event scope)`**
(most-specific-wins applies). One email per recipient (`AlertMailNotifier`, texts under
`alerts.email.*`, base locale); a failed email only affects that recipient.
(most-specific-wins applies). One email per recipient (`AlertMailNotifier`); a failed email
only affects that recipient. An organization alert and a project alert on the same event fire
independently.
- Email (`#lib/server/infra/notifications`): every email is wrapped by `renderEmail()` in
`src/notifications/email/_layout.html` (header, content, footer with the reason and a manage
link). Alerts use `alert.html` (field table built from the catalog) unless the definition sets
`mailTemplate` (`alert-code-report-analysis.html`); `link(context)` gives the app path of the
resource and `mailSummary(payload)` the subject summary (`[GitOps] <alert>: <summary>`). System
notices use `system-access-changed.html` / `system-security-notice.html`. Escape every user or
event value with `{{ }}`; `{{{ }}}` only for HTML built internally with `renderTemplateString`.
Texts are `alerts.email.*`, in the recipient's locale or English. Links are absolute with
`ORIGIN` (`absoluteUrl()`), omitted without it. These functions never reach the client: the
catalog endpoint strips them.
- Sending: alert and system emails go through `mailQueue` (concurrency 3, `withRetry` 4 attempts
1 s → 4 s → 16 s with jitter, only for `isRetryableMailError`: network errors and 4xx replies).
Definitive failures are logged by `createLogger('mail')` with the alert, the event and a
recipient hash, never the content or the address. `registerMailShutdown()` drains it on
`sveltekit:shutdown` (10 s). Invitations and password resets call `notify()` directly: their
tokens must not travel through the bus or the queue. Without SMTP (`isMailConfigured()`), the
engine skips events (debug log), warns once at startup and the alert pages show a banner.
- HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by
the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`,
`GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test`
Expand Down
30 changes: 28 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ automatic sign-up without domains), the Google button is hidden and the reason i

Organizations and projects can get an email when something happens. Alerts live in **Settings →
Alerts** of the organization (they cover all of its projects) or of a project. Each alert watches
one event, filters it on the event's fields and emails users or roles. Emails need the
`NOTIFICATION_SMTP_*` variables; without SMTP, alerts are kept but nothing is sent.
one event, filters it on the event's fields and emails users or roles. The same event can fire an
organization alert and a project alert; each one sends its own email.

Guided example: *tell the security team when an analysis of the `api-gateway` service has critical
vulnerabilities*.
Expand Down Expand Up @@ -163,6 +163,32 @@ 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.

### Email

Invitations, password resets, alerts and access notices are sent by SMTP:

| Variable | Default | |
|---|---|---|
| `NOTIFICATION_SMTP_HOST` | — | Required to send email |
| `NOTIFICATION_SMTP_FROM` | — | Required, sender address |
| `NOTIFICATION_SMTP_FROM_NAME` | — | Sender display name |
| `NOTIFICATION_SMTP_PORT` | `587` | `465` turns TLS on by default |
| `NOTIFICATION_SMTP_SECURE` | port-based | Force TLS on or off |
| `NOTIFICATION_SMTP_USER` / `NOTIFICATION_SMTP_PASSWORD` | — | Set both or neither |
| `NOTIFICATION_SMTP_REJECT_UNAUTHORIZED` | `true` | `false` only for self-signed test servers |
| `ORIGIN` | — | Public URL; links in emails are absolute. Without it emails have no links |

Without SMTP nothing breaks: alerts are kept, the alert pages show a warning and the server logs
it once at startup. Alert and notice emails go through an in-process queue (3 at a time) that
retries network errors and temporary SMTP replies (4 attempts: 1 s, 4 s, 16 s) and is drained for
up to 10 s on shutdown; invitations and password resets are sent directly because their links carry
tokens. Emails are in the recipient's language when known, English otherwise.

To try them locally, start [Mailpit](https://mailpit.axllent.org/) with
`docker compose --profile mail up mailpit`, set `NOTIFICATION_SMTP_HOST=localhost`,
`NOTIFICATION_SMTP_PORT=1025` and `NOTIFICATION_SMTP_FROM=gitops@localhost`, and open
http://localhost:8025.

## Development

```bash
Expand Down
10 changes: 10 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,13 @@ services:
- ./data:/app/data
- /run/host-services/ssh-auth.sock:/ssh-agent
restart: unless-stopped

# local SMTP for trying emails: `docker compose --profile mail up`, then set
# NOTIFICATION_SMTP_HOST=mailpit (or localhost outside Docker), NOTIFICATION_SMTP_PORT=1025,
# NOTIFICATION_SMTP_FROM=gitops@localhost and open http://localhost:8025
mailpit:
image: axllent/mailpit:v1.21
profiles: ['mail']
ports:
- '1025:1025'
- '8025:8025'
1 change: 1 addition & 0 deletions e2e/env-private.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const GITDB_SYNC_MODE = process.env.GITDB_SYNC_MODE;
export const GITDB_DATA_PATH = process.env.GITDB_DATA_PATH;
export const GITDB_ENCRYPTION_KEY = process.env.GITDB_ENCRYPTION_KEY;
export const VAULT_ENCRYPTION_KEY = process.env.VAULT_ENCRYPTION_KEY;
export const ORIGIN = process.env.ORIGIN;
export const NOTIFICATION_SMTP_HOST = process.env.NOTIFICATION_SMTP_HOST;
export const NOTIFICATION_SMTP_PORT = process.env.NOTIFICATION_SMTP_PORT;
export const NOTIFICATION_SMTP_SECURE = process.env.NOTIFICATION_SMTP_SECURE;
Expand Down
9 changes: 9 additions & 0 deletions e2e/global-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,15 @@ function buildEnv(): Record<string, string | undefined> {
GITDB_USERNAME: '',
GITDB_TOKEN: '',
GITDB_PASSWORD: '',
// never reach a real SMTP from a developer's `.env`: the suite runs with email disabled
NOTIFICATION_SMTP_HOST: '',
NOTIFICATION_SMTP_PORT: '',
NOTIFICATION_SMTP_SECURE: '',
NOTIFICATION_SMTP_USER: '',
NOTIFICATION_SMTP_PASSWORD: '',
NOTIFICATION_SMTP_FROM: '',
NOTIFICATION_SMTP_FROM_NAME: '',
NOTIFICATION_SMTP_REJECT_UNAUTHORIZED: '',
PORT: String(E2E_PORT),
};
}
Expand Down
2 changes: 2 additions & 0 deletions e2e/specs/alerts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ test.describe('project alerts', () => {
await loginAs('projectAdmin');
await expectAllowed(page, alertsUrl);
await expect(page.getByText('Todavía no hay alertas')).toBeVisible();
// e2e runs without SMTP: the page says alerts won't be sent
await expect(page.getByTestId('mail-disabled')).toBeVisible();
await expect(page.getByRole('link', { name: 'Crear alerta' }).first()).toHaveAttribute(
'href',
`${alertsUrl}/new`,
Expand Down
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export const variables = defineEnvVars({
GITDB_DATA_PATH: optional,
GITDB_ENCRYPTION_KEY: optional,
VAULT_ENCRYPTION_KEY: optional,
ORIGIN: optional,
NOTIFICATION_SMTP_HOST: optional,
NOTIFICATION_SMTP_PORT: optional,
NOTIFICATION_SMTP_SECURE: optional,
Expand Down
9 changes: 8 additions & 1 deletion src/lib/alerts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ export type CatalogField = Omit<EventDefinition['fields'][number], 'derive'> & {
derived?: boolean;
};

export type CatalogEntry = Omit<EventDefinition, 'fields'> & { fields: CatalogField[] };
export type CatalogEntry = Omit<
EventDefinition,
'fields' | 'link' | 'mailSummary' | 'mailTemplate'
> & {
fields: CatalogField[];
};

export type AlertOption = { id: string; label: string };

Expand Down Expand Up @@ -40,6 +45,8 @@ type Shared = {
referenceOptions: Record<string, AlertOption[]>;
users: AlertOption[];
roles: AlertOption[];
/** `false` when SMTP is not configured: alerts are saved but nothing is sent. */
mailConfigured: boolean;
};

export type AlertListData = Shared & {
Expand Down
13 changes: 12 additions & 1 deletion src/lib/components/alerts/AlertEditor.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import { untrack } from 'svelte';
import { enhance } from '$app/forms';
import type { SubmitFunction } from '$app/forms';
import { ArrowLeft, FlaskConical, Info, Save, Trash2 } from '@lucide/svelte';
import { ArrowLeft, FlaskConical, Info, MailWarning, Save, Trash2 } from '@lucide/svelte';
import { _ } from '#lib/i18n';
import type {
AlertEditorData,
Expand Down Expand Up @@ -115,6 +115,17 @@
{/if}
</div>

{#if !data.mailConfigured}
<p
class="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800"
role="status"
data-testid="mail-disabled"
>
<MailWarning class="mt-0.5 h-4 w-4 shrink-0" />
{$_('alerts.mailDisabled')}
</p>
{/if}

<!-- step 1: event -->
<section class="space-y-4" aria-labelledby="step-event">
<h4 id="step-event" class="text-base font-semibold text-slate-900">
Expand Down
13 changes: 12 additions & 1 deletion src/lib/components/alerts/AlertList.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<script lang="ts">
import { enhance } from '$app/forms';
import { BellRing, Pencil, Plus, Trash2 } from '@lucide/svelte';
import { BellRing, MailWarning, Pencil, Plus, Trash2 } from '@lucide/svelte';
import { _ } from '#lib/i18n';
import { summarizeConditions, summarizeRecipients } from '#lib/alerts/summary';
import type { AlertListData, AlertRow } from '#lib/alerts/types';
Expand Down Expand Up @@ -58,6 +58,17 @@
{/if}
</section>

{#if !data.mailConfigured}
<p
class="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800"
role="status"
data-testid="mail-disabled"
>
<MailWarning class="mt-0.5 h-4 w-4 shrink-0" />
{$_('alerts.mailDisabled')}
</p>
{/if}

{#if error}
<p
class="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700"
Expand Down
21 changes: 21 additions & 0 deletions src/lib/events/catalog/access.events.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields';
import type { EventDefinitions } from './types';
import { organizationPath, projectPath } from './links';

export const ACCESS_SCOPES = ['cluster', 'organization', 'project'] as const;

Expand Down Expand Up @@ -65,6 +66,9 @@ export const accessEvents: EventDefinitions<
AccessEvent | InvitationEvent | typeof ROLE_UPDATED | typeof KEY_CREATED | typeof KEY_REVOKED
> = {
[GRANTED]: {
link: (context) =>
projectPath(context, '/settings/access-control') ??
organizationPath(context, '/settings/access-control'),
...eventText(GRANTED),
module: 'access',
scope: 'organization',
Expand All @@ -73,6 +77,9 @@ export const accessEvents: EventDefinitions<
fields: accessFields(GRANTED),
},
[UPDATED]: {
link: (context) =>
projectPath(context, '/settings/access-control') ??
organizationPath(context, '/settings/access-control'),
...eventText(UPDATED),
module: 'access',
scope: 'organization',
Expand All @@ -81,6 +88,9 @@ export const accessEvents: EventDefinitions<
fields: accessFields(UPDATED),
},
[REVOKED]: {
link: (context) =>
projectPath(context, '/settings/access-control') ??
organizationPath(context, '/settings/access-control'),
...eventText(REVOKED),
module: 'access',
scope: 'organization',
Expand All @@ -89,6 +99,9 @@ export const accessEvents: EventDefinitions<
fields: accessFields(REVOKED),
},
[INVITED]: {
link: (context) =>
projectPath(context, '/settings/access-control') ??
organizationPath(context, '/settings/access-control'),
...eventText(INVITED),
module: 'access',
scope: 'organization',
Expand All @@ -97,6 +110,9 @@ export const accessEvents: EventDefinitions<
fields: [userField(INVITED), roleField(INVITED)],
},
[ACCEPTED]: {
link: (context) =>
projectPath(context, '/settings/access-control') ??
organizationPath(context, '/settings/access-control'),
...eventText(ACCEPTED),
module: 'access',
scope: 'organization',
Expand All @@ -105,6 +121,9 @@ export const accessEvents: EventDefinitions<
fields: [userField(ACCEPTED), roleField(ACCEPTED), scopeField(ACCEPTED)],
},
[ROLE_UPDATED]: {
link: (context) =>
projectPath(context, '/settings/roles-permissions') ??
organizationPath(context, '/settings/roles-permissions'),
...eventText(ROLE_UPDATED),
module: 'access',
scope: 'organization',
Expand All @@ -117,6 +136,7 @@ export const accessEvents: EventDefinitions<
],
},
[KEY_CREATED]: {
link: (context) => projectPath(context, '/settings/server-access-keys'),
...eventText(KEY_CREATED),
module: 'access',
scope: 'project',
Expand All @@ -132,6 +152,7 @@ export const accessEvents: EventDefinitions<
],
},
[KEY_REVOKED]: {
link: (context) => projectPath(context, '/settings/server-access-keys'),
...eventText(KEY_REVOKED),
module: 'access',
scope: 'project',
Expand Down
20 changes: 20 additions & 0 deletions src/lib/events/catalog/code-report.events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
} from '#lib/code-report/security-policy';
import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields';
import type { EventDefinitions } from './types';
import { projectPath } from './links';

/** Tools that report analyses: scanners plus the manual upload and the CI/CD API defaults. */
export const CODE_REPORT_TOOLS = [
Expand Down Expand Up @@ -75,6 +76,15 @@ export const codeReportEvents: EventDefinitions<
| typeof SERVICE_DELETED
> = {
[COMPLETED]: {
mailTemplate: 'alert-code-report-analysis',
link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`),
mailSummary: ({ summary }) =>
summary.total === 0
? { key: 'alerts.email.summary.noVulnerabilities' }
: {
key: 'alerts.email.summary.vulnerabilities',
values: { critical: summary.critical, high: summary.high, total: summary.total },
},
...eventText(COMPLETED),
module: 'code_report',
scope: 'project',
Expand Down Expand Up @@ -106,6 +116,9 @@ export const codeReportEvents: EventDefinitions<
],
},
[FAILED]: {
mailTemplate: 'alert-code-report-analysis',
link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`),
mailSummary: ({ tool }) => ({ key: 'alerts.email.summary.analysisFailed', values: { tool } }),
...eventText(FAILED),
module: 'code_report',
scope: 'project',
Expand All @@ -114,6 +127,11 @@ export const codeReportEvents: EventDefinitions<
fields: [serviceField(FAILED), toolField(FAILED), branchField(FAILED)],
},
[POLICY_VIOLATED]: {
link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`),
mailSummary: ({ policyName, violations }) => ({
key: 'alerts.email.summary.policyViolated',
values: { policy: policyName, count: violations },
}),
...eventText(POLICY_VIOLATED),
module: 'code_report',
scope: 'project',
Expand Down Expand Up @@ -145,6 +163,7 @@ export const codeReportEvents: EventDefinitions<
],
},
[SERVICE_CREATED]: {
link: (context) => projectPath(context, '/code-report/services'),
...eventText(SERVICE_CREATED),
module: 'code_report',
scope: 'project',
Expand All @@ -160,6 +179,7 @@ export const codeReportEvents: EventDefinitions<
],
},
[SERVICE_DELETED]: {
link: (context) => projectPath(context, '/code-report/services'),
...eventText(SERVICE_DELETED),
module: 'code_report',
scope: 'project',
Expand Down
11 changes: 11 additions & 0 deletions src/lib/events/catalog/links.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { EventLinkContext } from './types';

/** App paths for `EventDefinition.link`; `null` when the slugs needed are unknown. */
export function organizationPath(context: EventLinkContext, path = ''): string | null {
return context.organizationSlug ? `/org/${context.organizationSlug}${path}` : null;
}

export function projectPath(context: EventLinkContext, path = ''): string | null {
if (!context.organizationSlug || !context.projectSlug) return null;
return `/org/${context.organizationSlug}/projects/${context.projectSlug}${path}`;
}
Loading
Loading