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
20 changes: 15 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 Expand Up @@ -62,3 +67,8 @@ GITDB_SYNC_POLL_SECONDS=60

# Pepper used to hash user passwords and sign sessions
GITDB_ENCRYPTION_KEY="development"

# How long the organization events page (/org/<org>/settings/events) keeps events and their
# acknowledgements, e.g. 30d, 12h, 45m (a bare number means seconds). Default: 7d.
# Events live in memory: a restart clears them and each replica keeps its own list.
# GITOPS_EVENTS_EXPIRATION=7d
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Changelog

## 1.3.6 — 2026-11-20

- Gestión de alertas con condiciones configurables y destinatarios.
- Motor de alertas por email con plantillas y cola con reintentos.
- Registro de eventos de organización y proyecto con reconocimiento.
- Mejoras de acceso y compatibilidad con Google SSO.
115 changes: 107 additions & 8 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data
`*.data.ts`) for configuration constants: role permissions, default project settings, risk weights,
and tool policy mappings.

Current modules include `auth`, `config`, `organization`, `projects`, `storage`, and
`code-report`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
Current modules include `auth`, `config`, `organization`, `projects`, `storage`,
`code-report`, `vault`, `audit`, and `alerts`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
their `index.ts`, not internal layers.

GitDB is the single source of truth. Users, roles, API keys, organizations, projects, storage
Expand All @@ -119,6 +119,105 @@ Bitbucket, and GitLab; in production, ensure SSH authentication credentials are
SvelteKit's CSRF Origin check depends on this value instead of deriving it from the incoming Host
header, preventing bypasses when running behind a proxy that rewrites Host headers.

## Domain events

Services announce what happened on an in-process event bus in `#lib/server/events`; the design is
in `docs/adr/0001-event-bus-and-alerts.md`.

- Names: `<module>.<resource>.<action>`, snake_case, past participle
(`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). Declare each type
and its payload in `DomainEventMap` (`src/lib/events/domain-events.ts`, shared with the client).
- Every event needs an `EventDefinition` in the catalog (`src/lib/events/catalog/`, one
`<module>.events.ts` per module): scope, `readPermission`, `alertable` and its filterable fields.
`EVENT_CATALOG` is exhaustive and field keys without `derive` are checked against the payload at
compile time. Labels are i18n keys (`events.<type>.label`, `.description`,
`.fields.<key>`, `events.options.<group>.<value>`) and must exist in `es.json` and `en.json`
(enforced by a test).
- Publish only **after** the GitDB write succeeded, with the right `scope`
(`organizationId` / `projectId`). `publish()` returns immediately; handlers run asynchronously,
in order per subscriber, and a failing handler is only logged. Use `publishAfterWrite`
(`#lib/server/events/publish`) so resolving the scope or publishing can never fail a write that
already succeeded; `resolveProjectScope` adds the organization to project events.
- Delivery is at-most-once and per process; events are not persisted.
- The actor comes from the request context (`userId` / `apiKeyId` set in `hooks.server.ts`),
falling back to `system`.
- Inject `EventBus` through the service constructor from the module's `index.ts`; only composition
roots import the `eventBus` singleton. In unit tests use `RecordingEventBus` from
`#lib/server/events/testing`.
- Payloads **never** contain secrets (vault values, invitation/reset tokens or URLs, hashes, API
keys), and alert recipients are always filtered with `cancanService`.
- `eventLog` (`#lib/server/events`) keeps recent events in memory for
`/org/<org>/settings/events`, where users with `organization:events:read` see the events they
are allowed to read (each definition's `readPermission`, checked in the event's project or
organization) and, with `organization:events:update`, acknowledge them. Only the default
Organization Admin role gets `organization:events:all`; existing roles are not migrated (enable
it from the role editor). Retention: `GITOPS_EVENTS_EXPIRATION` (default `7d`). It is per
process and cleared on restart.

## Alerts

`$modules/alerts` turns domain events into emails.

- `AlertEntity` (GitDB `alerts`): an alert watches one `eventType` from an organization
(`scope: 'organization'`, covers every project of it) or a project. `conditions`
(`{ field, operator, value }`) use the catalog fields, combined with `match: 'all' | 'any'`; an
empty list always matches. Organization alerts on project events also get a `projectId` field
(`listAlertFields`, value taken from the event scope).
- `AlertService` validates every write against the catalog and the location and throws
`AlertValidationError` with field-level codes (`conditions.0.operator: 'invalid_operator'`):
alertable event compatible with the scope, operators of the field, typed values, references and
recipients (users, roles) inside the location, and **anti-escalation** (the author must hold the
event's `readPermission`).
- `AlertEngine` subscribes to `'*'` once per process (`registerAlertEngine()` in `hooks.server.ts`,
HMR-safe). Per event: fixed system notifications first (`system-notifications.data.ts`: access
granted/updated/revoked to the affected user, new personal API keys to their owner, never to the
actor, invitations skipped), then the enabled alerts of that type (cached 60 s, invalidated by
the service) whose location covers the event and whose conditions match. A per-alert in-memory
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`); 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`
(dry runs: never send, never touch the throttle). Project API keys only reach their project.

- UI: `/org/<org>/settings/alerts` and `/org/<org>/projects/<slug>/settings/alerts` (list, `new`,
`[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`,
`test`, `toggle`, `delete`; everything works without JavaScript). Components live in
`#lib/components/alerts/`: `ConditionBuilder` renders fields, operators and inputs only from the
`CatalogEntry` it receives (tested with `svelte/server` in `ConditionBuilder.test.ts`; Vitest
compiles `.svelte` through `vitest.config.ts`). Project pages also list the inherited
organization alerts, read-only. Error codes map to `alerts.errors.<code>`.

Making an event alertable:

1. Declare the payload in `DomainEventMap` and publish it with `publishAfterWrite` and the right
scope.
2. Add its `EventDefinition` with `alertable: true`, the correct `scope` and `readPermission`, and
the fields people will filter on (`reference` fields need a case in `PlatformDirectory`).
3. Add the `events.<type>.*` translations in `es.json` and `en.json`.
4. Nothing else: the catalog endpoint, the validation, the engine and the UI pick it up.

## Authorization

Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts`
Expand Down Expand Up @@ -158,8 +257,8 @@ return { roles, canCreate };

The root layout (`+layout.server.ts`) calculates granular read permissions for each settings section and
passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions:
- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`
- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`

This ensures the UI only displays navigation items for sections the user has permission to view.

Expand All @@ -168,11 +267,11 @@ Permissions always include their scope as a prefix (e.g., `organization:projects
`project:vault:secrets:all`) and are stored verbatim—there is no scope-stripping transformation:
- **GitOps Admin** (`cluster-admin`) — grants vault, openreport, stateiac full access
- **GitOps User** (`cluster-user`) — no inherent permissions; base role for system-level access
- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit
- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts
- **Organization Developer** — read/create/update projects only
- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access
- **Project Viewer** — read-only: project metadata, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access; reads alerts
- **Project Viewer** — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history

Module resources have granular sub-permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. These allow fine-grained access control within each module.

Expand Down
70 changes: 70 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ operational data versioned and auditable in Git.
- Cluster-wide Google sign-in (OpenID Connect) alongside local email and password login.
- Security reporting for vulnerabilities, SBOMs, secrets, licenses, and services.
- Pulumi state, history, and lock visibility for S3 and Google Cloud Storage backends.
- Email alerts on platform events (security analyses, vault, projects, access), with filters
built from an event catalog.
- Git-backed, auditable application data through GitDB.

## Get started
Expand Down Expand Up @@ -119,6 +121,74 @@ automatically, because the domain is checked against the Workspace `hd` claim, n
address. If the variables are inconsistent (only one credential set, an invalid domain, or
automatic sign-up without domains), the Google button is hidden and the reason is logged.

### Alerts

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. 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*.

1. Open the project's **Settings → Alerts** and click **Create alert**.
2. Event: **Analysis completed** (`code_report.analysis.completed`).
3. Conditions, matching **all**: **Service** *is* `api-gateway`, and **Critical 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**.

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

```bash
curl -X POST "$ORIGIN/api/alerts" \
-H "Authorization: Bearer $GITOPS_API_KEY" -H "Content-Type: application/json" \
-d '{
"projectId": "<project id>",
"name": "Critical vulnerabilities in api-gateway",
"eventType": "code_report.analysis.completed",
"match": "all",
"conditions": [
{ "field": "serviceId", "operator": "eq", "value": "<service id>" },
{ "field": "summary.critical", "operator": "gt", "value": 0 }
],
"recipients": { "roleIds": ["<project-admin role id>"] },
"throttleMinutes": 30
}'
```

`GET /api/events/catalog?scope=project&projectId=<id>` lists the events you may alert on and their
fields. Only recipients allowed to view the event get the email, and you can only create alerts on
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'
Loading
Loading