Skip to content
Closed
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
73 changes: 51 additions & 22 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,17 @@ La logica vive en `src/modules/<module>/` con `domain/`, `application/`, `infras
`index.ts` como composition root. El `domain/` contiene entidades (`*.domain.ts`) y datos
centralizados (`*.data.ts`) para constantes: permisos de roles, defaults de proyecto, pesos de
riesgo y mapeos de herramientas. Los modulos actuales son `auth`, `config`, `organization`,
`projects`, `storage` y `code-report`. Las rutas deben importar desde el `index.ts` publico.
`projects`, `storage`, `code-report`, `vault`, `audit`, `alerts` y `notifications`.

**Destinatarios de email externo:** El módulo `notifications` gestiona acceso a personas sin
cuenta GitOps (vendors, mailboxes). Cada dirección es un `ExternalRecipientEntity` con estados
(`pending`, `verified`, `unsubscribed`, `blocked`). Las direcciones se confirman vía token HMAC
(7 días, single-use, rate limited 3/h por dirección). Solo se envían a direcciones verificadas
con dominio permitido (configurado en `/org/<org>/settings/notifications`). Las alertas omiten
campos sensibles y links al app para externals. Rutas públicas sin sesión: `/notifications/verify`
y `/notifications/unsubscribe` aceptan POST con tokens HMAC.

Las rutas deben importar desde el `index.ts` publico.

GitDB es la unica fuente de verdad para usuarios, roles, API keys, organizaciones, proyectos,
metadata de storage y code reports. Se configura con `GITDB_REPOSITORY_URL` (URLs HTTPS o SSH
Expand All @@ -85,34 +95,47 @@ CSRF Origin check de SvelteKit no dependa del header Host, previniendo bypass en

## RBAC y seguridad

Los permisos usan `section:action` con scope global, de organizacion o de proyecto. Usar siempre
`can()` o `isAdmin()` desde `$modules/auth`; `locals.user.role` es un objeto, no el string
`admin`.
Los permisos usan `<scope>:<resource>:<action>` (ej: `organization:projects:read`, `project:vault:secrets:all`)
con scope `cluster`, `organization` o `project`. Usar siempre `can()` o `isAdmin()` desde `$modules/auth`;
`locals.user.role` es un objeto, no el string `admin`.

**Permisos de org:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`,
`organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`,
`organization:audit:read`, `organization:events:read`, `organization:alerts:read`,
`organization:notifications:read` (leer destinatarios externos y dominios permitidos),
`organization:notifications:update` (añadir direcciones externas, cambiar dominios).

**Permisos de proyecto:** `project:project:read`, `project:users:read`, `project:roles:read`,
`project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`
(leer destinatarios externos de alertas), `project:notifications:update` (añadir direcciones).

**Gating de permisos en UI:** En loaders de rutas, usar `cancanService.canSessionUser()` para verificar
permisos específicos y pasarlos a componentes como props (`canCreate`, `canUpdate`, `canDelete`) para
ocultar acciones que el usuario no puede realizar. El layout raíz (`+layout.server.ts`) calcula permisos
granulares de lectura para settings de org (proyectos, usuarios, roles, configuración global, backups, servidor-keys, audit)
y módulos de proyecto (vault, codereport, stateiac) combinándolos con lógica OR (`canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
para obtener flags de lectura de alto nivel que se filtran en AppSidebar según acceso específico.
granulares de lectura para settings de org (proyectos, usuarios, roles, configuración, backups, servidor-keys,
audit, eventos, alertas, notificaciones) y módulos de proyecto (vault, codereport, stateiac) combinándolos
con lógica OR para obtener flags de lectura de alto nivel que se filtran en AppSidebar según acceso específico.

Roles por defecto en `src/modules/auth/domain/role-permissions.data.ts`. Los permisos incluyen scope
como prefijo (ej: `organization:projects:read`, `project:vault:secrets:all`) y se almacenan verbatim sin
transformaciones. Recursos de módulos tienen sub-permisos granulares (ej: `project:vault:secrets:read`, `project:vault:environments:read`):
- **GitOps Admin** (`cluster-admin`) — vault, openreport, stateiac (todos)
como prefijo y se almacenan verbatim sin transformaciones. Módulos tienen sub-permisos granulares
(ej: `project:vault:secrets:read`, `project:codereport:reports:read`):
- **GitOps Admin** (`cluster-admin`) — acceso total a vault, openreport, stateiac
- **GitOps User** (`cluster-user`) — rol base sin permisos propios para acceso a nivel sistema
- **Organization Admin** — todos los permisos de org (proyectos, usuarios, roles, configuración global, backups, server-access-keys, audit)
- **Organization Developer** — solo read/create/update de proyectos
- **Project Admin** — metadata/usuarios/roles/server-keys/audit plus todos los permisos de módulos (vault, codereport, stateiac)
- **Project Developer/Viewer** — acceso granular a módulos con permisos diferenciados (solo lectura en Viewer)

Los permisos de organización se propagan a sus proyectos solo cuando no hay un assignment explícito a nivel de
proyecto. Un usuario con `organization:projects:read` puede satisfacer `project:project:read` en cualquier
proyecto—pero si tiene un rol específico del proyecto, ese assignment es autoritario y los permisos de org no
aplican (regla most-specific-wins). Permite delegación de autoridad granular con restricciones por-proyecto.

`canManageOrganization()` controla acceso al area `/settings`, mientras que `canViewOrganization()` incluye
tambien usuarios con acceso solo a proyectos bajo la organización (ven el overview pero no pueden acciones de org-scope).
- **Organization Admin** — todos los permisos de org: proyectos, usuarios, roles, settings, backups,
server-keys, audit, eventos, alertas, notificaciones
- **Organization Developer** — solo lectura/crear/actualizar proyectos
- **Project Admin** — metadata/usuarios/roles/server-keys/audit/alertas/notificaciones; acceso total
a módulos (vault, codereport, stateiac)
- **Project Developer** — lectura/crear/actualizar recursos; acceso granular a módulos; lee alertas
- **Project Viewer** — solo lectura: metadata, alertas, módulos

Los permisos de organización se propagan a sus proyectos solo cuando no hay assignment explícito a nivel de
proyecto (regla most-specific-wins). `canManageOrganization()` controla acceso al area `/settings`, mientras
que `canViewOrganization()` incluye usuarios con acceso solo a proyectos.

**Rutas públicas de notificaciones:** `/notifications/verify` y `/notifications/unsubscribe` aceptan POST con
tokens HMAC (permitidas sin sesión en `hooks.server.ts`) para confirmar direcciones y unsubscribirse de alertas
externas. Usan tokens stateless HMAC (signToken con `GITDB_ENCRYPTION_KEY`, TTL 90 días).

Al crear una organización (vía bootstrap o `/gitops-settings`), se llama automáticamente a
`roleService.createDefaultOrganizationRoles()`. Al crear un proyecto, se llama a
Expand All @@ -133,6 +156,12 @@ normalizan errores. Ejecutar `bun run check`, `bun run lint`, `bun run test` y

## Comportamiento conocido

**Imports de i18n desde notificaciones:** `#lib/server/infra/notifications/index.ts` no re-exporta
funciones i18n (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`, etc.) porque estas cargan
mensajes de Paraglide (requiere Vite), pero el index se importa desde `$modules/auth` que se
ejecuta fuera de Vite en tests e2e. Importar estas funciones directamente desde
`#lib/server/infra/notifications/i18n` en lugar del index principal.

**Startup y readiness del servidor:** El auth guard en `hooks.server.ts` verifica readiness via
`getServerReadyState()` antes de procesar cualquier request. Durante startup, los navegadores
reciben una página de landing "GitOps is starting" que se recarga automáticamente, mientras que
Expand Down
64 changes: 56 additions & 8 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,8 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data
and tool policy mappings.

Current modules include `auth`, `config`, `organization`, `projects`, `storage`,
`code-report`, `vault`, `audit`, and `alerts`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
`code-report`, `vault`, `audit`, `alerts`, and `notifications`. The `notifications` module handles
external email recipient management (domains, verification tokens, unsubscribe tracking). Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
their `index.ts`, not internal layers.

GitDB is the single source of truth. Users, roles, API keys, organizations, projects, storage
Expand All @@ -117,7 +118,10 @@ Bitbucket, and GitLab; in production, ensure SSH authentication credentials are

`ORIGIN` environment variable pins the application's public origin (e.g., `http://localhost:3000`).
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.
header, preventing bypasses when running behind a proxy that rewrites Host headers. It is also the
origin of the absolute links in emails (`absoluteUrl()`); only under `vite dev` do those links use
the origin of the requests the dev server receives instead (`rememberDevOrigin()` in
`hooks.server.ts`), so they work on port 5173 whatever `ORIGIN` says.

## Domain events

Expand Down Expand Up @@ -199,8 +203,39 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by
the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`,
`GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test`
(dry runs: never send, never touch the throttle). Project API keys only reach their project.

(dry runs that never touch the throttle; with `send: true`, `AlertEngine.sendTest()` also emails
the recipients a real event would reach, members filtered by cancan and verified externals only,
with a `[Test]` subject; needs SMTP and is limited to 5 per caller every 10 minutes, in memory.
It also registers the draft's new external addresses, so they get the confirmation email and
receive the next test once confirmed, before the alert is saved).
Project API keys only reach their project.

- External email recipients (`$modules/notifications`, #99): `recipients.externalEmails` holds
normalized addresses outside GitOps. Each address is an `ExternalRecipientEntity` (GitDB
`external_recipients`) shared by every alert of the organization: `pending` → `verified` (the
owner clicked the confirmation link) → `unsubscribed`, or `blocked` when its domain leaves
`allowedExternalEmailDomains` (`notification_settings`, one row per organization, empty by
default = no externals; exact domain match, `*.example.com` for subdomains, punycode).
`AlertService` rejects not allowed or invalid addresses (`domain_not_allowed`,
`invalid_email`) and requires `<scope>:notifications:update` to **add** addresses
(`forbidden_external`; keeping or removing existing ones does not need it); after the save,
`register()` creates them as pending and emails `external-recipient-verify` directly through
`notify()` (token in the link: random, stored hashed, 7 days, single use, rate limited 3/h per
address and 30/h per organization, per process). The engine sends to `deliverable()` addresses
only: verified, allowed domain and with an unsubscribe link, so nothing goes to externals
without `ORIGIN`. They skip the cancan filter (no account) and never get system notifications.
Their email is the reduced `alert` template: no `sensitive` catalog fields, no links into the
app, an unsubscribe footer link and a `List-Unsubscribe` header. The unsubscribe link is a
stateless HMAC token (`signToken`, `GITDB_ENCRYPTION_KEY`, 90 days) made single use by
`unsubscribeVersion`. Public pages `/notifications/verify` and `/notifications/unsubscribe`
(allowed without session in `hooks.server.ts`) only act on POST, so mail scanners opening the
link change nothing. `List-Unsubscribe-Post` (RFC 8058 one-click) is not sent: providers POST
without an `Origin` header and SvelteKit's CSRF check would reject it.
- `/org/<org>/settings/notifications` (`#lib/server/notifications/settings.ts`): allowed domains
(read with `organization:settings:read` or `organization:notifications:read`, changed with
`organization:settings:update` or `organization:notifications:update`) and the external recipients
status (`organization:notifications:read`, resend confirmation with `organization:notifications:update`).
Notification channels (#95) will live on this page too.
- UI: `/org/<org>/settings/alerts` and `/org/<org>/projects/<slug>/settings/alerts` (list, `new`,
`[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`,
`test`, `toggle`, `delete`; everything works without JavaScript). Components live in
Expand Down Expand Up @@ -257,8 +292,8 @@ return { roles, canCreate };

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

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

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

`organization:notifications:read` and `organization:notifications:update` gate external email recipient management at the organization level. At the project level, `project:notifications:read` and `project:notifications:update` control external recipients of project alerts (externals of alerts that scope to a project).

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

Organization-level permissions cascade into their projects only when no explicit project-level assignment exists
Expand All @@ -292,6 +329,11 @@ Machine-to-machine requests authenticate with `Authorization: Bearer gvs_...`; `
resolves them into `locals.apiKey` and `cancanService.canApiKey()` confines a project key to its
own project.

Unauthenticated public routes for external alert recipients: `/notifications/verify` and
`/notifications/unsubscribe` accept POST requests with HMAC tokens (verifying confirmations and
one-click unsubscribes). These are allowed without a session in `hooks.server.ts` and validate
their tokens rather than checking permissions.

`locals.user.role` is a session role object, not the string `admin`. Use `isAdmin()` or the `can*`
helpers. Keep authorization tests beside changes to permission behavior.

Expand All @@ -316,6 +358,12 @@ commands change.

## Known behavior

**i18n imports from notifications:** `#lib/server/infra/notifications/index.ts` does not re-export
i18n functions (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`, etc.) despite using them internally.
This is intentional: those functions load Paraglide messages (a Vite requirement), but the notifications
index is imported by `$modules/auth` which runs outside Vite during e2e tests. When you need these
functions, import them directly from `#lib/server/infra/notifications/i18n` instead of the main index.

**Server startup and readiness:** The auth guard in `hooks.server.ts` checks readiness via
`getServerReadyState()` before processing any request. During startup, browsers receive a
self-reloading "GitOps is starting" landing page, while API requests get a 503 response with
Expand Down
Loading
Loading