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
54 changes: 46 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 Down Expand Up @@ -154,6 +154,44 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
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`, texts under
`alerts.email.*`, base locale); a failed email only affects that recipient.
- 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.

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 and the engine pick it up.

## Authorization

Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts`
Expand Down Expand Up @@ -193,8 +231,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`, `organization:events: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 @@ -203,11 +241,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, events
- **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
3 changes: 3 additions & 0 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { sequence } from '@sveltejs/kit/hooks';
import { apiKeysService, authService, cancanService, ensureAuthReady } from '#modules/auth';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import { registerAlertEngine } from '#modules/alerts';
import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstrap';
import { startGitDb } from '#lib/server/gitdb';
import { markServerFailed, markServerReady } from '#lib/server/server-ready';
Expand All @@ -15,6 +16,8 @@ const startupLog = createLogger('startup');
const serverReady = (async () => {
await startGitDb();
await ensureAuthReady();
// once per process (HMR-safe): system notifications and alerts on every published event
registerAlertEngine();
await refreshBootstrapState();
markServerReady();
})();
Expand Down
10 changes: 10 additions & 0 deletions src/lib/config/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ const permissions = {
resource: 'events',
permissions: grantsFor('organization', 'events'),
},
// alerts of the organization (/org/<org>/settings/alerts), they cover all its projects
alerts: {
resource: 'alerts',
permissions: grantsFor('organization', 'alerts'),
},
},
},
project: {
Expand All @@ -86,6 +91,11 @@ const permissions = {
resource: 'audit',
permissions: grantsFor('project', 'audit'),
},
// alerts of one project (/org/<org>/projects/<slug>/settings/alerts)
alerts: {
resource: 'alerts',
permissions: grantsFor('project', 'alerts'),
},
modules: {
resource: 'modules',
sections: {
Expand Down
40 changes: 39 additions & 1 deletion src/lib/database/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
import { bool, defineRelations, entity, integer, json, text, timestamp, uuid } from '@getgitops/gitdb';
import {
bool,
defineRelations,
entity,
integer,
json,
text,
timestamp,
uuid,
} from '@getgitops/gitdb';

export const UserEntity = entity('users', {
id: uuid().primaryKey(),
Expand Down Expand Up @@ -268,6 +277,35 @@ export const VaultSettingsEntity = entity('vault_settings', {
.$defaultFn(() => new Date().toISOString()),
});

// alert on one event type (#79): `projectId` is null for organization alerts, which cover every
// project of the organization; `conditions` filter on catalog fields (`#lib/events/catalog`)
export const AlertEntity = entity('alerts', {
id: uuid().primaryKey(),
name: text().notNull(),
description: text(),
enabled: bool().notNull().default(true),
scope: text().notNull(),
organizationId: uuid().notNull(),
projectId: uuid().$defaultFn(() => null),
eventType: text().notNull(),
match: text().notNull().default('all'),
conditions: json()
.notNull()
.$defaultFn(() => []),
recipients: json().notNull(),
channels: json()
.notNull()
.$defaultFn(() => ['mail']),
throttleMinutes: integer().notNull().default(0),
createdByUserId: uuid().notNull(),
createdAt: timestamp()
.notNull()
.$defaultFn(() => 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'] }),
Expand Down
44 changes: 44 additions & 0 deletions src/lib/events/catalog/alert-fields.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import type { EventType } from '../domain-events';
import { OPERATORS } from './fields';
import type { EventDefinition, EventDefinitionScope, EventFieldDefinition } from './types';

/**
* Field an organization alert uses to narrow a project event to some projects. Its value comes
* from the event scope (`scope.projectId`), not from the payload.
*/
export const PROJECT_SCOPE_FIELD = {
key: 'projectId',
label: 'events.scopeFields.projectId',
type: 'reference',
reference: 'project',
operators: OPERATORS.reference,
// never called: the evaluator reads `scope.projectId` for this field (see `isScopeField`)
derive: () => undefined,
} as const satisfies EventFieldDefinition;

/**
* Fields an alert of `alertScope` can filter `definition` by: the catalog fields plus, for an
* organization alert on a project event, the project the event happened in.
*/
export function listAlertFields(
definition: EventDefinition,
alertScope: EventDefinitionScope,
): readonly EventFieldDefinition[] {
const fields = definition.fields as readonly EventFieldDefinition[];
const ownsProjectId = fields.some((field) => field.key === PROJECT_SCOPE_FIELD.key);
if (alertScope === 'organization' && definition.scope === 'project' && !ownsProjectId) {
return [...fields, PROJECT_SCOPE_FIELD as EventFieldDefinition];
}
return fields;
}

/** Whether `field` reads its value from the event scope rather than the payload. */
export function isScopeField(field: EventFieldDefinition): boolean {
return field === (PROJECT_SCOPE_FIELD as EventFieldDefinition);
}

export type AlertableEventInput = {
type: EventType;
payload: unknown;
scope?: { organizationId?: string | null; projectId?: string | null };
};
6 changes: 6 additions & 0 deletions src/lib/events/catalog/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export { VAULT_SECRET_CHANGED_FIELDS } from './vault.events';
export { PROJECT_CHANGED_FIELDS } from './projects.events';
export { ORGANIZATION_CHANGED_FIELDS } from './organization.events';
export { ACCESS_SCOPES } from './access.events';
export {
PROJECT_SCOPE_FIELD,
isScopeField,
listAlertFields,
type AlertableEventInput,
} from './alert-fields';

/**
* Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a
Expand Down
33 changes: 33 additions & 0 deletions src/lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1271,6 +1271,39 @@
"name": "Name"
}
}
},
"scopeFields": {
"projectId": "Project"
}
},
"alerts": {
"email": {
"alertSubject": "[GitOps] {alert}: {event}",
"alertIntro": "The alert “{alert}” was triggered by this event.",
"event": "Event",
"occurredAt": "Date",
"suppressed": "{count} more matching events were skipped during the previous window.",
"footer": "You receive this email because you are a recipient of this alert and can view this event.",
"systemFooter": "GitOps sends this notice automatically and it cannot be turned off.",
"system": {
"projectTarget": "the project {project} ({organization})",
"access_granted": {
"subject": "You now have access to {target}",
"body": "You have been given access to {target} with the role {role}."
},
"access_updated": {
"subject": "Your role in {target} has changed",
"body": "Your role in {target} is now {role}."
},
"access_revoked": {
"subject": "You no longer have access to {target}",
"body": "You no longer have access to {target}."
},
"api_key_created": {
"subject": "A personal API key was created",
"body": "The personal API key “{name}” ({prefix}…) was created on your account. If it wasn’t you, revoke it from your profile."
}
}
}
}
}
33 changes: 33 additions & 0 deletions src/lib/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -1271,6 +1271,39 @@
"name": "Nombre"
}
}
},
"scopeFields": {
"projectId": "Proyecto"
}
},
"alerts": {
"email": {
"alertSubject": "[GitOps] {alert}: {event}",
"alertIntro": "La alerta «{alert}» se ha disparado con este evento.",
"event": "Evento",
"occurredAt": "Fecha",
"suppressed": "Además, se omitieron {count} eventos que coincidían con la alerta durante la ventana anterior.",
"footer": "Recibes este email porque eres destinatario de esta alerta y tienes permiso para ver este evento.",
"systemFooter": "Este aviso lo envía GitOps automáticamente y no se puede desactivar.",
"system": {
"projectTarget": "el proyecto {project} ({organization})",
"access_granted": {
"subject": "Tienes acceso a {target}",
"body": "Te han dado acceso a {target} con el rol {role}."
},
"access_updated": {
"subject": "Tu rol en {target} ha cambiado",
"body": "Tu rol en {target} ha cambiado a {role}."
},
"access_revoked": {
"subject": "Ya no tienes acceso a {target}",
"body": "Ya no tienes acceso a {target}."
},
"api_key_created": {
"subject": "Se ha creado una API key personal",
"body": "Se ha creado la API key personal «{name}» ({prefix}…) en tu cuenta. Si no has sido tú, revócala desde tu perfil."
}
}
}
}
}
Loading
Loading