diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index f7a83d2d..9f1ff6e8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -8,7 +8,7 @@ con SvelteKit. Mantener este archivo y `CLAUDE.md` equivalentes en arquitectura GitOps combina autenticacion y RBAC, organizaciones y proyectos, Open Report de seguridad y visibilidad de Pulumi State. La ruta Vault es actualmente una base visual sin backend completo. -Google SSO es a nivel de clúster y se configura solo con variables de entorno +Google SSO es a nivel de sistema y se configura solo con variables de entorno (`GOOGLE_SSO_CLIENT_ID`, `GOOGLE_SSO_CLIENT_SECRET` y, opcionales, `GOOGLE_SSO_ALLOWED_DOMAINS` y `GOOGLE_SSO_AUTO_PROVISION`), leídas en cada request por `readGoogleSsoConfig()` desde `src/modules/auth/infrastructure/config/google-sso.config.ts` en `GoogleSsoConfig`; nada se @@ -21,7 +21,7 @@ se silencia como deshabilitada y se registra la razón; la UI nunca se rompe. `s `GoogleOidcClient` y autentica al usuario existente y no deshabilitado por `sub` o email verificado; vincula el `sub` en `user.authProviders[]` y acepta invitaciones pendientes. Los dominios se comprueban contra el claim `hd` de Workspace, no email. Con `GOOGLE_SSO_AUTO_PROVISION=true` -(requiere dominios permitidos), una cuenta Workspace desconocida recibe una cuenta `cluster-user` +(requiere dominios permitidos), una cuenta Workspace desconocida recibe una cuenta GitOps User (`cluster-user`) activa sin organización vía `userAccessService.provisionClusterUser()`. `user.disabled` solo lo aplica Google sign-in. Templates de notificación (`src/notifications/`) se leen en tiempo de ejecución. SAML es configuración solo. @@ -99,12 +99,12 @@ para obtener flags de lectura de alto nivel que se filtran en AppSidebar según 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`): -- **Cluster Admin**: vault, openreport, stateiac (todos) -- **Cluster User**: sin permisos propios; rol base para acceso a nivel cluster -- **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) +- **GitOps Admin** (`cluster-admin`) — vault, openreport, stateiac (todos) +- **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 @@ -114,7 +114,7 @@ aplican (regla most-specific-wins). Permite delegación de autoridad granular co `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). -Al crear una organizacion (via bootstrap o cluster-settings), se llama automaticamente a +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 `roleService.createDefaultProjectRoles()`. Ambas operaciones inicializan sus roles por defecto. diff --git a/CLAUDE.md b/CLAUDE.md index efe1a249..db87a1fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,7 +8,7 @@ GitOps combines identity and access management, organizations and projects, Open analysis, and Pulumi State visibility. The Vault route is currently a UI foundation and does not yet provide a complete secrets backend. SAML settings are configuration only. -Google SSO is cluster-wide and configured only through environment variables +Google SSO is system-wide and configured only through environment variables (`GOOGLE_SSO_CLIENT_ID`, `GOOGLE_SSO_CLIENT_SECRET`, optional `GOOGLE_SSO_ALLOWED_DOMAINS` and `GOOGLE_SSO_AUTO_PROVISION`), read on every request by `readGoogleSsoConfig()` from `src/modules/auth/infrastructure/config/google-sso.config.ts` into a `GoogleSsoConfig` domain @@ -23,13 +23,13 @@ JWKS via `GoogleOidcClient`, and signs in any existing, non-disabled user found verified email, linking the `sub` in `user.authProviders[]` and accepting pending invitations on first sign-in. Allowed domains are checked against the Workspace `hd` claim, not the email suffix. With `GOOGLE_SSO_AUTO_PROVISION=true` (requires at least one allowed domain), an unknown Workspace -account of an allowed domain gets an active `cluster-user` account with no organization membership +account of an allowed domain gets an active GitOps User (`cluster-user`) account with no organization membership through `userAccessService.provisionClusterUser()`; organizations still have to invite it. `user.disabled` is currently enforced only by Google sign-in. -Self-service registration (`/auth/registration`) lets a visitor create a plain `cluster-user` -account with no organization membership. It is gated by a cluster-wide toggle managed at -`/cluster-settings/registration` (persisted via `clusterSettingsService` in `$modules/config`, +Self-service registration (`/auth/registration`) lets a visitor create a plain GitOps User (`cluster-user`) +account with no organization membership. It is gated by a system-wide toggle managed at +`/gitops-settings/registration` (persisted via `clusterSettingsService` in `$modules/config`, off by default) and re-checked server-side on submit so it can't be bypassed while disabled. Once registered and signed in, the user lands on `/org`, where the `cluster:organization:create` permission (granted to `cluster-user` by default) surfaces a "New Organization" action that @@ -166,13 +166,13 @@ This ensures the UI only displays navigation items for sections the user has per Default roles and permissions are centralized in `src/modules/auth/domain/role-permissions.data.ts`. Permissions always include their scope as a prefix (e.g., `organization:projects:read`, `project:vault:secrets:all`) and are stored verbatim—there is no scope-stripping transformation: -- **Cluster Admin** (`vault:all`, `openreport:all`, `stateiac:all`) -- **Cluster User** (no inherent permissions; used as base role for cluster-level access) -- **Organization Admin** (all org-level permissions: projects, users, roles, settings, backups, server-keys, audit) -- **Organization Developer** (read/create/update projects only) -- **Project Admin** (all project-level permissions: project metadata, users, roles, server-keys, audit; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history) -- **Project Developer** (read/create/update project resources; no deletion or admin; granular module access) -- **Project Viewer** (read-only: project metadata, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history) +- **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 Developer** — read/create/update projects only +- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history +- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access +- **Project Viewer** — read-only: project metadata, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history 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. @@ -186,7 +186,7 @@ Two helpers distinguish organization visibility from management: `canManageOrgan while `canViewOrganization()` also includes users whose only access is to a project under that organization (they see the org overview, but cannot perform org-scope actions). -When creating an organization (via bootstrap or cluster settings), `roleService.createDefaultOrganizationRoles()` is +When creating an organization (via bootstrap or `/gitops-settings`), `roleService.createDefaultOrganizationRoles()` is automatically invoked. When creating a project, `roleService.createDefaultProjectRoles()` is automatically invoked. Both operations initialize their respective default roles. Keep authorization tests beside changes to permission behavior. Machine-to-machine requests authenticate with `Authorization: Bearer gvs_...`; `hooks.server.ts` diff --git a/README.md b/README.md index 77e68943..71f56bfd 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,7 @@ in testing mode, only the accounts listed as test users can sign in. By default only existing or invited users can sign in with Google. With `GOOGLE_SSO_AUTO_PROVISION=true` (requires at least one allowed domain), the first Google sign-in of -an unknown `@example.com` Workspace account creates a plain cluster user with no organization +an unknown `@example.com` Workspace account creates a plain GitOps User (`cluster-user`) with no organization membership; organizations still have to invite it. Personal Google accounts are never signed up automatically, because the domain is checked against the Workspace `hd` claim, not the email address. If the variables are inconsistent (only one credential set, an invalid domain, or diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts index abaae54c..4f6ddfe4 100644 --- a/e2e/fixtures/seed.ts +++ b/e2e/fixtures/seed.ts @@ -65,13 +65,13 @@ function requireSeedSlug(slug: string | null, entity: string): string { export async function seedAll(): Promise { const clusterAdminRole = await roleService.createRole({ - name: 'Cluster Admin', + name: 'GitOps Admin', slug: 'cluster-admin', scope: 'cluster', permissions: CLUSTER_ADMIN_PERMISSIONS, }); const clusterUserRole = await roleService.createRole({ - name: 'Cluster User', + name: 'GitOps User', slug: 'cluster-user', scope: 'cluster', permissions: [], diff --git a/e2e/specs/cluster-settings.spec.ts b/e2e/specs/gitops-settings.spec.ts similarity index 88% rename from e2e/specs/cluster-settings.spec.ts rename to e2e/specs/gitops-settings.spec.ts index 6f730e7e..6225ff85 100644 --- a/e2e/specs/cluster-settings.spec.ts +++ b/e2e/specs/gitops-settings.spec.ts @@ -2,11 +2,11 @@ import { test } from '../fixtures/auth'; import { expectAllowed, expectDenied } from '../fixtures/expect-access'; const clusterRoutes = [ - '/cluster-settings/orgs', - '/cluster-settings/roles-permissions', - '/cluster-settings/access-control', - '/cluster-settings/database', - '/cluster-settings/audit', + '/gitops-settings/orgs', + '/gitops-settings/roles-permissions', + '/gitops-settings/access-control', + '/gitops-settings/database', + '/gitops-settings/audit', ]; test.describe('cluster settings — cluster admin', () => { diff --git a/src/hooks.server.ts b/src/hooks.server.ts index d9988a7b..bd988fcb 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -77,6 +77,13 @@ const authGuard: Handle = async ({ event, resolve }) => { return new Response(null, { status: 302, headers: { location: '/bootstrap' } }); } + // legacy URL: the admin area moved from /cluster-settings to /gitops-settings; keep old + // bookmarks working (the new path is still guarded below) + if (pathname === '/cluster-settings' || pathname.startsWith('/cluster-settings/')) { + const location = pathname.replace('/cluster-settings', '/gitops-settings') + event.url.search; + return new Response(null, { status: 308, headers: { location } }); + } + // sign-in, sign-out, self-registration, password recovery, invitation acceptance and the Google // SSO round trip must work without (or with a broken) session; each route re-checks what it needs if ( @@ -151,7 +158,7 @@ const authGuard: Handle = async ({ event, resolve }) => { ) { return new Response(null, { status: 302, headers: { location: '/' } }); } - } else if (event.url.pathname.startsWith('/cluster-settings')) { + } else if (event.url.pathname.startsWith('/gitops-settings')) { if (!cancanService.canAccessAdminArea(currentUser)) { return new Response(null, { status: 302, headers: { location: '/' } }); } diff --git a/src/lib/components/AppNavbar.svelte b/src/lib/components/AppNavbar.svelte index e17df8f1..bfcb07fe 100644 --- a/src/lib/components/AppNavbar.svelte +++ b/src/lib/components/AppNavbar.svelte @@ -75,7 +75,7 @@ > {#if !organizationSlug}

- {$_('nav.noOrganizationSelected')} {$_('nav.chooseOne')}.

diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 6041c547..8d70506a 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -96,7 +96,7 @@ : [ { label: $_('sidebar.items.selectOrganization'), - href: '/cluster-settings/orgs', + href: '/gitops-settings/orgs', icon: Building2, }, ], @@ -323,36 +323,36 @@ { name: $_('sidebar.modules.clusterSettings'), icon: Building2, - base: '/cluster-settings', + base: '/gitops-settings', items: [ { label: $_('sidebar.items.organizations'), - href: '/cluster-settings/orgs', + href: '/gitops-settings/orgs', icon: Building2, }, { label: $_('sidebar.items.rolesAndPermissions'), - href: '/cluster-settings/roles-permissions', + href: '/gitops-settings/roles-permissions', icon: Shield, }, { label: $_('sidebar.items.accessControl'), - href: '/cluster-settings/access-control', + href: '/gitops-settings/access-control', icon: Users, }, { label: $_('sidebar.items.registration'), - href: '/cluster-settings/registration', + href: '/gitops-settings/registration', icon: KeyRound, }, { label: $_('sidebar.items.database'), - href: '/cluster-settings/database', + href: '/gitops-settings/database', icon: Database, }, { label: $_('sidebar.items.auditLog'), - href: '/cluster-settings/audit', + href: '/gitops-settings/audit', icon: ScrollText, }, ], @@ -429,7 +429,7 @@ { role: { id: 'role-1', name: 'Developer' }, createdAt: '2026-08-18T00:00:00.000Z', }), + isLinkedTo: vi.fn().mockReturnValue(false), }; userRepository.findById.mockResolvedValue(user); @@ -61,12 +63,51 @@ describe('ProfileService', () => { email: 'alice@example.com', role: { id: 'role-1', name: 'Developer' }, createdAt: '2026-08-18T00:00:00.000Z', + googleLinked: false, }); + expect(user.isLinkedTo).toHaveBeenCalledWith('google'); expect(userRepository.findById).toHaveBeenCalledWith('user-1'); expect(user.toJson).toHaveBeenCalledTimes(1); }); + it('reports a linked Google identity', async () => { + const userRepository = createUserRepositoryMock(); + const service = new ProfileService(userRepository, createPasswordServiceMock()); + + userRepository.findById.mockResolvedValue( + new UserDomain({ + id: 'user-1', + username: 'alice', + authProviders: [ + { provider: 'local', providerId: null }, + { provider: 'google', providerId: 'google-sub-1' }, + ], + }), + ); + + await expect(service.getAuthenticatedUserProfile('user-1')).resolves.toMatchObject({ + googleLinked: true, + }); + }); + + it('reports no Google link for a password-only user', async () => { + const userRepository = createUserRepositoryMock(); + const service = new ProfileService(userRepository, createPasswordServiceMock()); + + userRepository.findById.mockResolvedValue( + new UserDomain({ + id: 'user-1', + username: 'alice', + authProviders: [{ provider: 'local', providerId: null }], + }), + ); + + await expect(service.getAuthenticatedUserProfile('user-1')).resolves.toMatchObject({ + googleLinked: false, + }); + }); + it('returns null when the user profile does not exist', async () => { const userRepository = createUserRepositoryMock(); const passwordService = createPasswordServiceMock(); diff --git a/src/modules/auth/application/profile.service.ts b/src/modules/auth/application/profile.service.ts index 17165f4f..7bb8ef48 100644 --- a/src/modules/auth/application/profile.service.ts +++ b/src/modules/auth/application/profile.service.ts @@ -13,7 +13,7 @@ export class ProfileService { return null; } - return user.toJson(); + return { ...user.toJson(), googleLinked: user.isLinkedTo('google') }; } async updateEmail(userId: string, email: string | null): Promise { diff --git a/src/modules/auth/domain/user.domain.ts b/src/modules/auth/domain/user.domain.ts index 02341d46..0cb582c1 100644 --- a/src/modules/auth/domain/user.domain.ts +++ b/src/modules/auth/domain/user.domain.ts @@ -34,6 +34,11 @@ export class UserDomain extends Domain { ); } + /** True when an external identity of this provider (e.g. a Google `sub`) is linked to the user. */ + isLinkedTo(provider: string): boolean { + return this.authProviders.some((entry) => entry.provider === provider && !!entry.providerId); + } + toJson() { return { id: this.id, diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index d37c4a01..8451dd02 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -84,7 +84,7 @@ {#if !isBareLayout}