From efa27577eae5c4c5d0f78d3cf8e646d71b48c0ed Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 13:57:36 +0100 Subject: [PATCH 01/13] feat(events): ADR and in-process EventBus (#77) - docs/adr/0001: event naming, delivery semantics, persistence, actor and security rules - #lib/server/events: typed InProcessEventBus (async, per-subscriber ordering, isolated handlers, drain), RecordingEventBus for tests, HMR-safe singleton - request context carries userId / apiKeyId so events resolve their actor - CLAUDE.md: Domain events section Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 20 ++ docs/adr/0001-event-bus-and-alerts.md | 122 ++++++++++ src/hooks.server.ts | 8 +- src/lib/server/events/event-bus.test.ts | 285 ++++++++++++++++++++++++ src/lib/server/events/event-bus.ts | 153 +++++++++++++ src/lib/server/events/index.ts | 19 ++ src/lib/server/events/testing.ts | 51 +++++ src/lib/server/events/types.ts | 64 ++++++ src/lib/server/gitdb/index.ts | 3 +- src/lib/server/request-context.ts | 13 +- 10 files changed, 735 insertions(+), 3 deletions(-) create mode 100644 docs/adr/0001-event-bus-and-alerts.md create mode 100644 src/lib/server/events/event-bus.test.ts create mode 100644 src/lib/server/events/event-bus.ts create mode 100644 src/lib/server/events/index.ts create mode 100644 src/lib/server/events/testing.ts create mode 100644 src/lib/server/events/types.ts diff --git a/CLAUDE.md b/CLAUDE.md index db87a1fc..9e3c05a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,6 +119,26 @@ 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: `..`, snake_case, past participle + (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). Declare each type + and its payload in `DomainEventMap` (`src/lib/server/events/types.ts`). +- 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. +- 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`. + ## Authorization Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts` diff --git a/docs/adr/0001-event-bus-and-alerts.md b/docs/adr/0001-event-bus-and-alerts.md new file mode 100644 index 00000000..e828be73 --- /dev/null +++ b/docs/adr/0001-event-bus-and-alerts.md @@ -0,0 +1,122 @@ +# ADR 0001: Local domain event bus and configurable alerts + +- Status: Proposed +- Date: 2026-11-20 +- Issues: #76 (epic), #77 (this ADR and the `EventBus` class) + +## Context + +Notifications are direct calls from services to concrete notifiers (`InvitationNotifier`, +`PasswordResetNotifier`). To let organization and project admins create **configurable alerts** +("when `code_report.analysis.completed` happens for service `api-gateway` with critical +vulnerabilities, email these users or roles"), services need to announce what happened without +knowing who listens. + +Constraints: GitDB is the only persistence layer, the app runs as a single SvelteKit process per +replica, and we do not want to operate a broker (Redis, Kafka, a queue) for this. + +## Decision + +Services publish **typed domain events** on an **in-process event bus** +(`#lib/server/events`). An alert engine (#79) subscribes to every event, matches the alerts +configured for the event's scope and notifies recipients by email. + +``` +Service ──publish(type, payload)──▶ EventBus (in-process) ──▶ AlertEngine ('*') ──▶ notify(Mail) +``` + +### 1. Event names + +`..` in **snake_case**, the action as a **past participle**. The +resource may be omitted when the module is the resource. + +- `code_report.analysis.completed`, `code_report.analysis.failed`, `code_report.policy.violated` +- `vault.secret.created`, `vault.env.imported` +- `project.created`, `access.granted`, `api_key.revoked` + +Each type and its payload is declared in `DomainEventMap` (`src/lib/server/events/types.ts`), so +`publish()` and `subscribe()` are type-checked end to end. + +### 2. Delivery semantics + +- Publish **after** the GitDB write has succeeded (after the repository `await`). A failed write + publishes nothing. +- **Asynchronous** dispatch: `publish()` builds the envelope and returns it immediately; handlers + run on later microtasks and add no latency to the request. +- **At-most-once**: events in flight when the process dies are lost. This is acceptable for + alerts and must not be relied on for anything that needs a guarantee. +- **Per process**: an event published in one replica does not reach the others. Multi-replica + delivery is out of scope for v1. +- **Ordering**: each subscriber receives events in publish order (a per-subscriber queue). A slow + subscriber does not delay other subscribers. +- **Isolation**: every handler runs in its own `try/catch`. A failure is logged through + `createLogger('events')` with the event `type` and `id`, and never reaches the publisher, other + handlers, or later events. +- `drain()` waits for pending handlers (tests, graceful shutdown). + +### 3. Persistence + +- **Alerts** are configuration and are stored in **GitDB** (auditable, consistent with the rest of + the platform). +- **Events are not persisted.** +- **Alert executions** (firing history) are **not** stored in GitDB in v1, to avoid one commit per + email sent: only logs, plus optionally an in-memory buffer of the last N firings per alert. + +### 4. Actor + +`#lib/server/request-context` (`AsyncLocalStorage`) carries the request actor. Besides the commit +identity (`name`, `email`) it now carries `userId` for sessions and `apiKeyId` / +`apiKeyProjectId` for API keys, set by `hooks.server.ts`. The bus resolves the event actor from it +without changing service signatures: + +| Request context | `event.actor` | +| ------------------------------- | ------------------------------------------ | +| `apiKeyId` set | `{ kind: 'api_key', apiKeyId, projectId }` | +| `userId` set | `{ kind: 'user', userId }` | +| none (startup, background work) | `{ kind: 'system' }` | + +Publishers may pass an explicit `actor` to override it. Only `name` and `email` reach GitDB. + +### 5. Security rules (mandatory for the whole epic) + +- Payloads **never** contain secrets: no vault values, invitation or password reset tokens or + URLs, password or token hashes, or API keys (a `keyPrefix` is fine). +- No recipient receives information about a resource they cannot read: recipients are **always** + filtered with `cancanService` against the event's read permission and scope. + +## Implementation + +``` +src/lib/server/events/ + types.ts DomainEventMap, DomainEvent, EventActor, EventScope + event-bus.ts EventBus interface + InProcessEventBus + testing.ts RecordingEventBus for service unit tests + index.ts HMR-safe `eventBus` singleton + exports + event-bus.test.ts +``` + +- The singleton lives on `globalThis` (`Symbol.for('gitops.events.bus')`) so Vite HMR does not + create a second bus with duplicated subscribers in development. +- Services receive an `EventBus` through their **constructor** from their module's `index.ts` + (composition root); only composition roots import the `eventBus` singleton. Unit tests inject a + `RecordingEventBus` and assert on `events` / `ofType()`. +- No new dependencies. + +## Consequences + +- Services stay decoupled from alerts; adding a new consumer means subscribing, not editing + services. +- Delivery is best effort. If we later need cross-replica delivery or guarantees, the + `EventBus` interface allows swapping the implementation (e.g. an outbox in GitDB or a broker) + without touching publishers. +- Every new event must respect the payload rules above and is covered by a no-leak test (#78). + +## Alternatives considered + +- **External broker (Redis pub/sub, Kafka, a queue)**: delivery across replicas and durability, + at the cost of a new piece of infrastructure to run for a feature that tolerates losses. Rejected + for v1. +- **Node `EventEmitter`**: synchronous dispatch, a throwing listener breaks the publisher, and no + typing per event. Rejected in favour of a small dedicated class. +- **Persisting events in GitDB**: one commit per event is too much write volume and noise in the + audit history. diff --git a/src/hooks.server.ts b/src/hooks.server.ts index bd988fcb..d7e9f2f9 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -118,7 +118,12 @@ const authGuard: Handle = async ({ event, resolve }) => { event.locals.apiKey = apiKey; return runWithActor( - { name: `apikey:${apiKey.name}`, email: `apikey+${apiKey.id}@gitops.local` }, + { + name: `apikey:${apiKey.name}`, + email: `apikey+${apiKey.id}@gitops.local`, + apiKeyId: apiKey.id, + apiKeyProjectId: apiKey.projectId, + }, () => resolve(event), ); } @@ -167,6 +172,7 @@ const authGuard: Handle = async ({ event, resolve }) => { const actor = { name: currentUser.username, email: currentUser.email || `${currentUser.username}@gitops.local`, + userId: currentUser.id, }; return runWithActor(actor, () => resolve(event)); }; diff --git a/src/lib/server/events/event-bus.test.ts b/src/lib/server/events/event-bus.test.ts new file mode 100644 index 00000000..ce940131 --- /dev/null +++ b/src/lib/server/events/event-bus.test.ts @@ -0,0 +1,285 @@ +import { describe, expect, it, vi } from 'vitest'; +import { runWithActor } from '#lib/server/request-context'; +import { InProcessEventBus, actorFromRequest } from './event-bus'; +import { RecordingEventBus } from './testing'; + +type TestEvents = { + 'test.item.created': { itemId: string }; + 'test.item.deleted': { itemId: string; reason: string }; +}; + +function createBus() { + const logger = { error: vi.fn() }; + const bus = new InProcessEventBus({ logger }); + return { bus, logger }; +} + +describe('InProcessEventBus', () => { + it('builds the envelope and returns it from publish', () => { + const bus = new InProcessEventBus({ + logger: { error: vi.fn() }, + now: () => new Date('2026-11-20T10:00:00.000Z'), + generateId: () => 'event-1', + }); + + const event = bus.publish( + 'test.item.created', + { itemId: 'a' }, + { scope: { organizationId: 'org-1', projectId: 'project-1' } }, + ); + + expect(event).toEqual({ + id: 'event-1', + type: 'test.item.created', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + payload: { itemId: 'a' }, + }); + }); + + it('delivers each event only to the subscribers of its type', async () => { + const { bus } = createBus(); + const created = vi.fn(); + const deleted = vi.fn(); + bus.subscribe('test.item.created', created); + bus.subscribe('test.item.deleted', deleted); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(created).toHaveBeenCalledTimes(1); + expect(created.mock.calls[0][0].payload).toEqual({ itemId: 'a' }); + expect(deleted).not.toHaveBeenCalled(); + }); + + it("delivers every event to '*' subscribers", async () => { + const { bus } = createBus(); + const all = vi.fn(); + bus.subscribe('*', all); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.deleted', { itemId: 'a', reason: 'gone' }); + await bus.drain(); + + expect(all.mock.calls.map(([event]) => event.type)).toEqual([ + 'test.item.created', + 'test.item.deleted', + ]); + }); + + it('stops delivering after unsubscribe', async () => { + const { bus } = createBus(); + const handler = vi.fn(); + const unsubscribe = bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + unsubscribe(); + bus.publish('test.item.created', { itemId: 'b' }); + await bus.drain(); + + expect(handler).toHaveBeenCalledTimes(1); + }); + + it('does not deliver events already queued when the subscriber unsubscribes', async () => { + const { bus } = createBus(); + const handler = vi.fn(); + const unsubscribe = bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + unsubscribe(); + await bus.drain(); + + expect(handler).not.toHaveBeenCalled(); + }); + + it('isolates a failing handler and logs it with the event type and id', async () => { + const { bus, logger } = createBus(); + const healthy = vi.fn(); + bus.subscribe('test.item.created', () => { + throw new Error('sync boom'); + }); + bus.subscribe('test.item.created', async () => { + throw new Error('async boom'); + }); + bus.subscribe('test.item.created', healthy); + + const event = bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(healthy).toHaveBeenCalledTimes(1); + expect(logger.error).toHaveBeenCalledTimes(2); + expect(logger.error).toHaveBeenCalledWith( + expect.objectContaining({ eventType: 'test.item.created', eventId: event.id }), + expect.any(String), + ); + }); + + it('keeps delivering later events to a subscriber whose handler failed', async () => { + const { bus } = createBus(); + const seen: string[] = []; + bus.subscribe('test.item.created', (event) => { + if (event.payload.itemId === 'a') throw new Error('boom'); + seen.push(event.payload.itemId); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.created', { itemId: 'b' }); + await bus.drain(); + + expect(seen).toEqual(['b']); + }); + + it('does not wait for handlers in publish', async () => { + const { bus } = createBus(); + let release!: () => void; + const handler = vi.fn(() => new Promise((resolve) => (release = resolve))); + bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + + // handlers are scheduled, not called inline + expect(handler).not.toHaveBeenCalled(); + + await Promise.resolve(); + await Promise.resolve(); + expect(handler).toHaveBeenCalledTimes(1); + release(); + await bus.drain(); + }); + + it('preserves publish order per subscriber even with async handlers', async () => { + const { bus } = createBus(); + const seen: string[] = []; + bus.subscribe('test.item.created', async (event) => { + // the first event takes longer: it must still be handled first + await new Promise((resolve) => setTimeout(resolve, event.payload.itemId === 'a' ? 20 : 0)); + seen.push(event.payload.itemId); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.created', { itemId: 'b' }); + bus.publish('test.item.created', { itemId: 'c' }); + await bus.drain(); + + expect(seen).toEqual(['a', 'b', 'c']); + }); + + it('does not let a slow subscriber delay the others', async () => { + const { bus } = createBus(); + let release!: () => void; + bus.subscribe('test.item.created', () => new Promise((resolve) => (release = resolve))); + const fast = vi.fn(); + bus.subscribe('test.item.created', fast); + + bus.publish('test.item.created', { itemId: 'a' }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(fast).toHaveBeenCalledTimes(1); + release(); + await bus.drain(); + }); + + it('drain waits for pending handlers, including events they publish', async () => { + const { bus } = createBus(); + const finished: string[] = []; + bus.subscribe('test.item.created', async (event) => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished.push('created'); + bus.publish('test.item.deleted', { itemId: event.payload.itemId, reason: 'cascade' }); + }); + bus.subscribe('test.item.deleted', async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished.push('deleted'); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(finished).toEqual(['created', 'deleted']); + }); + + it('drain resolves immediately with nothing pending', async () => { + const { bus } = createBus(); + await expect(bus.drain()).resolves.toBeUndefined(); + }); + + describe('actor', () => { + it('resolves a user actor from the request context', () => { + const { bus } = createBus(); + + const event = runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'user-1' }, () => + bus.publish('test.item.created', { itemId: 'a' }), + ); + + expect(event.actor).toEqual({ kind: 'user', userId: 'user-1' }); + }); + + it('resolves an API key actor from the request context', () => { + const { bus } = createBus(); + + const event = runWithActor( + { + name: 'apikey:ci', + email: 'apikey+key-1@gitops.local', + apiKeyId: 'key-1', + apiKeyProjectId: 'project-1', + }, + () => bus.publish('test.item.created', { itemId: 'a' }), + ); + + expect(event.actor).toEqual({ kind: 'api_key', apiKeyId: 'key-1', projectId: 'project-1' }); + }); + + it('falls back to the system actor outside a request', () => { + const { bus } = createBus(); + + expect(bus.publish('test.item.created', { itemId: 'a' }).actor).toEqual({ kind: 'system' }); + }); + + it('lets the publisher override the actor', () => { + const { bus } = createBus(); + + const event = runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'user-1' }, () => + bus.publish('test.item.created', { itemId: 'a' }, { actor: { kind: 'system' } }), + ); + + expect(event.actor).toEqual({ kind: 'system' }); + }); + + it('maps request actors without ids to the system actor', () => { + expect(actorFromRequest({ name: 'legacy', email: 'legacy@example.com' })).toEqual({ + kind: 'system', + }); + expect(actorFromRequest(null)).toEqual({ kind: 'system' }); + }); + }); +}); + +describe('RecordingEventBus', () => { + it('records published events in order and still notifies subscribers', async () => { + const bus = new RecordingEventBus(); + const handler = vi.fn(); + bus.subscribe('test.item.deleted', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.deleted', { itemId: 'a', reason: 'gone' }); + await bus.drain(); + + expect(bus.types()).toEqual(['test.item.created', 'test.item.deleted']); + expect(bus.ofType('test.item.deleted').map((event) => event.payload)).toEqual([ + { itemId: 'a', reason: 'gone' }, + ]); + expect(handler).toHaveBeenCalledTimes(1); + }); + + it('clears recorded events', () => { + const bus = new RecordingEventBus(); + bus.publish('test.item.created', { itemId: 'a' }); + + bus.clear(); + + expect(bus.events).toEqual([]); + }); +}); diff --git a/src/lib/server/events/event-bus.ts b/src/lib/server/events/event-bus.ts new file mode 100644 index 00000000..34d855b3 --- /dev/null +++ b/src/lib/server/events/event-bus.ts @@ -0,0 +1,153 @@ +import type { Logger } from 'pino'; +import { createLogger } from '#lib/server/logger'; +import { getCurrentActor, type RequestActor } from '#lib/server/request-context'; +import type { + AnyEventEnvelope, + DomainEventMap, + EventActor, + EventEnvelope, + EventHandler, + EventTypeOf, + PublishOptions, + Unsubscribe, +} from './types'; + +export interface EventBus { + /** + * Publishes `type` and returns its envelope immediately; handlers run asynchronously. + * Call it only after the GitDB write it describes has succeeded. + */ + publish>( + type: K, + payload: M[K], + opts?: PublishOptions, + ): EventEnvelope; + + /** Subscribes to one event type, or to every type with `'*'`. Returns the unsubscribe function. */ + subscribe>( + type: K, + handler: EventHandler>, + ): Unsubscribe; + subscribe(type: '*', handler: EventHandler>): Unsubscribe; + + /** Resolves once every handler scheduled so far (and any they schedule) has finished. */ + drain(): Promise; +} + +type Subscription = { + type: EventTypeOf | '*'; + handler: EventHandler>; + active: boolean; + /** Per-subscriber queue: keeps delivery in publish order even for async handlers. */ + tail: Promise; +}; + +export type InProcessEventBusOptions = { + logger?: Pick; + resolveActor?: () => RequestActor | null; + now?: () => Date; + generateId?: () => string; +}; + +/** Maps the request context onto an event actor; no context means a system event. */ +export function actorFromRequest(actor: RequestActor | null): EventActor { + if (actor?.apiKeyId) { + return { kind: 'api_key', apiKeyId: actor.apiKeyId, projectId: actor.apiKeyProjectId ?? null }; + } + if (actor?.userId) return { kind: 'user', userId: actor.userId }; + return { kind: 'system' }; +} + +/** + * In-process, at-most-once event bus. Events are not persisted and never leave the process. + * + * - `publish()` never waits for handlers and never throws because of them. + * - Each subscriber receives events in publish order; a slow subscriber does not delay others. + * - A failing handler is logged with the event `type` and `id` and does not affect other handlers + * or later events. + */ +export class InProcessEventBus implements EventBus { + private readonly subscriptions = new Set>(); + private readonly log: Pick; + private readonly resolveActor: () => RequestActor | null; + private readonly now: () => Date; + private readonly generateId: () => string; + + constructor(options: InProcessEventBusOptions = {}) { + this.log = options.logger ?? createLogger('events'); + this.resolveActor = options.resolveActor ?? getCurrentActor; + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + } + + publish>( + type: K, + payload: M[K], + opts: PublishOptions = {}, + ): EventEnvelope { + const event: EventEnvelope = { + id: this.generateId(), + type, + occurredAt: this.now().toISOString(), + actor: opts.actor ?? actorFromRequest(this.resolveActor()), + scope: { ...opts.scope }, + payload, + }; + + this.dispatch(event as unknown as AnyEventEnvelope); + return event; + } + + subscribe>( + type: K, + handler: EventHandler>, + ): Unsubscribe; + subscribe(type: '*', handler: EventHandler>): Unsubscribe; + subscribe( + type: EventTypeOf | '*', + handler: EventHandler> | EventHandler, + ): Unsubscribe { + const subscription: Subscription = { + type, + handler: handler as EventHandler>, + active: true, + tail: Promise.resolve(), + }; + this.subscriptions.add(subscription); + + return () => { + subscription.active = false; + this.subscriptions.delete(subscription); + }; + } + + async drain(): Promise { + // handlers may publish more events while we wait: loop until every queue is settled + for (;;) { + const tails = [...this.subscriptions].map((s) => s.tail); + await Promise.all(tails); + const settled = [...this.subscriptions].every((s, i) => s.tail === tails[i]); + if (settled && tails.length === this.subscriptions.size) return; + } + } + + private dispatch(event: AnyEventEnvelope): void { + for (const subscription of this.subscriptions) { + if (subscription.type !== '*' && subscription.type !== event.type) continue; + // `.then` defers to a microtask, so publish() returns before any handler runs + subscription.tail = subscription.tail.then(() => this.run(subscription, event)); + } + } + + private async run(subscription: Subscription, event: AnyEventEnvelope): Promise { + if (!subscription.active) return; + try { + await subscription.handler(event); + } catch (error) { + this.log.error( + { err: error, eventType: event.type, eventId: event.id, subscribedTo: subscription.type }, + `[events] handler failed for ${event.type} (${event.id})`, + ); + } + } +} diff --git a/src/lib/server/events/index.ts b/src/lib/server/events/index.ts new file mode 100644 index 00000000..7aff03b8 --- /dev/null +++ b/src/lib/server/events/index.ts @@ -0,0 +1,19 @@ +import { InProcessEventBus, type EventBus } from './event-bus'; + +export { InProcessEventBus, actorFromRequest } from './event-bus'; +export type { EventBus, InProcessEventBusOptions } from './event-bus'; +export type * from './types'; + +const GLOBAL_KEY = Symbol.for('gitops.events.bus'); + +type GlobalWithBus = typeof globalThis & { [GLOBAL_KEY]?: EventBus }; + +/** + * Process-wide event bus. Stored on `globalThis` so Vite HMR re-evaluating this module in + * development keeps the same instance instead of piling up duplicate subscribers. + * + * Services receive it through their constructor from their module's `index.ts`; only composition + * roots import this singleton. + */ +export const eventBus: EventBus = ((globalThis as GlobalWithBus)[GLOBAL_KEY] ??= + new InProcessEventBus()); diff --git a/src/lib/server/events/testing.ts b/src/lib/server/events/testing.ts new file mode 100644 index 00000000..32239f5c --- /dev/null +++ b/src/lib/server/events/testing.ts @@ -0,0 +1,51 @@ +import { InProcessEventBus, type InProcessEventBusOptions } from './event-bus'; +import type { + AnyEventEnvelope, + DomainEventMap, + EventEnvelope, + EventTypeOf, + PublishOptions, +} from './types'; + +/** + * Event bus for unit tests: records every published event so services can be asserted on what + * they emit. Subscribers still work, so it can also wire a subscriber under test. + * + * ```ts + * const events = new RecordingEventBus(); + * const service = new VaultService(repository, events); + * await service.createSecret(input); + * expect(events.ofType('vault.secret.created')).toHaveLength(1); + * ``` + */ +export class RecordingEventBus extends InProcessEventBus { + readonly events: AnyEventEnvelope[] = []; + + constructor(options: InProcessEventBusOptions = {}) { + super({ logger: { error: () => {} }, ...options }); + } + + override publish>( + type: K, + payload: M[K], + opts?: PublishOptions, + ): EventEnvelope { + const event = super.publish(type, payload, opts); + this.events.push(event as unknown as AnyEventEnvelope); + return event; + } + + /** Recorded events of one type, in publish order. */ + ofType>(type: K): EventEnvelope[] { + return this.events.filter((event) => event.type === type) as unknown as EventEnvelope[]; + } + + /** Event types recorded so far, in publish order. */ + types(): EventTypeOf[] { + return this.events.map((event) => event.type); + } + + clear(): void { + this.events.length = 0; + } +} diff --git a/src/lib/server/events/types.ts b/src/lib/server/events/types.ts new file mode 100644 index 00000000..f1168bde --- /dev/null +++ b/src/lib/server/events/types.ts @@ -0,0 +1,64 @@ +/** + * Domain event types. See `docs/adr/0001-event-bus-and-alerts.md` for the design and rules. + * + * Event names follow `..` in snake_case, with the action as a past + * participle (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). + */ + +/** Who caused the event. Resolved from the request context when the publisher does not pass one. */ +export type EventActor = + | { kind: 'user'; userId: string } + | { kind: 'api_key'; apiKeyId: string; projectId: string | null } + | { kind: 'system' }; + +/** Where the event happened; the alert engine matches alerts by this scope. */ +export type EventScope = { + organizationId?: string | null; + projectId?: string | null; +}; + +/** + * Event type → payload. Each module adds its events here (declaration merging is not used: add + * the entries directly so the whole catalog stays in one place). + * + * Payloads must never contain secrets: no vault values, invitation or reset tokens, hashes or + * API keys. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- filled in by #78 +export interface DomainEventMap {} + +/** Event names of an event map. */ +export type EventTypeOf = Extract; + +/** Envelope published on the bus for event `K` of map `M`. */ +export type EventEnvelope> = { + /** `crypto.randomUUID()` */ + id: string; + type: K; + /** ISO 8601 */ + occurredAt: string; + actor: EventActor; + scope: EventScope; + payload: M[K]; +}; + +/** Discriminated union of every envelope of map `M` (what a `'*'` subscriber receives). */ +export type AnyEventEnvelope = { + [K in EventTypeOf]: EventEnvelope; +}[EventTypeOf]; + +export type EventType = EventTypeOf; + +export type DomainEvent = EventEnvelope; + +export type AnyDomainEvent = AnyEventEnvelope; + +export type PublishOptions = { + scope?: EventScope; + /** Overrides the actor resolved from the request context (e.g. background jobs). */ + actor?: EventActor; +}; + +export type EventHandler = (event: E) => void | Promise; + +export type Unsubscribe = () => void; diff --git a/src/lib/server/gitdb/index.ts b/src/lib/server/gitdb/index.ts index c39c0233..d9f12494 100644 --- a/src/lib/server/gitdb/index.ts +++ b/src/lib/server/gitdb/index.ts @@ -97,5 +97,6 @@ export function getGitDb(): CachedGitDb { } const actor = getCurrentActor(); - return actor ? instance.as(actor) : instance; + // only the commit identity reaches GitDB; ids in the request context are for domain events + return actor ? instance.as({ name: actor.name, email: actor.email }) : instance; } diff --git a/src/lib/server/request-context.ts b/src/lib/server/request-context.ts index 3938892a..91009273 100644 --- a/src/lib/server/request-context.ts +++ b/src/lib/server/request-context.ts @@ -1,13 +1,24 @@ import { AsyncLocalStorage } from 'node:async_hooks'; export type RequestActor = { + /** Commit author name written by GitDB. */ name: string; + /** Commit author email written by GitDB. */ email: string; + /** Set when the request is authenticated with a session. */ + userId?: string; + /** Set when the request is authenticated with an `Authorization: Bearer gvs_...` API key. */ + apiKeyId?: string; + /** Project the API key is confined to (`null` for keys that are not project-scoped). */ + apiKeyProjectId?: string | null; }; const storage = new AsyncLocalStorage(); -/** Runs `fn` with `actor` available to any `getGitDb()` call made during its execution. */ +/** + * Runs `fn` with `actor` available to anything that reads the request context during its + * execution: `getGitDb()` (commit author) and the domain event bus (event actor). + */ export function runWithActor(actor: RequestActor, fn: () => T): T { return storage.run(actor, fn); } From 306fe208f3c7dc5fbb0d1fcaf36da7d817eec3be Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 14:04:47 +0100 Subject: [PATCH 02/13] feat(events): event catalog and code_report domain events (#78) - #lib/events: shared DomainEventMap payloads and typed EVENT_CATALOG (exhaustive, compile-time checked field paths, derive fields, getFieldValue / listAlertableEvents) - code_report.analysis.completed/failed, code_report.policy.violated and code_report.service.created/deleted published after the GitDB write, with project scope - es/en translations for events, fields and options, enforced by a test Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 8 +- src/lib/events/catalog/catalog.test.ts | 184 +++++++++++++ src/lib/events/catalog/code-report.events.ts | 184 +++++++++++++ src/lib/events/catalog/fields.ts | 31 +++ src/lib/events/catalog/index.ts | 85 ++++++ src/lib/events/catalog/types.ts | 92 +++++++ src/lib/events/domain-events.ts | 78 ++++++ src/lib/i18n/locales/en.json | 90 ++++++ src/lib/i18n/locales/es.json | 90 ++++++ src/lib/server/events/types.ts | 12 +- .../code-report-analysis.service.test.ts | 260 ++++++++++++++++++ .../code-report-analysis.service.ts | 130 ++++++++- .../application/code-report-events.ts | 32 +++ .../application/code-report.service.test.ts | 91 ++++++ .../application/code-report.service.ts | 24 ++ src/modules/code-report/index.ts | 3 + 16 files changed, 1382 insertions(+), 12 deletions(-) create mode 100644 src/lib/events/catalog/catalog.test.ts create mode 100644 src/lib/events/catalog/code-report.events.ts create mode 100644 src/lib/events/catalog/fields.ts create mode 100644 src/lib/events/catalog/index.ts create mode 100644 src/lib/events/catalog/types.ts create mode 100644 src/lib/events/domain-events.ts create mode 100644 src/modules/code-report/application/code-report-analysis.service.test.ts create mode 100644 src/modules/code-report/application/code-report-events.ts create mode 100644 src/modules/code-report/application/code-report.service.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 9e3c05a1..50924f21 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -126,7 +126,13 @@ in `docs/adr/0001-event-bus-and-alerts.md`. - Names: `..`, snake_case, past participle (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). Declare each type - and its payload in `DomainEventMap` (`src/lib/server/events/types.ts`). + 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 + `.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..label`, `.description`, + `.fields.`, `events.options..`) 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. diff --git a/src/lib/events/catalog/catalog.test.ts b/src/lib/events/catalog/catalog.test.ts new file mode 100644 index 00000000..4e155a94 --- /dev/null +++ b/src/lib/events/catalog/catalog.test.ts @@ -0,0 +1,184 @@ +import { describe, expect, it } from 'vitest'; +import es from '#lib/i18n/locales/es.json'; +import en from '#lib/i18n/locales/en.json'; +import type { CodeReportAnalysisCompletedPayload } from '../domain-events'; +import { + EVENT_CATALOG, + defineEventCatalog, + getEventDefinition, + getFieldValue, + isEventType, + listAlertableEvents, + type EventCatalog, + type EventDefinition, + type EventFieldDefinition, +} from './index'; + +function completedPayload( + overrides: Partial = {}, +): CodeReportAnalysisCompletedPayload { + return { + analysisId: 'analysis-1', + serviceId: 'service-1', + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc', version: null }, + summary: { critical: 2, high: 1, medium: 0, low: 0, unknown: 0, total: 3, secrets: 0 }, + policies: { status: 'compliant', totalViolations: 0, blockingFailures: 0, failedPolicyIds: [] }, + ...overrides, + }; +} + +describe('event catalog: compile-time checks', () => { + it('rejects a field key that is not a path of the payload', () => { + const valid: EventFieldDefinition = { + key: 'gitInfo.branch', + label: 'x', + type: 'string', + operators: ['eq'], + }; + // @ts-expect-error 'gitInfo.tag' is not a path of the payload (and there is no `derive`) + const invalid: EventFieldDefinition = { + key: 'gitInfo.tag', + label: 'x', + type: 'string', + operators: ['eq'], + }; + const derived: EventFieldDefinition = { + key: 'anything', + label: 'x', + type: 'boolean', + operators: ['is_true'], + derive: (payload) => payload.summary.total > 0, + }; + + expect([valid.key, invalid.key, derived.key]).toHaveLength(3); + }); + + it('requires a definition for every event of DomainEventMap', () => { + const incomplete: Partial = { ...EVENT_CATALOG }; + delete incomplete['code_report.analysis.failed']; + // @ts-expect-error 'code_report.analysis.failed' is missing + const catalog: EventCatalog = incomplete; + + expect(Object.keys(catalog)).not.toContain('code_report.analysis.failed'); + }); +}); + +describe('defineEventCatalog', () => { + it('rejects an entry whose type does not match its key', () => { + const completed = EVENT_CATALOG['code_report.analysis.completed']; + expect(() => + defineEventCatalog({ + ...EVENT_CATALOG, + 'code_report.analysis.failed': { + ...completed, + } as unknown as EventDefinition<'code_report.analysis.failed'>, + }), + ).toThrow(/declares type/); + }); + + it('rejects duplicated field keys', () => { + const failed = EVENT_CATALOG['code_report.analysis.failed']; + expect(() => + defineEventCatalog({ + ...EVENT_CATALOG, + 'code_report.analysis.failed': { ...failed, fields: [...failed.fields, failed.fields[0]] }, + }), + ).toThrow(/twice/); + }); +}); + +describe('catalog helpers', () => { + it('looks up definitions and event types', () => { + expect(getEventDefinition('code_report.analysis.completed').readPermission).toBe( + 'project:codereport:reports:read', + ); + expect(isEventType('code_report.analysis.completed')).toBe(true); + expect(isEventType('code_report.analysis.unknown')).toBe(false); + expect(isEventType('toString')).toBe(false); + }); + + it('lists alertable events filtered by scope and module', () => { + const projectEvents = listAlertableEvents({ scope: 'project', module: 'code_report' }); + + expect(projectEvents.map((definition) => definition.type)).toContain( + 'code_report.analysis.completed', + ); + expect(listAlertableEvents({ scope: 'organization', module: 'code_report' })).toEqual([]); + }); + + it('reads nested payload paths', () => { + const event = { type: 'code_report.analysis.completed' as const, payload: completedPayload() }; + + expect(getFieldValue(event, 'gitInfo.branch')).toBe('main'); + expect(getFieldValue(event, 'summary.critical')).toBe(2); + expect(getFieldValue(event, 'serviceId')).toBe('service-1'); + }); + + it('computes derived fields', () => { + const clean = completedPayload({ + summary: { critical: 0, high: 0, medium: 0, low: 0, unknown: 0, total: 0, secrets: 0 }, + }); + const violated = completedPayload({ + policies: { + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }); + const type = 'code_report.analysis.completed' as const; + + expect(getFieldValue({ type, payload: completedPayload() }, 'hasVulnerabilities')).toBe(true); + expect(getFieldValue({ type, payload: clean }, 'hasVulnerabilities')).toBe(false); + expect(getFieldValue({ type, payload: clean }, 'policiesViolated')).toBe(false); + expect(getFieldValue({ type, payload: violated }, 'policiesViolated')).toBe(true); + }); + + it('returns undefined for unknown fields and missing paths', () => { + const type = 'code_report.analysis.completed' as const; + const payload = completedPayload({ gitInfo: null as never }); + + expect(getFieldValue({ type, payload }, 'gitInfo.branch')).toBeUndefined(); + // a real payload path that is not exposed in the catalog is not filterable + expect(getFieldValue({ type, payload }, 'analysisId')).toBeUndefined(); + }); +}); + +describe('catalog translations', () => { + function lookup(messages: unknown, key: string): unknown { + // keys may contain dots both as nesting and inside event types / field paths, so walk the + // object tree trying the longest matching segment first + if (key === '') return messages; + if (messages === null || typeof messages !== 'object') return undefined; + const record = messages as Record; + const segments = key.split('.'); + for (let length = segments.length; length > 0; length -= 1) { + const head = segments.slice(0, length).join('.'); + if (head in record) { + const found = lookup(record[head], segments.slice(length).join('.')); + if (found !== undefined) return found; + } + } + return undefined; + } + + function catalogKeys(): string[] { + return (Object.values(EVENT_CATALOG) as EventDefinition[]).flatMap((definition) => [ + definition.label, + definition.description, + ...definition.fields.flatMap((field) => [ + field.label, + ...(field.options ?? []).map((option) => option.label), + ]), + ]); + } + + it.each([ + ['es', es], + ['en', en], + ])('has a %s translation for every event, field and option', (_locale, messages) => { + const missing = catalogKeys().filter((key) => typeof lookup(messages, key) !== 'string'); + expect(missing).toEqual([]); + }); +}); diff --git a/src/lib/events/catalog/code-report.events.ts b/src/lib/events/catalog/code-report.events.ts new file mode 100644 index 00000000..29dc0189 --- /dev/null +++ b/src/lib/events/catalog/code-report.events.ts @@ -0,0 +1,184 @@ +import { + SECURITY_POLICY_ENFORCEMENTS, + SECURITY_POLICY_TYPES, +} from '#lib/code-report/security-policy'; +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +/** Tools that report analyses: scanners plus the manual upload and the CI/CD API defaults. */ +export const CODE_REPORT_TOOLS = [ + 'trivy', + 'grype', + 'semgrep', + 'gitleaks', + 'trufflehog', + 'sbom', + 'syft', + 'coverage', + 'manual-upload', + 'api', +] as const; + +const READ_REPORTS = 'project:codereport:reports:read'; + +const COMPLETED = 'code_report.analysis.completed'; +const FAILED = 'code_report.analysis.failed'; +const POLICY_VIOLATED = 'code_report.policy.violated'; +const SERVICE_CREATED = 'code_report.service.created'; +const SERVICE_DELETED = 'code_report.service.deleted'; + +function serviceField(type: typeof COMPLETED | typeof FAILED | typeof POLICY_VIOLATED) { + return { + key: 'serviceId', + label: fieldLabel(type, 'serviceId'), + type: 'reference', + reference: 'code_report_service', + operators: OPERATORS.reference, + } as const; +} + +function toolField(type: typeof COMPLETED | typeof FAILED | typeof POLICY_VIOLATED) { + return { + key: 'tool', + label: fieldLabel(type, 'tool'), + type: 'enum', + options: enumOptions('tool', CODE_REPORT_TOOLS), + operators: ['eq', 'neq', 'in'], + } as const; +} + +function branchField(type: typeof COMPLETED | typeof FAILED) { + return { + key: 'gitInfo.branch', + label: fieldLabel(type, 'gitInfo.branch'), + type: 'string', + operators: OPERATORS.string, + } as const; +} + +function countField( + key: K, +) { + return { + key, + label: fieldLabel(COMPLETED, key), + type: 'number', + operators: OPERATORS.number, + } as const; +} + +export const codeReportEvents: EventDefinitions< + | typeof COMPLETED + | typeof FAILED + | typeof POLICY_VIOLATED + | typeof SERVICE_CREATED + | typeof SERVICE_DELETED +> = { + [COMPLETED]: { + ...eventText(COMPLETED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + serviceField(COMPLETED), + toolField(COMPLETED), + branchField(COMPLETED), + countField('summary.critical'), + countField('summary.high'), + countField('summary.medium'), + countField('summary.low'), + countField('summary.total'), + { + key: 'hasVulnerabilities', + label: fieldLabel(COMPLETED, 'hasVulnerabilities'), + type: 'boolean', + operators: OPERATORS.boolean, + derive: (payload) => payload.summary.total > 0, + }, + { + key: 'policiesViolated', + label: fieldLabel(COMPLETED, 'policiesViolated'), + type: 'boolean', + operators: OPERATORS.boolean, + derive: (payload) => payload.policies.status === 'violated', + }, + ], + }, + [FAILED]: { + ...eventText(FAILED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [serviceField(FAILED), toolField(FAILED), branchField(FAILED)], + }, + [POLICY_VIOLATED]: { + ...eventText(POLICY_VIOLATED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + serviceField(POLICY_VIOLATED), + { + key: 'policyId', + label: fieldLabel(POLICY_VIOLATED, 'policyId'), + type: 'reference', + reference: 'code_report_policy', + operators: OPERATORS.reference, + }, + { + key: 'policyType', + label: fieldLabel(POLICY_VIOLATED, 'policyType'), + type: 'enum', + options: enumOptions('policyType', SECURITY_POLICY_TYPES), + operators: OPERATORS.enum, + }, + { + key: 'enforcement', + label: fieldLabel(POLICY_VIOLATED, 'enforcement'), + type: 'enum', + options: enumOptions('enforcement', SECURITY_POLICY_ENFORCEMENTS), + operators: OPERATORS.enum, + }, + ], + }, + [SERVICE_CREATED]: { + ...eventText(SERVICE_CREATED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + { + key: 'name', + label: fieldLabel(SERVICE_CREATED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, + [SERVICE_DELETED]: { + ...eventText(SERVICE_DELETED), + module: 'code_report', + scope: 'project', + readPermission: READ_REPORTS, + alertable: true, + fields: [ + { + key: 'serviceId', + label: fieldLabel(SERVICE_DELETED, 'serviceId'), + type: 'reference', + reference: 'code_report_service', + operators: OPERATORS.reference, + }, + { + key: 'name', + label: fieldLabel(SERVICE_DELETED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/fields.ts b/src/lib/events/catalog/fields.ts new file mode 100644 index 00000000..1ed6d7b9 --- /dev/null +++ b/src/lib/events/catalog/fields.ts @@ -0,0 +1,31 @@ +import type { EventType } from '../domain-events'; +import type { Operator } from './types'; + +/** Operator sets offered by the alert builder, per field type. */ +export const OPERATORS = { + reference: ['eq', 'neq', 'in', 'not_in'], + enum: ['eq', 'neq', 'in', 'not_in'], + string: ['eq', 'neq', 'contains', 'starts_with'], + number: ['eq', 'gt', 'gte', 'lt', 'lte'], + boolean: ['is_true', 'is_false'], + list: ['in', 'not_in'], +} as const satisfies Record; + +/** `label` and `description` i18n keys of an event. */ +export function eventText(type: K) { + return { + type, + label: `events.${type}.label`, + description: `events.${type}.description`, + } as const; +} + +/** i18n key of a field label. */ +export function fieldLabel(type: EventType, key: string): string { + return `events.${type}.fields.${key}`; +} + +/** Enum options whose labels live under `events.options..`. */ +export function enumOptions(group: string, values: readonly string[]) { + return values.map((value) => ({ value, label: `events.options.${group}.${value}` })); +} diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts new file mode 100644 index 00000000..ec1379e1 --- /dev/null +++ b/src/lib/events/catalog/index.ts @@ -0,0 +1,85 @@ +import type { DomainEventMap, EventType } from '../domain-events'; +import { codeReportEvents } from './code-report.events'; +import type { + EventCatalog, + EventDefinition, + EventDefinitionScope, + EventFieldDefinition, + EventModule, +} from './types'; + +export type * from './types'; +export { OPERATORS } from './fields'; +export { CODE_REPORT_TOOLS } from './code-report.events'; + +/** + * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a + * definition) and checks each field `key` without `derive` against its payload. + */ +export function defineEventCatalog(catalog: C): C { + for (const [type, definition] of Object.entries(catalog) as [string, EventDefinition][]) { + if (definition.type !== type) { + throw new Error(`Event catalog entry "${type}" declares type "${definition.type}"`); + } + const keys = definition.fields.map((field) => field.key); + const duplicate = keys.find((key, index) => keys.indexOf(key) !== index); + if (duplicate) { + throw new Error(`Event "${type}" declares field "${duplicate}" twice`); + } + } + return catalog; +} + +export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ + ...codeReportEvents, +}); + +export function isEventType(value: string): value is EventType { + return Object.hasOwn(EVENT_CATALOG, value); +} + +export function getEventDefinition(type: K): EventDefinition { + return EVENT_CATALOG[type] as EventDefinition; +} + +/** Events offered in the alert builder, optionally narrowed by scope and module. */ +export function listAlertableEvents( + filter: { scope?: EventDefinitionScope; module?: EventModule } = {}, +): EventDefinition[] { + return (Object.values(EVENT_CATALOG) as EventDefinition[]).filter( + (definition) => + definition.alertable && + (!filter.scope || definition.scope === filter.scope) && + (!filter.module || definition.module === filter.module), + ); +} + +export function getFieldDefinition( + type: K, + fieldKey: string, +): EventFieldDefinition | undefined { + return getEventDefinition(type).fields.find((field) => field.key === fieldKey); +} + +/** + * Value of a catalog field for an event: `derive(payload)` for computed fields, the dotted path + * otherwise. `undefined` when the field is not in the catalog or the path is missing. + */ +export function getFieldValue( + event: { type: EventType; payload: unknown }, + fieldKey: string, +): unknown { + const field = getFieldDefinition(event.type, fieldKey) as EventFieldDefinition | undefined; + if (!field) return undefined; + if (field.derive) return field.derive(event.payload); + return readPath(event.payload, field.key as string); +} + +function readPath(source: unknown, path: string): unknown { + let current = source; + for (const segment of path.split('.')) { + if (current === null || typeof current !== 'object') return undefined; + current = (current as Record)[segment]; + } + return current; +} diff --git a/src/lib/events/catalog/types.ts b/src/lib/events/catalog/types.ts new file mode 100644 index 00000000..2ac06ff3 --- /dev/null +++ b/src/lib/events/catalog/types.ts @@ -0,0 +1,92 @@ +import type { PermissionGrant } from '#lib/permissions'; +import type { DomainEventMap, EventType } from '../domain-events'; + +export type FieldType = 'string' | 'number' | 'boolean' | 'enum' | 'date' | 'reference'; + +export type Operator = + // string, enum, reference + | 'eq' + | 'neq' + | 'in' + | 'not_in' + // string + | 'contains' + | 'starts_with' + // number, date + | 'gt' + | 'gte' + | 'lt' + | 'lte' + // boolean + | 'is_true' + | 'is_false' + | 'exists'; + +export type FieldReference = + | 'code_report_service' + | 'code_report_policy' + | 'project' + | 'user' + | 'role' + | 'vault_environment' + | 'api_key'; + +export type EventModule = 'code_report' | 'vault' | 'projects' | 'organization' | 'access'; + +export type EventDefinitionScope = 'organization' | 'project'; + +type Leaf = string | number | boolean | bigint | symbol | null | undefined | Date; + +/** + * Dotted paths to the fields of `T` (`'serviceId' | 'gitInfo' | 'gitInfo.branch' | ...`). Arrays + * are leaves (filtered with `in` / `not_in`). Limited depth keeps the type cheap. + */ +export type PayloadPath = Depth['length'] extends 4 + ? never + : T extends Leaf | readonly unknown[] + ? never + : { + [K in Extract]: NonNullable extends Leaf | readonly unknown[] + ? K + : K | `${K}.${PayloadPath, [...Depth, 1]>}`; + }[Extract]; + +type FieldCommon = { + /** i18n key, `events..fields.` */ + label: string; + type: FieldType; + /** Operators offered by the alert builder for this field. */ + operators: readonly Operator[]; + /** For `enum` fields; `label` is an i18n key. */ + options?: readonly { value: string; label: string }[]; + /** For `reference` fields: the UI lists these entities in the alert's scope; the id is stored. */ + reference?: FieldReference; +}; + +/** + * A filterable field. Without `derive`, `key` must be a path of the payload (checked at compile + * time). With `derive`, `key` is a computed name and the value comes from `derive(payload)`. + */ +export type EventFieldDefinition

= FieldCommon & + ({ key: PayloadPath

; derive?: undefined } | { key: string; derive: (payload: P) => unknown }); + +export type EventDefinition = { + type: K; + module: EventModule; + scope: EventDefinitionScope; + /** i18n key, `events..label` */ + label: string; + /** i18n key, `events..description` */ + description: string; + /** Needed to create alerts on this event and to receive them. */ + readPermission: PermissionGrant; + fields: readonly EventFieldDefinition[]; + /** `false`: internal use or system notifications only, not offered in the alert builder. */ + alertable: boolean; +}; + +/** Definitions for a subset of events (one module's file). */ +export type EventDefinitions = { [P in K]: EventDefinition

}; + +/** Every event of `DomainEventMap` must have a definition. */ +export type EventCatalog = EventDefinitions; diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts new file mode 100644 index 00000000..b5a802af --- /dev/null +++ b/src/lib/events/domain-events.ts @@ -0,0 +1,78 @@ +/** + * Domain event payloads, shared by the server (bus, services, alert engine) and the client (alert + * builder UI). Type-only: keep this file free of server imports. + * + * Rules (docs/adr/0001-event-bus-and-alerts.md): names are `..` in + * snake_case with a past participle, and payloads never contain secrets (vault values, invitation + * or reset tokens/URLs, hashes, API keys). + */ + +export type CodeReportVulnerabilityCounts = { + critical: number; + high: number; + medium: number; + low: number; + unknown: number; + total: number; + /** Secrets detected by the scan (a count, never the matches). */ + secrets: number; +}; + +export type CodeReportEventGitInfo = { + repositoryUrl: string | null; + branch: string | null; + commit: string | null; + version: string | null; +}; + +export type CodeReportPolicyStatus = 'no_policies' | 'not_applicable' | 'compliant' | 'violated'; + +export type CodeReportAnalysisCompletedPayload = { + analysisId: string; + serviceId: string; + tool: string; + gitInfo: CodeReportEventGitInfo; + /** Counts computed server-side from the stored result. */ + summary: CodeReportVulnerabilityCounts; + policies: { + status: CodeReportPolicyStatus; + totalViolations: number; + blockingFailures: number; + failedPolicyIds: string[]; + }; +}; + +export type CodeReportAnalysisFailedPayload = { + analysisId: string; + serviceId: string; + tool: string; + gitInfo: CodeReportEventGitInfo; + error: string; +}; + +export type CodeReportPolicyViolatedPayload = { + analysisId: string; + serviceId: string; + tool: string; + policyId: string; + policyName: string; + policyType: string; + enforcement: 'warn' | 'block'; + violations: number; +}; + +export type CodeReportServicePayload = { + serviceId: string; + name: string; + slug: string; +}; + +export interface DomainEventMap { + 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; + 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; + 'code_report.policy.violated': CodeReportPolicyViolatedPayload; + 'code_report.service.created': CodeReportServicePayload; + 'code_report.service.deleted': CodeReportServicePayload; +} + +export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 355f7af0..e214aabe 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -948,5 +948,95 @@ "defaultRootLabel": "Projects", "select": "Select", "notAvailable": "N/A" + }, + "events": { + "code_report": { + "analysis": { + "completed": { + "label": "Analysis completed", + "description": "A scan tool finished analyzing a service.", + "fields": { + "serviceId": "Service", + "tool": "Tool", + "gitInfo": { + "branch": "Branch" + }, + "summary": { + "critical": "Critical vulnerabilities", + "high": "High vulnerabilities", + "medium": "Medium vulnerabilities", + "low": "Low vulnerabilities", + "total": "Total vulnerabilities" + }, + "hasVulnerabilities": "Has vulnerabilities", + "policiesViolated": "Violates security policies" + } + }, + "failed": { + "label": "Analysis failed", + "description": "A scan tool could not complete the analysis of a service.", + "fields": { + "serviceId": "Service", + "tool": "Tool", + "gitInfo": { + "branch": "Branch" + } + } + } + }, + "policy": { + "violated": { + "label": "Security policy violated", + "description": "A completed analysis violates a project security policy.", + "fields": { + "serviceId": "Service", + "policyId": "Policy", + "policyType": "Policy type", + "enforcement": "Enforcement" + } + } + }, + "service": { + "created": { + "label": "Service created", + "description": "A Code Report service was created.", + "fields": { + "name": "Name" + } + }, + "deleted": { + "label": "Service deleted", + "description": "A Code Report service was deleted.", + "fields": { + "serviceId": "Service", + "name": "Name" + } + } + } + }, + "options": { + "tool": { + "trivy": "Trivy", + "grype": "Grype", + "semgrep": "Semgrep", + "gitleaks": "Gitleaks", + "trufflehog": "TruffleHog", + "sbom": "SBOM", + "syft": "Syft", + "coverage": "Coverage", + "manual-upload": "Manual upload", + "api": "API" + }, + "policyType": { + "vulnerabilities": "Vulnerabilities", + "license": "Licenses", + "code_coverage": "Code coverage", + "secrets": "Secrets" + }, + "enforcement": { + "warn": "Warning", + "block": "Blocking" + } + } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 6427c05d..c5c01478 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -948,5 +948,95 @@ "defaultRootLabel": "Proyectos", "select": "Seleccionar", "notAvailable": "N/D" + }, + "events": { + "code_report": { + "analysis": { + "completed": { + "label": "Análisis completado", + "description": "Una herramienta de análisis ha terminado de analizar un servicio.", + "fields": { + "serviceId": "Servicio", + "tool": "Herramienta", + "gitInfo": { + "branch": "Rama" + }, + "summary": { + "critical": "Vulnerabilidades críticas", + "high": "Vulnerabilidades altas", + "medium": "Vulnerabilidades medias", + "low": "Vulnerabilidades bajas", + "total": "Total de vulnerabilidades" + }, + "hasVulnerabilities": "Tiene vulnerabilidades", + "policiesViolated": "Incumple políticas de seguridad" + } + }, + "failed": { + "label": "Análisis fallido", + "description": "Una herramienta de análisis no ha podido completar el análisis de un servicio.", + "fields": { + "serviceId": "Servicio", + "tool": "Herramienta", + "gitInfo": { + "branch": "Rama" + } + } + } + }, + "policy": { + "violated": { + "label": "Política de seguridad incumplida", + "description": "Un análisis completado incumple una política de seguridad del proyecto.", + "fields": { + "serviceId": "Servicio", + "policyId": "Política", + "policyType": "Tipo de política", + "enforcement": "Aplicación" + } + } + }, + "service": { + "created": { + "label": "Servicio creado", + "description": "Se ha creado un servicio en Code Report.", + "fields": { + "name": "Nombre" + } + }, + "deleted": { + "label": "Servicio eliminado", + "description": "Se ha eliminado un servicio de Code Report.", + "fields": { + "serviceId": "Servicio", + "name": "Nombre" + } + } + } + }, + "options": { + "tool": { + "trivy": "Trivy", + "grype": "Grype", + "semgrep": "Semgrep", + "gitleaks": "Gitleaks", + "trufflehog": "TruffleHog", + "sbom": "SBOM", + "syft": "Syft", + "coverage": "Cobertura", + "manual-upload": "Subida manual", + "api": "API" + }, + "policyType": { + "vulnerabilities": "Vulnerabilidades", + "license": "Licencias", + "code_coverage": "Cobertura de código", + "secrets": "Secretos" + }, + "enforcement": { + "warn": "Aviso", + "block": "Bloqueante" + } + } } } diff --git a/src/lib/server/events/types.ts b/src/lib/server/events/types.ts index f1168bde..dc0cea70 100644 --- a/src/lib/server/events/types.ts +++ b/src/lib/server/events/types.ts @@ -1,3 +1,5 @@ +import type { DomainEventMap } from '#lib/events/domain-events'; + /** * Domain event types. See `docs/adr/0001-event-bus-and-alerts.md` for the design and rules. * @@ -18,14 +20,10 @@ export type EventScope = { }; /** - * Event type → payload. Each module adds its events here (declaration merging is not used: add - * the entries directly so the whole catalog stays in one place). - * - * Payloads must never contain secrets: no vault values, invitation or reset tokens, hashes or - * API keys. + * Event type → payload. Declared in `#lib/events/domain-events` so the alert builder UI can share + * it without importing server code. */ -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- filled in by #78 -export interface DomainEventMap {} +export type { DomainEventMap }; /** Event names of an event map. */ export type EventTypeOf = Extract; diff --git a/src/modules/code-report/application/code-report-analysis.service.test.ts b/src/modules/code-report/application/code-report-analysis.service.test.ts new file mode 100644 index 00000000..e406c6ba --- /dev/null +++ b/src/modules/code-report/application/code-report-analysis.service.test.ts @@ -0,0 +1,260 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { runWithActor } from '#lib/server/request-context'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import type { SecurityPolicy } from '#lib/code-report/security-policy'; +import { CodeReportAnalysisDomain } from '../domain/code-report-analysis.domain'; +import { CodeReportAnalysisService } from './code-report-analysis.service'; + +class FakeAnalysisRepository { + rows = new Map>(); + failUpdates = false; + + async findById(id: string) { + const row = this.rows.get(id); + return row ? new CodeReportAnalysisDomain(row) : null; + } + + async create(input: Record & { id: string }) { + this.rows.set(input.id, { ...input, createdAt: new Date(), updatedAt: new Date() }); + } + + async update(id: string, changes: Record) { + if (this.failUpdates) throw new Error('GitDB write failed'); + const defined = Object.fromEntries( + Object.entries(changes).filter(([, value]) => value !== undefined), + ); + this.rows.set(id, { ...this.rows.get(id), ...defined }); + } +} + +const SERVICE = { id: 'service-1', projectId: 'project-1', tags: [] }; + +const trivyResult = { + Results: [ + { + Target: 'package-lock.json', + Vulnerabilities: [ + { VulnerabilityID: 'CVE-1', PkgName: 'a', Severity: 'CRITICAL' }, + { VulnerabilityID: 'CVE-2', PkgName: 'b', Severity: 'HIGH' }, + { VulnerabilityID: 'CVE-3', PkgName: 'c', Severity: 'LOW' }, + ], + Secrets: [{ RuleID: 'aws-key', Match: 'AKIAIOSFODNN7EXAMPLE' }], + }, + ], +}; + +function policy(overrides: Partial = {}): SecurityPolicy { + return { + id: 'policy-1', + projectId: 'project-1', + slug: 'no-critical', + name: 'No critical', + description: null, + type: 'vulnerabilities', + enabled: true, + enforcement: 'block', + scope: { mode: 'all', services: [], tags: [] }, + rules: { + maxCritical: 0, + maxHigh: null, + maxMedium: null, + maxLow: null, + minCvssScore: null, + ignoreUnfixed: false, + maxAgeDays: null, + ignoredCves: [], + }, + createdAt: '2026-01-01', + updatedAt: '2026-01-01', + ...overrides, + }; +} + +describe('CodeReportAnalysisService events', () => { + let repository: FakeAnalysisRepository; + let events: RecordingEventBus; + let policies: SecurityPolicy[]; + let service: CodeReportAnalysisService; + + beforeEach(() => { + repository = new FakeAnalysisRepository(); + events = new RecordingEventBus(); + policies = []; + service = new CodeReportAnalysisService( + repository as never, + { findById: async (id) => (id === SERVICE.id ? SERVICE : null) }, + { listByProject: async () => policies }, + { + events, + projects: { getProject: async () => ({ organization: { id: 'org-1' } }) }, + }, + ); + }); + + it('publishes analysis.completed with server-side counts and the project scope', async () => { + const { id } = await service.startAnalysis({ + serviceId: SERVICE.id, + tool: 'trivy', + gitInfo: { branch: 'main', commit: 'abc123', commitMessage: 'fix', author: 'ana' }, + }); + + await service.completeAnalysis(id, { result: trivyResult }); + + expect(events.types()).toEqual(['code_report.analysis.completed']); + const [event] = events.ofType('code_report.analysis.completed'); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + expect(event.payload).toEqual({ + analysisId: id, + serviceId: SERVICE.id, + tool: 'trivy', + gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc123', version: null }, + summary: { critical: 1, high: 1, medium: 0, low: 1, unknown: 0, total: 3, secrets: 1 }, + policies: { + status: 'no_policies', + totalViolations: 0, + blockingFailures: 0, + failedPolicyIds: [], + }, + }); + }); + + it('publishes one policy.violated per failed policy after analysis.completed', async () => { + policies = [ + policy(), + policy({ + id: 'policy-2', + slug: 'warn-high', + name: 'Warn high', + enforcement: 'warn', + rules: { ...policy().rules, maxCritical: null, maxHigh: 0 } as SecurityPolicy['rules'], + }), + policy({ + id: 'policy-3', + slug: 'ok', + name: 'Lenient', + rules: { ...policy().rules, maxCritical: 10 } as SecurityPolicy['rules'], + }), + ]; + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + + await service.completeAnalysis(id, { result: trivyResult }); + + expect(events.types()).toEqual([ + 'code_report.analysis.completed', + 'code_report.policy.violated', + 'code_report.policy.violated', + ]); + expect(events.ofType('code_report.analysis.completed')[0].payload.policies).toEqual({ + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['policy-1', 'policy-2'], + }); + expect(events.ofType('code_report.policy.violated').map((event) => event.payload)).toEqual([ + { + analysisId: id, + serviceId: SERVICE.id, + tool: 'trivy', + policyId: 'policy-1', + policyName: 'No critical', + policyType: 'vulnerabilities', + enforcement: 'block', + violations: 1, + }, + expect.objectContaining({ policyId: 'policy-2', enforcement: 'warn', violations: 1 }), + ]); + }); + + it('publishes analysis.failed with the reason', async () => { + const { id } = await service.startAnalysis({ + serviceId: SERVICE.id, + tool: 'gitleaks', + gitInfo: { branch: 'feature/x' }, + }); + + await service.failAnalysis(id, { error: 'scanner crashed' }); + + expect(events.types()).toEqual(['code_report.analysis.failed']); + expect(events.ofType('code_report.analysis.failed')[0].payload).toEqual({ + analysisId: id, + serviceId: SERVICE.id, + tool: 'gitleaks', + gitInfo: { repositoryUrl: null, branch: 'feature/x', commit: null, version: null }, + error: 'scanner crashed', + }); + }); + + it('attributes CI/CD reports to the API key', async () => { + await runWithActor( + { + name: 'apikey:ci', + email: 'apikey+key-1@gitops.local', + apiKeyId: 'key-1', + apiKeyProjectId: 'project-1', + }, + () => + service.reportAnalysis({ serviceId: SERVICE.id, status: 'completed', result: trivyResult }), + ); + + expect(events.ofType('code_report.analysis.completed')[0].actor).toEqual({ + kind: 'api_key', + apiKeyId: 'key-1', + projectId: 'project-1', + }); + }); + + it('does not publish for in_progress reports', async () => { + await service.reportAnalysis({ serviceId: SERVICE.id, status: 'in_progress' }); + + expect(events.events).toEqual([]); + }); + + it('publishes nothing when the analysis does not exist or input is invalid', async () => { + await expect(service.completeAnalysis('missing', { result: {} })).rejects.toThrow(); + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + await expect(service.completeAnalysis(id, { result: null })).rejects.toThrow(); + await expect(service.failAnalysis(id, { error: ' ' })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); + + it('publishes nothing when the GitDB write fails', async () => { + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + repository.failUpdates = true; + + await expect(service.completeAnalysis(id, { result: trivyResult })).rejects.toThrow(); + await expect(service.failAnalysis(id, { error: 'boom' })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); + + it('never fails the request when publishing fails', async () => { + const throwing = new CodeReportAnalysisService( + repository as never, + { findById: async () => SERVICE }, + undefined, + { + events: { + publish: () => { + throw new Error('bus down'); + }, + }, + }, + ); + const { id } = await throwing.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + + await expect(throwing.completeAnalysis(id, { result: trivyResult })).resolves.toMatchObject({ + status: 'completed', + }); + }); + + it('never includes the scan result or secret matches in the payload', async () => { + const { id } = await service.startAnalysis({ serviceId: SERVICE.id, tool: 'trivy' }); + + await service.completeAnalysis(id, { result: trivyResult }); + + const serialized = JSON.stringify(events.events); + expect(serialized).not.toContain('AKIAIOSFODNN7EXAMPLE'); + expect(serialized).not.toContain('CVE-1'); + }); +}); diff --git a/src/modules/code-report/application/code-report-analysis.service.ts b/src/modules/code-report/application/code-report-analysis.service.ts index 623317c3..986f08b8 100644 --- a/src/modules/code-report/application/code-report-analysis.service.ts +++ b/src/modules/code-report/application/code-report-analysis.service.ts @@ -2,11 +2,21 @@ import crypto from 'crypto'; import { CodeReportAnalysisRepository } from '../infrastructure/repositories/code-report-analysis.repository'; import type { CodeReportAnalysisDomain } from '../domain/code-report-analysis.domain'; import type { CodeReportGitInfo } from '../domain/code-report-analysis.domain'; -import { extractSecrets, extractVulnerabilities } from '#lib/code-report/analysis-summary'; +import { + extractSecrets, + extractVulnerabilities, + summarizeAnalysisResult, +} from '#lib/code-report/analysis-summary'; import { evaluatePolicies, type PolicyComplianceReport } from '#lib/code-report/policy-evaluation'; import type { SecurityPolicy } from '#lib/code-report/security-policy'; import { TOOL_POLICY_TYPES, DEFAULT_POLICY_TYPES } from '../domain/tool-policy-types.data'; import { createLogger } from '#lib/server/logger'; +import { + eventGitInfo, + resolveProjectScope, + type CodeReportEventPublisher, + type ProjectScopeLookup, +} from './code-report-events'; const log = createLogger('code-report-analysis'); @@ -18,12 +28,24 @@ type PolicyLookup = { listByProject(projectId: string): Promise; }; +type AnalysisEventsOptions = { + events?: CodeReportEventPublisher; + projects?: ProjectScopeLookup; +}; + export class CodeReportAnalysisService { + private readonly events?: CodeReportEventPublisher; + private readonly projects?: ProjectScopeLookup; + constructor( private readonly repository: CodeReportAnalysisRepository, private readonly serviceLookup: ServiceLookup, private readonly policyLookup?: PolicyLookup, - ) {} + options: AnalysisEventsOptions = {}, + ) { + this.events = options.events; + this.projects = options.projects; + } async listByService(serviceId: string) { const analyses = await this.repository.findByServiceId(serviceId); @@ -112,18 +134,116 @@ export class CodeReportAnalysisService { throw new Error('Result is required to complete an analysis'); } + const securityPolicies = await this.evaluateSecurityPolicies( + analysis.serviceId, + analysis.tool, + input.result, + ); + const gitInfo = this.resolveGitInfo(analysis.gitInfo, input.gitInfo, input.result); + await this.repository.update(id, { status: 'completed', result: input.result, summary: input.summary, - securityPolicies: await this.evaluateSecurityPolicies(analysis.serviceId, analysis.tool, input.result), - gitInfo: this.resolveGitInfo(analysis.gitInfo, input.gitInfo, input.result), + securityPolicies, + gitInfo, error: null, }); + await this.publishCompleted( + { id, serviceId: analysis.serviceId, tool: analysis.tool }, + input.result, + gitInfo, + securityPolicies, + ); + return this.getById(id); } + // events never break the write that already succeeded: failures are only logged + private async publishCompleted( + analysis: { id: string; serviceId: string; tool: string }, + result: unknown, + gitInfo: CodeReportGitInfo | undefined, + report: PolicyComplianceReport | null, + ) { + if (!this.events) return; + try { + const scope = await this.scopeForService(analysis.serviceId); + const counts = summarizeAnalysisResult(result); + + this.events.publish( + 'code_report.analysis.completed', + { + analysisId: analysis.id, + serviceId: analysis.serviceId, + tool: analysis.tool, + gitInfo: eventGitInfo(gitInfo), + summary: { + ...counts.vulnerabilities, + total: counts.totalVulnerabilities, + secrets: counts.exposedSecrets, + }, + policies: { + status: report?.status ?? 'no_policies', + totalViolations: report?.totalViolations ?? 0, + blockingFailures: report?.blockingFailures ?? 0, + failedPolicyIds: report?.failed.map((evaluation) => evaluation.policyId) ?? [], + }, + }, + { scope }, + ); + + for (const evaluation of report?.failed ?? []) { + this.events.publish( + 'code_report.policy.violated', + { + analysisId: analysis.id, + serviceId: analysis.serviceId, + tool: analysis.tool, + policyId: evaluation.policyId, + policyName: evaluation.policyName, + policyType: evaluation.type, + enforcement: evaluation.enforcement, + violations: evaluation.violations.length, + }, + { scope }, + ); + } + } catch (error) { + log.error({ err: error, analysisId: analysis.id }, 'failed to publish analysis events'); + } + } + + private async publishFailed( + analysis: { id: string; serviceId: string; tool: string }, + gitInfo: CodeReportGitInfo | null | undefined, + error: string, + ) { + if (!this.events) return; + try { + const scope = await this.scopeForService(analysis.serviceId); + this.events.publish( + 'code_report.analysis.failed', + { + analysisId: analysis.id, + serviceId: analysis.serviceId, + tool: analysis.tool, + gitInfo: eventGitInfo(gitInfo), + error, + }, + { scope }, + ); + } catch (publishError) { + log.error({ err: publishError, analysisId: analysis.id }, 'failed to publish analysis events'); + } + } + + private async scopeForService(serviceId: string) { + const service = await this.serviceLookup.findById(serviceId); + return resolveProjectScope(service?.projectId, this.projects); + } + private resolveGitInfo( current: CodeReportGitInfo | null | undefined, incoming: CodeReportGitInfo | null | undefined, @@ -232,6 +352,8 @@ export class CodeReportAnalysisService { gitInfo: input.gitInfo, }); + await this.publishFailed(analysis, input.gitInfo ?? analysis.gitInfo, error); + return this.getById(id); } diff --git a/src/modules/code-report/application/code-report-events.ts b/src/modules/code-report/application/code-report-events.ts new file mode 100644 index 00000000..2f60b2ef --- /dev/null +++ b/src/modules/code-report/application/code-report-events.ts @@ -0,0 +1,32 @@ +import type { EventBus, EventScope } from '#lib/server/events'; +import type { CodeReportEventGitInfo } from '#lib/events/domain-events'; +import type { CodeReportGitInfo } from '../domain/code-report-analysis.domain'; + +/** What the code-report services need from the bus. */ +export type CodeReportEventPublisher = Pick; + +/** Project lookup used to add the organization to the event scope. */ +export type ProjectScopeLookup = { + getProject(id: string): Promise<{ organization?: { id: string } | null }>; +}; + +export async function resolveProjectScope( + projectId: string | null | undefined, + projects: ProjectScopeLookup | undefined, +): Promise { + if (!projectId) return { organizationId: null, projectId: null }; + const project = projects ? await projects.getProject(projectId).catch(() => null) : null; + return { organizationId: project?.organization?.id ?? null, projectId }; +} + +/** Only the identifying git fields travel in events (no commit messages or author emails). */ +export function eventGitInfo( + gitInfo: CodeReportGitInfo | null | undefined, +): CodeReportEventGitInfo { + return { + repositoryUrl: gitInfo?.repositoryUrl ?? null, + branch: gitInfo?.branch ?? null, + commit: gitInfo?.commit ?? null, + version: gitInfo?.version ?? null, + }; +} diff --git a/src/modules/code-report/application/code-report.service.test.ts b/src/modules/code-report/application/code-report.service.test.ts new file mode 100644 index 00000000..e986b2ca --- /dev/null +++ b/src/modules/code-report/application/code-report.service.test.ts @@ -0,0 +1,91 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; +import { CodeReportServiceDomain } from '../domain/code-report-service.domain'; +import { CodeReportService } from './code-report.service'; + +class FakeServiceRepository { + rows: CodeReportServiceDomain[] = []; + + async findById(id: string) { + return this.rows.find((row) => row.id === id) ?? null; + } + + async findBySlug(projectId: string, slug: string) { + return this.rows.find((row) => row.projectId === projectId && row.slug === slug) ?? null; + } + + async create(input: Record) { + this.rows.push(new CodeReportServiceDomain(input)); + } + + async deleteById(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} + +const PROJECT = { id: 'project-1', slug: 'shop', organization: { id: 'org-1' } }; + +const projectService = { + getProjectBySlug: async (slug: string) => (slug === PROJECT.slug ? PROJECT : null), + getProject: async (id: string) => { + if (id !== PROJECT.id) throw new Error('Project not found'); + return PROJECT; + }, +}; + +describe('CodeReportService events', () => { + let repository: FakeServiceRepository; + let events: RecordingEventBus; + let service: CodeReportService; + + beforeEach(() => { + repository = new FakeServiceRepository(); + events = new RecordingEventBus(); + service = new CodeReportService( + repository as never, + projectService as never, + { deleteAllByService: async () => {} }, + events, + ); + }); + + it('publishes service.created with the project scope', async () => { + const created = await service.createService({ project: 'shop', name: 'API Gateway' }); + + expect(events.types()).toEqual(['code_report.service.created']); + const [event] = events.ofType('code_report.service.created'); + expect(event.payload).toEqual({ + serviceId: created.id, + name: 'API Gateway', + slug: 'api-gateway', + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + }); + + it('publishes service.deleted after deleting', async () => { + const created = await service.createService({ project: 'shop', name: 'API Gateway' }); + events.clear(); + + await service.deleteService(created.id); + + expect(events.ofType('code_report.service.deleted').map((event) => event.payload)).toEqual([ + { serviceId: created.id, name: 'API Gateway', slug: 'api-gateway' }, + ]); + expect(events.ofType('code_report.service.deleted')[0].scope).toEqual({ + organizationId: 'org-1', + projectId: 'project-1', + }); + }); + + it('publishes nothing when creation or deletion is rejected', async () => { + await expect(service.createService({ project: 'missing', name: 'API' })).rejects.toThrow(); + await service.createService({ project: 'shop', name: 'API' }); + events.clear(); + await expect(service.createService({ project: 'shop', name: 'API' })).rejects.toThrow( + /already exists/, + ); + await expect(service.deleteService('missing')).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/code-report/application/code-report.service.ts b/src/modules/code-report/application/code-report.service.ts index 7c867e4f..49df39e2 100644 --- a/src/modules/code-report/application/code-report.service.ts +++ b/src/modules/code-report/application/code-report.service.ts @@ -2,6 +2,10 @@ import crypto from 'crypto'; import { CodeReportServiceRepository } from '../infrastructure/repositories/code-report-service.repository'; import { ProjectService } from '../../projects/application/project.service'; import { DEFAULT_RISK_WEIGHTS, type RiskWeights } from '../domain/risk-weights.data'; +import { createLogger } from '#lib/server/logger'; +import { resolveProjectScope, type CodeReportEventPublisher } from './code-report-events'; + +const log = createLogger('code-report'); export type VulnerabilityTotals = { critical: number; @@ -19,6 +23,7 @@ export class CodeReportService { private readonly repository: CodeReportServiceRepository, private readonly projectService: ProjectService, private readonly analysisCleanup?: AnalysisCleanup, + private readonly events?: CodeReportEventPublisher, ) {} async listByProject(projectId: string) { @@ -122,6 +127,12 @@ export class CodeReportService { throw new Error('Failed to create service'); } + this.events?.publish( + 'code_report.service.created', + { serviceId: created.id, name: created.name, slug: created.slug }, + { scope: { organizationId: project.organization?.id ?? null, projectId } }, + ); + return created.toJson(); } @@ -176,6 +187,19 @@ export class CodeReportService { } await this.analysisCleanup?.deleteAllByService(id); await this.repository.deleteById(id); + + if (this.events) { + try { + const scope = await resolveProjectScope(service.projectId, this.projectService); + this.events.publish( + 'code_report.service.deleted', + { serviceId: service.id, name: service.name, slug: service.slug }, + { scope }, + ); + } catch (error) { + log.error({ err: error, serviceId: id }, 'failed to publish service deleted event'); + } + } } private normalizeTags(tags?: string[]): string[] { diff --git a/src/modules/code-report/index.ts b/src/modules/code-report/index.ts index 5b129fd7..59356f9f 100644 --- a/src/modules/code-report/index.ts +++ b/src/modules/code-report/index.ts @@ -6,6 +6,7 @@ import { CodeReportServiceRepository } from './infrastructure/repositories/code- import { CodeReportAnalysisRepository } from './infrastructure/repositories/code-report-analysis.repository'; import { CodeReportSecurityPolicyRepository } from './infrastructure/repositories/code-report-security-policy.repository'; import { projectService } from '../projects'; +import { eventBus } from '#lib/server/events'; const codeReportServiceRepository = new CodeReportServiceRepository(); const codeReportAnalysisRepository = new CodeReportAnalysisRepository(); @@ -18,11 +19,13 @@ export const codeReportAnalysisService = new CodeReportAnalysisService( codeReportAnalysisRepository, codeReportServiceRepository, codeReportSecurityPolicyService, + { events: eventBus, projects: projectService }, ); export const codeReportService = new CodeReportService( codeReportServiceRepository, projectService, codeReportAnalysisService, + eventBus, ); export const codeReportCveService = new CodeReportCveService( codeReportService, From 5dd40e5aaefc03cfcf652de25e247913365de767 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 14:15:20 +0100 Subject: [PATCH 03/13] feat(events): vault domain events (#78) - vault.secret.created/updated/deleted with key, folder and affected environment ids (never values); updated also reports changedFields - vault.env.imported once per import instead of one event per secret - vault.environment.created/deleted - shared resolveProjectScope in #lib/server/events/scope - es/en translations and no-leak tests Co-Authored-By: Claude Opus 5.5 --- src/lib/events/catalog/index.ts | 3 + src/lib/events/catalog/vault.events.ts | 135 ++++++++++++ src/lib/events/domain-events.ts | 38 ++++ src/lib/i18n/locales/en.json | 68 ++++++ src/lib/i18n/locales/es.json | 68 ++++++ src/lib/server/events/index.ts | 1 + src/lib/server/events/scope.ts | 19 ++ .../application/code-report-events.ts | 17 +- .../vault/application/vault.service.test.ts | 203 +++++++++++++++++- .../vault/application/vault.service.ts | 145 ++++++++++++- src/modules/vault/index.ts | 7 +- 11 files changed, 677 insertions(+), 27 deletions(-) create mode 100644 src/lib/events/catalog/vault.events.ts create mode 100644 src/lib/server/events/scope.ts diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts index ec1379e1..bd3a0eb7 100644 --- a/src/lib/events/catalog/index.ts +++ b/src/lib/events/catalog/index.ts @@ -1,5 +1,6 @@ import type { DomainEventMap, EventType } from '../domain-events'; import { codeReportEvents } from './code-report.events'; +import { vaultEvents } from './vault.events'; import type { EventCatalog, EventDefinition, @@ -11,6 +12,7 @@ import type { export type * from './types'; export { OPERATORS } from './fields'; export { CODE_REPORT_TOOLS } from './code-report.events'; +export { VAULT_SECRET_CHANGED_FIELDS } from './vault.events'; /** * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a @@ -32,6 +34,7 @@ export function defineEventCatalog(catalog: C): C export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ ...codeReportEvents, + ...vaultEvents, }); export function isEventType(value: string): value is EventType { diff --git a/src/lib/events/catalog/vault.events.ts b/src/lib/events/catalog/vault.events.ts new file mode 100644 index 00000000..748b4cf0 --- /dev/null +++ b/src/lib/events/catalog/vault.events.ts @@ -0,0 +1,135 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +export const VAULT_SECRET_CHANGED_FIELDS = ['key', 'description', 'folder', 'values'] as const; + +const READ_SECRETS = 'project:vault:secrets:read'; +const READ_ENVIRONMENTS = 'project:vault:environments:read'; + +const SECRET_CREATED = 'vault.secret.created'; +const SECRET_UPDATED = 'vault.secret.updated'; +const SECRET_DELETED = 'vault.secret.deleted'; +const ENV_IMPORTED = 'vault.env.imported'; +const ENVIRONMENT_CREATED = 'vault.environment.created'; +const ENVIRONMENT_DELETED = 'vault.environment.deleted'; + +type SecretEvent = typeof SECRET_CREATED | typeof SECRET_UPDATED | typeof SECRET_DELETED; +type EnvironmentEvent = typeof ENVIRONMENT_CREATED | typeof ENVIRONMENT_DELETED; + +function secretFields(type: K) { + return [ + { key: 'key', label: fieldLabel(type, 'key'), type: 'string', operators: OPERATORS.string }, + { + key: 'environmentIds', + label: fieldLabel(type, 'environmentIds'), + type: 'reference', + reference: 'vault_environment', + operators: OPERATORS.list, + }, + { + key: 'folderPath', + label: fieldLabel(type, 'folderPath'), + type: 'string', + operators: OPERATORS.string, + }, + ] as const; +} + +function environmentFields(type: K) { + return [ + { + key: 'environmentId', + label: fieldLabel(type, 'environmentId'), + type: 'reference', + reference: 'vault_environment', + operators: OPERATORS.reference, + }, + { key: 'name', label: fieldLabel(type, 'name'), type: 'string', operators: OPERATORS.string }, + ] as const; +} + +export const vaultEvents: EventDefinitions = { + [SECRET_CREATED]: { + ...eventText(SECRET_CREATED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: secretFields(SECRET_CREATED), + }, + [SECRET_UPDATED]: { + ...eventText(SECRET_UPDATED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: [ + ...secretFields(SECRET_UPDATED), + { + key: 'changedFields', + label: fieldLabel(SECRET_UPDATED, 'changedFields'), + type: 'enum', + options: enumOptions('secretChangedField', VAULT_SECRET_CHANGED_FIELDS), + operators: OPERATORS.list, + }, + ], + }, + [SECRET_DELETED]: { + ...eventText(SECRET_DELETED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: secretFields(SECRET_DELETED), + }, + [ENV_IMPORTED]: { + ...eventText(ENV_IMPORTED), + module: 'vault', + scope: 'project', + readPermission: READ_SECRETS, + alertable: true, + fields: [ + { + key: 'environmentId', + label: fieldLabel(ENV_IMPORTED, 'environmentId'), + type: 'reference', + reference: 'vault_environment', + operators: OPERATORS.reference, + }, + { + key: 'folderPath', + label: fieldLabel(ENV_IMPORTED, 'folderPath'), + type: 'string', + operators: OPERATORS.string, + }, + { + key: 'created', + label: fieldLabel(ENV_IMPORTED, 'created'), + type: 'number', + operators: OPERATORS.number, + }, + { + key: 'updated', + label: fieldLabel(ENV_IMPORTED, 'updated'), + type: 'number', + operators: OPERATORS.number, + }, + ], + }, + [ENVIRONMENT_CREATED]: { + ...eventText(ENVIRONMENT_CREATED), + module: 'vault', + scope: 'project', + readPermission: READ_ENVIRONMENTS, + alertable: true, + fields: environmentFields(ENVIRONMENT_CREATED), + }, + [ENVIRONMENT_DELETED]: { + ...eventText(ENVIRONMENT_DELETED), + module: 'vault', + scope: 'project', + readPermission: READ_ENVIRONMENTS, + alertable: true, + fields: environmentFields(ENVIRONMENT_DELETED), + }, +}; diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts index b5a802af..64321c60 100644 --- a/src/lib/events/domain-events.ts +++ b/src/lib/events/domain-events.ts @@ -67,12 +67,50 @@ export type CodeReportServicePayload = { slug: string; }; +export type VaultSecretChangedField = 'key' | 'description' | 'folder' | 'values'; + +/** Never carries secret values: only which environments hold (or changed) a value. */ +export type VaultSecretPayload = { + secretId: string; + key: string; + folderId: string | null; + /** `/` for the vault root. */ + folderPath: string; + /** Environments with a value (created/deleted) or whose value changed (updated). */ + environmentIds: string[]; +}; + +export type VaultSecretUpdatedPayload = VaultSecretPayload & { + changedFields: VaultSecretChangedField[]; +}; + +export type VaultEnvImportedPayload = { + environmentId: string; + environmentSlug: string; + folderId: string | null; + folderPath: string; + created: number; + updated: number; +}; + +export type VaultEnvironmentPayload = { + environmentId: string; + name: string; + slug: string; +}; + export interface DomainEventMap { 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; 'code_report.policy.violated': CodeReportPolicyViolatedPayload; 'code_report.service.created': CodeReportServicePayload; 'code_report.service.deleted': CodeReportServicePayload; + 'vault.secret.created': VaultSecretPayload; + 'vault.secret.updated': VaultSecretUpdatedPayload; + 'vault.secret.deleted': VaultSecretPayload; + 'vault.env.imported': VaultEnvImportedPayload; + 'vault.environment.created': VaultEnvironmentPayload; + 'vault.environment.deleted': VaultEnvironmentPayload; } export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index e214aabe..3bd53946 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1036,6 +1036,74 @@ "enforcement": { "warn": "Warning", "block": "Blocking" + }, + "secretChangedField": { + "key": "Key", + "description": "Description", + "folder": "Folder", + "values": "Values" + } + }, + "vault": { + "secret": { + "created": { + "label": "Secret created", + "description": "A secret was created in the project vault.", + "fields": { + "key": "Secret key", + "environmentIds": "Environments", + "folderPath": "Folder" + } + }, + "updated": { + "label": "Secret updated", + "description": "A secret of the project vault was modified.", + "fields": { + "key": "Secret key", + "environmentIds": "Environments", + "folderPath": "Folder", + "changedFields": "Changed fields" + } + }, + "deleted": { + "label": "Secret deleted", + "description": "A secret was deleted from the project vault.", + "fields": { + "key": "Secret key", + "environmentIds": "Environments", + "folderPath": "Folder" + } + } + }, + "env": { + "imported": { + "label": ".env file imported", + "description": "Secrets were imported from a .env file.", + "fields": { + "environmentId": "Environment", + "folderPath": "Folder", + "created": "Secrets created", + "updated": "Secrets updated" + } + } + }, + "environment": { + "created": { + "label": "Environment created", + "description": "An environment was created in the project vault.", + "fields": { + "environmentId": "Environment", + "name": "Name" + } + }, + "deleted": { + "label": "Environment deleted", + "description": "An environment was deleted from the project vault.", + "fields": { + "environmentId": "Environment", + "name": "Name" + } + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index c5c01478..a25af6a9 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1036,6 +1036,74 @@ "enforcement": { "warn": "Aviso", "block": "Bloqueante" + }, + "secretChangedField": { + "key": "Key", + "description": "Descripción", + "folder": "Carpeta", + "values": "Valores" + } + }, + "vault": { + "secret": { + "created": { + "label": "Secreto creado", + "description": "Se ha creado un secreto en el vault del proyecto.", + "fields": { + "key": "Key del secreto", + "environmentIds": "Entornos", + "folderPath": "Carpeta" + } + }, + "updated": { + "label": "Secreto actualizado", + "description": "Se ha modificado un secreto del vault del proyecto.", + "fields": { + "key": "Key del secreto", + "environmentIds": "Entornos", + "folderPath": "Carpeta", + "changedFields": "Campos modificados" + } + }, + "deleted": { + "label": "Secreto eliminado", + "description": "Se ha eliminado un secreto del vault del proyecto.", + "fields": { + "key": "Key del secreto", + "environmentIds": "Entornos", + "folderPath": "Carpeta" + } + } + }, + "env": { + "imported": { + "label": "Fichero .env importado", + "description": "Se han importado secretos desde un fichero .env.", + "fields": { + "environmentId": "Entorno", + "folderPath": "Carpeta", + "created": "Secretos creados", + "updated": "Secretos actualizados" + } + } + }, + "environment": { + "created": { + "label": "Entorno creado", + "description": "Se ha creado un entorno en el vault del proyecto.", + "fields": { + "environmentId": "Entorno", + "name": "Nombre" + } + }, + "deleted": { + "label": "Entorno eliminado", + "description": "Se ha eliminado un entorno del vault del proyecto.", + "fields": { + "environmentId": "Entorno", + "name": "Nombre" + } + } } } } diff --git a/src/lib/server/events/index.ts b/src/lib/server/events/index.ts index 7aff03b8..6e0f1c2c 100644 --- a/src/lib/server/events/index.ts +++ b/src/lib/server/events/index.ts @@ -3,6 +3,7 @@ import { InProcessEventBus, type EventBus } from './event-bus'; export { InProcessEventBus, actorFromRequest } from './event-bus'; export type { EventBus, InProcessEventBusOptions } from './event-bus'; export type * from './types'; +export { resolveProjectScope, type ProjectScopeLookup } from './scope'; const GLOBAL_KEY = Symbol.for('gitops.events.bus'); diff --git a/src/lib/server/events/scope.ts b/src/lib/server/events/scope.ts new file mode 100644 index 00000000..4fcda847 --- /dev/null +++ b/src/lib/server/events/scope.ts @@ -0,0 +1,19 @@ +import type { EventScope } from './types'; + +/** Project lookup used to add the organization to a project-scoped event. */ +export type ProjectScopeLookup = { + getProject(id: string): Promise<{ organization?: { id: string } | null }>; +}; + +/** + * Scope of an event that happened inside a project. A failed lookup only drops the organization: + * resolving the scope must never fail the write that already succeeded. + */ +export async function resolveProjectScope( + projectId: string | null | undefined, + projects: ProjectScopeLookup | undefined, +): Promise { + if (!projectId) return { organizationId: null, projectId: null }; + const project = projects ? await projects.getProject(projectId).catch(() => null) : null; + return { organizationId: project?.organization?.id ?? null, projectId }; +} diff --git a/src/modules/code-report/application/code-report-events.ts b/src/modules/code-report/application/code-report-events.ts index 2f60b2ef..19d4b282 100644 --- a/src/modules/code-report/application/code-report-events.ts +++ b/src/modules/code-report/application/code-report-events.ts @@ -1,24 +1,11 @@ -import type { EventBus, EventScope } from '#lib/server/events'; +import type { EventBus } from '#lib/server/events'; +export { resolveProjectScope, type ProjectScopeLookup } from '#lib/server/events/scope'; import type { CodeReportEventGitInfo } from '#lib/events/domain-events'; import type { CodeReportGitInfo } from '../domain/code-report-analysis.domain'; /** What the code-report services need from the bus. */ export type CodeReportEventPublisher = Pick; -/** Project lookup used to add the organization to the event scope. */ -export type ProjectScopeLookup = { - getProject(id: string): Promise<{ organization?: { id: string } | null }>; -}; - -export async function resolveProjectScope( - projectId: string | null | undefined, - projects: ProjectScopeLookup | undefined, -): Promise { - if (!projectId) return { organizationId: null, projectId: null }; - const project = projects ? await projects.getProject(projectId).catch(() => null) : null; - return { organizationId: project?.organization?.id ?? null, projectId }; -} - /** Only the identifying git fields travel in events (no commit messages or author emails). */ export function eventGitInfo( gitInfo: CodeReportGitInfo | null | undefined, diff --git a/src/modules/vault/application/vault.service.test.ts b/src/modules/vault/application/vault.service.test.ts index ec53119b..5452b60d 100644 --- a/src/modules/vault/application/vault.service.test.ts +++ b/src/modules/vault/application/vault.service.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it } from 'vitest'; +import { RecordingEventBus } from '#lib/server/events/testing'; import { VaultService } from './vault.service'; type Json = Record; @@ -20,6 +21,29 @@ class FakeVaultRepository { return found ? jsonRow(found) : null; } + failWrites = false; + + async listEnvironments(projectId: string) { + return this.environments + .filter((environment) => environment.projectId === projectId) + .map((environment) => ({ ...jsonRow(environment), order: Number(environment.order ?? 0) })); + } + + async findEnvironmentById(id: string) { + const found = this.environments.find((environment) => environment.id === id); + return found ? jsonRow(found) : null; + } + + async createEnvironment(input: Json) { + if (this.failWrites) throw new Error('GitDB write failed'); + this.environments.push(input); + } + + async deleteEnvironment(id: string) { + if (this.failWrites) throw new Error('GitDB write failed'); + this.environments = this.environments.filter((environment) => environment.id !== id); + } + async listFolders(projectId: string) { return this.folders.filter((folder) => folder.projectId === projectId).map(jsonRow); } @@ -56,15 +80,18 @@ class FakeVaultRepository { } async createSecret(input: Json) { + if (this.failWrites) throw new Error('GitDB write failed'); this.secrets.push({ ...input, folderId: input.folderId ?? null }); } async updateSecret(id: string, changes: Json) { + if (this.failWrites) throw new Error('GitDB write failed'); const secret = this.secrets.find((candidate) => candidate.id === id); if (secret) Object.assign(secret, changes); } async deleteSecret(id: string) { + if (this.failWrites) throw new Error('GitDB write failed'); this.secrets = this.secrets.filter((secret) => secret.id !== id); } @@ -155,9 +182,9 @@ describe('VaultService secrets', () => { it('rejects creating a secret in a folder from another project', async () => { repository.folders.push({ id: 'folder-1', projectId: 'other', path: '/x' }); - await expect( - service.createSecret('p1', { folderId: 'folder-1', key: 'X' }), - ).rejects.toThrow('Folder not found'); + await expect(service.createSecret('p1', { folderId: 'folder-1', key: 'X' })).rejects.toThrow( + 'Folder not found', + ); }); it('finds a secret by key', async () => { @@ -181,9 +208,9 @@ describe('VaultService secrets', () => { it('throws when updating a secret from another project', async () => { await repository.createSecret({ id: 's1', projectId: 'other', folderId: null, key: 'X' }); - await expect( - service.updateSecret('p1', 's1', { key: 'X', values: {} }), - ).rejects.toThrow('Secret not found'); + await expect(service.updateSecret('p1', 's1', { key: 'X', values: {} })).rejects.toThrow( + 'Secret not found', + ); }); it('deletes a secret', async () => { @@ -212,7 +239,11 @@ describe('VaultService secrets', () => { }); it('overrides the description when provided to setSecretValue', async () => { - await service.createSecret('p1', { key: 'zone', description: 'Region', values: { prod: 'eu' } }); + await service.createSecret('p1', { + key: 'zone', + description: 'Region', + values: { prod: 'eu' }, + }); const updated = await service.setSecretValue('p1', null, 'zone', 'prod', 'us', 'New region'); expect(updated.description).toBe('New region'); }); @@ -223,3 +254,161 @@ describe('VaultService secrets', () => { ); }); }); + +describe('VaultService events', () => { + const SECRET_VALUE = 'super-secret-value-123'; + let repository: FakeVaultRepository; + let events: RecordingEventBus; + let service: VaultService; + + beforeEach(() => { + repository = new FakeVaultRepository(); + events = new RecordingEventBus(); + service = new VaultService(repository as never, { + events, + projects: { getProject: async () => ({ organization: { id: 'org-1' } }) }, + }); + repository.environments.push( + { id: 'env-dev', projectId: 'p1', slug: 'dev', name: 'Development', order: 0 }, + { id: 'env-prod', projectId: 'p1', slug: 'prod', name: 'Production', order: 1 }, + ); + repository.folders.push({ id: 'folder-1', projectId: 'p1', path: '/database' }); + }); + + it('publishes secret.created with environments and folder, scoped to the project', async () => { + const secret = await service.createSecret('p1', { + folderId: 'folder-1', + key: 'db password', + values: { prod: SECRET_VALUE }, + }); + + expect(events.types()).toEqual(['vault.secret.created']); + const [event] = events.ofType('vault.secret.created'); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'p1' }); + expect(event.payload).toEqual({ + secretId: secret.id, + key: 'DB_PASSWORD', + folderId: 'folder-1', + folderPath: '/database', + environmentIds: ['env-prod'], + }); + }); + + it('publishes secret.updated with only the changed environments and fields', async () => { + const secret = await service.createSecret('p1', { + key: 'zone', + values: { dev: 'eu', prod: 'eu' }, + }); + events.clear(); + + await service.updateSecret('p1', secret.id, { key: 'zone', values: { dev: 'eu', prod: 'us' } }); + + expect(events.ofType('vault.secret.updated').map((event) => event.payload)).toEqual([ + { + secretId: secret.id, + key: 'ZONE', + folderId: null, + folderPath: '/', + environmentIds: ['env-prod'], + changedFields: ['values'], + }, + ]); + }); + + it('publishes secret.updated from setSecretValue and secret.deleted from deleteSecretByKey', async () => { + await service.createSecret('p1', { key: 'zone', values: { prod: 'eu' } }); + events.clear(); + + await service.setSecretValue('p1', null, 'zone', 'dev', SECRET_VALUE); + await service.deleteSecretByKey('p1', null, 'zone'); + + expect(events.types()).toEqual(['vault.secret.updated', 'vault.secret.deleted']); + expect(events.ofType('vault.secret.updated')[0].payload.environmentIds).toEqual(['env-dev']); + expect(events.ofType('vault.secret.deleted')[0].payload).toMatchObject({ + key: 'ZONE', + environmentIds: ['env-dev', 'env-prod'], + }); + }); + + it('publishes a single env.imported event for an import', async () => { + await service.createSecret('p1', { key: 'EXISTING', values: { dev: 'old' } }); + events.clear(); + + await service.importEnvFile( + 'p1', + 'dev', + null, + `EXISTING=new\nNEW_ONE=${SECRET_VALUE}\nOTHER=x`, + ); + + expect(events.types()).toEqual(['vault.env.imported']); + expect(events.ofType('vault.env.imported')[0].payload).toEqual({ + environmentId: 'env-dev', + environmentSlug: 'dev', + folderId: null, + folderPath: '/', + created: 2, + updated: 1, + }); + }); + + it('publishes environment.created and environment.deleted', async () => { + await service.createEnvironment('p1', { name: 'Stage' }); + const stage = repository.environments.find((environment) => environment.slug === 'stage')!; + await service.deleteEnvironment('p1', String(stage.id)); + + expect(events.types()).toEqual(['vault.environment.created', 'vault.environment.deleted']); + expect(events.ofType('vault.environment.created')[0].payload).toEqual({ + environmentId: stage.id, + name: 'Stage', + slug: 'stage', + }); + expect(events.ofType('vault.environment.deleted')[0].payload.environmentId).toBe(stage.id); + }); + + it('publishes nothing when the operation is rejected', async () => { + await expect(service.updateSecret('p1', 'missing', { key: 'X' })).rejects.toThrow(); + await expect(service.deleteSecret('p1', 'missing')).rejects.toThrow(); + await expect(service.createEnvironment('p1', { name: 'dev' })).rejects.toThrow(); + await expect(service.importEnvFile('p1', 'missing', null, 'A=1')).rejects.toThrow(); + await expect(service.importEnvFile('p1', 'dev', null, '# nothing')).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); + + it('publishes nothing when the GitDB write fails', async () => { + const secret = await service.createSecret('p1', { key: 'zone', values: { prod: 'eu' } }); + events.clear(); + repository.failWrites = true; + + await expect(service.createSecret('p1', { key: 'other' })).rejects.toThrow(); + await expect( + service.updateSecret('p1', secret.id, { key: 'zone', values: { prod: 'us' } }), + ).rejects.toThrow(); + await expect(service.deleteSecret('p1', secret.id)).rejects.toThrow(); + await expect(service.createEnvironment('p1', { name: 'Stage' })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); + + it('never includes secret values in any vault event', async () => { + const secret = await service.createSecret('p1', { + key: 'token', + values: { prod: SECRET_VALUE }, + }); + await service.updateSecret('p1', secret.id, { + key: 'token', + values: { prod: `${SECRET_VALUE}-rotated`, dev: SECRET_VALUE }, + }); + await service.importEnvFile('p1', 'prod', null, `IMPORTED=${SECRET_VALUE}`); + await service.deleteSecret('p1', secret.id); + + expect(events.types()).toEqual([ + 'vault.secret.created', + 'vault.secret.updated', + 'vault.env.imported', + 'vault.secret.deleted', + ]); + expect(JSON.stringify(events.events)).not.toContain(SECRET_VALUE); + }); +}); diff --git a/src/modules/vault/application/vault.service.ts b/src/modules/vault/application/vault.service.ts index e86c2d06..c7dc962b 100644 --- a/src/modules/vault/application/vault.service.ts +++ b/src/modules/vault/application/vault.service.ts @@ -1,6 +1,16 @@ import crypto from 'crypto'; import { VaultRepository } from '../infrastructure/repositories/vault.repository'; import type { VaultEncryptionProvider, VaultSecretValues } from '../domain/vault.domain'; +import type { EventBus } from '#lib/server/events'; +import { resolveProjectScope, type ProjectScopeLookup } from '#lib/server/events/scope'; +import type { + DomainEventMap, + VaultSecretChangedField, + VaultSecretPayload, +} from '#lib/events/domain-events'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('vault'); const DEFAULT_ENVIRONMENTS = [ { slug: 'dev', name: 'Development' }, @@ -19,8 +29,32 @@ export type VaultSecretInput = { values?: VaultSecretValues; }; +type VaultEventType = Extract; + +type VaultEventsOptions = { + events?: Pick; + projects?: ProjectScopeLookup; +}; + +type SecretSnapshot = { + id: string; + key: string; + folderId?: string | null; + description?: string | null; + values?: VaultSecretValues; +}; + export class VaultService { - constructor(private readonly repository: VaultRepository) {} + private readonly events?: Pick; + private readonly projects?: ProjectScopeLookup; + + constructor( + private readonly repository: VaultRepository, + options: VaultEventsOptions = {}, + ) { + this.events = options.events; + this.projects = options.projects; + } async getProjectVault(projectId: string) { await this.ensureDefaultEnvironments(projectId); @@ -67,6 +101,11 @@ export class VaultService { description: input.description?.trim() || undefined, order: nextOrder, }); + await this.emit(projectId, 'vault.environment.created', { + environmentId: id, + name, + slug, + }); return this.repository.findEnvironmentById(id); } @@ -102,6 +141,11 @@ export class VaultService { if (environments.length <= 1) throw new Error('Debe existir al menos un entorno'); await this.repository.deleteEnvironment(environment.id); + await this.emit(projectId, 'vault.environment.deleted', { + environmentId: environment.id, + name: environment.name, + slug: environment.slug, + }); } async moveEnvironment(projectId: string, id: string, direction: 'up' | 'down') { @@ -286,7 +330,8 @@ export class VaultService { continue; } - await this.createSecret(projectId, { + // one vault.env.imported event for the whole file instead of one per secret + await this.insertSecret(projectId, { folderId, key: normalizedKey, values: { [environmentSlug]: value }, @@ -294,6 +339,15 @@ export class VaultService { created += 1; } + await this.emit(projectId, 'vault.env.imported', { + environmentId: environment.id, + environmentSlug, + folderId: folderId ?? null, + folderPath: await this.folderPath(folderId), + created, + updated, + }); + return { created, updated }; } @@ -350,6 +404,16 @@ export class VaultService { } async createSecret(projectId: string, input: VaultSecretInput) { + const secret = await this.insertSecret(projectId, input); + await this.emit( + projectId, + 'vault.secret.created', + await this.secretPayload(projectId, secret, Object.keys(secret.values ?? {})), + ); + return secret; + } + + private async insertSecret(projectId: string, input: VaultSecretInput) { await this.requireOptionalProjectFolder(projectId, input.folderId); const capitalize = (await this.getSettings(projectId)).capitalizeSecrets; const key = this.normalizeSecretKey(input.key, capitalize); @@ -373,13 +437,30 @@ export class VaultService { await this.requireOptionalProjectFolder(projectId, input.folderId); const capitalize = (await this.getSettings(projectId)).capitalizeSecrets; + // copy: the stored row may be the same object the repository mutates on update + const current = secret.toJson() as SecretSnapshot; + const before: SecretSnapshot = { ...current, values: { ...current.values } }; + await this.repository.updateSecret(id, { folderId: input.folderId || null, key: this.normalizeSecretKey(input.key, capitalize), description: input.description?.trim(), values: this.normalizeValues(input.values), }); - return (await this.repository.findSecretById(id))!.toJson(); + const after = (await this.repository.findSecretById(id))!.toJson(); + + const changedValues = this.changedEnvironmentSlugs(before.values, after.values); + const changedFields: VaultSecretChangedField[] = []; + if (before.key !== after.key) changedFields.push('key'); + if ((before.description ?? '') !== (after.description ?? '')) changedFields.push('description'); + if ((before.folderId ?? null) !== (after.folderId ?? null)) changedFields.push('folder'); + if (changedValues.length > 0) changedFields.push('values'); + + await this.emit(projectId, 'vault.secret.updated', { + ...(await this.secretPayload(projectId, after, changedValues)), + changedFields, + }); + return after; } async deleteSecret(projectId: string, id: string) { @@ -387,6 +468,62 @@ export class VaultService { if (!secret || secret.projectId !== projectId) throw new Error('Secret not found'); await this.repository.deleteSecret(id); + const snapshot = secret.toJson() as SecretSnapshot; + await this.emit( + projectId, + 'vault.secret.deleted', + await this.secretPayload(projectId, snapshot, Object.keys(snapshot.values ?? {})), + ); + } + + // events never break the write that already succeeded: failures are only logged + private async emit( + projectId: string, + type: K, + payload: DomainEventMap[K], + ) { + if (!this.events) return; + try { + const scope = await resolveProjectScope(projectId, this.projects); + this.events.publish(type, payload, { scope }); + } catch (error) { + log.error({ err: error, eventType: type, projectId }, 'failed to publish vault event'); + } + } + + /** Secret metadata for events: never the values, only the environments involved. */ + private async secretPayload( + projectId: string, + secret: SecretSnapshot, + environmentSlugs: string[], + ): Promise { + const environments = await this.repository.listEnvironments(projectId).catch(() => []); + const slugs = new Set(environmentSlugs); + return { + secretId: secret.id, + key: secret.key, + folderId: secret.folderId ?? null, + folderPath: await this.folderPath(secret.folderId), + // in the vault's environment order, so payloads are deterministic + environmentIds: environments + .sort((a, b) => a.order - b.order) + .filter((environment) => slugs.has(environment.slug)) + .map((environment) => environment.id), + }; + } + + private async folderPath(folderId: string | null | undefined): Promise { + if (!folderId) return '/'; + const folder = await this.repository.findFolderById(folderId).catch(() => null); + return folder?.path ?? '/'; + } + + private changedEnvironmentSlugs( + before: VaultSecretValues | undefined, + after: VaultSecretValues | undefined, + ): string[] { + const slugs = new Set([...Object.keys(before ?? {}), ...Object.keys(after ?? {})]); + return [...slugs].filter((slug) => before?.[slug] !== after?.[slug]); } async findSecretByKey(projectId: string, folderId: string | null, key: string) { @@ -413,7 +550,7 @@ export class VaultService { return this.updateSecret(projectId, secret.id, { folderId, key, - description: description !== undefined ? description : secret.description ?? undefined, + description: description !== undefined ? description : (secret.description ?? undefined), values: { ...secret.values, [environment]: value }, }); } diff --git a/src/modules/vault/index.ts b/src/modules/vault/index.ts index 0797d4cb..d8f591f7 100644 --- a/src/modules/vault/index.ts +++ b/src/modules/vault/index.ts @@ -1,7 +1,12 @@ import { VAULT_ENCRYPTION_PROVIDERS, VaultService } from './application/vault.service'; import { VaultRepository } from './infrastructure/repositories/vault.repository'; +import { eventBus } from '#lib/server/events'; +import { projectService } from '../projects'; const vaultRepository = new VaultRepository(); -export const vaultService = new VaultService(vaultRepository); +export const vaultService = new VaultService(vaultRepository, { + events: eventBus, + projects: projectService, +}); export { VAULT_ENCRYPTION_PROVIDERS }; From 92e75895cd25777d1e0044863018fcfd5150fd8c Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 14:23:34 +0100 Subject: [PATCH 04/13] feat(events): project and organization domain events (#78) - project.created/updated/deleted scoped to the organization (alerts are set up by org admins), updated reports changedFields - organization.updated with changedFields - es/en translations and tests Co-Authored-By: Claude Opus 5.5 --- src/lib/events/catalog/index.ts | 6 ++ src/lib/events/catalog/organization.events.ts | 25 +++++ src/lib/events/catalog/projects.events.ts | 75 ++++++++++++++ src/lib/events/domain-events.ts | 26 +++++ src/lib/i18n/locales/en.json | 49 ++++++++++ src/lib/i18n/locales/es.json | 49 ++++++++++ .../application/organization.service.test.ts | 39 +++++++- .../application/organization.service.ts | 28 +++++- src/modules/organization/index.ts | 3 +- .../application/project.service.test.ts | 97 ++++++++++++++++++- .../projects/application/project.service.ts | 66 ++++++++++++- src/modules/projects/index.ts | 3 +- 12 files changed, 456 insertions(+), 10 deletions(-) create mode 100644 src/lib/events/catalog/organization.events.ts create mode 100644 src/lib/events/catalog/projects.events.ts diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts index bd3a0eb7..6cb95335 100644 --- a/src/lib/events/catalog/index.ts +++ b/src/lib/events/catalog/index.ts @@ -1,6 +1,8 @@ import type { DomainEventMap, EventType } from '../domain-events'; import { codeReportEvents } from './code-report.events'; import { vaultEvents } from './vault.events'; +import { projectEvents } from './projects.events'; +import { organizationEvents } from './organization.events'; import type { EventCatalog, EventDefinition, @@ -13,6 +15,8 @@ export type * from './types'; export { OPERATORS } from './fields'; export { CODE_REPORT_TOOLS } from './code-report.events'; export { VAULT_SECRET_CHANGED_FIELDS } from './vault.events'; +export { PROJECT_CHANGED_FIELDS } from './projects.events'; +export { ORGANIZATION_CHANGED_FIELDS } from './organization.events'; /** * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a @@ -35,6 +39,8 @@ export function defineEventCatalog(catalog: C): C export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ ...codeReportEvents, ...vaultEvents, + ...projectEvents, + ...organizationEvents, }); export function isEventType(value: string): value is EventType { diff --git a/src/lib/events/catalog/organization.events.ts b/src/lib/events/catalog/organization.events.ts new file mode 100644 index 00000000..0598aedb --- /dev/null +++ b/src/lib/events/catalog/organization.events.ts @@ -0,0 +1,25 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +export const ORGANIZATION_CHANGED_FIELDS = ['name', 'slug', 'description'] as const; + +const UPDATED = 'organization.updated'; + +export const organizationEvents: EventDefinitions = { + [UPDATED]: { + ...eventText(UPDATED), + module: 'organization', + scope: 'organization', + readPermission: 'organization:settings:read', + alertable: true, + fields: [ + { + key: 'changedFields', + label: fieldLabel(UPDATED, 'changedFields'), + type: 'enum', + options: enumOptions('organizationChangedField', ORGANIZATION_CHANGED_FIELDS), + operators: OPERATORS.list, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/projects.events.ts b/src/lib/events/catalog/projects.events.ts new file mode 100644 index 00000000..af2e0f9a --- /dev/null +++ b/src/lib/events/catalog/projects.events.ts @@ -0,0 +1,75 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +export const PROJECT_CHANGED_FIELDS = [ + 'name', + 'slug', + 'description', + 'status', + 'modules', + 'organization', + 'settings', +] as const; + +const READ_PROJECTS = 'organization:projects:read'; + +const CREATED = 'project.created'; +const UPDATED = 'project.updated'; +const DELETED = 'project.deleted'; + +function nameField(type: K) { + return { + key: 'name', + label: fieldLabel(type, 'name'), + type: 'string', + operators: OPERATORS.string, + } as const; +} + +function projectField(type: K) { + return { + key: 'projectId', + label: fieldLabel(type, 'projectId'), + type: 'reference', + reference: 'project', + operators: OPERATORS.reference, + } as const; +} + +// projects are watched from their organization: an org admin alerts on its projects +export const projectEvents: EventDefinitions = { + [CREATED]: { + ...eventText(CREATED), + module: 'projects', + scope: 'organization', + readPermission: READ_PROJECTS, + alertable: true, + fields: [nameField(CREATED)], + }, + [UPDATED]: { + ...eventText(UPDATED), + module: 'projects', + scope: 'organization', + readPermission: READ_PROJECTS, + alertable: true, + fields: [ + projectField(UPDATED), + nameField(UPDATED), + { + key: 'changedFields', + label: fieldLabel(UPDATED, 'changedFields'), + type: 'enum', + options: enumOptions('projectChangedField', PROJECT_CHANGED_FIELDS), + operators: OPERATORS.list, + }, + ], + }, + [DELETED]: { + ...eventText(DELETED), + module: 'projects', + scope: 'organization', + readPermission: READ_PROJECTS, + alertable: true, + fields: [projectField(DELETED), nameField(DELETED)], + }, +}; diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts index 64321c60..bdf762d8 100644 --- a/src/lib/events/domain-events.ts +++ b/src/lib/events/domain-events.ts @@ -99,6 +99,28 @@ export type VaultEnvironmentPayload = { slug: string; }; +export type ProjectChangedField = + 'name' | 'slug' | 'description' | 'status' | 'modules' | 'organization' | 'settings'; + +export type ProjectPayload = { + projectId: string; + name: string; + slug: string; +}; + +export type ProjectUpdatedPayload = ProjectPayload & { + changedFields: ProjectChangedField[]; +}; + +export type OrganizationChangedField = 'name' | 'slug' | 'description'; + +export type OrganizationUpdatedPayload = { + organizationId: string; + name: string; + slug: string; + changedFields: OrganizationChangedField[]; +}; + export interface DomainEventMap { 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; @@ -111,6 +133,10 @@ export interface DomainEventMap { 'vault.env.imported': VaultEnvImportedPayload; 'vault.environment.created': VaultEnvironmentPayload; 'vault.environment.deleted': VaultEnvironmentPayload; + 'project.created': ProjectPayload; + 'project.updated': ProjectUpdatedPayload; + 'project.deleted': ProjectPayload; + 'organization.updated': OrganizationUpdatedPayload; } export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 3bd53946..76dfcc59 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1042,6 +1042,20 @@ "description": "Description", "folder": "Folder", "values": "Values" + }, + "projectChangedField": { + "name": "Name", + "slug": "Slug", + "description": "Description", + "status": "Status", + "modules": "Modules", + "organization": "Organization", + "settings": "Settings" + }, + "organizationChangedField": { + "name": "Name", + "slug": "Slug", + "description": "Description" } }, "vault": { @@ -1105,6 +1119,41 @@ } } } + }, + "project": { + "created": { + "label": "Project created", + "description": "A project was created in the organization.", + "fields": { + "name": "Name" + } + }, + "updated": { + "label": "Project updated", + "description": "A project of the organization was modified.", + "fields": { + "projectId": "Project", + "name": "Name", + "changedFields": "Changed fields" + } + }, + "deleted": { + "label": "Project deleted", + "description": "A project was deleted from the organization.", + "fields": { + "projectId": "Project", + "name": "Name" + } + } + }, + "organization": { + "updated": { + "label": "Organization updated", + "description": "The organization details were modified.", + "fields": { + "changedFields": "Changed fields" + } + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index a25af6a9..5def0db7 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1042,6 +1042,20 @@ "description": "Descripción", "folder": "Carpeta", "values": "Valores" + }, + "projectChangedField": { + "name": "Nombre", + "slug": "Slug", + "description": "Descripción", + "status": "Estado", + "modules": "Módulos", + "organization": "Organización", + "settings": "Ajustes" + }, + "organizationChangedField": { + "name": "Nombre", + "slug": "Slug", + "description": "Descripción" } }, "vault": { @@ -1105,6 +1119,41 @@ } } } + }, + "project": { + "created": { + "label": "Proyecto creado", + "description": "Se ha creado un proyecto en la organización.", + "fields": { + "name": "Nombre" + } + }, + "updated": { + "label": "Proyecto actualizado", + "description": "Se ha modificado un proyecto de la organización.", + "fields": { + "projectId": "Proyecto", + "name": "Nombre", + "changedFields": "Campos modificados" + } + }, + "deleted": { + "label": "Proyecto eliminado", + "description": "Se ha eliminado un proyecto de la organización.", + "fields": { + "projectId": "Proyecto", + "name": "Nombre" + } + } + }, + "organization": { + "updated": { + "label": "Organización actualizada", + "description": "Se han modificado los datos de la organización.", + "fields": { + "changedFields": "Campos modificados" + } + } } } } diff --git a/src/modules/organization/application/organization.service.test.ts b/src/modules/organization/application/organization.service.test.ts index 2a2942d0..a4610d4c 100644 --- a/src/modules/organization/application/organization.service.test.ts +++ b/src/modules/organization/application/organization.service.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, beforeEach } from 'vitest'; import { OrganizationService } from './organization.service'; import { OrganizationDomain } from '../domain/organization.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; class FakeOrganizationRepository { rows: OrganizationDomain[] = []; @@ -84,9 +85,7 @@ describe('OrganizationService', () => { describe('createOrganization', () => { it('requires a non-empty name', async () => { - await expect(service.createOrganization({ name: ' ' })).rejects.toThrow( - /name is required/, - ); + await expect(service.createOrganization({ name: ' ' })).rejects.toThrow(/name is required/); }); it('auto-generates a normalized slug from the name when none is provided', async () => { @@ -179,3 +178,37 @@ describe('OrganizationService', () => { }); }); }); + +describe('OrganizationService events', () => { + let repository: FakeOrganizationRepository; + let events: RecordingEventBus; + let service: OrganizationService; + + beforeEach(async () => { + repository = new FakeOrganizationRepository(); + events = new RecordingEventBus(); + service = new OrganizationService(repository as any, events); + await repository.create({ id: 'org-1', slug: 'kettu', name: 'Kettu' }); + }); + + it('publishes organization.updated with the changed fields', async () => { + await service.updateOrganization('org-1', { name: 'Kettu', description: 'Software studio' }); + + expect(events.types()).toEqual(['organization.updated']); + const [event] = events.ofType('organization.updated'); + expect(event.payload).toEqual({ + organizationId: 'org-1', + name: 'Kettu', + slug: 'kettu', + changedFields: ['description'], + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: null }); + }); + + it('publishes nothing when the update is rejected', async () => { + await expect(service.updateOrganization('missing', { name: 'X' })).rejects.toThrow(); + await expect(service.updateOrganization('org-1', { name: ' ' })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/organization/application/organization.service.ts b/src/modules/organization/application/organization.service.ts index bad956bb..16809317 100644 --- a/src/modules/organization/application/organization.service.ts +++ b/src/modules/organization/application/organization.service.ts @@ -1,5 +1,10 @@ import crypto from 'crypto'; import { OrganizationRepository } from '../infrastructure/repositories/organization.repository'; +import type { EventBus } from '#lib/server/events'; +import type { OrganizationChangedField } from '#lib/events/domain-events'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('organization'); export type Organization = { id: string; @@ -11,7 +16,10 @@ export type Organization = { }; export class OrganizationService { - constructor(private readonly repository: OrganizationRepository) {} + constructor( + private readonly repository: OrganizationRepository, + private readonly events?: Pick, + ) {} async listOrganizations() { const organizations = await this.repository.findAll(); @@ -87,6 +95,7 @@ export class OrganizationService { throw new Error('Organization not found'); } + const before = { ...organization.toJson() }; const patch: { name?: string; slug?: string; description?: string } = {}; if (changes.name !== undefined) { @@ -121,7 +130,22 @@ export class OrganizationService { throw new Error('Failed to update organization'); } - return updated.toJson(); + const after = updated.toJson(); + if (this.events) { + try { + const changedFields = (['name', 'slug', 'description'] as const).filter( + (field) => (before[field] ?? '') !== (after[field] ?? ''), + ) satisfies OrganizationChangedField[]; + this.events.publish( + 'organization.updated', + { organizationId: after.id, name: after.name, slug: after.slug, changedFields }, + { scope: { organizationId: after.id, projectId: null } }, + ); + } catch (error) { + log.error({ err: error, organizationId: id }, 'failed to publish organization event'); + } + } + return after; } async deleteOrganization(id: string) { diff --git a/src/modules/organization/index.ts b/src/modules/organization/index.ts index 06b88f79..b86fae97 100644 --- a/src/modules/organization/index.ts +++ b/src/modules/organization/index.ts @@ -1,8 +1,9 @@ import { OrganizationService } from './application/organization.service'; import { OrganizationRepository } from './infrastructure/repositories/organization.repository'; +import { eventBus } from '#lib/server/events'; const organizationRepository = new OrganizationRepository(); -export const organizationService = new OrganizationService(organizationRepository); +export const organizationService = new OrganizationService(organizationRepository, eventBus); export type { Organization } from './application/organization.service'; export { OrganizationDomain } from './domain/organization.domain'; diff --git a/src/modules/projects/application/project.service.test.ts b/src/modules/projects/application/project.service.test.ts index ac0dd6a6..7fe3fd6a 100644 --- a/src/modules/projects/application/project.service.test.ts +++ b/src/modules/projects/application/project.service.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it, beforeEach } from 'vitest'; import { ProjectService } from './project.service'; import { ProjectDomain } from '../domain/project.domain'; +import { OrganizationDomain } from '../../organization/domain/organization.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; const DEFAULT_ORGANIZATION_ID = 'org-1'; @@ -64,7 +66,11 @@ class FakeProjectRepository { if (changes.status !== undefined) project.status = changes.status as 'active' | 'inactive'; if (changes.modules !== undefined) project.modules = changes.modules; if (changes.organizationId !== undefined) { - project.organization = { id: changes.organizationId, name: 'Org', slug: 'org' } as any; + project.organization = new OrganizationDomain({ + id: changes.organizationId, + name: 'Org', + slug: 'org', + }); } } @@ -257,3 +263,92 @@ describe('ProjectService', () => { }); }); }); + +describe('ProjectService events', () => { + let repository: FakeProjectRepository; + let events: RecordingEventBus; + let service: ProjectService; + + beforeEach(() => { + repository = new FakeProjectRepository(); + events = new RecordingEventBus(); + service = new ProjectService(repository as any, new FakeOrganizationLookup(), events); + }); + + it('publishes project.created scoped to its organization', async () => { + const project = await service.createProject({ + organizationId: DEFAULT_ORGANIZATION_ID, + name: 'Shop', + }); + + expect(events.types()).toEqual(['project.created']); + const [event] = events.ofType('project.created'); + expect(event.payload).toEqual({ projectId: project.id, name: 'Shop', slug: 'shop' }); + expect(event.scope).toEqual({ organizationId: DEFAULT_ORGANIZATION_ID, projectId: project.id }); + }); + + it('publishes project.updated with only the fields that changed', async () => { + const project = await service.createProject({ + organizationId: DEFAULT_ORGANIZATION_ID, + name: 'Shop', + }); + events.clear(); + + await service.updateProject(project.id, { + name: 'Shop', + description: 'Online store', + status: 'inactive', + modules: { vault: true }, + }); + + expect(events.ofType('project.updated').map((event) => event.payload)).toEqual([ + { + projectId: project.id, + name: 'Shop', + slug: 'shop', + changedFields: ['description', 'status', 'modules'], + }, + ]); + }); + + it('reports an organization move and scopes the event to the new organization', async () => { + const project = await service.createProject({ + organizationId: DEFAULT_ORGANIZATION_ID, + name: 'Shop', + }); + events.clear(); + + await service.updateProject(project.id, { organizationId: 'org-2' }); + + const [event] = events.ofType('project.updated'); + expect(event.payload.changedFields).toEqual(['organization']); + expect(event.scope.organizationId).toBe('org-2'); + }); + + it('publishes project.deleted', async () => { + const project = await service.createProject({ + organizationId: DEFAULT_ORGANIZATION_ID, + name: 'Shop', + }); + events.clear(); + + await service.deleteProject(project.id); + + expect(events.ofType('project.deleted').map((event) => event.payload)).toEqual([ + { projectId: project.id, name: 'Shop', slug: 'shop' }, + ]); + }); + + it('publishes nothing when the operation is rejected', async () => { + await service.createProject({ organizationId: DEFAULT_ORGANIZATION_ID, name: 'Shop' }); + events.clear(); + + await expect( + service.createProject({ organizationId: DEFAULT_ORGANIZATION_ID, name: 'Shop' }), + ).rejects.toThrow(); + await expect(service.updateProject('missing', { name: 'X' })).rejects.toThrow(); + await expect(service.deleteProject('missing')).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/projects/application/project.service.ts b/src/modules/projects/application/project.service.ts index 47c4e014..a82ba92b 100644 --- a/src/modules/projects/application/project.service.ts +++ b/src/modules/projects/application/project.service.ts @@ -6,6 +6,11 @@ import { type ProjectModules, type ProjectSettings, } from '../domain/project.domain'; +import type { EventBus } from '#lib/server/events'; +import type { DomainEventMap, ProjectChangedField } from '#lib/events/domain-events'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('projects'); export type ProjectStatusValue = 'active' | 'inactive'; @@ -17,6 +22,7 @@ export class ProjectService { constructor( private readonly repository: ProjectRepository, private readonly organizationLookup: OrganizationLookup, + private readonly events?: Pick, ) {} async listProjects() { @@ -96,7 +102,13 @@ export class ProjectService { throw new Error('Failed to create project'); } - return created.toJson(); + const json = created.toJson(); + this.publish('project.created', json, () => ({ + projectId: json.id, + name: json.name, + slug: json.slug ?? slug, + })); + return json; } async updateProject( @@ -115,6 +127,10 @@ export class ProjectService { if (!project) { throw new Error('Project not found'); } + // deep copy: the stored row may be the same object the repository mutates on update + const before = JSON.parse(JSON.stringify(project.toJson())) as ReturnType< + typeof project.toJson + >; const patch: { name?: string; @@ -179,7 +195,14 @@ export class ProjectService { throw new Error('Failed to update project'); } - return updated.toJson(); + const after = updated.toJson(); + this.publish('project.updated', after, () => ({ + projectId: after.id, + name: after.name, + slug: after.slug ?? '', + changedFields: this.changedFields(before, after), + })); + return after; } async deleteProject(id: string) { @@ -189,6 +212,45 @@ export class ProjectService { } await this.repository.deleteById(id); + + const json = project.toJson(); + this.publish('project.deleted', json, () => ({ + projectId: json.id, + name: json.name, + slug: json.slug ?? '', + })); + } + + // events never break the write that already succeeded: failures are only logged + private publish( + type: K, + project: { id: string; organization?: { id: string } | null }, + buildPayload: () => DomainEventMap[K], + ) { + if (!this.events) return; + try { + this.events.publish(type, buildPayload(), { + scope: { organizationId: project.organization?.id ?? null, projectId: project.id }, + }); + } catch (error) { + log.error({ err: error, eventType: type, projectId: project.id }, 'failed to publish event'); + } + } + + private changedFields( + before: { [key: string]: unknown; organization?: { id: string } | null }, + after: { [key: string]: unknown; organization?: { id: string } | null }, + ): ProjectChangedField[] { + const same = (left: unknown, right: unknown) => + JSON.stringify(left ?? null) === JSON.stringify(right ?? null); + const fields: ProjectChangedField[] = []; + for (const field of ['name', 'slug', 'description', 'status', 'modules', 'settings'] as const) { + if (!same(before[field], after[field])) fields.push(field); + } + if ((before.organization?.id ?? null) !== (after.organization?.id ?? null)) { + fields.push('organization'); + } + return fields; } private normalizeSlug(value: string): string { diff --git a/src/modules/projects/index.ts b/src/modules/projects/index.ts index cc2ef734..ffe1ae5c 100644 --- a/src/modules/projects/index.ts +++ b/src/modules/projects/index.ts @@ -1,7 +1,8 @@ import { ProjectService } from './application/project.service'; import { ProjectRepository } from './infrastructure/repositories/project.repostitory'; import { organizationService } from '../organization'; +import { eventBus } from '#lib/server/events'; const projectRepository = new ProjectRepository(); -export const projectService = new ProjectService(projectRepository, organizationService); +export const projectService = new ProjectService(projectRepository, organizationService, eventBus); From 279de7f3c162dbc725990fd337329081d8a9899e Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 14:29:55 +0100 Subject: [PATCH 05/13] feat(events): access, invitation, role and API key domain events (#78) - access.granted/updated/revoked for cluster, organization and project access - user.invited and invitation.accepted (no token, URL or email) - role.updated with added/removed permissions - api_key.created/revoked with the public prefix only (never the key or its hash) - publishAfterWrite helper so events never fail a successful write - es/en translations and no-leak tests Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 +- src/lib/events/catalog/access.events.ts | 156 ++++++++++++ src/lib/events/catalog/index.ts | 3 + src/lib/events/domain-events.ts | 59 +++++ src/lib/i18n/locales/en.json | 83 +++++++ src/lib/i18n/locales/es.json | 83 +++++++ src/lib/server/events/index.ts | 1 + src/lib/server/events/publish.ts | 25 ++ src/lib/server/events/scope.ts | 2 +- .../auth/application/apikeys.service.test.ts | 88 +++++++ .../auth/application/apikeys.service.ts | 36 +++ .../application/invitation.service.test.ts | 77 ++++++ .../auth/application/invitation.service.ts | 26 +- .../auth/application/role.service.test.ts | 68 ++++++ src/modules/auth/application/role.service.ts | 33 +++ .../application/user-access.service.test.ts | 227 ++++++++++++++++++ .../auth/application/user-access.service.ts | 107 ++++++++- src/modules/auth/index.ts | 20 +- 18 files changed, 1090 insertions(+), 8 deletions(-) create mode 100644 src/lib/events/catalog/access.events.ts create mode 100644 src/lib/server/events/publish.ts diff --git a/CLAUDE.md b/CLAUDE.md index 50924f21..c2d670a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -135,7 +135,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`. (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. + 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`. diff --git a/src/lib/events/catalog/access.events.ts b/src/lib/events/catalog/access.events.ts new file mode 100644 index 00000000..282824a8 --- /dev/null +++ b/src/lib/events/catalog/access.events.ts @@ -0,0 +1,156 @@ +import { OPERATORS, enumOptions, eventText, fieldLabel } from './fields'; +import type { EventDefinitions } from './types'; + +export const ACCESS_SCOPES = ['cluster', 'organization', 'project'] as const; + +const READ_USERS = 'organization:users:read'; + +const GRANTED = 'access.granted'; +const UPDATED = 'access.updated'; +const REVOKED = 'access.revoked'; +const INVITED = 'user.invited'; +const ACCEPTED = 'invitation.accepted'; +const ROLE_UPDATED = 'role.updated'; +const KEY_CREATED = 'api_key.created'; +const KEY_REVOKED = 'api_key.revoked'; + +type AccessEvent = typeof GRANTED | typeof UPDATED | typeof REVOKED; +type InvitationEvent = typeof INVITED | typeof ACCEPTED; + +function userField(type: AccessEvent | InvitationEvent) { + return { + key: 'userId', + label: fieldLabel(type, 'userId'), + type: 'reference', + reference: 'user', + operators: OPERATORS.reference, + } as const; +} + +function roleField(type: AccessEvent | InvitationEvent | typeof ROLE_UPDATED) { + return { + key: 'roleId', + label: fieldLabel(type, 'roleId'), + type: 'reference', + reference: 'role', + operators: OPERATORS.reference, + } as const; +} + +function scopeField(type: AccessEvent | typeof ACCEPTED) { + return { + key: 'scope', + label: fieldLabel(type, 'scope'), + type: 'enum', + options: enumOptions('accessScope', ACCESS_SCOPES), + operators: OPERATORS.enum, + } as const; +} + +function accessFields(type: AccessEvent) { + return [userField(type), roleField(type), scopeField(type)] as const; +} + +function permissionsField(key: 'addedPermissions' | 'removedPermissions') { + return { + key, + label: fieldLabel(ROLE_UPDATED, key), + type: 'string', + operators: OPERATORS.list, + } as const; +} + +// access events also feed the fixed system notifications (#81) for the affected user +export const accessEvents: EventDefinitions< + AccessEvent | InvitationEvent | typeof ROLE_UPDATED | typeof KEY_CREATED | typeof KEY_REVOKED +> = { + [GRANTED]: { + ...eventText(GRANTED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(GRANTED), + }, + [UPDATED]: { + ...eventText(UPDATED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(UPDATED), + }, + [REVOKED]: { + ...eventText(REVOKED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: accessFields(REVOKED), + }, + [INVITED]: { + ...eventText(INVITED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: [userField(INVITED), roleField(INVITED)], + }, + [ACCEPTED]: { + ...eventText(ACCEPTED), + module: 'access', + scope: 'organization', + readPermission: READ_USERS, + alertable: true, + fields: [userField(ACCEPTED), roleField(ACCEPTED), scopeField(ACCEPTED)], + }, + [ROLE_UPDATED]: { + ...eventText(ROLE_UPDATED), + module: 'access', + scope: 'organization', + readPermission: 'organization:roles:read', + alertable: true, + fields: [ + roleField(ROLE_UPDATED), + permissionsField('addedPermissions'), + permissionsField('removedPermissions'), + ], + }, + [KEY_CREATED]: { + ...eventText(KEY_CREATED), + module: 'access', + scope: 'project', + readPermission: 'project:server-keys:read', + alertable: true, + fields: [ + { + key: 'name', + label: fieldLabel(KEY_CREATED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, + [KEY_REVOKED]: { + ...eventText(KEY_REVOKED), + module: 'access', + scope: 'project', + readPermission: 'project:server-keys:read', + alertable: true, + fields: [ + { + key: 'apiKeyId', + label: fieldLabel(KEY_REVOKED, 'apiKeyId'), + type: 'reference', + reference: 'api_key', + operators: OPERATORS.reference, + }, + { + key: 'name', + label: fieldLabel(KEY_REVOKED, 'name'), + type: 'string', + operators: OPERATORS.string, + }, + ], + }, +}; diff --git a/src/lib/events/catalog/index.ts b/src/lib/events/catalog/index.ts index 6cb95335..d22ce290 100644 --- a/src/lib/events/catalog/index.ts +++ b/src/lib/events/catalog/index.ts @@ -3,6 +3,7 @@ import { codeReportEvents } from './code-report.events'; import { vaultEvents } from './vault.events'; import { projectEvents } from './projects.events'; import { organizationEvents } from './organization.events'; +import { accessEvents } from './access.events'; import type { EventCatalog, EventDefinition, @@ -17,6 +18,7 @@ export { CODE_REPORT_TOOLS } from './code-report.events'; 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'; /** * Builds the catalog. The parameter type makes it exhaustive (every `DomainEventMap` entry needs a @@ -41,6 +43,7 @@ export const EVENT_CATALOG: EventCatalog = defineEventCatalog({ ...vaultEvents, ...projectEvents, ...organizationEvents, + ...accessEvents, }); export function isEventType(value: string): value is EventType { diff --git a/src/lib/events/domain-events.ts b/src/lib/events/domain-events.ts index bdf762d8..83d1e5bd 100644 --- a/src/lib/events/domain-events.ts +++ b/src/lib/events/domain-events.ts @@ -121,6 +121,57 @@ export type OrganizationUpdatedPayload = { changedFields: OrganizationChangedField[]; }; +export type AccessScope = 'cluster' | 'organization' | 'project'; + +export type AccessStatus = 'active' | 'invited'; + +/** A role assignment: a cluster account role, or a membership in an organization or project. */ +export type AccessPayload = { + /** The user-access entry id (the user id for cluster-level access). */ + accessId: string; + userId: string; + roleId: string | null; + scope: AccessScope; + status: AccessStatus; +}; + +export type AccessUpdatedPayload = AccessPayload & { + previousRoleId: string | null; + previousStatus: AccessStatus; +}; + +/** Never carries the invitation token, its URL or the invitee's email. */ +export type UserInvitedPayload = { + userId: string; + roleId: string; + organizationId: string; +}; + +export type InvitationAcceptedPayload = { + userId: string; + accessId: string; + roleId: string | null; + scope: AccessScope; +}; + +export type RoleUpdatedPayload = { + roleId: string; + name: string; + scope: AccessScope; + nameChanged: boolean; + addedPermissions: string[]; + removedPermissions: string[]; +}; + +/** Never carries the key or its hash: `keyPrefix` is the public, non-secret identifier. */ +export type ApiKeyPayload = { + apiKeyId: string; + name: string; + keyPrefix: string; + projectId: string | null; + userId: string | null; +}; + export interface DomainEventMap { 'code_report.analysis.completed': CodeReportAnalysisCompletedPayload; 'code_report.analysis.failed': CodeReportAnalysisFailedPayload; @@ -137,6 +188,14 @@ export interface DomainEventMap { 'project.updated': ProjectUpdatedPayload; 'project.deleted': ProjectPayload; 'organization.updated': OrganizationUpdatedPayload; + 'access.granted': AccessPayload; + 'access.updated': AccessUpdatedPayload; + 'access.revoked': AccessPayload; + 'user.invited': UserInvitedPayload; + 'invitation.accepted': InvitationAcceptedPayload; + 'role.updated': RoleUpdatedPayload; + 'api_key.created': ApiKeyPayload; + 'api_key.revoked': ApiKeyPayload; } export type EventType = Extract; diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 76dfcc59..484fad22 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1056,6 +1056,11 @@ "name": "Name", "slug": "Slug", "description": "Description" + }, + "accessScope": { + "cluster": "GitOps", + "organization": "Organization", + "project": "Project" } }, "vault": { @@ -1154,6 +1159,84 @@ "changedFields": "Changed fields" } } + }, + "access": { + "granted": { + "label": "Access granted", + "description": "A user was given access with a role.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + }, + "updated": { + "label": "Access changed", + "description": "The role or status of a user access changed.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + }, + "revoked": { + "label": "Access revoked", + "description": "A user access was removed.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + } + }, + "user": { + "invited": { + "label": "User invited", + "description": "A user was invited to the organization.", + "fields": { + "userId": "User", + "roleId": "Role" + } + } + }, + "invitation": { + "accepted": { + "label": "Invitation accepted", + "description": "A user accepted their invitation.", + "fields": { + "userId": "User", + "roleId": "Role", + "scope": "Scope" + } + } + }, + "role": { + "updated": { + "label": "Role updated", + "description": "The name or permissions of a role changed.", + "fields": { + "roleId": "Role", + "addedPermissions": "Added permissions", + "removedPermissions": "Removed permissions" + } + } + }, + "api_key": { + "created": { + "label": "API key created", + "description": "An API key was created.", + "fields": { + "name": "Name" + } + }, + "revoked": { + "label": "API key revoked", + "description": "An API key was revoked.", + "fields": { + "apiKeyId": "API key", + "name": "Name" + } + } } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 5def0db7..72b5deb9 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1056,6 +1056,11 @@ "name": "Nombre", "slug": "Slug", "description": "Descripción" + }, + "accessScope": { + "cluster": "GitOps", + "organization": "Organización", + "project": "Proyecto" } }, "vault": { @@ -1154,6 +1159,84 @@ "changedFields": "Campos modificados" } } + }, + "access": { + "granted": { + "label": "Acceso concedido", + "description": "Se ha dado acceso a un usuario con un rol.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + }, + "updated": { + "label": "Acceso modificado", + "description": "Ha cambiado el rol o el estado del acceso de un usuario.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + }, + "revoked": { + "label": "Acceso retirado", + "description": "Se ha retirado el acceso de un usuario.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + } + }, + "user": { + "invited": { + "label": "Usuario invitado", + "description": "Se ha invitado a un usuario a la organización.", + "fields": { + "userId": "Usuario", + "roleId": "Rol" + } + } + }, + "invitation": { + "accepted": { + "label": "Invitación aceptada", + "description": "Un usuario ha aceptado su invitación.", + "fields": { + "userId": "Usuario", + "roleId": "Rol", + "scope": "Ámbito" + } + } + }, + "role": { + "updated": { + "label": "Rol modificado", + "description": "Han cambiado el nombre o los permisos de un rol.", + "fields": { + "roleId": "Rol", + "addedPermissions": "Permisos añadidos", + "removedPermissions": "Permisos retirados" + } + } + }, + "api_key": { + "created": { + "label": "API key creada", + "description": "Se ha creado una API key.", + "fields": { + "name": "Nombre" + } + }, + "revoked": { + "label": "API key revocada", + "description": "Se ha revocado una API key.", + "fields": { + "apiKeyId": "API key", + "name": "Nombre" + } + } } } } diff --git a/src/lib/server/events/index.ts b/src/lib/server/events/index.ts index 6e0f1c2c..1e384a6b 100644 --- a/src/lib/server/events/index.ts +++ b/src/lib/server/events/index.ts @@ -4,6 +4,7 @@ export { InProcessEventBus, actorFromRequest } from './event-bus'; export type { EventBus, InProcessEventBusOptions } from './event-bus'; export type * from './types'; export { resolveProjectScope, type ProjectScopeLookup } from './scope'; +export { publishAfterWrite, type EventPublisher } from './publish'; const GLOBAL_KEY = Symbol.for('gitops.events.bus'); diff --git a/src/lib/server/events/publish.ts b/src/lib/server/events/publish.ts new file mode 100644 index 00000000..6ee48601 --- /dev/null +++ b/src/lib/server/events/publish.ts @@ -0,0 +1,25 @@ +import type { Logger } from 'pino'; +import type { EventBus } from './event-bus'; +import type { DomainEventMap, EventScope, EventType } from './types'; + +export type EventPublisher = Pick; + +/** + * Publishes an event describing a write that already succeeded. Resolving the scope or publishing + * never throws back into the caller: a failure is logged and the request carries on. + */ +export async function publishAfterWrite( + events: EventPublisher | undefined, + log: Pick, + type: K, + payload: DomainEventMap[K], + scope: EventScope | (() => Promise), +): Promise { + if (!events) return; + try { + const resolved = typeof scope === 'function' ? await scope() : scope; + events.publish(type, payload, { scope: resolved }); + } catch (error) { + log.error({ err: error, eventType: type }, `[events] failed to publish ${type}`); + } +} diff --git a/src/lib/server/events/scope.ts b/src/lib/server/events/scope.ts index 4fcda847..7c488f3a 100644 --- a/src/lib/server/events/scope.ts +++ b/src/lib/server/events/scope.ts @@ -2,7 +2,7 @@ import type { EventScope } from './types'; /** Project lookup used to add the organization to a project-scoped event. */ export type ProjectScopeLookup = { - getProject(id: string): Promise<{ organization?: { id: string } | null }>; + getProject(id: string): Promise<{ organization?: { id: string } | null } | null>; }; /** diff --git a/src/modules/auth/application/apikeys.service.test.ts b/src/modules/auth/application/apikeys.service.test.ts index 562504c7..fefd3128 100644 --- a/src/modules/auth/application/apikeys.service.test.ts +++ b/src/modules/auth/application/apikeys.service.test.ts @@ -1,5 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ApiKeysService } from './apikeys.service'; +import { RecordingEventBus } from '#lib/server/events/testing'; import type { ApiKeyView } from '../domain/entities'; function apiKey(overrides: Partial = {}): ApiKeyView { @@ -291,3 +292,90 @@ describe('ApiKeysService', () => { expect(repository.updateKeyMaterial).not.toHaveBeenCalled(); }); }); + +describe('ApiKeysService events', () => { + const projectLookup = { + getProject: async () => ({ id: 'project-1', organization: { id: 'org-1' } }), + }; + + it('publishes api_key.created for a project key with the prefix but never the key', async () => { + const repository = createRepositoryMock(); + const events = new RecordingEventBus(); + const service = new ApiKeysService( + repository, + createRoleRepositoryMock(), + projectLookup, + events, + ); + + const { token, key } = await service.createProjectApiKey({ + projectId: 'project-1', + roleId: 'role-1', + name: 'CI pipeline', + expiresAt: null, + createdByUserId: 'user-1', + }); + + expect(events.types()).toEqual(['api_key.created']); + const [event] = events.ofType('api_key.created'); + expect(event.payload).toEqual({ + apiKeyId: key.id, + name: 'CI pipeline', + keyPrefix: token.slice(0, 10), + projectId: 'project-1', + userId: null, + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + + const serialized = JSON.stringify(events.events); + expect(serialized).not.toContain(token); + expect(serialized).not.toContain(repository.create.mock.calls[0][0].keyHash); + }); + + it('publishes api_key.created for a personal key without a project scope', async () => { + const events = new RecordingEventBus(); + const service = new ApiKeysService(createRepositoryMock(), undefined, undefined, events); + + await service.createApiKey('user-1', 'Laptop', null); + + expect(events.ofType('api_key.created')[0]).toMatchObject({ + payload: { name: 'Laptop', projectId: null, userId: 'user-1' }, + scope: {}, + }); + }); + + it('publishes api_key.revoked for personal and project keys', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => apiKey()); + repository.findByIdAny.mockImplementation(async () => + apiKey({ id: 'key-2', name: 'CI', userId: null, projectId: 'project-1' }), + ); + const events = new RecordingEventBus(); + const service = new ApiKeysService(repository, undefined, projectLookup, events); + + await service.revokeApiKey('user-1', 'key-1'); + await service.revokeProjectApiKey('project-1', 'key-2'); + + expect(events.ofType('api_key.revoked').map((event) => event.payload.apiKeyId)).toEqual([ + 'key-1', + 'key-2', + ]); + expect(events.ofType('api_key.revoked')[1].scope.projectId).toBe('project-1'); + }); + + it('publishes nothing when creation or revocation is rejected', async () => { + const repository = createRepositoryMock(); + repository.findById.mockImplementation(async () => apiKey({ revokedAt: '2026-01-01' })); + repository.create.mockImplementation(async () => { + throw new Error('GitDB write failed'); + }); + const events = new RecordingEventBus(); + const service = new ApiKeysService(repository, undefined, undefined, events); + + await expect(service.createApiKey('user-1', ' ', null)).rejects.toThrow(); + await expect(service.createApiKey('user-1', 'Laptop', null)).rejects.toThrow(); + await expect(service.revokeApiKey('user-1', 'key-1')).rejects.toThrow(/already revoked/); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/apikeys.service.ts b/src/modules/auth/application/apikeys.service.ts index 115d497f..fad92181 100644 --- a/src/modules/auth/application/apikeys.service.ts +++ b/src/modules/auth/application/apikeys.service.ts @@ -2,6 +2,11 @@ import crypto from 'crypto'; import type { ApiKeyView, AuthenticatedApiKey, SessionRole } from '../domain/entities'; import type { RoleDomain } from '../domain/role.domain'; import { ApiKeyRepository } from '../infrastructure/repositories/apikey.repository'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import { resolveProjectScope } from '#lib/server/events/scope'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('api-keys'); const TOKEN_PREFIX = 'gvs_'; const PREFIX_LENGTH = 10; @@ -28,6 +33,7 @@ export class ApiKeysService { private readonly apiKeyRepository: ApiKeyRepository, private readonly roleRepository?: RoleLookup, private readonly projectLookup?: ProjectLookup, + private readonly events?: EventPublisher, ) {} async listActiveApiKeys(userId: string): Promise { @@ -134,6 +140,7 @@ export class ApiKeysService { } await this.apiKeyRepository.revoke(userId, keyId); + await this.publishKeyEvent('api_key.revoked', existing); } async revokeProjectApiKey(projectId: string, keyId: string): Promise { @@ -144,6 +151,27 @@ export class ApiKeysService { } await this.apiKeyRepository.revokeAny(keyId); + await this.publishKeyEvent('api_key.revoked', existing); + } + + /** The key and its hash never leave this service: events only carry the public prefix. */ + private async publishKeyEvent( + type: 'api_key.created' | 'api_key.revoked', + key: Pick, + ): Promise { + await publishAfterWrite( + this.events, + log, + type, + { + apiKeyId: key.id, + name: key.name, + keyPrefix: key.keyPrefix, + projectId: key.projectId, + userId: key.userId, + }, + async () => (key.projectId ? resolveProjectScope(key.projectId, this.projectLookup) : {}), + ); } async regenerateApiKey( @@ -229,6 +257,14 @@ export class ApiKeysService { expiresAt: input.expiresAt, }); + await this.publishKeyEvent('api_key.created', { + id, + name, + keyPrefix, + projectId: input.projectId, + userId: input.userId, + }); + return { token, key: { diff --git a/src/modules/auth/application/invitation.service.test.ts b/src/modules/auth/application/invitation.service.test.ts index 00fafa41..32ae1748 100644 --- a/src/modules/auth/application/invitation.service.test.ts +++ b/src/modules/auth/application/invitation.service.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'vitest'; import crypto from 'crypto'; import { InvitationService } from './invitation.service'; import { UserDomain } from '../domain/user.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; function hash(token: string) { return crypto.createHash('sha256').update(token).digest('hex'); @@ -190,3 +191,79 @@ describe('InvitationService', () => { }); }); }); + +describe('InvitationService events', () => { + let userRepository: FakeUserRepository; + let userAccessRepository: FakeUserAccessRepository; + let events: RecordingEventBus; + let service: InvitationService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + userAccessRepository = new FakeUserAccessRepository(); + events = new RecordingEventBus(); + service = new InvitationService( + userRepository as any, + userAccessRepository as any, + { hashPassword: (password: string) => `hashed:${password}` }, + undefined, + { events, projects: { getProject: async () => ({ organization: { id: 'org-1' } }) } }, + ); + userRepository.rows.push(invitedUser()); + userAccessRepository.rows.push( + { + id: 'access-org', + userId: 'jose-id', + status: 'invited', + roleId: 'role-org', + scope: 'organization', + organizationId: 'org-1', + projectId: null, + } as any, + { + id: 'access-project', + userId: 'jose-id', + status: 'invited', + roleId: 'role-project', + scope: 'project', + organizationId: null, + projectId: 'project-1', + } as any, + { id: 'access-old', userId: 'jose-id', status: 'active', scope: 'organization' } as any, + ); + }); + + it('publishes one invitation.accepted per activated membership, without the token', async () => { + const { token } = await service.issueToken('jose-id'); + + await service.acceptInvitation(token, 'a-strong-password'); + + expect( + events.ofType('invitation.accepted').map((event) => [event.payload, event.scope]), + ).toEqual([ + [ + { userId: 'jose-id', accessId: 'access-org', roleId: 'role-org', scope: 'organization' }, + { organizationId: 'org-1', projectId: null }, + ], + [ + { + userId: 'jose-id', + accessId: 'access-project', + roleId: 'role-project', + scope: 'project', + }, + { organizationId: 'org-1', projectId: 'project-1' }, + ], + ]); + expect(JSON.stringify(events.events)).not.toContain(token); + }); + + it('publishes nothing when the invitation is rejected', async () => { + const { token } = await service.issueToken('jose-id'); + + await expect(service.acceptInvitation('wrong', 'a-strong-password')).rejects.toThrow(); + await expect(service.acceptInvitation(token, 'short')).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/invitation.service.ts b/src/modules/auth/application/invitation.service.ts index 1e0e58b1..1a7baf56 100644 --- a/src/modules/auth/application/invitation.service.ts +++ b/src/modules/auth/application/invitation.service.ts @@ -2,6 +2,12 @@ import crypto from 'crypto'; import type { UserAccessRepository } from '../infrastructure/repositories/user-access.repository'; import type { UserRepository } from '../infrastructure/repositories/user.repository'; import type { PasswordService } from './password.service'; +import { publishAfterWrite } from '#lib/server/events/publish'; +import { resolveProjectScope } from '#lib/server/events/scope'; +import { createLogger } from '#lib/server/logger'; +import type { AccessEventsOptions } from './user-access.service'; + +const log = createLogger('invitation'); export type InvitationView = { userId: string; @@ -21,6 +27,7 @@ export class InvitationService { private readonly userAccessRepository: Pick, private readonly passwordService: Pick, private readonly ttlDays: number = DEFAULT_TTL_DAYS, + private readonly eventOptions: AccessEventsOptions = {}, ) {} /** Issues a new token, stores only its hash, and returns the raw token for the invite link. */ @@ -50,12 +57,25 @@ export class InvitationService { ); const access = await this.userAccessRepository.findByUserId(user.id); + const accepted = access.filter((entry) => entry.status === 'invited'); await Promise.all( - access - .filter((entry) => entry.status === 'invited') - .map((entry) => this.userAccessRepository.update(entry.id, { status: 'active' })), + accepted.map((entry) => this.userAccessRepository.update(entry.id, { status: 'active' })), ); + // one event per activated membership, so each organization/project sees its own + for (const entry of accepted) { + await publishAfterWrite( + this.eventOptions.events, + log, + 'invitation.accepted', + { userId: user.id, accessId: entry.id, roleId: entry.roleId || null, scope: entry.scope }, + async () => + entry.scope === 'project' + ? resolveProjectScope(entry.projectId, this.eventOptions.projects) + : { organizationId: entry.organizationId ?? null, projectId: null }, + ); + } + return { userId: user.id, username: user.username, email: user.email }; } diff --git a/src/modules/auth/application/role.service.test.ts b/src/modules/auth/application/role.service.test.ts index 6eb096f2..ae7a9118 100644 --- a/src/modules/auth/application/role.service.test.ts +++ b/src/modules/auth/application/role.service.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, beforeEach } from 'vitest'; import { RoleService } from './role.service'; import { RoleDomain } from '../domain/role.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; class FakeRoleRepository { rows: RoleDomain[] = []; @@ -288,3 +289,70 @@ describe('RoleService', () => { }); }); }); + +describe('RoleService events', () => { + let roleRepository: FakeRoleRepository; + let events: RecordingEventBus; + let service: RoleService; + + beforeEach(async () => { + roleRepository = new FakeRoleRepository(); + events = new RecordingEventBus(); + service = new RoleService( + roleRepository as any, + new FakeUserRepository() as any, + new FakeUserAccessRepository() as any, + { + events, + projects: { getProject: async () => ({ organization: { id: 'org-1' } }) }, + }, + ); + await roleRepository.create({ + id: 'role-1', + slug: 'project-dev', + name: 'Project Developer', + scope: 'project', + projectId: 'project-1', + permissions: ['project:vault:secrets:read', 'project:vault:secrets:update'], + } as any); + }); + + it('publishes role.updated with the permission diff and the project scope', async () => { + await service.updateRole('role-1', { + permissions: ['project:vault:secrets:read', 'project:vault:secrets:delete'], + }); + + expect(events.types()).toEqual(['role.updated']); + const [event] = events.ofType('role.updated'); + expect(event.payload).toEqual({ + roleId: 'role-1', + name: 'Project Developer', + scope: 'project', + nameChanged: false, + addedPermissions: ['project:vault:secrets:delete'], + removedPermissions: ['project:vault:secrets:update'], + }); + expect(event.scope).toEqual({ organizationId: 'org-1', projectId: 'project-1' }); + }); + + it('reports a rename', async () => { + await service.updateRole('role-1', { name: 'Developer' }); + + expect(events.ofType('role.updated')[0].payload).toMatchObject({ + name: 'Developer', + nameChanged: true, + addedPermissions: [], + removedPermissions: [], + }); + }); + + it('does not publish when creating default roles or on rejected updates', async () => { + await service.createDefaultProjectRoles('project-2'); + await service.createDefaultOrganizationRoles('org-2'); + await expect(service.updateRole('missing', { name: 'X' })).rejects.toThrow(); + await expect(service.updateRole('role-1', { name: ' ' })).rejects.toThrow(); + await expect(service.updateRole('role-1', { permissions: ['nope'] })).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/role.service.ts b/src/modules/auth/application/role.service.ts index a298799d..703d3a61 100644 --- a/src/modules/auth/application/role.service.ts +++ b/src/modules/auth/application/role.service.ts @@ -11,6 +11,12 @@ import { PROJECT_DEVELOPER_PERMISSIONS, PROJECT_VIEWER_PERMISSIONS, } from '../domain/role-permissions.data'; +import { publishAfterWrite } from '#lib/server/events/publish'; +import { resolveProjectScope } from '#lib/server/events/scope'; +import { createLogger } from '#lib/server/logger'; +import type { AccessEventsOptions } from './user-access.service'; + +const log = createLogger('roles'); export class RoleService { constructor( @@ -20,6 +26,7 @@ export class RoleService { >, private readonly userRepository: Pick, private readonly userAccessRepository: Pick, + private readonly eventOptions: AccessEventsOptions = {}, ) {} async listRoles(scope: RoleScope = 'cluster', scopeId?: string): Promise { @@ -141,6 +148,7 @@ export class RoleService { throw new Error('Role not found'); } + const previous = { name: role.name, permissions: [...(role.permissions ?? [])] }; const patch: { name?: string; permissions?: string[] } = {}; if (changes.name !== undefined) { @@ -162,6 +170,31 @@ export class RoleService { throw new Error('Failed to update role'); } + const before = new Set(previous.permissions); + const after = new Set(updated.permissions ?? []); + await publishAfterWrite( + this.eventOptions.events, + log, + 'role.updated', + { + roleId: updated.id, + name: updated.name, + scope: updated.scope, + nameChanged: previous.name !== updated.name, + addedPermissions: [...after].filter((permission) => !before.has(permission)), + removedPermissions: [...before].filter((permission) => !after.has(permission)), + }, + async () => { + if (updated.scope === 'project') { + return resolveProjectScope(updated.projectId, this.eventOptions.projects); + } + if (updated.scope === 'organization') { + return { organizationId: updated.organizationId ?? null, projectId: null }; + } + return {}; + }, + ); + return updated.toJson(); } diff --git a/src/modules/auth/application/user-access.service.test.ts b/src/modules/auth/application/user-access.service.test.ts index 6e23b908..64e31e79 100644 --- a/src/modules/auth/application/user-access.service.test.ts +++ b/src/modules/auth/application/user-access.service.test.ts @@ -7,6 +7,7 @@ import { import { RoleDomain } from '../domain/role.domain'; import { UserAccessDomain } from '../domain/user-access.domain'; import { UserDomain } from '../domain/user.domain'; +import { RecordingEventBus } from '#lib/server/events/testing'; function role(input: { id: string; @@ -78,6 +79,19 @@ class FakeUserRepository { this.rows = this.rows.filter((entry) => entry.id !== id); } + roleRepository?: FakeRoleRepository; + + async updateRoleId(id: string, roleId: string) { + const row = this.rows.find((entry) => entry.id === id); + const nextRole = await this.roleRepository?.findById(roleId); + if (row && nextRole) row.role = nextRole; + } + + async updateStatus(id: string, status: 'active' | 'invited') { + const row = this.rows.find((entry) => entry.id === id); + if (row) row.status = status; + } + async createUser(input: { id: string; username: string; @@ -657,3 +671,216 @@ describe('UserAccessService', () => { ).rejects.toThrow(/does not belong/); }); }); + +describe('UserAccessService events', () => { + let userRepository: FakeUserRepository; + let roleRepository: FakeRoleRepository; + let userAccessRepository: FakeUserAccessRepository; + let events: RecordingEventBus; + let service: UserAccessService; + + beforeEach(() => { + userRepository = new FakeUserRepository(); + roleRepository = new FakeRoleRepository(); + userAccessRepository = new FakeUserAccessRepository(); + userAccessRepository.userRepository = userRepository; + userAccessRepository.roleRepository = roleRepository; + userRepository.roleRepository = roleRepository; + events = new RecordingEventBus(); + service = new UserAccessService( + userRepository as any, + roleRepository as any, + userAccessRepository as any, + { hashPassword: (password: string) => `hashed:${password}` }, + { sendInvitation: vi.fn(async () => {}) }, + { issueToken: vi.fn(async () => ({ token: 'raw-token', expiresAt: '2024-01-08' })) }, + { events, projects: { getProject: async () => ({ organization: { id: 'gitops' } }) } }, + ); + roleRepository.rows.push( + role({ id: 'cluster-user-id', slug: 'cluster-user' }), + role({ id: 'cluster-admin-id', slug: 'cluster-admin' }), + role({ + id: 'org-dev', + slug: 'org-developer', + scope: 'organization', + organizationId: 'gitops', + }), + role({ id: 'org-admin', slug: 'org-admin', scope: 'organization', organizationId: 'gitops' }), + role({ id: 'project-dev', slug: 'project-dev', scope: 'project', projectId: 'shop' }), + ); + userRepository.rows.push( + user({ id: 'ana', username: 'ana', email: 'ana@example.com', role: roleRepository.rows[0] }), + ); + }); + + it('publishes access.granted for organization and project assignments', async () => { + const orgAccess = await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + const projectAccess = await service.assignProjectUser({ + projectId: 'shop', + userId: 'ana', + roleId: 'project-dev', + }); + + expect(events.ofType('access.granted').map((event) => [event.payload, event.scope])).toEqual([ + [ + { + accessId: orgAccess.id, + userId: 'ana', + roleId: 'org-dev', + scope: 'organization', + status: 'active', + }, + { organizationId: 'gitops', projectId: null }, + ], + [ + { + accessId: projectAccess.id, + userId: 'ana', + roleId: 'project-dev', + scope: 'project', + status: 'active', + }, + { organizationId: 'gitops', projectId: 'shop' }, + ], + ]); + }); + + it('publishes access.granted and user.invited for an invitation, without token or URL', async () => { + await service.inviteOrganizationUser({ + organizationId: 'gitops', + organizationName: 'GitOps', + email: 'new@example.com', + inviteUrl: 'https://gitops.example.com/auth/invitation', + }); + + expect(events.types()).toEqual(['access.granted', 'user.invited']); + const invited = userRepository.rows.find((row) => row.email === 'new@example.com')!; + expect(events.ofType('user.invited')[0].payload).toEqual({ + userId: invited.id, + roleId: 'org-dev', + organizationId: 'gitops', + }); + const serialized = JSON.stringify(events.events); + expect(serialized).not.toContain('raw-token'); + expect(serialized).not.toContain('auth/invitation'); + expect(serialized).not.toContain('new@example.com'); + }); + + it('publishes access.updated with the previous role and status', async () => { + const access = await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + events.clear(); + + await service.updateAccess({ + accessId: access.id, + scope: 'organization', + scopeId: 'gitops', + roleId: 'org-admin', + status: 'active', + }); + + expect(events.ofType('access.updated')[0].payload).toEqual({ + accessId: access.id, + userId: 'ana', + roleId: 'org-admin', + scope: 'organization', + status: 'active', + previousRoleId: 'org-dev', + previousStatus: 'active', + }); + }); + + it('publishes access.updated for a cluster role change', async () => { + await service.updateAccess({ + accessId: 'ana', + scope: 'cluster', + roleId: 'cluster-admin-id', + status: 'active', + }); + + const [event] = events.ofType('access.updated'); + expect(event.payload).toMatchObject({ + accessId: 'ana', + userId: 'ana', + scope: 'cluster', + roleId: 'cluster-admin-id', + previousRoleId: 'cluster-user-id', + }); + expect(event.scope).toEqual({}); + }); + + it('publishes access.revoked for a project membership', async () => { + const access = await service.assignProjectUser({ + projectId: 'shop', + userId: 'ana', + roleId: 'project-dev', + }); + events.clear(); + + await service.removeAccess({ accessId: access.id, scope: 'project', scopeId: 'shop' }); + + expect(events.ofType('access.revoked').map((event) => event.payload.accessId)).toEqual([ + access.id, + ]); + }); + + it('revokes every membership and the account when removing an organization user', async () => { + const orgAccess = await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + const projectAccess = await service.assignProjectUser({ + projectId: 'shop', + userId: 'ana', + roleId: 'project-dev', + }); + events.clear(); + + await service.removeAccess({ + accessId: orgAccess.id, + scope: 'organization', + scopeId: 'gitops', + }); + + expect( + events.ofType('access.revoked').map((event) => [event.payload.accessId, event.payload.scope]), + ).toEqual([ + [orgAccess.id, 'organization'], + [projectAccess.id, 'project'], + ['ana', 'cluster'], + ]); + }); + + it('publishes nothing when the operation is rejected', async () => { + await service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }); + events.clear(); + + await expect( + service.assignOrganizationUser({ + organizationId: 'gitops', + userId: 'ana', + roleId: 'org-dev', + }), + ).rejects.toThrow(/already has access/); + await expect( + service.assignProjectUser({ projectId: 'shop', userId: 'ana', roleId: 'org-dev' }), + ).rejects.toThrow(); + await expect( + service.removeAccess({ accessId: 'missing', scope: 'project', scopeId: 'shop' }), + ).rejects.toThrow(); + + expect(events.events).toEqual([]); + }); +}); diff --git a/src/modules/auth/application/user-access.service.ts b/src/modules/auth/application/user-access.service.ts index 516d2248..1f4ef70e 100644 --- a/src/modules/auth/application/user-access.service.ts +++ b/src/modules/auth/application/user-access.service.ts @@ -7,6 +7,13 @@ import type { RoleRepository } from '../infrastructure/repositories/role.reposit import type { UserAccessRepository } from '../infrastructure/repositories/user-access.repository'; import type { UserRepository } from '../infrastructure/repositories/user.repository'; import type { PasswordService } from './password.service'; +import { publishAfterWrite, type EventPublisher } from '#lib/server/events/publish'; +import { resolveProjectScope, type ProjectScopeLookup } from '#lib/server/events/scope'; +import type { EventScope } from '#lib/server/events'; +import type { AccessPayload } from '#lib/events/domain-events'; +import { createLogger } from '#lib/server/logger'; + +const log = createLogger('user-access'); type UserAccessRow = { id: string; @@ -22,6 +29,11 @@ type UserAccessRow = { createdAt: string; }; +type AccessEntry = Pick< + UserAccessDomain, + 'id' | 'userId' | 'roleId' | 'scope' | 'organizationId' | 'projectId' | 'status' +> & { user?: UserAccessDomain['user'] }; + export type InvitationNotifierPort = { sendInvitation(input: { email: string; @@ -38,7 +50,15 @@ export type InvitationTokenIssuerPort = { issueToken(userId: string): Promise<{ token: string; expiresAt: string }>; }; +export type AccessEventsOptions = { + events?: EventPublisher; + projects?: ProjectScopeLookup; +}; + export class UserAccessService { + private readonly events?: EventPublisher; + private readonly projects?: ProjectScopeLookup; + constructor( private readonly userRepository: Pick< UserRepository, @@ -59,7 +79,11 @@ export class UserAccessService { private readonly passwordService: Pick, private readonly invitationNotifier: InvitationNotifierPort, private readonly invitationTokens: InvitationTokenIssuerPort, - ) {} + options: AccessEventsOptions = {}, + ) { + this.events = options.events; + this.projects = options.projects; + } async listUsers(scope: RoleScope, scopeId?: string): Promise { this.validateScope(scope, scopeId); @@ -155,6 +179,14 @@ export class UserAccessService { expiresAt: invitation.expiresAt, invitedBy: input.invitedBy ?? null, }); + + await publishAfterWrite( + this.events, + log, + 'user.invited', + { userId: user.id, roleId: role.id, organizationId }, + { organizationId, projectId: null }, + ); } return this.toRow(access); @@ -273,6 +305,7 @@ export class UserAccessService { status: string; }): Promise { const access = await this.findAccessInScope(input.accessId, input.scope, input.scopeId); + const before = this.snapshot(access); if (input.scope === 'cluster') { const role = await this.findRoleForScope(input.roleId, 'cluster', ''); const status = this.sanitizeStatus(input.status); @@ -282,6 +315,7 @@ export class UserAccessService { ]); const updated = await this.userRepository.findById(access.id); if (!updated) throw new Error('Failed to update user access'); + await this.publishAccessUpdated(before, role.id, status); return this.toClusterRow(updated); } @@ -292,6 +326,7 @@ export class UserAccessService { const updated = await this.userAccessRepository.findById(access.id); if (!updated) throw new Error('Failed to update user access'); + await this.publishAccessUpdated(before, role.id, status); return this.toRow(updated); } @@ -306,10 +341,79 @@ export class UserAccessService { const userAccess = await this.userAccessRepository.findByUserId(access.userId); await Promise.all(userAccess.map((entry) => this.userAccessRepository.deleteById(entry.id))); await this.userRepository.deleteById(userId); + + // removing the account revokes every membership it had, plus the account itself + for (const entry of userAccess) await this.publishAccess('access.revoked', entry); + await this.publishAccess( + 'access.revoked', + input.scope === 'cluster' + ? access + : { + id: userId, + userId, + roleId: access.user?.role?.id ?? '', + scope: 'cluster', + organizationId: null, + projectId: null, + status: access.user?.status ?? 'active', + }, + ); return; } await this.userAccessRepository.deleteById(access.id); + await this.publishAccess('access.revoked', access); + } + + private async publishAccess( + type: 'access.granted' | 'access.revoked', + entry: AccessEntry, + ): Promise { + await publishAfterWrite(this.events, log, type, this.accessPayload(entry), () => + this.accessScope(entry), + ); + } + + private async publishAccessUpdated( + before: AccessEntry, + roleId: string, + status: UserAccessStatus, + ): Promise { + await publishAfterWrite( + this.events, + log, + 'access.updated', + { + ...this.accessPayload({ ...before, roleId, status }), + previousRoleId: before.roleId || null, + previousStatus: before.status === 'invited' ? 'invited' : 'active', + }, + () => this.accessScope(before), + ); + } + + // copy: the repository may mutate the stored entry in place on update + private snapshot(entry: AccessEntry): AccessEntry { + const { id, userId, roleId, scope, organizationId, projectId, status } = entry; + return { id, userId, roleId, scope, organizationId, projectId, status }; + } + + private accessPayload(entry: AccessEntry): AccessPayload { + return { + accessId: entry.id, + userId: entry.userId, + roleId: entry.roleId || null, + scope: entry.scope, + status: entry.status === 'invited' ? 'invited' : 'active', + }; + } + + private async accessScope(entry: AccessEntry): Promise { + if (entry.scope === 'project') return resolveProjectScope(entry.projectId, this.projects); + if (entry.scope === 'organization') { + return { organizationId: entry.organizationId ?? null, projectId: null }; + } + return {}; } async resendInvitation(input: { @@ -377,6 +481,7 @@ export class UserAccessService { const created = await this.userAccessRepository.findOne(lookup); if (!created) throw new Error('Failed to create user access'); + await this.publishAccess('access.granted', created); return created; } diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index 4fa028d8..c978ab1c 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -19,6 +19,9 @@ import { GoogleOidcClient } from './infrastructure/oidc/google-oidc.client'; import { InvitationNotifier } from './infrastructure/notifications/invitation.notifier'; import { PasswordResetNotifier } from './infrastructure/notifications/password-reset.notifier'; import { projectService } from '../projects'; +import { eventBus } from '#lib/server/events'; + +const accessEvents = { events: eventBus, projects: projectService }; const userRepository = new UserRepository(); const roleRepository = new RoleRepository(); @@ -29,7 +32,12 @@ const passwordResetNotifier = new PasswordResetNotifier(); export const passwordService = new PasswordService(); const sessionService = new SessionService(passwordService); -export const apiKeysService = new ApiKeysService(apiKeyRepository, roleRepository, projectService); +export const apiKeysService = new ApiKeysService( + apiKeyRepository, + roleRepository, + projectService, + eventBus, +); export const authService = new AuthService( userRepository, @@ -39,11 +47,18 @@ export const authService = new AuthService( ); export const userService = new UserService(userRepository, roleRepository, passwordService); export const profileService = new ProfileService(userRepository, passwordService); -export const roleService = new RoleService(roleRepository, userRepository, userAccessRepository); +export const roleService = new RoleService( + roleRepository, + userRepository, + userAccessRepository, + accessEvents, +); export const invitationService = new InvitationService( userRepository, userAccessRepository, passwordService, + undefined, + accessEvents, ); export const passwordResetService = new PasswordResetService( userRepository, @@ -57,6 +72,7 @@ export const userAccessService = new UserAccessService( passwordService, invitationNotifier, invitationService, + accessEvents, ); export const ssoService = new SsoService( readGoogleSsoConfig, From 67184740d2dedce21a63b9b70c44290a698622f2 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 15:07:38 +0100 Subject: [PATCH 06/13] fix(e2e): map $app/env/private for the in-process global setup The e2e tsconfig still mapped $env/dynamic/private (to a file that no longer exists) while the app reads $app/env/private, so global setup failed before any spec ran. Add a stand-in that reads process.env after global setup assigns the throwaway configuration. Co-Authored-By: Claude Opus 5.5 --- e2e/env-private.ts | 30 ++++++++++++++++++++++++++++++ e2e/tsconfig.json | 2 +- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 e2e/env-private.ts diff --git a/e2e/env-private.ts b/e2e/env-private.ts new file mode 100644 index 00000000..d04c4f5c --- /dev/null +++ b/e2e/env-private.ts @@ -0,0 +1,30 @@ +// Stand-in for SvelteKit's `$app/env/private` when Playwright's global setup imports app modules +// in-process (GitDB start + seed). Imported after global-setup assigns process.env, so these +// snapshots see the throwaway E2E configuration. Keep in sync with `src/env.ts`. + +export const GITDB_REPOSITORY_URL = process.env.GITDB_REPOSITORY_URL; +export const GITDB_BRANCH = process.env.GITDB_BRANCH; +export const GITDB_TOKEN = process.env.GITDB_TOKEN; +export const GITDB_USERNAME = process.env.GITDB_USERNAME; +export const GITDB_PASSWORD = process.env.GITDB_PASSWORD; +export const GITDB_AUTHOR_NAME = process.env.GITDB_AUTHOR_NAME; +export const GITDB_AUTHOR_EMAIL = process.env.GITDB_AUTHOR_EMAIL; +export const GITDB_SYNC_POLL_SECONDS = process.env.GITDB_SYNC_POLL_SECONDS; +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 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; +export const NOTIFICATION_SMTP_USER = process.env.NOTIFICATION_SMTP_USER; +export const NOTIFICATION_SMTP_PASSWORD = process.env.NOTIFICATION_SMTP_PASSWORD; +export const NOTIFICATION_SMTP_FROM = process.env.NOTIFICATION_SMTP_FROM; +export const NOTIFICATION_SMTP_FROM_NAME = process.env.NOTIFICATION_SMTP_FROM_NAME; +export const NOTIFICATION_SMTP_REJECT_UNAUTHORIZED = + process.env.NOTIFICATION_SMTP_REJECT_UNAUTHORIZED; +export const GOOGLE_SSO_CLIENT_ID = process.env.GOOGLE_SSO_CLIENT_ID; +export const GOOGLE_SSO_CLIENT_SECRET = process.env.GOOGLE_SSO_CLIENT_SECRET; +export const GOOGLE_SSO_ALLOWED_DOMAINS = process.env.GOOGLE_SSO_ALLOWED_DOMAINS; +export const GOOGLE_SSO_AUTO_PROVISION = process.env.GOOGLE_SSO_AUTO_PROVISION; +export const GITOPS_EVENTS_EXPIRATION = process.env.GITOPS_EVENTS_EXPIRATION; diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json index bef3a036..285608e5 100644 --- a/e2e/tsconfig.json +++ b/e2e/tsconfig.json @@ -8,7 +8,7 @@ "#lib/*": ["../src/lib/*"], "$modules": ["../src/modules"], "#modules/*": ["../src/modules/*"], - "$env/dynamic/private": ["../test/env-dynamic-private.ts"] + "$app/env/private": ["./env-private.ts"] } } } From cdceed8917e601523a80458f9ef93952809adc5f Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 15:07:38 +0100 Subject: [PATCH 07/13] feat(events): organization events page with acknowledgements - InMemoryEventLog subscribed to the bus: recent events plus a shared ack (who and when), retention via GITOPS_EVENTS_EXPIRATION (default 7d), capped at 10,000 events - /org//events: events the viewer may read (each definition's readPermission, checked in the event's project or organization), filters by module and status, ack action - request context store is process-wide so the long-lived bus sees the actor after Vite HMR - sidebar entry, es/en translations, unit tests and an e2e spec Co-Authored-By: Claude Opus 5.5 --- .env.example | 5 + CLAUDE.md | 4 + docs/adr/0001-event-bus-and-alerts.md | 8 +- e2e/specs/org-events.spec.ts | 61 +++++ src/env.ts | 1 + src/lib/components/AppSidebar.svelte | 6 + src/lib/i18n/locales/en.json | 36 ++- src/lib/i18n/locales/es.json | 36 ++- src/lib/server/events/config.ts | 34 +++ src/lib/server/events/event-log.test.ts | 152 +++++++++++++ src/lib/server/events/event-log.ts | 111 ++++++++++ src/lib/server/events/index.ts | 28 ++- src/lib/server/request-context.test.ts | 20 ++ src/lib/server/request-context.ts | 8 +- src/routes/org/[org]/events/+page.server.ts | 113 ++++++++++ src/routes/org/[org]/events/+page.svelte | 208 ++++++++++++++++++ .../org/[org]/events/event-view.test.ts | 147 +++++++++++++ src/routes/org/[org]/events/event-view.ts | 155 +++++++++++++ 18 files changed, 1128 insertions(+), 5 deletions(-) create mode 100644 e2e/specs/org-events.spec.ts create mode 100644 src/lib/server/events/config.ts create mode 100644 src/lib/server/events/event-log.test.ts create mode 100644 src/lib/server/events/event-log.ts create mode 100644 src/lib/server/request-context.test.ts create mode 100644 src/routes/org/[org]/events/+page.server.ts create mode 100644 src/routes/org/[org]/events/+page.svelte create mode 100644 src/routes/org/[org]/events/event-view.test.ts create mode 100644 src/routes/org/[org]/events/event-view.ts diff --git a/.env.example b/.env.example index 0c869720..fc7b8316 100644 --- a/.env.example +++ b/.env.example @@ -62,3 +62,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//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 diff --git a/CLAUDE.md b/CLAUDE.md index c2d670a3..66399a19 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,6 +146,10 @@ in `docs/adr/0001-event-bus-and-alerts.md`. `#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//events`, where + users see the events they are allowed to read (each definition's `readPermission`, checked in + the event's project or organization) and acknowledge them. Retention: `GITOPS_EVENTS_EXPIRATION` + (default `7d`). It is per process and cleared on restart. ## Authorization diff --git a/docs/adr/0001-event-bus-and-alerts.md b/docs/adr/0001-event-bus-and-alerts.md index e828be73..96354351 100644 --- a/docs/adr/0001-event-bus-and-alerts.md +++ b/docs/adr/0001-event-bus-and-alerts.md @@ -58,7 +58,13 @@ Each type and its payload is declared in `DomainEventMap` (`src/lib/server/event - **Alerts** are configuration and are stored in **GitDB** (auditable, consistent with the rest of the platform). -- **Events are not persisted.** +- **Events are not persisted in GitDB.** For the organization events page (`/org//events`), + an in-memory log (`eventLog`, `InMemoryEventLog`) subscribes to the bus and keeps recent events + together with a shared acknowledgement (who and when). Retention is configured with + `GITOPS_EVENTS_EXPIRATION` (`30d`, `12h`, `45m`, a bare number is seconds; default `7d`), capped + at 10,000 events. Like the bus, it is per process: a restart clears it, including the + acknowledgements, and each replica shows its own list. Persisting events (and acks) in GitDB + was considered and rejected for now: one commit per event and per ack. - **Alert executions** (firing history) are **not** stored in GitDB in v1, to avoid one commit per email sent: only logs, plus optionally an in-memory buffer of the last N firings per alert. diff --git a/e2e/specs/org-events.spec.ts b/e2e/specs/org-events.spec.ts new file mode 100644 index 00000000..e4c33b09 --- /dev/null +++ b/e2e/specs/org-events.spec.ts @@ -0,0 +1,61 @@ +import { test, expect, getSeed } from '../fixtures/auth'; +import { expectAllowed, expectDenied } from '../fixtures/expect-access'; + +const seed = getSeed(); +const eventsUrl = `/org/${seed.primaryOrgSlug}/events`; + +// a CI run through the machine-to-machine API: the analysis completes and publishes +// code_report.analysis.completed, which the in-memory event log keeps for the page +async function completeAnalysis(request: import('@playwright/test').APIRequestContext) { + const headers = { Authorization: `Bearer ${seed.apiKeys.write}` }; + const started = await request.post('/api/code-report/scan', { + headers, + data: { + status: 'in_progress', + service: seed.seededServiceSlug, + project: seed.primaryProjectSlug, + tool: 'trivy', + }, + }); + expect(started.status()).toBe(200); + const { analysis } = await started.json(); + + const completed = await request.post('/api/code-report/scan', { + headers, + data: { + status: 'completed', + analysisId: analysis.id, + result: { Results: [{ Vulnerabilities: [{ VulnerabilityID: 'CVE-1', Severity: 'HIGH' }] }] }, + }, + }); + expect(completed.status()).toBe(200); +} + +test.describe('organization events page', () => { + test('an org admin sees a CI analysis event and acknowledges it', async ({ + page, + request, + loginAs, + }) => { + await completeAnalysis(request); + await loginAs('orgAdmin'); + + await expectAllowed(page, `${eventsUrl}?status=pending`); + const row = page.locator('li', { hasText: 'Análisis completado' }).first(); + await expect(row).toBeVisible(); + await expect(row).toContainText('API key'); + + await row.getByRole('button', { name: 'Marcar como revisado' }).click(); + await expect(row).toContainText(`Revisado por ${seed.personas.orgAdmin.username}`); + + await page.goto(`${eventsUrl}?status=acked`); + await expect(page.locator('li', { hasText: 'Análisis completado' }).first()).toContainText( + `Revisado por ${seed.personas.orgAdmin.username}`, + ); + }); + + test('users outside the organization cannot open it', async ({ page, loginAs }) => { + await loginAs('orgOutsider'); + await expectDenied(page, eventsUrl); + }); +}); diff --git a/src/env.ts b/src/env.ts index fe90f90e..9f995c2c 100644 --- a/src/env.ts +++ b/src/env.ts @@ -28,4 +28,5 @@ export const variables = defineEnvVars({ GOOGLE_SSO_CLIENT_SECRET: optional, GOOGLE_SSO_ALLOWED_DOMAINS: optional, GOOGLE_SSO_AUTO_PROVISION: optional, + GITOPS_EVENTS_EXPIRATION: optional, }); diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 8d70506a..09ec879d 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -1,6 +1,7 @@ + + + {$_('org.events.title')} - GitOps + + +

+
+
+

{$_('org.events.title')}

+

{$_('org.events.description')}

+

+ {$_('org.events.retentionNotice', { values: { retention } })} +

+
+
+ + {$_('org.events.pendingCount', { values: { count: pendingCount } })} +
+
+ +
+ + + +
+ + {#if error} +
+ {error} +
+ {/if} + + {#if data.events.length === 0} +
+ +

{$_('org.events.emptyTitle')}

+

{$_('org.events.emptyDescription')}

+
+ {:else} +
    + {#each data.events as event (event.id)} +
  • +
    +
    + + {$_(`org.events.modules.${event.module}`)} + +

    {$_(event.label)}

    +
    +

    + {formatDate(event.occurredAt)} · {actorName(event)} + {#if event.project} + · {$_('org.events.inProject', { + values: { name: event.project.name ?? event.project.id }, + })} + {/if} +

    + {#if event.fields.length > 0} +
    + + {$_('org.events.details')} + +
    + {#each event.fields as field (field.label)} +
    +
    {$_(field.label)}:
    +
    + {field.translate ? $_(field.value) : field.value} +
    +
    + {/each} +
    +
    + {/if} +
    + +
    + {#if event.ack} +
    + + + {$_('org.events.ackedBy', { + values: { name: event.ack.username, date: formatDate(event.ack.at) }, + })} + +
    + {:else} +
    + + +
    + {/if} +
    +
  • + {/each} +
+ {/if} +
diff --git a/src/routes/org/[org]/events/event-view.test.ts b/src/routes/org/[org]/events/event-view.test.ts new file mode 100644 index 00000000..cdb268d9 --- /dev/null +++ b/src/routes/org/[org]/events/event-view.test.ts @@ -0,0 +1,147 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { AnyDomainEvent, LoggedEvent } from '#lib/server/events'; +import { + createEventVisibility, + parseModuleFilter, + parseStatusFilter, + toEventView, +} from './event-view'; + +function logged(event: Partial, ack: LoggedEvent['ack'] = null): LoggedEvent { + return { + event: { + id: 'event-1', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'user', userId: 'user-1' }, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + ...event, + } as AnyDomainEvent, + ack, + }; +} + +const secretCreated = logged({ + type: 'vault.secret.created', + payload: { + secretId: 's1', + key: 'DB_PASSWORD', + folderId: null, + folderPath: '/', + environmentIds: ['env-prod'], + }, +}); + +const projectUpdated = logged({ + type: 'project.updated', + payload: { projectId: 'project-1', name: 'Shop', slug: 'shop', changedFields: ['name'] }, +}); + +describe('createEventVisibility', () => { + it("checks the event's read permission in the project for project grants", async () => { + const can = vi.fn(async () => true); + const isVisible = createEventVisibility('org-1', can); + + await expect(isVisible(secretCreated)).resolves.toBe(true); + expect(can).toHaveBeenCalledWith('project:vault:secrets:read', { + scope: 'project', + organizationId: 'org-1', + projectId: 'project-1', + }); + }); + + it('checks organization grants in the organization', async () => { + const can = vi.fn(async () => false); + const isVisible = createEventVisibility('org-1', can); + + await expect(isVisible(projectUpdated)).resolves.toBe(false); + expect(can).toHaveBeenCalledWith('organization:projects:read', { + scope: 'organization', + organizationId: 'org-1', + }); + }); + + it('caches checks per permission and project', async () => { + const can = vi.fn(async () => true); + const isVisible = createEventVisibility('org-1', can); + + await isVisible(secretCreated); + await isVisible({ ...secretCreated, event: { ...secretCreated.event, id: 'event-2' } }); + + expect(can).toHaveBeenCalledTimes(1); + }); + + it('hides events of other organizations, unknown types and failed checks', async () => { + const isVisible = createEventVisibility('org-2', async () => true); + const failing = createEventVisibility('org-1', async () => { + throw new Error('boom'); + }); + + await expect(isVisible(secretCreated)).resolves.toBe(false); + await expect( + createEventVisibility('org-1', async () => true)(logged({ type: 'unknown.event' as never })), + ).resolves.toBe(false); + await expect(failing(secretCreated)).resolves.toBe(false); + }); +}); + +describe('toEventView', () => { + const lookups = { + usernames: new Map([['user-1', 'ana']]), + projectNames: new Map([['project-1', 'Shop']]), + apiKeyNames: new Map([['key-1', 'CI']]), + }; + + it('resolves the actor, project and catalog fields, never secret values', () => { + const view = toEventView(secretCreated, lookups); + + expect(view).toMatchObject({ + id: 'event-1', + module: 'vault', + label: 'events.vault.secret.created.label', + actor: { kind: 'user', name: 'ana' }, + project: { id: 'project-1', name: 'Shop' }, + ack: null, + }); + expect(view?.fields).toEqual([ + { label: 'events.vault.secret.created.fields.key', value: 'DB_PASSWORD' }, + { label: 'events.vault.secret.created.fields.environmentIds', value: 'env-prod' }, + { label: 'events.vault.secret.created.fields.folderPath', value: '/' }, + ]); + }); + + it('shows API key and system actors and the acknowledgement', () => { + const byKey = toEventView( + logged( + { ...projectUpdated.event, actor: { kind: 'api_key', apiKeyId: 'key-1', projectId: null } }, + { userId: 'user-2', username: 'bob', at: '2026-11-20T11:00:00.000Z' }, + ), + lookups, + ); + const bySystem = toEventView( + logged({ ...projectUpdated.event, actor: { kind: 'system' } }), + lookups, + ); + + expect(byKey?.actor).toEqual({ kind: 'api_key', name: 'CI' }); + expect(byKey?.ack).toEqual({ username: 'bob', at: '2026-11-20T11:00:00.000Z' }); + expect(bySystem?.actor).toEqual({ kind: 'system', name: null }); + }); + + it('resolves reference fields to names', () => { + const view = toEventView(projectUpdated, lookups); + + expect(view?.fields[0]).toEqual({ + label: 'events.project.updated.fields.projectId', + value: 'Shop', + }); + }); +}); + +describe('filters', () => { + it('parses status and module filters, ignoring unknown values', () => { + expect(parseStatusFilter('pending')).toBe('pending'); + expect(parseStatusFilter('nope')).toBe('all'); + expect(parseModuleFilter('vault')).toBe('vault'); + expect(parseModuleFilter('nope')).toBeNull(); + }); +}); diff --git a/src/routes/org/[org]/events/event-view.ts b/src/routes/org/[org]/events/event-view.ts new file mode 100644 index 00000000..d1d7cdf9 --- /dev/null +++ b/src/routes/org/[org]/events/event-view.ts @@ -0,0 +1,155 @@ +import { + getEventDefinition, + getFieldValue, + isEventType, + type EventDefinition, + type EventModule, +} from '#lib/events/catalog'; +import type { LoggedEvent } from '#lib/server/events'; + +export const EVENT_MODULES: readonly EventModule[] = [ + 'code_report', + 'vault', + 'projects', + 'organization', + 'access', +]; + +export type EventStatusFilter = 'all' | 'pending' | 'acked'; + +export type EventFieldView = { + /** i18n key */ + label: string; + value: string; + /** `value` is an i18n key (booleans) rather than display text. */ + translate?: boolean; +}; + +export type EventView = { + id: string; + type: string; + module: EventModule; + /** i18n key */ + label: string; + occurredAt: string; + actor: { kind: 'user' | 'api_key' | 'system'; name: string | null }; + project: { id: string; name: string | null } | null; + fields: EventFieldView[]; + ack: { username: string; at: string } | null; +}; + +type PermissionContext = + | { scope: 'organization'; organizationId: string } + | { scope: 'project'; organizationId: string; projectId: string }; + +export type PermissionCheck = (permission: string, context: PermissionContext) => Promise; + +/** + * Whether the viewer may see (and acknowledge) an event: the event's `readPermission` checked in + * the scope it belongs to. Results are cached per permission and project for one request. + */ +export function createEventVisibility(organizationId: string, can: PermissionCheck) { + const cache = new Map>(); + + return (entry: LoggedEvent): Promise => { + if (!isEventType(entry.event.type)) return Promise.resolve(false); + if (entry.event.scope.organizationId !== organizationId) return Promise.resolve(false); + + const { readPermission } = getEventDefinition(entry.event.type); + const projectId = entry.event.scope.projectId ?? null; + // project grants are checked against the project; organization grants against the org + const context: PermissionContext = + readPermission.startsWith('project:') && projectId + ? { scope: 'project', organizationId, projectId } + : { scope: 'organization', organizationId }; + + const key = `${readPermission}|${context.scope === 'project' ? context.projectId : ''}`; + let allowed = cache.get(key); + if (!allowed) { + allowed = can(readPermission, context).catch(() => false); + cache.set(key, allowed); + } + return allowed; + }; +} + +export type EventViewLookups = { + usernames: Map; + projectNames: Map; + apiKeyNames?: Map; + serviceNames?: Map; + roleNames?: Map; +}; + +const REFERENCE_LOOKUP: Partial< + Record, keyof EventViewLookups> +> = { + user: 'usernames', + project: 'projectNames', + api_key: 'apiKeyNames', + code_report_service: 'serviceNames', + role: 'roleNames', +}; + +function formatValue( + value: unknown, + reference: EventDefinition['fields'][number]['reference'], + lookups: EventViewLookups, +): string { + if (value === null || value === undefined || value === '') return '—'; + if (Array.isArray(value)) { + return value.length === 0 + ? '—' + : value.map((item) => formatValue(item, reference, lookups)).join(', '); + } + if (typeof value === 'string') { + const lookup = reference ? REFERENCE_LOOKUP[reference] : undefined; + return (lookup && lookups[lookup]?.get(value)) || value; + } + return String(value); +} + +export function toEventView(entry: LoggedEvent, lookups: EventViewLookups): EventView | null { + const { event } = entry; + if (!isEventType(event.type)) return null; + const definition = getEventDefinition(event.type) as EventDefinition; + + const actor: EventView['actor'] = + event.actor.kind === 'user' + ? { kind: 'user', name: lookups.usernames.get(event.actor.userId) ?? event.actor.userId } + : event.actor.kind === 'api_key' + ? { + kind: 'api_key', + name: lookups.apiKeyNames?.get(event.actor.apiKeyId) ?? null, + } + : { kind: 'system', name: null }; + + const projectId = event.scope.projectId ?? null; + + return { + id: event.id, + type: event.type, + module: definition.module, + label: definition.label, + occurredAt: event.occurredAt, + actor, + project: projectId + ? { id: projectId, name: lookups.projectNames.get(projectId) ?? null } + : null, + fields: definition.fields.map((field) => { + const value = getFieldValue(event, field.key as string); + return typeof value === 'boolean' + ? { label: field.label, value: value ? 'common.yes' : 'common.no', translate: true } + : { label: field.label, value: formatValue(value, field.reference, lookups) }; + }), + ack: entry.ack ? { username: entry.ack.username, at: entry.ack.at } : null, + }; +} + +export function parseStatusFilter(value: string | null): EventStatusFilter { + return value === 'pending' || value === 'acked' ? value : 'all'; +} + +export function parseModuleFilter(value: string | null): EventModule | null { + return EVENT_MODULES.find((module) => module === value) ?? null; +} From 3ce2c53cdb7a3623975bcfde97dbdfa52dc777c2 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 15:46:48 +0100 Subject: [PATCH 08/13] feat(events): move the events page to org settings behind organization:events - /org//settings/events, listed under organization settings in the sidebar - new organization:events permission: read to open the page, update to acknowledge - default Organization Admin role gets organization:events:all; existing roles are not migrated, the permission shows up in the role editor to enable it - e2e: page in the organization settings permission matrix Co-Authored-By: Claude Opus 5.5 --- .env.example | 2 +- CLAUDE.md | 15 ++++++++----- docs/adr/0001-event-bus-and-alerts.md | 2 +- e2e/specs/org-events.spec.ts | 7 +++++- e2e/specs/organization-settings.spec.ts | 1 + src/lib/components/AppSidebar.svelte | 12 +++++----- src/lib/config/permissions.ts | 5 +++++ .../auth/domain/role-permissions.data.ts | 1 + src/routes/+layout.server.ts | 3 +++ src/routes/+layout.svelte | 1 + .../{ => settings}/events/+page.server.ts | 22 ++++++++++++------- .../[org]/{ => settings}/events/+page.svelte | 7 +++--- .../{ => settings}/events/event-view.test.ts | 0 .../[org]/{ => settings}/events/event-view.ts | 0 14 files changed, 53 insertions(+), 25 deletions(-) rename src/routes/org/[org]/{ => settings}/events/+page.server.ts (88%) rename src/routes/org/[org]/{ => settings}/events/+page.svelte (97%) rename src/routes/org/[org]/{ => settings}/events/event-view.test.ts (100%) rename src/routes/org/[org]/{ => settings}/events/event-view.ts (100%) diff --git a/.env.example b/.env.example index fc7b8316..c1d6bc38 100644 --- a/.env.example +++ b/.env.example @@ -63,7 +63,7 @@ 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//events) keeps events and their +# How long the organization events page (/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 diff --git a/CLAUDE.md b/CLAUDE.md index 66399a19..cb1948e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,10 +146,13 @@ in `docs/adr/0001-event-bus-and-alerts.md`. `#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//events`, where - users see the events they are allowed to read (each definition's `readPermission`, checked in - the event's project or organization) and acknowledge them. Retention: `GITOPS_EVENTS_EXPIRATION` - (default `7d`). It is per process and cleared on restart. +- `eventLog` (`#lib/server/events`) keeps recent events in memory for + `/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. ## Authorization @@ -191,7 +194,7 @@ 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 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` This ensures the UI only displays navigation items for sections the user has permission to view. @@ -200,7 +203,7 @@ 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 - **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 diff --git a/docs/adr/0001-event-bus-and-alerts.md b/docs/adr/0001-event-bus-and-alerts.md index 96354351..10d04511 100644 --- a/docs/adr/0001-event-bus-and-alerts.md +++ b/docs/adr/0001-event-bus-and-alerts.md @@ -58,7 +58,7 @@ Each type and its payload is declared in `DomainEventMap` (`src/lib/server/event - **Alerts** are configuration and are stored in **GitDB** (auditable, consistent with the rest of the platform). -- **Events are not persisted in GitDB.** For the organization events page (`/org//events`), +- **Events are not persisted in GitDB.** For the organization events page (`/org//settings/events`), an in-memory log (`eventLog`, `InMemoryEventLog`) subscribes to the bus and keeps recent events together with a shared acknowledgement (who and when). Retention is configured with `GITOPS_EVENTS_EXPIRATION` (`30d`, `12h`, `45m`, a bare number is seconds; default `7d`), capped diff --git a/e2e/specs/org-events.spec.ts b/e2e/specs/org-events.spec.ts index e4c33b09..5d2178f6 100644 --- a/e2e/specs/org-events.spec.ts +++ b/e2e/specs/org-events.spec.ts @@ -2,7 +2,7 @@ import { test, expect, getSeed } from '../fixtures/auth'; import { expectAllowed, expectDenied } from '../fixtures/expect-access'; const seed = getSeed(); -const eventsUrl = `/org/${seed.primaryOrgSlug}/events`; +const eventsUrl = `/org/${seed.primaryOrgSlug}/settings/events`; // a CI run through the machine-to-machine API: the analysis completes and publishes // code_report.analysis.completed, which the in-memory event log keeps for the page @@ -58,4 +58,9 @@ test.describe('organization events page', () => { await loginAs('orgOutsider'); await expectDenied(page, eventsUrl); }); + + test('org roles without organization:events:read cannot open it', async ({ page, loginAs }) => { + await loginAs('orgDeveloper'); + await expectDenied(page, eventsUrl); + }); }); diff --git a/e2e/specs/organization-settings.spec.ts b/e2e/specs/organization-settings.spec.ts index adfa2dc5..d1fcb516 100644 --- a/e2e/specs/organization-settings.spec.ts +++ b/e2e/specs/organization-settings.spec.ts @@ -12,6 +12,7 @@ const settingsRoutes = [ `/org/${org}/settings/system-backup`, `/org/${org}/settings/server-access-keys`, `/org/${org}/settings/audit`, + `/org/${org}/settings/events`, ]; test.describe('organization settings — org admin', () => { diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 09ec879d..a0a4b609 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -47,6 +47,7 @@ export let canReadOrgBackups = false; export let canReadOrgServerKeys = false; export let canReadOrgAudit = false; + export let canReadOrgEvents = false; export let canReadProjectInfo = false; export let canReadProjectUsers = false; export let canReadProjectRoles = false; @@ -93,11 +94,6 @@ href: `/org/${organizationSlug}/cves`, icon: ShieldAlert, }, - { - label: $_('sidebar.items.events'), - href: `/org/${organizationSlug}/events`, - icon: Activity, - }, ] : [ { @@ -308,6 +304,12 @@ icon: ScrollText, visible: canReadOrgAudit, }, + { + label: $_('sidebar.items.events'), + href: `/org/${organizationSlug}/settings/events`, + icon: Activity, + visible: canReadOrgEvents, + }, ] .filter((item) => item.visible) .map(({ visible, ...item }) => item); diff --git a/src/lib/config/permissions.ts b/src/lib/config/permissions.ts index 91f169f9..1478064e 100644 --- a/src/lib/config/permissions.ts +++ b/src/lib/config/permissions.ts @@ -59,6 +59,11 @@ const permissions = { resource: 'audit', permissions: grantsFor('organization', 'audit'), }, + // events page (/org//settings/events): read to see it, update to acknowledge events + events: { + resource: 'events', + permissions: grantsFor('organization', 'events'), + }, }, }, project: { diff --git a/src/modules/auth/domain/role-permissions.data.ts b/src/modules/auth/domain/role-permissions.data.ts index 1b7c5dcc..f8fe1d96 100644 --- a/src/modules/auth/domain/role-permissions.data.ts +++ b/src/modules/auth/domain/role-permissions.data.ts @@ -16,6 +16,7 @@ export const ORGANIZATION_ADMIN_PERMISSIONS = [ 'organization:backups:all', 'organization:server-keys:all', 'organization:audit:all', + 'organization:events:all', ]; export const ORGANIZATION_DEVELOPER_PERMISSIONS = [ diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts index 983c71d8..dd18806d 100644 --- a/src/routes/+layout.server.ts +++ b/src/routes/+layout.server.ts @@ -58,6 +58,7 @@ export async function load({ locals, url }) { canReadOrgBackups, canReadOrgServerKeys, canReadOrgAudit, + canReadOrgEvents, ] = await Promise.all([ orgSectionPermission('organization:projects:read'), orgSectionPermission('organization:users:read'), @@ -66,6 +67,7 @@ export async function load({ locals, url }) { orgSectionPermission('organization:backups:read'), orgSectionPermission('organization:server-keys:read'), orgSectionPermission('organization:audit:read'), + orgSectionPermission('organization:events:read'), ]); const currentProjectSlug = url.pathname.match(/\/projects\/([^/]+)/)?.[1] ?? null; @@ -167,6 +169,7 @@ export async function load({ locals, url }) { canReadOrgBackups, canReadOrgServerKeys, canReadOrgAudit, + canReadOrgEvents, canReadProjectInfo, canReadProjectUsers, canReadProjectRoles, diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 8451dd02..2284ea09 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -60,6 +60,7 @@ canReadOrgBackups={data.canReadOrgBackups} canReadOrgServerKeys={data.canReadOrgServerKeys} canReadOrgAudit={data.canReadOrgAudit} + canReadOrgEvents={data.canReadOrgEvents} canReadProjectInfo={data.canReadProjectInfo} canReadProjectUsers={data.canReadProjectUsers} canReadProjectRoles={data.canReadProjectRoles} diff --git a/src/routes/org/[org]/events/+page.server.ts b/src/routes/org/[org]/settings/events/+page.server.ts similarity index 88% rename from src/routes/org/[org]/events/+page.server.ts rename to src/routes/org/[org]/settings/events/+page.server.ts index bf2ab3e1..1b3bc0a0 100644 --- a/src/routes/org/[org]/events/+page.server.ts +++ b/src/routes/org/[org]/settings/events/+page.server.ts @@ -21,11 +21,11 @@ import { const PAGE_SIZE = 200; -async function requireViewer(locals: Locals, organizationId: string) { - if (!locals.user || !(await cancanService.canViewOrganization(locals.user, organizationId))) { - throw error(403, 'Forbidden'); - } - return locals.user; +function canEvents(locals: Locals, organizationId: string, action: 'read' | 'update') { + return cancanService.canSessionUser(locals.user, `organization:events:${action}`, { + scope: 'organization', + organizationId, + }); } function visibilityFor(locals: Locals, organizationId: string) { @@ -36,7 +36,10 @@ function visibilityFor(locals: Locals, organizationId: string) { export async function load({ parent, locals, url }) { const { organization } = await parent(); - await requireViewer(locals, organization.id); + if (!(await canEvents(locals, organization.id, 'read'))) { + throw error(403, 'Forbidden'); + } + const canAck = await canEvents(locals, organization.id, 'update'); const module = parseModuleFilter(url.searchParams.get('module')); const status = parseStatusFilter(url.searchParams.get('status')); @@ -85,6 +88,7 @@ export async function load({ parent, locals, url }) { orgSlug: organization.slug, events: visible.map((entry) => toEventView(entry, lookups)).filter((e): e is EventView => !!e), filters: { module, status }, + canAck, modules: EVENT_MODULES, retentionMs: readEventsExpirationMs(), }; @@ -95,8 +99,10 @@ export const actions = { const organization = await organizationService.tryFindBySlug(params.org); if (!organization) return fail(404, { error: 'Organization not found' }); - const user = await requireViewer(locals, organization.id).catch(() => null); - if (!user) return fail(403, { error: 'Forbidden' }); + const user = locals.user; + if (!user || !(await canEvents(locals, organization.id, 'update'))) { + return fail(403, { error: 'Forbidden' }); + } const form = await request.formData(); const eventId = String(form.get('eventId') ?? ''); diff --git a/src/routes/org/[org]/events/+page.svelte b/src/routes/org/[org]/settings/events/+page.svelte similarity index 97% rename from src/routes/org/[org]/events/+page.svelte rename to src/routes/org/[org]/settings/events/+page.svelte index a8d3a91b..3431c54e 100644 --- a/src/routes/org/[org]/events/+page.svelte +++ b/src/routes/org/[org]/settings/events/+page.svelte @@ -9,6 +9,7 @@ orgSlug: string; events: EventView[]; filters: { module: string | null; status: EventStatusFilter }; + canAck: boolean; modules: readonly string[]; retentionMs: number; }; @@ -67,10 +68,10 @@ {$_('org.events.title')} - GitOps -
+
-

{$_('org.events.title')}

+

{$_('org.events.title')}

{$_('org.events.description')}

{$_('org.events.retentionNotice', { values: { retention } })} @@ -187,7 +188,7 @@ })}

- {:else} + {:else if data.canAck}
+ {/if} + +
+ + + {$_('alerts.editor.back')} + + {#if message} + + {/if} +
+ + +
+

+ 1. {$_('alerts.editor.stepEvent')} +

+ +
+
+ + + {#if errors.name} + + {/if} +
+
+ + +

+ {definition ? $_(definition.description) : $_('alerts.editor.eventHelp')} +

+ {#if errors.eventType} + + {/if} + +
+
+ +
+ + +
+ + +
+ + +
+

+ 2. {$_('alerts.editor.stepConditions')} +

+ {#if droppedConditions > 0} +

+ {$_('alerts.editor.droppedConditions', { values: { count: droppedConditions } })} +

+ {/if} + {#if definition} + + {:else} +

{$_('alerts.editor.chooseEventFirst')}

+ + {/if} +
+ + +
+

+ 3. {$_('alerts.editor.stepRecipients')} +

+

+ + {$_('alerts.editor.recipientsNotice')} +

+
+
+ + {$_('alerts.editor.roles')} + + { + draft.recipients.roleIds = selected; + }} + /> +
+
+ {$_('alerts.editor.users')} + { + draft.recipients.userIds = selected; + }} + /> +
+
+ {#if errors.recipients || errors['recipients.userIds'] || errors['recipients.roleIds']} + + {/if} + +
+ {$_('alerts.editor.channels')} + + {#each ['in_app', 'slack'] as channel (channel)} + + {/each} +
+ +
+ + +

+ {$_('alerts.editor.throttleHelp')} +

+ {#if errors.throttleMinutes} + + {/if} +
+
+ + +
+

+ 4. {$_('alerts.editor.stepSave')} +

+ + {#if needsSampleProject && projects.length > 0} +
+ + +
+ {/if} + + {#if test} +
+

+ {test.matched ? $_('alerts.test.matched') : $_('alerts.test.notMatched')} +

+ {#if test.recipients.length > 0} +

+ {$_('alerts.test.recipients', { + values: { names: test.recipients.map((recipient) => recipient.username).join(', ') }, + })} +

+ {:else} +

{$_('alerts.test.noRecipients')}

+ {/if} + {#if test.deniedCount > 0} +

+ {$_('alerts.test.denied', { values: { count: test.deniedCount } })} +

+ {/if} +

{$_('alerts.test.nothingSent')}

+
+ {/if} + +
+ {#if data.canSave} + + + {/if} + {#if data.canDelete} + + {/if} +
+
+ diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte new file mode 100644 index 00000000..cfc44630 --- /dev/null +++ b/src/lib/components/alerts/AlertList.svelte @@ -0,0 +1,227 @@ + + +
+
+
+

{$_('alerts.list.title')}

+

+ {data.scope === 'project' + ? $_('alerts.list.descriptionProject') + : $_('alerts.list.descriptionOrganization')} +

+
+ {#if data.canCreate && data.alerts.length > 0} + + + {$_('alerts.list.create')} + + {/if} +
+ + {#if error} + + {/if} + + {#if data.alerts.length === 0} +
+ +

{$_('alerts.list.emptyTitle')}

+
    + {#each examples as example (example)} +
  • “{$_(example)}”
  • + {/each} +
+ {#if data.canCreate} + + + {$_('alerts.list.create')} + + {/if} +
+ {:else} + {@render table(data.alerts, false)} + {/if} + + {#if data.scope === 'project' && data.inherited.length > 0} +
+
+

{$_('alerts.list.inheritedTitle')}

+

{$_('alerts.list.inheritedDescription')}

+
+ {@render table(data.inherited, true)} +
+ {/if} +
+ +{#snippet table(alerts: AlertRow[], readonly: boolean)} +
+ + + + + + + + + {#if !readonly && (data.canUpdate || data.canDelete)} + + {/if} + + + + {#each alerts as alert (alert.id)} + + + + + + + {#if !readonly && (data.canUpdate || data.canDelete)} + + {/if} + + {/each} + +
{$_('alerts.list.name')}{$_('alerts.list.event')}{$_('alerts.list.conditions')}{$_('alerts.list.recipients')}{$_('alerts.list.status')}{$_('alerts.list.actions')}
+ {#if !readonly && data.canUpdate} + {alert.name} + {:else} + {alert.name} + {/if} + {#if alert.throttleMinutes > 0} +

+ {$_('alerts.list.throttle', { values: { minutes: alert.throttleMinutes } })} +

+ {/if} +
+

{eventLabel(alert)}

+

{moduleLabel(alert)}

+
{conditionsOf(alert)} + {summarizeRecipients(alert.recipients, data.users, data.roles, t)} + + {#if !readonly && data.canUpdate} +
+ + + +
+ {:else} + + {alert.enabled ? $_('alerts.list.enabled') : $_('alerts.list.disabled')} + + {/if} +
+
+ {#if data.canUpdate} + + + {$_('alerts.list.edit')} + + {/if} + {#if data.canDelete} +
{ + if (!confirm($_('alerts.list.confirmDelete'))) cancel(); + }} + > + + +
+ {/if} +
+
+
+{/snippet} diff --git a/src/lib/components/alerts/ConditionBuilder.svelte b/src/lib/components/alerts/ConditionBuilder.svelte new file mode 100644 index 00000000..1bc3d253 --- /dev/null +++ b/src/lib/components/alerts/ConditionBuilder.svelte @@ -0,0 +1,288 @@ + + +
+
+ {$_('alerts.editor.matchLabel')} + + +
+ + {#if conditions.length === 0} +

+ {$_('alerts.editor.noConditions')} +

+ {/if} + +
    + {#each conditions as condition, index (index)} + {@const field = fieldOf(condition.field)} +
  1. +
    + + + {#if errors[`conditions.${index}.field`]} + + {/if} +
    + +
    + + + {#if errors[`conditions.${index}.operator`]} + + {/if} +
    + +
    + + {$_('alerts.editor.value')} + + + {#if !field || !needsValue(condition.operator)} +

    —

    + {:else if field.type === 'enum' || field.type === 'reference'} + ({ + id: option.value, + label: $_(option.label), + })) + : (referenceOptions[field.reference ?? ''] ?? [])} + selected={valueList(condition.value)} + invalid={Boolean(errors[`conditions.${index}.value`])} + describedBy={errorId(index, 'value')} + onchange={(selected) => + setValue(index, isList(condition.operator) ? selected : (selected[0] ?? ''))} + /> + {:else if field.type === 'number'} + setValue(index, event.currentTarget.value)} + /> + {:else if field.type === 'date'} + setValue(index, event.currentTarget.value)} + /> + {:else} + setValue(index, event.currentTarget.value)} + /> + {/if} + {#if errors[`conditions.${index}.value`]} + + {/if} +
    + +
    + +
    +
  2. + {/each} +
+ + {#if errors.conditions} + + {/if} + + +
diff --git a/src/lib/components/alerts/ConditionBuilder.test.ts b/src/lib/components/alerts/ConditionBuilder.test.ts new file mode 100644 index 00000000..41a1e666 --- /dev/null +++ b/src/lib/components/alerts/ConditionBuilder.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it, vi } from 'vitest'; +import { render } from 'svelte/server'; +import type { CatalogEntry } from '#lib/alerts/types'; + +// `#lib/i18n` reads `$app/env`, which only exists inside SvelteKit +vi.mock('$app/env', () => ({ browser: false })); + +const { default: ConditionBuilder } = await import('./ConditionBuilder.svelte'); + +/** A made-up event: nothing in the component knows about it. */ +const definition: CatalogEntry = { + type: 'code_report.analysis.completed', + module: 'code_report', + scope: 'project', + label: 'events.code_report.analysis.completed.label', + description: 'events.code_report.analysis.completed.description', + readPermission: 'project:codereport:reports:read', + alertable: true, + fields: [ + { key: 'branch', label: 'test.fields.branch', type: 'string', operators: ['eq', 'contains'] }, + { key: 'count', label: 'test.fields.count', type: 'number', operators: ['gt', 'lte'] }, + { key: 'when', label: 'test.fields.when', type: 'date', operators: ['gt'] }, + { key: 'flag', label: 'test.fields.flag', type: 'boolean', operators: ['is_true', 'is_false'] }, + { + key: 'tool', + label: 'test.fields.tool', + type: 'enum', + operators: ['eq', 'in'], + options: [ + { value: 'trivy', label: 'test.options.trivy' }, + { value: 'grype', label: 'test.options.grype' }, + ], + }, + { + key: 'serviceId', + label: 'test.fields.service', + type: 'reference', + reference: 'code_report_service', + operators: ['eq', 'in'], + }, + ], +}; + +const referenceOptions = { + code_report_service: [ + { id: 'svc-1', label: 'api-gateway' }, + { id: 'svc-2', label: 'web' }, + ], +}; + +function html(conditions: Array<{ field: string; operator: string; value: string | string[] }>) { + return render(ConditionBuilder, { + props: { + definition, + conditions: conditions as never, + match: 'all', + referenceOptions, + errors: { 'conditions.1.value': 'invalid' }, + }, + }).body; +} + +describe('ConditionBuilder', () => { + it('offers every catalog field of the event, and only its operators', () => { + const body = html([{ field: 'branch', operator: 'eq', value: 'main' }]); + + for (const field of definition.fields) { + expect(body).toContain(`value="${field.key}"`); + } + expect(body).toContain('name="conditions.0.field"'); + // operators of `branch` only + expect(body).toContain('value="contains"'); + expect(body).not.toContain('value="gt"'); + }); + + it('renders the input that matches each field type', () => { + const body = html([ + { field: 'branch', operator: 'eq', value: 'main' }, + { field: 'count', operator: 'gt', value: '0' }, + { field: 'when', operator: 'gt', value: '2026-01-01T00:00:00.000Z' }, + { field: 'flag', operator: 'is_true', value: '' }, + { field: 'tool', operator: 'in', value: ['trivy'] }, + { field: 'serviceId', operator: 'eq', value: 'svc-2' }, + ]); + const rows = body.split('data-testid="condition-row"').slice(1); + + expect(rows[0]).toMatch(/type="text"[^>]*name="conditions\.0\.value"/); + expect(rows[1]).toMatch(/type="number"/); + expect(rows[2]).toMatch(/type="date"/); + expect(rows[2]).toContain('value="2026-01-01"'); + // booleans take no value + expect(rows[3]).toContain('data-input="none"'); + expect(rows[3]).not.toContain('name="conditions.3.value"'); + // enum + `in`: multiple choice with the catalog options + expect(rows[4]).toMatch(/type="checkbox"[^>]*name="conditions\.4\.value"[^>]*value="trivy"/); + expect(rows[4]).toContain('value="grype"'); + expect(rows[4]).toContain('name="conditions.4.multiple" value="true"'); + // reference + `eq`: single choice among the entities of the scope + expect(rows[5]).toMatch(/type="radio"[^>]*name="conditions\.5\.value"[^>]*value="svc-2"/); + expect(rows[5]).toContain('api-gateway'); + }); + + it('links server errors to their input', () => { + const body = html([ + { field: 'branch', operator: 'eq', value: 'main' }, + { field: 'count', operator: 'gt', value: 'x' }, + ]); + expect(body).toContain('id="condition-1-value-error"'); + expect(body).toMatch(/aria-describedby="condition-1-value-error"/); + }); + + it('shows a new catalog field without touching the component', () => { + const extended: CatalogEntry = { + ...definition, + fields: [ + ...definition.fields, + { + key: 'summary.secrets', + label: 'test.fields.secrets', + type: 'number', + operators: ['gte'], + }, + ], + }; + const body = render(ConditionBuilder, { + props: { + definition: extended, + conditions: [{ field: 'summary.secrets', operator: 'gte', value: '1' }], + match: 'any', + referenceOptions, + }, + }).body; + + expect(body).toContain('value="summary.secrets"'); + expect(body).toContain('value="gte"'); + expect(body).toMatch(/type="number"[^>]*name="conditions\.0\.value"/); + }); +}); diff --git a/src/lib/components/alerts/OptionPicker.svelte b/src/lib/components/alerts/OptionPicker.svelte new file mode 100644 index 00000000..2f6ac7d7 --- /dev/null +++ b/src/lib/components/alerts/OptionPicker.svelte @@ -0,0 +1,88 @@ + + +
+ {label} + {#if options.length > SEARCH_THRESHOLD} + + {/if} + {#if options.length === 0} +

{$_('alerts.editor.noOptions')}

+ {:else} +
+ {#each options as option (option.id)} + + {/each} +
+ {/if} +
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index eb91ab2b..3f1d5e15 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -56,7 +56,8 @@ "database": "Database", "auditLog": "Audit Log", "registration": "Registration", - "events": "Events" + "events": "Events", + "alerts": "Alerts" } }, "footer": { @@ -1304,6 +1305,126 @@ "body": "The personal API key “{name}” ({prefix}…) was created on your account. If it wasn’t you, revoke it from your profile." } } + }, + "operators": { + "eq": "is", + "neq": "is not", + "in": "is one of", + "not_in": "is none of", + "contains": "contains", + "starts_with": "starts with", + "gt": "greater than", + "gte": "greater than or equal to", + "lt": "less than", + "lte": "less than or equal to", + "is_true": "is yes", + "is_false": "is no", + "exists": "has a value" + }, + "summary": { + "and": "and", + "or": "or", + "always": "Always (no conditions)", + "noRecipients": "No recipients" + }, + "errors": { + "required": "This field is required.", + "too_long": "It is too long.", + "invalid": "The value is not valid.", + "unknown_event": "That event does not exist.", + "not_alertable": "That event does not support alerts.", + "scope_mismatch": "This event can only be watched from the organization.", + "forbidden": "You are not allowed to view this event, so you cannot create alerts on it.", + "unknown_field": "This field does not exist for the chosen event.", + "invalid_operator": "Operator not allowed for this field.", + "unknown_option": "Pick one of the options.", + "unknown_reference": "Pick an item from this scope.", + "too_many": "There are too many items.", + "unknown_user": "Some user does not belong to this scope.", + "unknown_role": "Some role does not belong to this scope.", + "invalid_channel": "Channel not available." + }, + "channels": { + "mail": "Email", + "in_app": "In-app notification", + "slack": "Slack", + "soon": "Coming soon" + }, + "list": { + "title": "Alerts", + "descriptionOrganization": "Get an email when an event happens in the organization or in any of its projects.", + "descriptionProject": "Get an email when an event happens in this project.", + "create": "Create alert", + "emptyTitle": "No alerts yet", + "example1": "Tell the security team when an analysis has critical vulnerabilities", + "example2": "Tell me when someone deletes a production secret", + "example3": "Tell me when a project API key is created", + "name": "Name", + "event": "Event", + "conditions": "Filters", + "recipients": "Recipients", + "status": "Status", + "actions": "Actions", + "enabled": "Active", + "disabled": "Inactive", + "toggle": "Turn “{name}” on or off", + "edit": "Edit", + "delete": "Delete", + "confirmDelete": "Delete this alert? This cannot be undone.", + "throttle": "At most one email every {minutes} min", + "inheritedTitle": "Organization alerts", + "inheritedDescription": "These alerts are defined in the organization and also fire for this project’s events. They can only be changed from the organization settings." + }, + "editor": { + "newTitle": "New alert", + "editTitle": "Edit alert", + "subtitle": "Pick an event, filter on its fields and choose who gets the email.", + "back": "Back to alerts", + "stepEvent": "Event", + "stepConditions": "Conditions", + "stepRecipients": "Recipients and delivery", + "stepSave": "Test and save", + "name": "Name", + "description": "Description (optional)", + "enabled": "Alert active", + "event": "Event", + "chooseEvent": "Pick an event…", + "eventHelp": "Only events you can view are listed.", + "applyEvent": "Use this event", + "chooseEventFirst": "Pick an event first to see its fields.", + "droppedConditions": "{count} conditions that do not exist in the new event were removed.", + "matchLabel": "Match", + "matchAll": "all conditions (AND)", + "matchAny": "any of them (OR)", + "noConditions": "No conditions: the alert fires on every event of this type.", + "field": "Field", + "operator": "Operator", + "value": "Value", + "addCondition": "Add condition", + "removeCondition": "Remove condition {index}", + "search": "Search…", + "searchIn": "Search in {label}", + "noOptions": "No items available.", + "roles": "Roles", + "users": "Users", + "recipientsNotice": "Only recipients allowed to view this event will get the email.", + "channels": "Channel", + "throttle": "Send at most one email every (minutes)", + "throttleHelp": "0 = no limit. Skipped events are summed up in the next email.", + "sampleProject": "Project of the example event", + "sampleProjectAny": "The one the conditions name", + "test": "Test alert", + "create": "Create alert", + "saveChanges": "Save changes", + "fixErrors": "Check the highlighted fields." + }, + "test": { + "matched": "The example event matches the conditions.", + "notMatched": "The example event does not match the conditions.", + "recipients": "It would be sent to: {names}", + "noRecipients": "It would not be sent to anyone.", + "denied": "{count} recipients would not get it because they cannot view this event.", + "nothingSent": "This is a test: no email was sent." } } } diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index fbab6bbc..2add992c 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -56,7 +56,8 @@ "database": "Base de datos", "auditLog": "Registro de auditoría", "registration": "Registro", - "events": "Eventos" + "events": "Eventos", + "alerts": "Alertas" } }, "footer": { @@ -1304,6 +1305,126 @@ "body": "Se ha creado la API key personal «{name}» ({prefix}…) en tu cuenta. Si no has sido tú, revócala desde tu perfil." } } + }, + "operators": { + "eq": "es", + "neq": "no es", + "in": "es uno de", + "not_in": "no es ninguno de", + "contains": "contiene", + "starts_with": "empieza por", + "gt": "mayor que", + "gte": "mayor o igual que", + "lt": "menor que", + "lte": "menor o igual que", + "is_true": "es sí", + "is_false": "es no", + "exists": "tiene valor" + }, + "summary": { + "and": "y", + "or": "o", + "always": "Siempre (sin condiciones)", + "noRecipients": "Sin destinatarios" + }, + "errors": { + "required": "Este campo es obligatorio.", + "too_long": "Es demasiado largo.", + "invalid": "El valor no es válido.", + "unknown_event": "Ese evento no existe.", + "not_alertable": "Ese evento no admite alertas.", + "scope_mismatch": "Este evento solo se puede vigilar desde la organización.", + "forbidden": "No tienes permiso para ver este evento, así que no puedes crear alertas sobre él.", + "unknown_field": "Este campo no existe para el evento elegido.", + "invalid_operator": "Operador no permitido para este campo.", + "unknown_option": "Elige una de las opciones.", + "unknown_reference": "Elige un elemento de este ámbito.", + "too_many": "Hay demasiados elementos.", + "unknown_user": "Algún usuario no pertenece a este ámbito.", + "unknown_role": "Algún rol no pertenece a este ámbito.", + "invalid_channel": "Canal no disponible." + }, + "channels": { + "mail": "Email", + "in_app": "Notificación en la app", + "slack": "Slack", + "soon": "Próximamente" + }, + "list": { + "title": "Alertas", + "descriptionOrganization": "Recibe un email cuando ocurra un evento en la organización o en cualquiera de sus proyectos.", + "descriptionProject": "Recibe un email cuando ocurra un evento en este proyecto.", + "create": "Crear alerta", + "emptyTitle": "Todavía no hay alertas", + "example1": "Avisar al equipo de seguridad si un análisis tiene vulnerabilidades críticas", + "example2": "Avisar cuando alguien borre un secreto de producción", + "example3": "Avisar cuando se cree una API key del proyecto", + "name": "Nombre", + "event": "Evento", + "conditions": "Filtros", + "recipients": "Destinatarios", + "status": "Estado", + "actions": "Acciones", + "enabled": "Activa", + "disabled": "Inactiva", + "toggle": "Activar o desactivar «{name}»", + "edit": "Editar", + "delete": "Borrar", + "confirmDelete": "¿Borrar esta alerta? No se puede deshacer.", + "throttle": "Máx. un email cada {minutes} min", + "inheritedTitle": "Alertas de la organización", + "inheritedDescription": "Estas alertas se definen en la organización y también se disparan con los eventos de este proyecto. Solo se pueden cambiar desde los ajustes de la organización." + }, + "editor": { + "newTitle": "Nueva alerta", + "editTitle": "Editar alerta", + "subtitle": "Elige un evento, filtra por sus campos y decide quién recibe el email.", + "back": "Volver a las alertas", + "stepEvent": "Evento", + "stepConditions": "Condiciones", + "stepRecipients": "Destinatarios y envío", + "stepSave": "Probar y guardar", + "name": "Nombre", + "description": "Descripción (opcional)", + "enabled": "Alerta activa", + "event": "Evento", + "chooseEvent": "Elige un evento…", + "eventHelp": "Solo aparecen los eventos que puedes ver.", + "applyEvent": "Usar este evento", + "chooseEventFirst": "Elige primero un evento para ver sus campos.", + "droppedConditions": "Se han quitado {count} condiciones que no existen en el nuevo evento.", + "matchLabel": "Coincidir con", + "matchAll": "todas las condiciones (Y)", + "matchAny": "cualquiera de ellas (O)", + "noConditions": "Sin condiciones: la alerta salta con cada evento de este tipo.", + "field": "Campo", + "operator": "Operador", + "value": "Valor", + "addCondition": "Añadir condición", + "removeCondition": "Quitar la condición {index}", + "search": "Buscar…", + "searchIn": "Buscar en {label}", + "noOptions": "No hay elementos disponibles.", + "roles": "Roles", + "users": "Usuarios", + "recipientsNotice": "Solo recibirán el email los destinatarios con permiso para ver este evento.", + "channels": "Canal", + "throttle": "No enviar más de un email cada (minutos)", + "throttleHelp": "0 = sin límite. Los eventos que se salten se resumen en el siguiente email.", + "sampleProject": "Proyecto del evento de ejemplo", + "sampleProjectAny": "El que indiquen las condiciones", + "test": "Probar alerta", + "create": "Crear alerta", + "saveChanges": "Guardar cambios", + "fixErrors": "Revisa los campos marcados." + }, + "test": { + "matched": "El evento de ejemplo cumple las condiciones.", + "notMatched": "El evento de ejemplo no cumple las condiciones.", + "recipients": "Se enviaría a: {names}", + "noRecipients": "No se enviaría a nadie.", + "denied": "{count} destinatarios no lo recibirían porque no pueden ver este evento.", + "nothingSent": "Es una prueba: no se ha enviado ningún email." } } } diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts index 54aa5ae2..a39d9951 100644 --- a/src/lib/server/alerts/operations.ts +++ b/src/lib/server/alerts/operations.ts @@ -17,8 +17,11 @@ import { type AlertLocation, type AlertRow, } from '#modules/alerts'; +import type { CatalogEntry } from '#lib/alerts/types'; import { actorFor, callerCan, canManageAlerts, contextOf, type AlertLocals } from './access'; +export type { CatalogEntry }; + /** Outcome of an alert operation, mapped to JSON by the API and to `fail()` by form actions. */ export type AlertResult = | { ok: true; status: number; data: T } @@ -35,11 +38,6 @@ function failure(error: unknown): AlertResult { throw error; } -/** Alertable event definitions as plain data (no `derive` functions). */ -export type CatalogEntry = Omit & { - fields: Array & { derived?: boolean }>; -}; - function serializable(definition: EventDefinition, location: AlertLocation): CatalogEntry { return { ...definition, diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts new file mode 100644 index 00000000..441f71fc --- /dev/null +++ b/src/lib/server/alerts/page.ts @@ -0,0 +1,385 @@ +import { error, fail, redirect } from '@sveltejs/kit'; +import { alertDirectory, alertService, type AlertLocation, type AlertRow } from '#modules/alerts'; +import { organizationService } from '#modules/organization'; +import { projectService } from '#modules/projects'; +import { + getEventDefinition, + isEventType, + listAlertFields, + type EventDefinition, + type FieldReference, +} from '#lib/events/catalog'; +import type { + AlertDraft, + AlertEditorData, + AlertListData, + AlertOption, + DraftCondition, +} from '#lib/alerts/types'; +import { canManageAlerts, type AlertLocals } from './access'; +import { + createAlert, + deleteAlert, + listAlerts, + listCatalog, + testDraftAlert, + updateAlert, + type CatalogEntry, +} from './operations'; + +/** Where the pages of a location live and how they link back. */ +export type AlertPageContext = { + location: AlertLocation; + /** `/org//settings/alerts` or `/org//projects//settings/alerts` */ + basePath: string; +}; + +async function permissions(locals: AlertLocals, location: AlertLocation) { + const [canRead, canCreate, canUpdate, canDelete] = await Promise.all([ + canManageAlerts(locals, location, 'read'), + canManageAlerts(locals, location, 'create'), + canManageAlerts(locals, location, 'update'), + canManageAlerts(locals, location, 'delete'), + ]); + return { canRead, canCreate, canUpdate, canDelete }; +} + +/** Options for every reference the catalog fields use, all inside the location. */ +async function referenceOptions( + catalog: CatalogEntry[], + location: AlertLocation, +): Promise> { + const references = new Set(); + for (const definition of catalog) { + for (const field of definition.fields) if (field.reference) references.add(field.reference); + } + const entries = await Promise.all( + [...references].map( + async (reference) => + [ + reference, + await alertDirectory.listReferences(reference, location).catch(() => []), + ] as const, + ), + ); + return Object.fromEntries( + entries.map(([reference, options]) => [ + reference, + options.map((option) => ({ id: option.id, label: option.label })), + ]), + ); +} + +async function recipientOptions(location: AlertLocation) { + const [members, roles] = await Promise.all([ + alertDirectory.listMembers(location).catch(() => []), + alertDirectory.listRoles(location).catch(() => []), + ]); + return { + users: members + .filter((member) => !member.disabled) + .map((member) => ({ id: member.userId, label: member.username })) + .sort((a, b) => a.label.localeCompare(b.label)), + roles: roles.map((role) => ({ id: role.id, label: role.name })), + }; +} + +export async function loadAlertList( + locals: AlertLocals, + context: AlertPageContext, +): Promise { + const { location } = context; + const allowed = await permissions(locals, location); + if (!allowed.canRead) throw error(403, 'Forbidden'); + + const listed = await listAlerts(locals, location); + if (!listed.ok) throw error(listed.status, listed.error); + + // the organization catalog knows every event the inherited alerts may watch + const catalog = await listCatalog(locals, location); + const inheritedCatalog = + location.scope === 'project' + ? await listCatalog(locals, { ...location, scope: 'organization', projectId: null }) + : []; + const organizationLocation: AlertLocation = { + ...location, + scope: 'organization', + projectId: null, + }; + const [references, own, organizationRecipients] = await Promise.all([ + referenceOptions([...catalog, ...inheritedCatalog], organizationLocation), + recipientOptions(location), + location.scope === 'project' ? recipientOptions(organizationLocation) : null, + ]); + // names for the recipients of the location's alerts and of the inherited organization ones + const merge = (a: AlertOption[], b: AlertOption[] = []) => [ + ...a, + ...b.filter((option) => !a.some((existing) => existing.id === option.id)), + ]; + const recipients = { + users: merge(own.users, organizationRecipients?.users), + roles: merge(own.roles, organizationRecipients?.roles), + }; + + return { + basePath: context.basePath, + scope: location.scope, + alerts: listed.data.alerts, + inherited: listed.data.inherited, + catalog: [ + ...catalog, + ...inheritedCatalog.filter((entry) => !catalog.some((c) => c.type === entry.type)), + ], + referenceOptions: references, + users: recipients.users, + roles: recipients.roles, + canCreate: allowed.canCreate, + canUpdate: allowed.canUpdate, + canDelete: allowed.canDelete, + }; +} + +function emptyDraft(eventType: string | null): AlertDraft { + return { + name: '', + description: '', + enabled: true, + eventType: eventType ?? '', + match: 'all', + conditions: [], + recipients: { userIds: [], roleIds: [] }, + throttleMinutes: 0, + }; +} + +function toDraft(alert: AlertRow): AlertDraft { + return { + name: alert.name, + description: alert.description ?? '', + enabled: alert.enabled, + eventType: alert.eventType, + match: alert.match, + conditions: alert.conditions.map((condition) => ({ + field: condition.field, + operator: condition.operator, + value: condition.value === undefined ? '' : condition.value, + })), + recipients: { ...alert.recipients }, + throttleMinutes: alert.throttleMinutes, + }; +} + +export async function loadAlertEditor( + locals: AlertLocals, + context: AlertPageContext, + options: { alertId?: string; eventType?: string | null }, +): Promise { + const { location } = context; + const allowed = await permissions(locals, location); + if (!allowed.canRead) throw error(403, 'Forbidden'); + + let alert: AlertRow | null = null; + if (options.alertId) { + alert = (await alertService.get(options.alertId).catch(() => null))?.toJson() ?? null; + const sameLocation = + alert && + alert.organizationId === location.organizationId && + alert.scope === location.scope && + (location.scope === 'organization' || alert.projectId === location.projectId); + if (!alert || !sameLocation) throw error(404, 'Alert not found'); + } else if (!allowed.canCreate) { + throw error(403, 'Forbidden'); + } + + const catalog = await listCatalog(locals, location); + const [references, recipients] = await Promise.all([ + referenceOptions(catalog, location), + recipientOptions(location), + ]); + + const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null); + if (!alert && options.eventType && !catalog.some((entry) => entry.type === options.eventType)) { + draft.eventType = ''; + } + + return { + basePath: context.basePath, + scope: location.scope, + alertId: alert?.id ?? null, + draft, + catalog, + referenceOptions: references, + users: recipients.users, + roles: recipients.roles, + canSave: alert ? allowed.canUpdate : allowed.canCreate, + canDelete: Boolean(alert) && allowed.canDelete, + }; +} + +/** `conditions..` names → condition list; rows without a field are dropped. */ +export function parseAlertForm(form: FormData): AlertDraft { + const indices = new Set(); + for (const key of form.keys()) { + const match = key.match(/^conditions\.(\d+)\.field$/); + if (match) indices.add(Number(match[1])); + } + + const conditions = [...indices] + .sort((a, b) => a - b) + .map((index) => { + const values = form + .getAll(`conditions.${index}.value`) + .map(String) + .filter((value) => value !== ''); + const multiple = form.get(`conditions.${index}.multiple`) === 'true'; + return { + field: String(form.get(`conditions.${index}.field`) ?? ''), + // validated by the service; the draft only echoes it back + operator: String( + form.get(`conditions.${index}.operator`) ?? '', + ) as DraftCondition['operator'], + value: multiple ? values : (values[0] ?? ''), + }; + }) + .filter((condition) => condition.field); + + return { + name: String(form.get('name') ?? ''), + description: String(form.get('description') ?? ''), + enabled: form.get('enabled') === 'on' || form.get('enabled') === 'true', + eventType: String(form.get('eventType') ?? ''), + match: form.get('match') === 'any' ? 'any' : 'all', + conditions, + recipients: { + userIds: form.getAll('userIds').map(String), + roleIds: form.getAll('roleIds').map(String), + }, + throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0, + }; +} + +/** The draft as service input: empty optional values become `undefined`. */ +function toInput(draft: AlertDraft) { + return { + ...draft, + conditions: draft.conditions.map((condition) => ({ + ...condition, + value: condition.value === '' ? undefined : condition.value, + })), + }; +} + +/** Form actions shared by the organization and project alert pages. */ +export function alertActions( + resolve: (event: { + params: Record; + locals: AlertLocals; + }) => Promise, +) { + return { + /** + * Without JavaScript the editor posts here to add/remove a condition row or to switch the + * event: nothing is saved, the page comes back with the updated draft. + */ + async draft(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const intent = String(form.get('intent') ?? ''); + if (intent === 'add_condition' && isEventType(draft.eventType)) { + const definition = getEventDefinition(draft.eventType) as EventDefinition; + const [first] = listAlertFields(definition, context.location.scope); + if (first) { + draft.conditions.push({ + field: first.key as string, + operator: first.operators[0], + value: '', + }); + } + } else if (intent.startsWith('remove_condition:')) { + const index = Number(intent.split(':')[1]); + draft.conditions.splice(index, 1); + } else if (intent === 'change_event') { + draft.conditions = []; + } + return { draft }; + }, + + async save(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const alertId = String(form.get('alertId') ?? '') || null; + const result = alertId + ? await updateAlert(event.locals, alertId, toInput(draft)) + : await createAlert(event.locals, context.location, toInput(draft)); + if (!result.ok) { + return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} }); + } + throw redirect(303, `${context.basePath}?saved=${result.data.id}`); + }, + + async test(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const draft = parseAlertForm(form); + const sampleProjectId = String(form.get('sampleProjectId') ?? '') || undefined; + const result = await testDraftAlert(event.locals, context.location, { + ...toInput(draft), + sampleProjectId, + }); + if (!result.ok) { + return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} }); + } + return { draft, test: result.data }; + }, + + async toggle(event: { request: Request; params: Record; locals: AlertLocals }) { + await resolve(event); + const form = await event.request.formData(); + const alertId = String(form.get('alertId') ?? ''); + const result = await updateAlert(event.locals, alertId, { + enabled: form.get('enabled') === 'true', + }); + if (!result.ok) return fail(result.status, { error: result.error, alertId }); + return { toggled: alertId }; + }, + + async delete(event: { request: Request; params: Record; locals: AlertLocals }) { + const context = await resolve(event); + const form = await event.request.formData(); + const alertId = String(form.get('alertId') ?? ''); + const result = await deleteAlert(event.locals, alertId); + if (!result.ok) return fail(result.status, { error: result.error, alertId }); + if (form.get('redirect') === 'list') throw redirect(303, context.basePath); + return { deleted: alertId }; + }, + }; +} + +/** `/org//settings/alerts/…` */ +export async function organizationAlertContext(event: { + params: Record; +}): Promise { + const organization = await organizationService.tryFindBySlug(event.params.org); + if (!organization) throw error(404, 'Organization not found'); + return { + location: { scope: 'organization', organizationId: organization.id, projectId: null }, + basePath: `/org/${organization.slug}/settings/alerts`, + }; +} + +/** `/org//projects//settings/alerts/…` */ +export async function projectAlertContext(event: { + params: Record; +}): Promise { + const project = await projectService.getProjectBySlug(event.params.slug).catch(() => null); + const organization = project?.organization; + if (!project || !organization || organization.slug !== event.params.org) { + throw error(404, 'Project not found'); + } + return { + location: { scope: 'project', organizationId: organization.id, projectId: project.id }, + basePath: `/org/${organization.slug}/projects/${project.slug}/settings/alerts`, + }; +} diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 2284ea09..f3f1e751 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -61,11 +61,13 @@ canReadOrgServerKeys={data.canReadOrgServerKeys} canReadOrgAudit={data.canReadOrgAudit} canReadOrgEvents={data.canReadOrgEvents} + canReadOrganizationAlerts={data.canReadOrganizationAlerts} canReadProjectInfo={data.canReadProjectInfo} canReadProjectUsers={data.canReadProjectUsers} canReadProjectRoles={data.canReadProjectRoles} canReadProjectServerKeys={data.canReadProjectServerKeys} canReadProjectAudit={data.canReadProjectAudit} + canReadProjectAlerts={data.canReadProjectAlerts} canReadProjectVault={data.canReadProjectVault} canReadProjectCodeReport={data.canReadProjectCodeReport} canReadProjectStateIac={data.canReadProjectStateIac} diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.server.ts new file mode 100644 index 00000000..453f6cc3 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.server.ts @@ -0,0 +1,7 @@ +import { alertActions, loadAlertList, projectAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertList(event.locals, await projectAlertContext(event)); +} + +export const actions = alertActions(projectAlertContext); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.svelte new file mode 100644 index 00000000..4fec48a2 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/+page.svelte @@ -0,0 +1,13 @@ + + + + {$_('alerts.list.title')} - GitOps + + + diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.server.ts new file mode 100644 index 00000000..0e23a41f --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, projectAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await projectAlertContext(event), { + alertId: event.params.id, + }); +} + +export const actions = alertActions(projectAlertContext); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/[id]/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.server.ts new file mode 100644 index 00000000..40172dd7 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, projectAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await projectAlertContext(event), { + eventType: event.url.searchParams.get('event'), + }); +} + +export const actions = alertActions(projectAlertContext); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/new/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/settings/alerts/+page.server.ts b/src/routes/org/[org]/settings/alerts/+page.server.ts new file mode 100644 index 00000000..2416d6d0 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/+page.server.ts @@ -0,0 +1,7 @@ +import { alertActions, loadAlertList, organizationAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertList(event.locals, await organizationAlertContext(event)); +} + +export const actions = alertActions(organizationAlertContext); diff --git a/src/routes/org/[org]/settings/alerts/+page.svelte b/src/routes/org/[org]/settings/alerts/+page.svelte new file mode 100644 index 00000000..4fec48a2 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/+page.svelte @@ -0,0 +1,13 @@ + + + + {$_('alerts.list.title')} - GitOps + + + diff --git a/src/routes/org/[org]/settings/alerts/[id]/+page.server.ts b/src/routes/org/[org]/settings/alerts/[id]/+page.server.ts new file mode 100644 index 00000000..a15bbeb3 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/[id]/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, organizationAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await organizationAlertContext(event), { + alertId: event.params.id, + }); +} + +export const actions = alertActions(organizationAlertContext); diff --git a/src/routes/org/[org]/settings/alerts/[id]/+page.svelte b/src/routes/org/[org]/settings/alerts/[id]/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/[id]/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/src/routes/org/[org]/settings/alerts/new/+page.server.ts b/src/routes/org/[org]/settings/alerts/new/+page.server.ts new file mode 100644 index 00000000..19e0d9ad --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/new/+page.server.ts @@ -0,0 +1,9 @@ +import { alertActions, loadAlertEditor, organizationAlertContext } from '#lib/server/alerts/page'; + +export async function load(event) { + return loadAlertEditor(event.locals, await organizationAlertContext(event), { + eventType: event.url.searchParams.get('event'), + }); +} + +export const actions = alertActions(organizationAlertContext); diff --git a/src/routes/org/[org]/settings/alerts/new/+page.svelte b/src/routes/org/[org]/settings/alerts/new/+page.svelte new file mode 100644 index 00000000..f35bb4a6 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/new/+page.svelte @@ -0,0 +1,25 @@ + + + + {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} - GitOps + + +
+
+

+ {data.alertId ? $_('alerts.editor.editTitle') : $_('alerts.editor.newTitle')} +

+

{$_('alerts.editor.subtitle')}

+
+ {#key data.alertId} + + {/key} +
diff --git a/vitest.config.ts b/vitest.config.ts index 1b12b932..ff235cf4 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -1,7 +1,10 @@ import path from 'path'; +import { svelte } from '@sveltejs/vite-plugin-svelte'; import { defineConfig } from 'vitest/config'; export default defineConfig({ + // compiles `.svelte` files so components can be rendered in tests (`svelte/server`) + plugins: [svelte({ configFile: false })], resolve: { alias: { $lib: path.resolve(import.meta.dirname, 'src/lib'), From 777383111e8f1e1f4c20f58a23aa7c91ed74f9a7 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 19:06:52 +0100 Subject: [PATCH 12/13] feat(email): alert templates, mail queue with retries and shared layout (#81) - _layout.html shared by every email (header, content, footer with the reason and a link to manage the alert); invite and password reset moved onto it, still sent directly because their links carry tokens - alert.html (field table built from the catalog), alert-code-report-analysis.html (service, branch, commit, coloured severities, violated policies) and system-access-changed / system-security-notice for the fixed notices - EventDefinition.mailTemplate, link(context) and mailSummary(payload); subject "[GitOps] : "; absolute links from ORIGIN, omitted without it; recipient language or English; stripped from the client catalog - MailQueue: concurrency 3, withRetry 4 attempts 1s/4s/16s with jitter only for network errors and 4xx SMTP replies, definitive failures logged with a recipient hash and no content, drained on sveltekit:shutdown (10 s) - without SMTP: startup warning, debug per skipped event, banner on the alert pages - e2e no longer inherits SMTP settings from a developer's .env - docs: README email section, CLAUDE.md, .env.example, optional mailpit service Co-Authored-By: Claude Opus 5.5 --- .env.example | 15 +- CLAUDE.md | 22 +- README.md | 30 +- docker-compose.yml | 10 + e2e/env-private.ts | 1 + e2e/global-setup.ts | 9 + e2e/specs/alerts.spec.ts | 2 + src/env.ts | 1 + src/lib/alerts/types.ts | 9 +- src/lib/components/alerts/AlertEditor.svelte | 13 +- src/lib/components/alerts/AlertList.svelte | 13 +- src/lib/events/catalog/access.events.ts | 21 ++ src/lib/events/catalog/code-report.events.ts | 20 ++ src/lib/events/catalog/links.ts | 11 + src/lib/events/catalog/organization.events.ts | 2 + src/lib/events/catalog/projects.events.ts | 4 + src/lib/events/catalog/types.ts | 17 + src/lib/events/catalog/vault.events.ts | 7 + src/lib/i18n/locales/en.json | 37 ++- src/lib/i18n/locales/es.json | 37 ++- src/lib/server/alerts/operations.ts | 12 +- src/lib/server/alerts/page.ts | 10 +- src/lib/server/infra/notifications/config.ts | 23 ++ src/lib/server/infra/notifications/index.ts | 49 ++- .../infra/notifications/mail-queue.test.ts | 167 ++++++++++ .../server/infra/notifications/mail-queue.ts | 126 ++++++++ src/lib/server/infra/notifications/retry.ts | 64 ++++ .../server/infra/notifications/template.ts | 39 +++ .../alerts/application/alert-engine.ts | 19 +- .../alerts/application/recipient-resolver.ts | 6 +- src/modules/alerts/application/testing.ts | 6 + src/modules/alerts/application/types.ts | 8 +- src/modules/alerts/index.ts | 35 +- .../alert-mail.notifier.test.ts | 281 +++++++++++++--- .../infrastructure/alert-mail.notifier.ts | 300 ++++++++++++++---- .../alerts/infrastructure/event-summary.ts | 4 + .../infrastructure/platform-directory.ts | 12 +- .../notifications/invitation.notifier.ts | 44 +-- .../notifications/password-reset.notifier.ts | 30 +- src/notifications/email/_layout.html | 97 ++++++ .../email/alert-code-report-analysis.html | 39 +++ src/notifications/email/alert.html | 15 + src/notifications/email/invite.html | 155 ++------- src/notifications/email/password-reset.html | 155 ++------- .../email/system-access-changed.html | 6 + .../email/system-security-notice.html | 18 ++ src/routes/api/alerts/server.test.ts | 3 + 47 files changed, 1566 insertions(+), 438 deletions(-) create mode 100644 src/lib/events/catalog/links.ts create mode 100644 src/lib/server/infra/notifications/mail-queue.test.ts create mode 100644 src/lib/server/infra/notifications/mail-queue.ts create mode 100644 src/lib/server/infra/notifications/retry.ts create mode 100644 src/notifications/email/_layout.html create mode 100644 src/notifications/email/alert-code-report-analysis.html create mode 100644 src/notifications/email/alert.html create mode 100644 src/notifications/email/system-access-changed.html create mode 100644 src/notifications/email/system-security-notice.html diff --git a/.env.example b/.env.example index c1d6bc38..08039b46 100644 --- a/.env.example +++ b/.env.example @@ -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 @@ -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: /auth/sso/google/callback diff --git a/CLAUDE.md b/CLAUDE.md index 7c702c3e..a6f7e76e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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] : `). 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` diff --git a/README.md b/README.md index 0acde952..d6a87575 100644 --- a/README.md +++ b/README.md @@ -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*. @@ -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 diff --git a/docker-compose.yml b/docker-compose.yml index b96ea9e2..5f284fdb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -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' diff --git a/e2e/env-private.ts b/e2e/env-private.ts index d04c4f5c..e355c661 100644 --- a/e2e/env-private.ts +++ b/e2e/env-private.ts @@ -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; diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index 97ba1be4..eec93581 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -49,6 +49,15 @@ function buildEnv(): Record { 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), }; } diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts index 786ed957..d7e3e1ed 100644 --- a/e2e/specs/alerts.spec.ts +++ b/e2e/specs/alerts.spec.ts @@ -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`, diff --git a/src/env.ts b/src/env.ts index 9f995c2c..da5dff00 100644 --- a/src/env.ts +++ b/src/env.ts @@ -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, diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts index ea6cdb62..c552527c 100644 --- a/src/lib/alerts/types.ts +++ b/src/lib/alerts/types.ts @@ -10,7 +10,12 @@ export type CatalogField = Omit & { derived?: boolean; }; -export type CatalogEntry = Omit & { fields: CatalogField[] }; +export type CatalogEntry = Omit< + EventDefinition, + 'fields' | 'link' | 'mailSummary' | 'mailTemplate' +> & { + fields: CatalogField[]; +}; export type AlertOption = { id: string; label: string }; @@ -40,6 +45,8 @@ type Shared = { referenceOptions: Record; users: AlertOption[]; roles: AlertOption[]; + /** `false` when SMTP is not configured: alerts are saved but nothing is sent. */ + mailConfigured: boolean; }; export type AlertListData = Shared & { diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte index 4ef199d1..f63a2e3d 100644 --- a/src/lib/components/alerts/AlertEditor.svelte +++ b/src/lib/components/alerts/AlertEditor.svelte @@ -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, @@ -115,6 +115,17 @@ {/if}
+ {#if !data.mailConfigured} +

+ + {$_('alerts.mailDisabled')} +

+ {/if} +

diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte index cfc44630..6adbd62e 100644 --- a/src/lib/components/alerts/AlertList.svelte +++ b/src/lib/components/alerts/AlertList.svelte @@ -1,6 +1,6 @@ '; +const ORIGIN = 'https://gitops.example.com'; + +function analysisEvent(): AnyDomainEvent { + return { + id: 'event-1', + type: 'code_report.analysis.completed', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: 'org-1', projectId: 'p1' }, + payload: { + analysisId: 'analysis-1', + serviceId: 'svc-gateway', + tool: 'trivy', + gitInfo: { + repositoryUrl: null, + branch: 'feature/', + commit: 'abcdef1234567890', + version: null, + }, + summary: { critical: 3, high: 5, medium: 1, low: 0, unknown: 0, total: 9, secrets: 0 }, + policies: { + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }, + }; +} + +function alertEmail(overrides: Partial = {}): AlertEmail { + return { + recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com' }, + alert: { id: 'alert-1', name: 'Críticas en api-gateway', description: null, scope: 'project' }, + event: analysisEvent(), + definition: getEventDefinition('code_report.analysis.completed') as EventDefinition, + suppressed: 0, + names: new Map([['svc-gateway', `api-gateway ${XSS}`]]), + where: { organization: 'Kettu', organizationSlug: 'kettu', project: 'Web', projectSlug: 'web' }, + ...overrides, + }; +} + +function expectClean(html: string) { + expect(html).not.toMatch(/\{\{|\}\}/); + expect(html).not.toContain(' + +{#if visible && entry && content} + +{/if} diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index 6936ddef..0c0c0c19 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -68,6 +68,11 @@ "slack": "Slack", "gitdbSyncStatus": "GitDB sync status" }, + "whatsNew": { + "title": "What's new in version {version}", + "viewChangelog": "View changelog", + "close": "Dismiss what's new" + }, "profile": { "title": "Profile", "subtitle": "Manage your identity, password and API access from one place.", diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 6a5994bb..c0670ca3 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -68,6 +68,11 @@ "slack": "Slack", "gitdbSyncStatus": "Estado de sincronización GitDB" }, + "whatsNew": { + "title": "Novedades de la versión {version}", + "viewChangelog": "Ver changelog", + "close": "Cerrar novedades" + }, "profile": { "title": "Perfil", "subtitle": "Gestiona tu identidad, contraseña y acceso API desde un solo lugar.", diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index f3f1e751..12c71bf3 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -5,6 +5,7 @@ import AppNavbar from '#lib/components/AppNavbar.svelte'; import AppSidebar from '#lib/components/AppSidebar.svelte'; import Footer from '#lib/components/Footer.svelte'; + import WhatsNewBanner from '#lib/components/WhatsNewBanner.svelte'; import { setupI18n } from '#lib/i18n'; export let data: any; @@ -39,11 +40,14 @@ organizationSlug={data.organization?.slug ?? null} projectSlug={data.currentProjectSlug ?? ''} /> +
-