Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
11 changes: 9 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +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/<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

Expand Down Expand Up @@ -187,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.

Expand All @@ -196,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
Expand Down
8 changes: 7 additions & 1 deletion docs/adr/0001-event-bus-and-alerts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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
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.

Expand Down
30 changes: 30 additions & 0 deletions e2e/env-private.ts
Original file line number Diff line number Diff line change
@@ -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;
66 changes: 66 additions & 0 deletions e2e/specs/org-events.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { test, expect, getSeed } from '../fixtures/auth';
import { expectAllowed, expectDenied } from '../fixtures/expect-access';

const seed = getSeed();
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
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);
});

test('org roles without organization:events:read cannot open it', async ({ page, loginAs }) => {
await loginAs('orgDeveloper');
await expectDenied(page, eventsUrl);
});
});
1 change: 1 addition & 0 deletions e2e/specs/organization-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
2 changes: 1 addition & 1 deletion e2e/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
}
}
}
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
});
8 changes: 8 additions & 0 deletions src/lib/components/AppSidebar.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script lang="ts">
import { createPageStore } from '#lib/page-store';
import {
Activity,
BarChart3,
Building2,
ChevronDown,
Expand Down Expand Up @@ -46,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;
Expand Down Expand Up @@ -302,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);
Expand Down
5 changes: 5 additions & 0 deletions src/lib/config/permissions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ const permissions = {
resource: 'audit',
permissions: grantsFor('organization', 'audit'),
},
// events page (/org/<org>/settings/events): read to see it, update to acknowledge events
events: {
resource: 'events',
permissions: grantsFor('organization', 'events'),
},
},
},
project: {
Expand Down
36 changes: 35 additions & 1 deletion src/lib/i18n/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@
"organizations": "Organizations",
"database": "Database",
"auditLog": "Audit Log",
"registration": "Registration"
"registration": "Registration",
"events": "Events"
}
},
"footer": {
Expand Down Expand Up @@ -382,6 +383,39 @@
"title": "Organization CVEs",
"infoMessage": "This list aggregates CVEs from all organization projects using the latest completed analysis for each service.",
"emptyMessage": "No CVEs have been detected in this organization yet."
},
"events": {
"title": "Events",
"description": "What happened in the organization and its projects. Mark each event as reviewed once you have dealt with it.",
"retentionNotice": "Events are kept in memory for {retention}: they are lost when the server restarts.",
"retentionDays": "{count} days",
"retentionHours": "{count} hours",
"retentionMinutes": "{count} minutes",
"pendingCount": "{count} pending review",
"filterModule": "Module",
"filterStatus": "Status",
"allModules": "All modules",
"statusAll": "All",
"statusPending": "Pending",
"statusAcked": "Reviewed",
"applyFilters": "Filter",
"emptyTitle": "No events",
"emptyDescription": "Analyses, vault changes, access changes and other organization activity will show up here.",
"actorSystem": "System",
"actorApiKey": "API key {name}",
"actorApiKeyUnknown": "API key",
"inProject": "in {name}",
"details": "Show details",
"ack": "Mark as reviewed",
"ackedBy": "Reviewed by {name} · {date}",
"ackFailed": "The event could not be marked as reviewed.",
"modules": {
"code_report": "Code Report",
"vault": "Vault",
"projects": "Projects",
"organization": "Organization",
"access": "Access"
}
}
},
"project": {
Expand Down
36 changes: 35 additions & 1 deletion src/lib/i18n/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@
"organizations": "Organizaciones",
"database": "Base de datos",
"auditLog": "Registro de auditoría",
"registration": "Registro"
"registration": "Registro",
"events": "Eventos"
}
},
"footer": {
Expand Down Expand Up @@ -382,6 +383,39 @@
"title": "CVEs de la organización",
"infoMessage": "Este listado agrupa los CVEs de todos los proyectos de la organización usando el último análisis completado de cada servicio.",
"emptyMessage": "Todavía no se han detectado CVEs en esta organización."
},
"events": {
"title": "Eventos",
"description": "Lo que ha ocurrido en la organización y en sus proyectos. Marca cada evento como revisado cuando lo hayas atendido.",
"retentionNotice": "Los eventos se guardan en memoria durante {retention}: se pierden al reiniciar el servidor.",
"retentionDays": "{count} días",
"retentionHours": "{count} horas",
"retentionMinutes": "{count} minutos",
"pendingCount": "{count} pendientes de revisar",
"filterModule": "Módulo",
"filterStatus": "Estado",
"allModules": "Todos los módulos",
"statusAll": "Todos",
"statusPending": "Pendientes",
"statusAcked": "Revisados",
"applyFilters": "Filtrar",
"emptyTitle": "No hay eventos",
"emptyDescription": "Aquí aparecerán los análisis, cambios en el vault, accesos y demás actividad de la organización.",
"actorSystem": "Sistema",
"actorApiKey": "API key {name}",
"actorApiKeyUnknown": "API key",
"inProject": "en {name}",
"details": "Ver detalles",
"ack": "Marcar como revisado",
"ackedBy": "Revisado por {name} · {date}",
"ackFailed": "No se ha podido marcar el evento como revisado.",
"modules": {
"code_report": "Code Report",
"vault": "Vault",
"projects": "Proyectos",
"organization": "Organización",
"access": "Accesos"
}
}
},
"project": {
Expand Down
34 changes: 34 additions & 0 deletions src/lib/server/events/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as env from '$app/env/private';

export const DEFAULT_EVENTS_EXPIRATION = '7d';

const UNIT_MS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } as const;

/**
* Parses a duration such as `30d`, `12h`, `45m` or `90s` (a bare number means seconds) into
* milliseconds. Returns `null` for anything else.
*/
export function parseDuration(value: string): number | null {
const match = /^(\d+)\s*([smhd]?)$/i.exec(value.trim());
if (!match) return null;
const amount = Number(match[1]);
if (!Number.isSafeInteger(amount) || amount <= 0) return null;
const unit = (match[2] || 's').toLowerCase() as keyof typeof UNIT_MS;
return amount * UNIT_MS[unit];
}

/**
* How long the organization events page keeps events (`GITOPS_EVENTS_EXPIRATION`, default 7 days).
* An invalid value falls back to the default and is reported through `onInvalid`.
*/
export function readEventsExpirationMs(onInvalid?: (value: string) => void): number {
const raw = env.GITOPS_EVENTS_EXPIRATION?.trim();
const fallback = parseDuration(DEFAULT_EVENTS_EXPIRATION)!;
if (!raw) return fallback;
const parsed = parseDuration(raw);
if (parsed === null) {
onInvalid?.(raw);
return fallback;
}
return parsed;
}
Loading
Loading