From 67184740d2dedce21a63b9b70c44290a698622f2 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 15:07:38 +0100 Subject: [PATCH 1/3] 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 0000000..d04c4f5 --- /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 bef3a03..285608e 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 2/3] 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 0c86972..fc7b831 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 c2d670a..66399a1 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 e828be7..9635435 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 0000000..e4c33b0 --- /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 fe90f90..9f995c2 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 8d70506..09ec879 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 0000000..cdb268d --- /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 0000000..d1d7cdf --- /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 3/3] 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 fc7b831..c1d6bc3 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 66399a1..cb1948e 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 9635435..10d0451 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 e4c33b0..5d2178f 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 adfa2dc..d1fcb51 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 09ec879..a0a4b60 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 91f169f..1478064 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 1b7c5dc..f8fe1d9 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 983c71d..dd18806 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 8451dd0..2284ea0 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 bf2ab3e..1b3bc0a 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 a8d3a91..3431c54 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}