diff --git a/.env.example b/.env.example index f9a05458..0c869720 100644 --- a/.env.example +++ b/.env.example @@ -28,7 +28,19 @@ GITDB_SYNC_POLL_SECONDS=60 # NOTIFICATION_SMTP_PASSWORD= # NOTIFICATION_SMTP_FROM=noreply@example.com # NOTIFICATION_SMTP_FROM_NAME=GitOps -# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true# Git repository backing GitDB. Cloned into /data/gitdb at startup. +# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true + +# Optional cluster-wide Google sign-in (OpenID Connect). Shown on the login page when both the +# client ID and secret are set. Redirect URI to register in GCP: /auth/sso/google/callback +GOOGLE_SSO_CLIENT_ID= +GOOGLE_SSO_CLIENT_SECRET= +# Comma-separated Google Workspace domains allowed to sign in (empty: any verified Google account) +GOOGLE_SSO_ALLOWED_DOMAINS=gigigo.com,example.org +# Sign up unknown Workspace accounts of the allowed domains as cluster users (needs allowed domains) +GOOGLE_SSO_AUTO_PROVISION= + + +# Git repository backing GitDB. Cloned into /data/gitdb at startup. GITDB_REPOSITORY_URL=git@github.com:getgitops/gitops-db-dev.git GITDB_BRANCH=main diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index fad4150a..9f1ff6e8 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -7,7 +7,24 @@ 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 y SAML son configuracion, no estrategias de autenticacion implementadas. + +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 +persiste en GitDB. Si ambas credenciales están válidas, `/auth/login` muestra "Continuar con +Google" y `/org//settings/global` muestra Google SSO en solo lectura (sin exponer credenciales). +Una configuración inválida (credencial faltante, dominio inválido, inconsistencia en auto-provision) +se silencia como deshabilitada y se registra la razón; la UI nunca se rompe. `ssoService` en +`$modules/auth` ejecuta Authorization Code + PKCE (`/auth/sso/google/start` y +`/auth/sso/google/callback`, ambas sin sesión), verifica el ID token contra JWKS de Google con +`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 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. - SvelteKit 2, Svelte 5, Vite 8 y TypeScript 6 strict - Tailwind CSS 4 y `@lucide/svelte` @@ -17,6 +34,8 @@ Google SSO y SAML son configuracion, no estrategias de autenticacion implementad - Vitest, ESLint y Prettier - Playwright para tests e2e de RBAC (`e2e/`) +Las variables de entorno se declaran en `src/env.ts` y se documentan en `.env.example`; Google SSO usa las `GOOGLE_SSO_*` descritas arriba. + Comandos: ```bash @@ -80,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 @@ -95,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/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..165c7121 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + # Mantiene al día los SHA de las actions fijadas en los workflows. + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + # No se adoptan releases de menos de 7 días. + cooldown: + default-days: 7 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9e3866f5..4d51f607 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,12 +12,12 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: - bun-version: latest + bun-version: 1.4.3 - name: Install dependencies run: bun install @@ -30,12 +30,12 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: - bun-version: latest + bun-version: 1.4.3 - name: Install dependencies run: bun install @@ -48,12 +48,12 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: - bun-version: latest + bun-version: 1.4.3 - name: Install dependencies run: bun install diff --git a/.github/workflows/code-report.yml b/.github/workflows/code-report.yml index 524d4d13..4f79ef62 100644 --- a/.github/workflows/code-report.yml +++ b/.github/workflows/code-report.yml @@ -10,18 +10,18 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Bun - uses: oven-sh/setup-bun@v2 + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: - bun-version: latest + bun-version: 1.4.3 - name: Install dependencies run: bun install - name: Install GitOps CLI - run: bun install --global @getgitops/cli + run: bun install --global @getgitops/cli@1.2.1 - name: Run Code Report scan env: diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml index 766cb585..7f5e4cad 100644 --- a/.github/workflows/docker-publish.yml +++ b/.github/workflows/docker-publish.yml @@ -20,10 +20,10 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Log in to the Container Registry - uses: docker/login-action@v3 + uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} @@ -31,7 +31,7 @@ jobs: - name: Extract metadata (tags, labels) for Docker id: meta - uses: docker/metadata-action@v5 + uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0 with: images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} tags: | @@ -40,10 +40,10 @@ jobs: type=semver,pattern={{major}} - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0 - name: Build and push Docker image - uses: docker/build-push-action@v6 + uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2 with: context: . push: true diff --git a/CLAUDE.md b/CLAUDE.md index 3df4eef2..db87a1fc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,12 +6,30 @@ Guidance for working on GitOps, an open source internal developer platform built GitOps combines identity and access management, organizations and projects, Open Report security analysis, and Pulumi State visibility. The Vault route is currently a UI foundation and does not -yet provide a complete secrets backend. Google SSO and SAML settings are configuration only; no -external authentication strategy is implemented. - -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`, +yet provide a complete secrets backend. SAML settings are configuration only. + +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 +object; nothing is persisted in GitDB. When both credentials are set and the config is valid, `/auth/login` +shows "Continue with Google" next to the password form, and each organization's +`/org//settings/global` shows Google SSO as enabled (read-only status, credentials never exposed). +A misconfigured provider (missing credential, invalid domain, inconsistent auto-provision settings) +silently counts as disabled and logs the reason; the UI never breaks. `ssoService` in `$modules/auth` +runs Authorization Code + PKCE through `/auth/sso/google/start` and `/auth/sso/google/callback` +(both allow unauthenticated access in `hooks.server.ts`), verifies the ID token against Google's +JWKS via `GoogleOidcClient`, and signs in any existing, non-disabled user found by Google `sub` or +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 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 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 @@ -36,6 +54,10 @@ The roadmap is in `IDEAS.md`. Do not describe roadmap items as implemented featu - Vitest, ESLint, and Prettier - Playwright for RBAC end-to-end tests (`e2e/`) +Environment variables are declared in `src/env.ts` and documented in `.env.example`; Google SSO uses the `GOOGLE_SSO_*` variables described above. + +Email notification templates (`src/notifications/`) are read from disk at runtime; the Docker image copies them so emails can be sent from the container. + ```bash bun install bun run dev @@ -144,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. @@ -164,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/Dockerfile b/Dockerfile index 82b050bf..af3e15d5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -32,6 +32,8 @@ RUN apk add --no-cache git openssh-client && \ COPY --from=builder /app/build ./build COPY --from=builder /app/node_modules ./node_modules COPY --from=builder /app/package.json ./package.json +# email templates are read from disk at runtime (src/lib/server/infra/notifications/template.ts) +COPY --from=builder /app/src/notifications ./src/notifications # Persistent data directory (SQLite DB + gitdb clone) # VOLUME ["/app/data"] diff --git a/README.md b/README.md index 6bcdc2bd..71f56bfd 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ operational data versioned and auditable in Git. - Identity and access management for users, organizations, projects, roles, permissions, invitations, sessions, and API keys. +- Cluster-wide Google sign-in (OpenID Connect) alongside local email and password login. - Security reporting for vulnerabilities, SBOMs, secrets, licenses, and services. - Pulumi state, history, and lock visibility for S3 and Google Cloud Storage backends. - Git-backed, auditable application data through GitDB. @@ -79,6 +80,44 @@ docker compose up --build ``` The container is available at `http://localhost:3000` and stores persistent data in `./data`. +The image ships `git` without an SSH client, so point `GITDB_REPOSITORY_URL` at an HTTPS remote +and authenticate with `GITDB_TOKEN` (or `GITDB_USERNAME`/`GITDB_PASSWORD`); with an SSH +(`git@...`) remote the container can commit locally but cannot push. + +### Google sign-in + +Google sign-in is configured once for the whole cluster, through environment variables: + +1. In Google Cloud Console, open **APIs & Services → Credentials** and create an **OAuth client ID** + of type **Web application** (configure the consent screen as *Internal* for Workspace-only + access). +2. Under **Authorized redirect URIs** (not *JavaScript origins*), add + `https:///auth/sso/google/callback`. For local use add the URI of the port you run + on, which must match exactly: `http://localhost:5173/auth/sso/google/callback` for + `bun run dev`, `http://localhost:3000/auth/sso/google/callback` for Docker. +3. Set the variables and restart GitOps: + + ```bash + GOOGLE_SSO_CLIENT_ID=123456789-abc.apps.googleusercontent.com + GOOGLE_SSO_CLIENT_SECRET=... + # optional: comma-separated Google Workspace domains allowed to sign in + GOOGLE_SSO_ALLOWED_DOMAINS=example.com + # optional: sign up unknown Workspace accounts of the allowed domains automatically + GOOGLE_SSO_AUTO_PROVISION=false + ``` + +The login page then shows **Continue with Google**, and every organization's **Settings → Global** +shows Google SSO as enabled for the cluster. Leave `GOOGLE_SSO_ALLOWED_DOMAINS` empty to accept +personal `@gmail.com` accounts, which carry no Workspace domain. With an *External* consent screen +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 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 +automatic sign-up without domains), the Google button is hidden and the reason is logged. ## Development 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/env.ts b/src/env.ts index ba75f784..fe90f90e 100644 --- a/src/env.ts +++ b/src/env.ts @@ -24,4 +24,8 @@ export const variables = defineEnvVars({ NOTIFICATION_SMTP_FROM: optional, NOTIFICATION_SMTP_FROM_NAME: optional, NOTIFICATION_SMTP_REJECT_UNAUTHORIZED: optional, + GOOGLE_SSO_CLIENT_ID: optional, + GOOGLE_SSO_CLIENT_SECRET: optional, + GOOGLE_SSO_ALLOWED_DOMAINS: optional, + GOOGLE_SSO_AUTO_PROVISION: optional, }); diff --git a/src/hooks.server.ts b/src/hooks.server.ts index b3cf628c..bd988fcb 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -7,12 +7,7 @@ import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstr import { startGitDb } from '#lib/server/gitdb'; import { markServerFailed, markServerReady } from '#lib/server/server-ready'; import { runWithActor } from '#lib/server/request-context'; -import { - createLogger, - createRequestLogger, - logHttpRequest, - logger, -} from '#lib/server/logger'; +import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger'; const startupLog = createLogger('startup'); @@ -82,10 +77,19 @@ const authGuard: Handle = async ({ event, resolve }) => { return new Response(null, { status: 302, headers: { location: '/bootstrap' } }); } - // sign-in, sign-out, self-registration, password recovery and invitation acceptance must work - // without (or with a broken) session; each route re-checks whatever it needs server-side + // 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 ( pathname === '/auth/login' || + pathname === '/auth/sso/google/start' || + pathname === '/auth/sso/google/callback' || pathname === '/auth/logout' || pathname === '/auth/invitation' || pathname === '/auth/registration' || @@ -154,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/application/sso.service.test.ts b/src/modules/auth/application/sso.service.test.ts new file mode 100644 index 00000000..d425c693 --- /dev/null +++ b/src/modules/auth/application/sso.service.test.ts @@ -0,0 +1,434 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { SsoError, SsoService } from './sso.service'; +import { GoogleSsoConfig } from '../domain/google-sso-config.domain'; +import { UserDomain, type UserAuthProvider } from '../domain/user.domain'; +import { UserAccessDomain } from '../domain/user-access.domain'; +import type { GoogleIdTokenClaims } from '../infrastructure/oidc/google-oidc.client'; + +const REDIRECT_URI = 'https://gitops.local/auth/sso/google/callback'; +const TIMESTAMPS = { createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z' }; + +class FakeUserRepository { + rows: UserDomain[] = []; + activated: string[] = []; + lastLogins: string[] = []; + + async findByAuthProvider(provider: string, providerId: string) { + return this.rows.find((user) => user.hasAuthProvider(provider, providerId)) ?? null; + } + + async findByEmail(email: string) { + return this.rows.find((user) => user.email === email) ?? null; + } + + async updateAuthProviders(userId: string, authProviders: UserAuthProvider[]) { + const user = this.rows.find((entry) => entry.id === userId)!; + user.authProviders = authProviders; + } + + async activateInvitedUser(userId: string) { + this.activated.push(userId); + this.rows.find((entry) => entry.id === userId)!.status = 'active'; + } + + async touchLastLogin(userId: string) { + this.lastLogins.push(userId); + } +} + +class FakeUserAccessRepository { + rows: UserAccessDomain[] = []; + + async findByUserId(userId: string) { + return this.rows.filter((row) => row.userId === userId); + } + + async update(id: string, changes: { status: 'active' | 'invited' }) { + const row = this.rows.find((entry) => entry.id === id)!; + row.status = changes.status; + return row; + } +} + +/** Mirrors UserAccessService.provisionClusterUser on top of the fake user repository. */ +class FakeUserProvisioner { + calls: string[] = []; + + constructor(private readonly users: FakeUserRepository) {} + + async provisionClusterUser(email: string) { + this.calls.push(email); + const created = user({ id: `user-${this.users.rows.length + 1}`, username: 'new', email }); + this.users.rows.push(created); + return created; + } +} + +function user(overrides: Record = {}) { + return new UserDomain({ + id: 'user-1', + username: 'ana', + email: 'ana@gigigo.com', + password: 'hash', + status: 'active', + role: null, + authProviders: [{ provider: 'local', providerId: null }], + ...TIMESTAMPS, + ...overrides, + }); +} + +function access(overrides: Record = {}) { + return new UserAccessDomain({ + id: 'access-1', + userId: 'user-1', + roleId: 'role-dev', + scope: 'organization', + organizationId: 'org-1', + status: 'active', + ...TIMESTAMPS, + ...overrides, + }); +} + +describe('SsoService', () => { + let config: GoogleSsoConfig | null; + let configError: Error | null; + let users: FakeUserRepository; + let accesses: FakeUserAccessRepository; + let provisioner: FakeUserProvisioner; + let googleClaims: GoogleIdTokenClaims; + let googleClient: { + buildAuthorizationUrl: ReturnType; + exchangeCode: ReturnType; + }; + let now: number; + let service: SsoService; + + beforeEach(() => { + config = new GoogleSsoConfig('client-123', 'super-secret', ['gigigo.com'], false); + configError = null; + users = new FakeUserRepository(); + accesses = new FakeUserAccessRepository(); + provisioner = new FakeUserProvisioner(users); + now = Date.UTC(2026, 0, 1); + googleClaims = { + sub: 'google-sub-1', + email: 'ana@gigigo.com', + email_verified: true, + hd: 'gigigo.com', + }; + googleClient = { + buildAuthorizationUrl: vi.fn( + (request: { state: string; nonce: string }) => + `https://accounts.google.com/auth?state=${request.state}&nonce=${request.nonce}`, + ), + // echo the nonce from the authorization request, as Google does + exchangeCode: vi.fn(async () => ({ ...googleClaims, nonce: lastNonce() })), + }; + service = new SsoService( + () => { + if (configError) throw configError; + return config; + }, + users as any, + accesses as any, + provisioner, + googleClient as any, + () => 'signing-key', + () => now, + ); + + users.rows.push(user()); + accesses.rows.push(access()); + }); + + function lastNonce() { + const url = googleClient.buildAuthorizationUrl.mock.results.at(-1)?.value as string; + return new URL(url).searchParams.get('nonce') ?? undefined; + } + + function start() { + const started = service.startGoogleSignIn({ redirectUri: REDIRECT_URI }); + const state = new URL(started.authorizationUrl).searchParams.get('state')!; + return { ...started, state }; + } + + async function signIn(overrides: { state?: string; flowCookie?: string } = {}) { + const started = start(); + return service.completeGoogleSignIn({ + flowCookie: overrides.flowCookie ?? started.flowCookie, + state: overrides.state ?? started.state, + code: 'auth-code', + redirectUri: REDIRECT_URI, + }); + } + + async function expectSsoError(promise: Promise, code: string) { + await expect(promise).rejects.toBeInstanceOf(SsoError); + await expect(promise).rejects.toMatchObject({ code }); + } + + describe('status', () => { + it('reports the cluster configuration without the client credentials', () => { + const status = service.getGoogleStatus(); + + expect(status).toEqual({ + enabled: true, + allowedDomains: ['gigigo.com'], + autoProvision: false, + }); + expect(JSON.stringify(status)).not.toContain('super-secret'); + expect(JSON.stringify(status)).not.toContain('client-123'); + expect(service.isGoogleEnabled()).toBe(true); + }); + + it('is disabled when Google sign-in is not configured', () => { + config = null; + expect(service.isGoogleEnabled()).toBe(false); + expect(service.getGoogleStatus()).toEqual({ + enabled: false, + allowedDomains: [], + autoProvision: false, + }); + }); + + it('treats a misconfigured provider as disabled instead of throwing', () => { + configError = new Error( + 'GOOGLE_SSO_CLIENT_ID and GOOGLE_SSO_CLIENT_SECRET must be set together', + ); + expect(service.isGoogleEnabled()).toBe(false); + expect(service.getGoogleStatus().enabled).toBe(false); + }); + }); + + describe('startGoogleSignIn', () => { + it('builds a PKCE request with the hosted domain hint', () => { + start(); + + const request = googleClient.buildAuthorizationUrl.mock.calls[0]?.[0]; + expect(request).toMatchObject({ + clientId: 'client-123', + redirectUri: REDIRECT_URI, + hostedDomain: 'gigigo.com', + }); + expect(request.codeChallenge).toMatch(/^[A-Za-z0-9_-]{43}$/); + }); + + it('omits the hosted domain hint when several domains are allowed', () => { + config = new GoogleSsoConfig( + 'client-123', + 'super-secret', + ['gigigo.com', 'example.org'], + false, + ); + start(); + expect(googleClient.buildAuthorizationUrl.mock.calls[0]?.[0].hostedDomain).toBeUndefined(); + }); + + it('fails when Google sign-in is not configured', () => { + config = null; + expect(() => start()).toThrow(SsoError); + expect(() => start()).toThrow(/not enabled/); + }); + + it('fails with not_configured when it is misconfigured', () => { + configError = new Error('"bad" is not a valid domain'); + try { + start(); + expect.unreachable(); + } catch (error) { + expect(error).toMatchObject({ code: 'not_configured' }); + } + }); + }); + + describe('completeGoogleSignIn', () => { + it('signs in an existing user and links the Google identity', async () => { + const result = await signIn(); + + expect(result).toEqual({ userId: 'user-1' }); + expect(users.rows[0].authProviders).toContainEqual({ + provider: 'google', + providerId: 'google-sub-1', + }); + expect(users.lastLogins).toEqual(['user-1']); + const exchange = googleClient.exchangeCode.mock.calls[0]?.[0]; + expect(exchange.clientSecret).toBe('super-secret'); + }); + + it('signs in users regardless of the organizations they belong to', async () => { + accesses.rows = []; + await expect(signIn()).resolves.toEqual({ userId: 'user-1' }); + expect(provisioner.calls).toEqual([]); + }); + + it('resolves an already linked user by Google subject even if the email changed', async () => { + users.rows[0].email = 'ana.old@gigigo.com'; + users.rows[0].authProviders.push({ provider: 'google', providerId: 'google-sub-1' }); + + await expect(signIn()).resolves.toEqual({ userId: 'user-1' }); + }); + + it('accepts a pending invitation instead of asking for a password', async () => { + users.rows[0].status = 'invited'; + accesses.rows = [ + access({ id: 'access-1', status: 'invited' }), + access({ id: 'access-2', organizationId: 'org-2', status: 'invited' }), + ]; + + await signIn(); + + expect(users.activated).toEqual(['user-1']); + expect(accesses.rows.map((row) => row.status)).toEqual(['active', 'active']); + }); + + it('rejects users with no account', async () => { + users.rows = []; + await expectSsoError(signIn(), 'not_invited'); + expect(provisioner.calls).toEqual([]); + }); + + it('rejects disabled accounts', async () => { + users.rows[0].disabled = true; + await expectSsoError(signIn(), 'account_disabled'); + expect(users.lastLogins).toEqual([]); + }); + + it('rejects unverified emails', async () => { + googleClaims.email_verified = false; + await expectSsoError(signIn(), 'email_not_verified'); + }); + + it('rejects accounts outside the allowed Workspace domains', async () => { + googleClaims.hd = 'evil.com'; + await expectSsoError(signIn(), 'domain_not_allowed'); + }); + + it('does not trust the email suffix without the hd claim', async () => { + delete googleClaims.hd; + await expectSsoError(signIn(), 'domain_not_allowed'); + }); + + it('accepts any verified account when no domain is restricted', async () => { + config = new GoogleSsoConfig('client-123', 'super-secret', [], false); + delete googleClaims.hd; + await expect(signIn()).resolves.toEqual({ userId: 'user-1' }); + }); + + describe('with automatic sign-up', () => { + beforeEach(() => { + config = new GoogleSsoConfig('client-123', 'super-secret', ['gigigo.com'], true); + }); + + it('creates a cluster user for a new Workspace account of an allowed domain', async () => { + users.rows = []; + + const result = await signIn(); + + expect(provisioner.calls).toEqual(['ana@gigigo.com']); + expect(users.rows[0].authProviders).toContainEqual({ + provider: 'google', + providerId: 'google-sub-1', + }); + expect(users.lastLogins).toEqual([result.userId]); + }); + + it('does not provision users that already exist', async () => { + await signIn(); + expect(provisioner.calls).toEqual([]); + }); + + it('still rejects disabled accounts', async () => { + users.rows[0].disabled = true; + await expectSsoError(signIn(), 'account_disabled'); + expect(provisioner.calls).toEqual([]); + }); + + it('still rejects accounts outside the allowed domains', async () => { + users.rows = []; + googleClaims.hd = 'evil.com'; + await expectSsoError(signIn(), 'domain_not_allowed'); + expect(provisioner.calls).toEqual([]); + }); + + it('never provisions a personal account without the hd claim', async () => { + users.rows = []; + delete googleClaims.hd; + await expectSsoError(signIn(), 'domain_not_allowed'); + expect(provisioner.calls).toEqual([]); + }); + + it('fails closed when provisioning fails', async () => { + users.rows = []; + provisioner.provisionClusterUser = async () => { + throw new Error('GitDB unavailable'); + }; + await expectSsoError(signIn(), 'not_invited'); + }); + }); + + it('rejects a mismatched state', async () => { + await expectSsoError(signIn({ state: 'forged' }), 'invalid_state'); + expect(googleClient.exchangeCode).not.toHaveBeenCalled(); + }); + + it('rejects a tampered flow cookie', async () => { + const [payload] = start().flowCookie.split('.'); + await expectSsoError(signIn({ flowCookie: `${payload}.forged` }), 'invalid_state'); + }); + + it('rejects a missing flow cookie', async () => { + const started = start(); + await expectSsoError( + service.completeGoogleSignIn({ + flowCookie: undefined, + state: started.state, + code: 'auth-code', + redirectUri: REDIRECT_URI, + }), + 'invalid_state', + ); + }); + + it('rejects an expired flow', async () => { + const started = start(); + now += 11 * 60 * 1000; + + await expectSsoError( + service.completeGoogleSignIn({ + flowCookie: started.flowCookie, + state: started.state, + code: 'auth-code', + redirectUri: REDIRECT_URI, + }), + 'invalid_state', + ); + }); + + it('rejects a replayed ID token with another nonce', async () => { + googleClient.exchangeCode.mockResolvedValueOnce({ ...googleClaims, nonce: 'other' }); + await expectSsoError(signIn(), 'invalid_state'); + }); + + it('maps Google failures to provider_error', async () => { + googleClient.exchangeCode.mockRejectedValueOnce(new Error('invalid_grant')); + await expectSsoError(signIn(), 'provider_error'); + }); + + it('fails when Google sign-in was disabled mid-flow', async () => { + const started = start(); + config = null; + + await expectSsoError( + service.completeGoogleSignIn({ + flowCookie: started.flowCookie, + state: started.state, + code: 'auth-code', + redirectUri: REDIRECT_URI, + }), + 'not_configured', + ); + }); + }); +}); diff --git a/src/modules/auth/application/sso.service.ts b/src/modules/auth/application/sso.service.ts new file mode 100644 index 00000000..188f076d --- /dev/null +++ b/src/modules/auth/application/sso.service.ts @@ -0,0 +1,244 @@ +import crypto from 'crypto'; +import type { GoogleSsoConfig } from '../domain/google-sso-config.domain'; +import type { UserDomain } from '../domain/user.domain'; +import type { UserAccessRepository } from '../infrastructure/repositories/user-access.repository'; +import type { UserRepository } from '../infrastructure/repositories/user.repository'; +import type { GoogleOidcClient } from '../infrastructure/oidc/google-oidc.client'; +import type { UserAccessService } from './user-access.service'; + +const GOOGLE = 'google'; +const FLOW_TTL_MS = 10 * 60 * 1000; + +export type SsoErrorCode = + | 'not_configured' + | 'invalid_state' + | 'provider_error' + | 'email_not_verified' + | 'domain_not_allowed' + | 'not_invited' + | 'account_disabled'; + +/** Sign-in failure with a stable code the login page maps to a user-facing message. */ +export class SsoError extends Error { + constructor( + public readonly code: SsoErrorCode, + message: string, + ) { + super(message); + } +} + +/** What organization admins may see of the cluster-wide setup: never the client credentials. */ +export type GoogleSsoStatus = { + enabled: boolean; + allowedDomains: string[]; + autoProvision: boolean; +}; + +type SsoFlow = { + state: string; + nonce: string; + codeVerifier: string; + expiresAt: number; +}; + +export class SsoService { + constructor( + /** returns null when Google sign-in is not configured; throws when misconfigured */ + private readonly readConfig: () => GoogleSsoConfig | null, + private readonly userRepository: Pick< + UserRepository, + | 'findByAuthProvider' + | 'findByEmail' + | 'updateAuthProviders' + | 'activateInvitedUser' + | 'touchLastLogin' + >, + private readonly userAccessRepository: Pick, + private readonly userProvisioner: Pick, + private readonly googleClient: Pick, + private readonly signingKey: () => string, + private readonly now: () => number = () => Date.now(), + ) {} + + /** A misconfigured provider counts as disabled, so the login page never breaks because of it. */ + isGoogleEnabled(): boolean { + return this.tryReadConfig() !== null; + } + + getGoogleStatus(): GoogleSsoStatus { + const config = this.tryReadConfig(); + return { + enabled: config !== null, + allowedDomains: config ? [...config.allowedDomains] : [], + autoProvision: config?.autoProvision ?? false, + }; + } + + startGoogleSignIn(input: { redirectUri: string }): { + authorizationUrl: string; + flowCookie: string; + } { + const config = this.requireConfig(); + + const flow: SsoFlow = { + state: this.randomToken(), + nonce: this.randomToken(), + codeVerifier: this.randomToken(), + expiresAt: this.now() + FLOW_TTL_MS, + }; + + const authorizationUrl = this.googleClient.buildAuthorizationUrl({ + clientId: config.clientId, + redirectUri: input.redirectUri, + state: flow.state, + nonce: flow.nonce, + codeChallenge: crypto.createHash('sha256').update(flow.codeVerifier).digest('base64url'), + hostedDomain: config.allowedDomains.length === 1 ? config.allowedDomains[0] : undefined, + }); + + return { authorizationUrl, flowCookie: this.signFlow(flow) }; + } + + async completeGoogleSignIn(input: { + flowCookie: string | undefined; + state: string; + code: string; + redirectUri: string; + }): Promise<{ userId: string }> { + const flow = this.readFlow(input.flowCookie); + if (!flow || !input.state || !this.safeEqual(flow.state, input.state)) { + throw new SsoError('invalid_state', 'The sign-in request expired or was tampered with'); + } + if (!input.code) throw new SsoError('provider_error', 'Google did not return a code'); + + const config = this.requireConfig(); + + let claims; + try { + claims = await this.googleClient.exchangeCode({ + clientId: config.clientId, + clientSecret: config.clientSecret, + code: input.code, + codeVerifier: flow.codeVerifier, + redirectUri: input.redirectUri, + }); + } catch (error) { + throw new SsoError( + 'provider_error', + error instanceof Error ? error.message : 'Google sign-in failed', + ); + } + + if (!claims.nonce || !this.safeEqual(claims.nonce, flow.nonce)) { + throw new SsoError('invalid_state', 'ID token nonce mismatch'); + } + const email = claims.email?.trim().toLowerCase(); + if (!email || !claims.email_verified) { + throw new SsoError('email_not_verified', 'Google account email is not verified'); + } + if (!config.allowsHostedDomain(claims.hd)) { + throw new SsoError('domain_not_allowed', 'Google account domain is not allowed'); + } + + let user = + (await this.userRepository.findByAuthProvider(GOOGLE, claims.sub)) ?? + (await this.userRepository.findByEmail(email)); + if (user?.disabled) throw new SsoError('account_disabled', 'Account is disabled'); + + if (!user) { + if (!config.allowsAutoProvision(claims.hd)) { + throw new SsoError('not_invited', 'No account for this Google identity'); + } + user = await this.provisionUser(email); + } + + await this.linkGoogleIdentity(user, claims.sub); + if (user.status === 'invited') await this.acceptPendingInvitation(user.id); + await this.userRepository.touchLastLogin(user.id); + + return { userId: user.id }; + } + + private tryReadConfig(): GoogleSsoConfig | null { + try { + return this.readConfig(); + } catch { + return null; + } + } + + private requireConfig(): GoogleSsoConfig { + let config: GoogleSsoConfig | null; + try { + config = this.readConfig(); + } catch (error) { + const reason = error instanceof Error ? error.message : String(error); + throw new SsoError('not_configured', `Google sign-in is misconfigured: ${reason}`); + } + if (!config) throw new SsoError('not_configured', 'Google sign-in is not enabled'); + return config; + } + + private async provisionUser(email: string): Promise { + try { + return await this.userProvisioner.provisionClusterUser(email); + } catch { + throw new SsoError('not_invited', 'Automatic sign-up failed for this Google identity'); + } + } + + private async linkGoogleIdentity(user: UserDomain, sub: string): Promise { + if (user.hasAuthProvider(GOOGLE, sub)) return; + await this.userRepository.updateAuthProviders(user.id, [ + ...user.authProviders.filter((entry) => entry.provider !== GOOGLE), + { provider: GOOGLE, providerId: sub }, + ]); + } + + /** Google has verified the invited email, which is what the invitation link proves. */ + private async acceptPendingInvitation(userId: string): Promise { + await this.userRepository.activateInvitedUser(userId); + const access = await this.userAccessRepository.findByUserId(userId); + await Promise.all( + access + .filter((entry) => entry.status === 'invited') + .map((entry) => this.userAccessRepository.update(entry.id, { status: 'active' })), + ); + } + + private signFlow(flow: SsoFlow): string { + const payload = Buffer.from(JSON.stringify(flow)).toString('base64url'); + return `${payload}.${this.sign(payload)}`; + } + + private readFlow(cookie: string | undefined): SsoFlow | null { + if (!cookie) return null; + const [payload, signature] = cookie.split('.'); + if (!payload || !signature || !this.safeEqual(signature, this.sign(payload))) return null; + + try { + const flow = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as SsoFlow; + return typeof flow.expiresAt === 'number' && flow.expiresAt > this.now() ? flow : null; + } catch { + return null; + } + } + + private sign(payload: string): string { + return crypto + .createHmac('sha256', this.signingKey()) + .update(`sso-flow:${payload}`) + .digest('base64url'); + } + + private randomToken(): string { + return crypto.randomBytes(32).toString('base64url'); + } + + private safeEqual(left: string, right: string): boolean { + const a = Buffer.from(left); + const b = Buffer.from(right); + return a.length === b.length && crypto.timingSafeEqual(a, b); + } +} diff --git a/src/modules/auth/application/user-access.service.test.ts b/src/modules/auth/application/user-access.service.test.ts index b35aebf6..6e23b908 100644 --- a/src/modules/auth/application/user-access.service.test.ts +++ b/src/modules/auth/application/user-access.service.test.ts @@ -251,6 +251,38 @@ describe('UserAccessService', () => { expect(userRepository.rows[0].role?.slug).toBe('cluster-user'); }); + describe('provisionClusterUser', () => { + it('creates an active cluster-user account with no organization access', async () => { + const created = await service.provisionClusterUser('Ana@Gigigo.com'); + + expect(created.status).toBe('active'); + expect(userRepository.rows[0]).toMatchObject({ + username: 'ana', + email: 'ana@gigigo.com', + status: 'active', + }); + expect(userRepository.rows[0].role?.slug).toBe('cluster-user'); + expect(userAccessRepository.rows).toHaveLength(0); + expect(invitationNotifier.sendInvitation).not.toHaveBeenCalled(); + }); + + it('returns the existing account for that email instead of creating another', async () => { + userRepository.rows.push( + user({ id: 'existing', username: 'ana', email: 'ana@gigigo.com', role: null }), + ); + + const provisioned = await service.provisionClusterUser('ana@gigigo.com'); + + expect(provisioned.id).toBe('existing'); + expect(userRepository.rows).toHaveLength(1); + }); + + it('requires an email', async () => { + await expect(service.provisionClusterUser(' ')).rejects.toThrow(/Email is required/); + expect(userRepository.rows).toHaveLength(0); + }); + }); + describe('inviteOrganizationUser', () => { function seedOrganizationRole() { roleRepository.rows.push( diff --git a/src/modules/auth/application/user-access.service.ts b/src/modules/auth/application/user-access.service.ts index cf5abaef..516d2248 100644 --- a/src/modules/auth/application/user-access.service.ts +++ b/src/modules/auth/application/user-access.service.ts @@ -129,7 +129,8 @@ export class UserAccessService { : await this.findDefaultOrganizationRole(organizationId); const user = - (await this.userRepository.findByEmail(email)) ?? (await this.createInvitedUser(email)); + (await this.userRepository.findByEmail(email)) ?? + (await this.createUserFromEmail(email, 'invited')); // an already active account just gets access, there is nothing to activate const status: UserAccessStatus = user.status === 'active' ? 'active' : 'invited'; @@ -159,7 +160,21 @@ export class UserAccessService { return this.toRow(access); } - private async createInvitedUser(email: string) { + /** + * Creates an active `cluster-user` account, with no organization membership, for an identity + * already verified by an SSO provider. Callers must have checked it against the SSO policy. + */ + async provisionClusterUser(email: string): Promise { + const normalized = email.trim().toLowerCase(); + if (!normalized) throw new Error('Email is required'); + + return ( + (await this.userRepository.findByEmail(normalized)) ?? + (await this.createUserFromEmail(normalized, 'active')) + ); + } + + private async createUserFromEmail(email: string, status: UserAccessStatus) { const clusterUserRole = await this.ensureClusterUserRole(); const username = await this.buildUsernameFromEmail(email); @@ -167,10 +182,10 @@ export class UserAccessService { id: crypto.randomUUID(), username, email, - // placeholder credential: the invited user must set a password before signing in + // placeholder credential: the user signs in through an invitation or SSO, or resets it passwordHash: this.passwordService.hashPassword(crypto.randomBytes(32).toString('hex')), role: this.toRoleView(clusterUserRole), - status: 'invited', + status, }); const user = await this.userRepository.findByUsername(username); diff --git a/src/modules/auth/domain/google-sso-config.domain.test.ts b/src/modules/auth/domain/google-sso-config.domain.test.ts new file mode 100644 index 00000000..89fa20fb --- /dev/null +++ b/src/modules/auth/domain/google-sso-config.domain.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest'; +import { GoogleSsoConfig } from './google-sso-config.domain'; + +describe('GoogleSsoConfig', () => { + it('accepts any hosted domain when no domain is restricted', () => { + const config = new GoogleSsoConfig('id', 'secret', [], false); + expect(config.allowsHostedDomain(undefined)).toBe(true); + expect(config.allowsHostedDomain('anything.com')).toBe(true); + }); + + it('only accepts the allowed Workspace domains, case-insensitively', () => { + const config = new GoogleSsoConfig('id', 'secret', ['gigigo.com'], false); + expect(config.allowsHostedDomain('Gigigo.com')).toBe(true); + expect(config.allowsHostedDomain('evil.com')).toBe(false); + // a personal account has no hd claim, whatever its email suffix + expect(config.allowsHostedDomain(undefined)).toBe(false); + }); + + it('auto-provisions only Workspace accounts of an allowed domain', () => { + const config = new GoogleSsoConfig('id', 'secret', ['gigigo.com'], true); + expect(config.allowsAutoProvision('gigigo.com')).toBe(true); + expect(config.allowsAutoProvision('evil.com')).toBe(false); + expect(config.allowsAutoProvision(undefined)).toBe(false); + expect( + new GoogleSsoConfig('id', 'secret', ['gigigo.com'], false).allowsAutoProvision('gigigo.com'), + ).toBe(false); + }); + + it('refuses automatic sign-up without a domain restriction', () => { + expect(() => new GoogleSsoConfig('id', 'secret', [], true)).toThrow(/allowed Workspace domain/); + }); + + it('requires the client credentials', () => { + expect(() => new GoogleSsoConfig(' ', 'secret', [], false)).toThrow(/Client ID/); + expect(() => new GoogleSsoConfig('id', '', [], false)).toThrow(/Client Secret/); + }); +}); diff --git a/src/modules/auth/domain/google-sso-config.domain.ts b/src/modules/auth/domain/google-sso-config.domain.ts new file mode 100644 index 00000000..b90dd73f --- /dev/null +++ b/src/modules/auth/domain/google-sso-config.domain.ts @@ -0,0 +1,39 @@ +const DOMAIN_PATTERN = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/; + +/** Cluster-wide Google sign-in settings, sourced from the GOOGLE_SSO_* environment variables. */ +export class GoogleSsoConfig { + readonly allowedDomains: readonly string[]; + + constructor( + readonly clientId: string, + readonly clientSecret: string, + allowedDomains: readonly string[], + /** signs up any verified account of an allowed Workspace domain without an invitation */ + readonly autoProvision: boolean, + ) { + if (!clientId.trim()) throw new Error('Google Client ID is required'); + if (!clientSecret.trim()) throw new Error('Google Client Secret is required'); + + const normalized = [ + ...new Set(allowedDomains.map((domain) => domain.trim().toLowerCase()).filter(Boolean)), + ]; + const invalid = normalized.find((domain) => !DOMAIN_PATTERN.test(domain)); + if (invalid) throw new Error(`"${invalid}" is not a valid domain`); + if (autoProvision && normalized.length === 0) { + throw new Error('Automatic sign-up requires at least one allowed Workspace domain'); + } + this.allowedDomains = normalized; + } + + allowsHostedDomain(hostedDomain: string | null | undefined): boolean { + if (this.allowedDomains.length === 0) return true; + return Boolean(hostedDomain) && this.allowedDomains.includes(hostedDomain!.toLowerCase()); + } + + /** Only Workspace accounts (`hd` claim) of an allowed domain, never any Google account. */ + allowsAutoProvision(hostedDomain: string | null | undefined): boolean { + return ( + this.autoProvision && this.allowedDomains.length > 0 && this.allowsHostedDomain(hostedDomain) + ); + } +} diff --git a/src/modules/auth/domain/user.domain.ts b/src/modules/auth/domain/user.domain.ts index 5cf9a952..0cb582c1 100644 --- a/src/modules/auth/domain/user.domain.ts +++ b/src/modules/auth/domain/user.domain.ts @@ -1,6 +1,8 @@ import { Domain } from './domain'; import { RoleDomain } from './role.domain'; +export type UserAuthProvider = { provider: string; providerId: string | null }; + export class UserDomain extends Domain { public username: string = ''; public email: string | null = null; @@ -9,6 +11,8 @@ export class UserDomain extends Domain { public status: 'active' | 'invited' = 'active'; public invitationExpiresAt: Date | null = null; public passwordResetExpiresAt: Date | null = null; + public authProviders: UserAuthProvider[] = []; + public disabled: boolean = false; constructor(data: any) { super(data); this.username = data.username; @@ -20,6 +24,19 @@ export class UserDomain extends Domain { ? new Date(data.passwordResetExpiresAt) : null; this.role = data.role ? new RoleDomain(data.role) : null; + this.authProviders = Array.isArray(data.authProviders) ? data.authProviders : []; + this.disabled = Boolean(data.disabled); + } + + hasAuthProvider(provider: string, providerId: string): boolean { + return this.authProviders.some( + (entry) => entry.provider === provider && entry.providerId === providerId, + ); + } + + /** 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() { diff --git a/src/modules/auth/index.ts b/src/modules/auth/index.ts index fe7a3094..4fa028d8 100644 --- a/src/modules/auth/index.ts +++ b/src/modules/auth/index.ts @@ -9,10 +9,13 @@ import { InvitationService } from './application/invitation.service'; import { PasswordResetService } from './application/password-reset.service'; import { CanCanService } from './application/cancan.service'; import { RoleService } from './application/role.service'; +import { SsoService } from './application/sso.service'; import { UserRepository } from './infrastructure/repositories/user.repository'; import { RoleRepository } from './infrastructure/repositories/role.repository'; import { ApiKeyRepository } from './infrastructure/repositories/apikey.repository'; import { UserAccessRepository } from './infrastructure/repositories/user-access.repository'; +import { readGoogleSsoConfig } from './infrastructure/config/google-sso.config'; +import { GoogleOidcClient } from './infrastructure/oidc/google-oidc.client'; import { InvitationNotifier } from './infrastructure/notifications/invitation.notifier'; import { PasswordResetNotifier } from './infrastructure/notifications/password-reset.notifier'; import { projectService } from '../projects'; @@ -55,6 +58,15 @@ export const userAccessService = new UserAccessService( invitationNotifier, invitationService, ); +export const ssoService = new SsoService( + readGoogleSsoConfig, + userRepository, + userAccessRepository, + userAccessService, + new GoogleOidcClient(), + () => passwordService.ensureEncryptionKey(), +); +export { SsoError, type SsoErrorCode, type GoogleSsoStatus } from './application/sso.service'; export const cancanService = new CanCanService( userRepository, userAccessRepository, diff --git a/src/modules/auth/infrastructure/config/google-sso.config.test.ts b/src/modules/auth/infrastructure/config/google-sso.config.test.ts new file mode 100644 index 00000000..6382c2e8 --- /dev/null +++ b/src/modules/auth/infrastructure/config/google-sso.config.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { readGoogleSsoConfig } from './google-sso.config'; + +const KEYS = [ + 'GOOGLE_SSO_CLIENT_ID', + 'GOOGLE_SSO_CLIENT_SECRET', + 'GOOGLE_SSO_ALLOWED_DOMAINS', + 'GOOGLE_SSO_AUTO_PROVISION', +]; + +const original = new Map(); + +beforeEach(() => { + for (const key of KEYS) { + original.set(key, process.env[key]); + delete process.env[key]; + } +}); + +afterEach(() => { + for (const key of KEYS) { + const value = original.get(key); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } +}); + +function setCredentials() { + process.env.GOOGLE_SSO_CLIENT_ID = 'client-123.apps.googleusercontent.com'; + process.env.GOOGLE_SSO_CLIENT_SECRET = 'super-secret'; +} + +describe('readGoogleSsoConfig', () => { + it('returns null when Google sign-in is not configured', () => { + expect(readGoogleSsoConfig()).toBeNull(); + }); + + it('requires the client id and secret together', () => { + process.env.GOOGLE_SSO_CLIENT_ID = 'client-123'; + expect(() => readGoogleSsoConfig()).toThrow(/must be set together/); + + delete process.env.GOOGLE_SSO_CLIENT_ID; + process.env.GOOGLE_SSO_CLIENT_SECRET = 'super-secret'; + expect(() => readGoogleSsoConfig()).toThrow(/must be set together/); + }); + + it('reads the credentials with no domain restriction and no automatic sign-up by default', () => { + setCredentials(); + expect(readGoogleSsoConfig()).toMatchObject({ + clientId: 'client-123.apps.googleusercontent.com', + clientSecret: 'super-secret', + allowedDomains: [], + autoProvision: false, + }); + }); + + it('normalizes the allowed domains list', () => { + setCredentials(); + process.env.GOOGLE_SSO_ALLOWED_DOMAINS = ' Gigigo.com, gigigo.com example.org,'; + expect(readGoogleSsoConfig()?.allowedDomains).toEqual(['gigigo.com', 'example.org']); + }); + + it('rejects invalid domains', () => { + setCredentials(); + process.env.GOOGLE_SSO_ALLOWED_DOMAINS = 'gigigo.com,not_a_domain'; + expect(() => readGoogleSsoConfig()).toThrow(/valid domain/); + }); + + it('enables automatic sign-up only with allowed domains', () => { + setCredentials(); + process.env.GOOGLE_SSO_AUTO_PROVISION = 'true'; + expect(() => readGoogleSsoConfig()).toThrow(/allowed Workspace domain/); + + process.env.GOOGLE_SSO_ALLOWED_DOMAINS = 'gigigo.com'; + expect(readGoogleSsoConfig()?.autoProvision).toBe(true); + + process.env.GOOGLE_SSO_AUTO_PROVISION = 'no'; + expect(readGoogleSsoConfig()?.autoProvision).toBe(false); + }); +}); diff --git a/src/modules/auth/infrastructure/config/google-sso.config.ts b/src/modules/auth/infrastructure/config/google-sso.config.ts new file mode 100644 index 00000000..f28dd6cc --- /dev/null +++ b/src/modules/auth/infrastructure/config/google-sso.config.ts @@ -0,0 +1,30 @@ +import * as env from '$app/env/private'; +import { GoogleSsoConfig } from '../../domain/google-sso-config.domain'; + +function value(name: keyof typeof env): string | null { + return env[name]?.trim() || null; +} + +/** + * Reads GOOGLE_SSO_* on every call so tests and config reloads see fresh values. Returns null when + * Google sign-in is not configured and throws when it is configured inconsistently. + */ +export function readGoogleSsoConfig(): GoogleSsoConfig | null { + const clientId = value('GOOGLE_SSO_CLIENT_ID'); + const clientSecret = value('GOOGLE_SSO_CLIENT_SECRET'); + if (!clientId && !clientSecret) return null; + if (!clientId || !clientSecret) { + throw new Error('GOOGLE_SSO_CLIENT_ID and GOOGLE_SSO_CLIENT_SECRET must be set together'); + } + + const autoProvision = ['1', 'true', 'yes', 'on'].includes( + (value('GOOGLE_SSO_AUTO_PROVISION') ?? '').toLowerCase(), + ); + + return new GoogleSsoConfig( + clientId, + clientSecret, + (value('GOOGLE_SSO_ALLOWED_DOMAINS') ?? '').split(/[\s,]+/), + autoProvision, + ); +} diff --git a/src/modules/auth/infrastructure/oidc/google-oidc.client.test.ts b/src/modules/auth/infrastructure/oidc/google-oidc.client.test.ts new file mode 100644 index 00000000..24582ffb --- /dev/null +++ b/src/modules/auth/infrastructure/oidc/google-oidc.client.test.ts @@ -0,0 +1,185 @@ +import crypto from 'crypto'; +import { describe, expect, it, vi } from 'vitest'; +import { GoogleOidcClient } from './google-oidc.client'; + +const CLIENT_ID = 'client-123.apps.googleusercontent.com'; +const NOW = Date.UTC(2026, 0, 1); + +const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); +const jwk = { ...publicKey.export({ format: 'jwk' }), kid: 'key-1', alg: 'RS256', use: 'sig' }; + +function sign(payload: Record, header: Record = {}) { + const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64url'); + const head = encode({ alg: 'RS256', kid: 'key-1', typ: 'JWT', ...header }); + const body = encode(payload); + const signature = crypto + .sign('RSA-SHA256', Buffer.from(`${head}.${body}`), privateKey) + .toString('base64url'); + return `${head}.${body}.${signature}`; +} + +function claims(overrides: Record = {}) { + return { + iss: 'https://accounts.google.com', + aud: CLIENT_ID, + sub: 'google-sub-1', + email: 'ana@gigigo.com', + email_verified: true, + hd: 'gigigo.com', + nonce: 'nonce-1', + exp: Math.floor(NOW / 1000) + 300, + ...overrides, + }; +} + +function jwksFetch() { + return vi.fn( + async () => + new Response(JSON.stringify({ keys: [jwk] }), { + headers: { 'cache-control': 'public, max-age=3600' }, + }), + ); +} + +describe('GoogleOidcClient', () => { + describe('verifyIdToken', () => { + it('accepts a valid Google ID token', async () => { + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + const result = await client.verifyIdToken(sign(claims()), CLIENT_ID); + + expect(result).toMatchObject({ + sub: 'google-sub-1', + email: 'ana@gigigo.com', + email_verified: true, + hd: 'gigigo.com', + nonce: 'nonce-1', + }); + }); + + it('rejects a token signed with another key', async () => { + const other = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 }).privateKey; + const token = sign(claims()); + const [head, body] = token.split('.'); + const forged = crypto.sign('RSA-SHA256', Buffer.from(`${head}.${body}`), other); + + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + await expect( + client.verifyIdToken(`${head}.${body}.${forged.toString('base64url')}`, CLIENT_ID), + ).rejects.toThrow(/signature/); + }); + + it('rejects a tampered payload', async () => { + const [head, , signature] = sign(claims()).split('.'); + const body = Buffer.from(JSON.stringify(claims({ email: 'admin@gigigo.com' }))).toString( + 'base64url', + ); + + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + await expect(client.verifyIdToken(`${head}.${body}.${signature}`, CLIENT_ID)).rejects.toThrow( + /signature/, + ); + }); + + it('rejects a token issued for another client', async () => { + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + await expect( + client.verifyIdToken(sign(claims({ aud: 'someone-else' })), CLIENT_ID), + ).rejects.toThrow(/audience/); + }); + + it('rejects a token from another issuer', async () => { + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + await expect( + client.verifyIdToken(sign(claims({ iss: 'https://evil.example.com' })), CLIENT_ID), + ).rejects.toThrow(/issuer/); + }); + + it('rejects an expired token', async () => { + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + await expect( + client.verifyIdToken(sign(claims({ exp: Math.floor(NOW / 1000) - 120 })), CLIENT_ID), + ).rejects.toThrow(/expired/); + }); + + it('rejects non-RS256 tokens', async () => { + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + await expect( + client.verifyIdToken(sign(claims(), { alg: 'none' }), CLIENT_ID), + ).rejects.toThrow(/algorithm/); + }); + + it('caches the JWKS and refetches once for an unknown kid', async () => { + const fetchFn = jwksFetch(); + const client = new GoogleOidcClient(fetchFn, () => NOW); + + await client.verifyIdToken(sign(claims()), CLIENT_ID); + await client.verifyIdToken(sign(claims()), CLIENT_ID); + expect(fetchFn).toHaveBeenCalledTimes(1); + + await expect( + client.verifyIdToken(sign(claims(), { kid: 'rotated' }), CLIENT_ID), + ).rejects.toThrow(/signing key/); + expect(fetchFn).toHaveBeenCalledTimes(2); + }); + }); + + it('builds a PKCE authorization URL', () => { + const client = new GoogleOidcClient(jwksFetch(), () => NOW); + const url = new URL( + client.buildAuthorizationUrl({ + clientId: CLIENT_ID, + redirectUri: 'https://gitops.local/auth/sso/google/callback', + state: 'state-1', + nonce: 'nonce-1', + codeChallenge: 'challenge', + hostedDomain: 'gigigo.com', + }), + ); + + expect(url.origin).toBe('https://accounts.google.com'); + expect(url.searchParams.get('response_type')).toBe('code'); + expect(url.searchParams.get('scope')).toBe('openid email profile'); + expect(url.searchParams.get('code_challenge_method')).toBe('S256'); + expect(url.searchParams.get('hd')).toBe('gigigo.com'); + }); + + it('exchanges the code and verifies the returned ID token', async () => { + const idToken = sign(claims()); + const fetchFn = vi.fn(async (input: string, _init?: Parameters[1]) => + input.includes('/token') + ? new Response(JSON.stringify({ id_token: idToken })) + : new Response(JSON.stringify({ keys: [jwk] })), + ); + const client = new GoogleOidcClient(fetchFn, () => NOW); + + const result = await client.exchangeCode({ + clientId: CLIENT_ID, + clientSecret: 'secret', + code: 'code-1', + codeVerifier: 'verifier', + redirectUri: 'https://gitops.local/auth/sso/google/callback', + }); + + expect(result.sub).toBe('google-sub-1'); + const body = fetchFn.mock.calls[0]?.[1]?.body as URLSearchParams; + expect(body.get('code_verifier')).toBe('verifier'); + expect(body.get('grant_type')).toBe('authorization_code'); + }); + + it('surfaces a failed token exchange', async () => { + const client = new GoogleOidcClient( + vi.fn(async () => new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 })), + () => NOW, + ); + + await expect( + client.exchangeCode({ + clientId: CLIENT_ID, + clientSecret: 'secret', + code: 'bad', + codeVerifier: 'verifier', + redirectUri: 'https://gitops.local/cb', + }), + ).rejects.toThrow(/invalid_grant/); + }); +}); diff --git a/src/modules/auth/infrastructure/oidc/google-oidc.client.ts b/src/modules/auth/infrastructure/oidc/google-oidc.client.ts new file mode 100644 index 00000000..5349fe03 --- /dev/null +++ b/src/modules/auth/infrastructure/oidc/google-oidc.client.ts @@ -0,0 +1,164 @@ +import crypto from 'crypto'; + +const AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth'; +const TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token'; +const JWKS_URI = 'https://www.googleapis.com/oauth2/v3/certs'; +const ISSUERS = ['https://accounts.google.com', 'accounts.google.com']; +const CLOCK_SKEW_SECONDS = 60; +const DEFAULT_JWKS_TTL_MS = 60 * 60 * 1000; + +export type GoogleIdTokenClaims = { + sub: string; + email?: string; + email_verified?: boolean; + hd?: string; + name?: string; + nonce?: string; +}; + +export type GoogleAuthorizationRequest = { + clientId: string; + redirectUri: string; + state: string; + nonce: string; + codeChallenge: string; + hostedDomain?: string; +}; + +export type GoogleCodeExchange = { + clientId: string; + clientSecret: string; + code: string; + codeVerifier: string; + redirectUri: string; +}; + +type Jwk = crypto.webcrypto.JsonWebKey & { kid?: string }; +type FetchLike = (input: string, init?: Parameters[1]) => Promise; + +export class GoogleOidcError extends Error {} + +export class GoogleOidcClient { + private jwks: { keys: Jwk[]; expiresAt: number } | null = null; + + constructor( + private readonly fetchFn: FetchLike = (input, init) => fetch(input, init), + private readonly now: () => number = () => Date.now(), + ) {} + + buildAuthorizationUrl(request: GoogleAuthorizationRequest): string { + const url = new URL(AUTHORIZATION_ENDPOINT); + url.searchParams.set('client_id', request.clientId); + url.searchParams.set('redirect_uri', request.redirectUri); + url.searchParams.set('response_type', 'code'); + url.searchParams.set('scope', 'openid email profile'); + url.searchParams.set('state', request.state); + url.searchParams.set('nonce', request.nonce); + url.searchParams.set('code_challenge', request.codeChallenge); + url.searchParams.set('code_challenge_method', 'S256'); + url.searchParams.set('prompt', 'select_account'); + if (request.hostedDomain) url.searchParams.set('hd', request.hostedDomain); + return url.toString(); + } + + async exchangeCode(exchange: GoogleCodeExchange): Promise { + const response = await this.fetchFn(TOKEN_ENDPOINT, { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code: exchange.code, + code_verifier: exchange.codeVerifier, + client_id: exchange.clientId, + client_secret: exchange.clientSecret, + redirect_uri: exchange.redirectUri, + }), + }); + + const body = (await response.json().catch(() => ({}))) as { + id_token?: string; + error?: string; + }; + if (!response.ok || !body.id_token) { + throw new GoogleOidcError(`Google token exchange failed: ${body.error ?? response.status}`); + } + + return this.verifyIdToken(body.id_token, exchange.clientId); + } + + async verifyIdToken(idToken: string, clientId: string): Promise { + const parts = idToken.split('.'); + if (parts.length !== 3) throw new GoogleOidcError('Malformed ID token'); + const [encodedHeader, encodedPayload, encodedSignature] = parts; + + const header = this.decodeSegment(encodedHeader) as { alg?: string; kid?: string }; + if (header.alg !== 'RS256' || !header.kid) { + throw new GoogleOidcError('Unsupported ID token algorithm'); + } + + const jwk = await this.findKey(header.kid); + const validSignature = crypto.verify( + 'RSA-SHA256', + Buffer.from(`${encodedHeader}.${encodedPayload}`), + crypto.createPublicKey({ key: jwk, format: 'jwk' }), + Buffer.from(encodedSignature, 'base64url'), + ); + if (!validSignature) throw new GoogleOidcError('Invalid ID token signature'); + + const claims = this.decodeSegment(encodedPayload) as GoogleIdTokenClaims & { + iss?: string; + aud?: string | string[]; + exp?: number; + }; + const nowSeconds = Math.floor(this.now() / 1000); + const audiences = Array.isArray(claims.aud) ? claims.aud : [claims.aud]; + + if (!claims.iss || !ISSUERS.includes(claims.iss)) { + throw new GoogleOidcError('Unexpected ID token issuer'); + } + if (!audiences.includes(clientId)) throw new GoogleOidcError('ID token audience mismatch'); + if (typeof claims.exp !== 'number' || claims.exp + CLOCK_SKEW_SECONDS < nowSeconds) { + throw new GoogleOidcError('ID token expired'); + } + if (!claims.sub) throw new GoogleOidcError('ID token has no subject'); + + return { + sub: claims.sub, + email: claims.email, + email_verified: claims.email_verified === true || String(claims.email_verified) === 'true', + hd: claims.hd, + name: claims.name, + nonce: claims.nonce, + }; + } + + private async findKey(kid: string): Promise { + let key = (await this.loadJwks(false)).find((entry) => entry.kid === kid); + if (!key) key = (await this.loadJwks(true)).find((entry) => entry.kid === kid); + if (!key) throw new GoogleOidcError('Unknown ID token signing key'); + return key; + } + + private async loadJwks(force: boolean): Promise { + if (!force && this.jwks && this.jwks.expiresAt > this.now()) return this.jwks.keys; + + const response = await this.fetchFn(JWKS_URI); + if (!response.ok) throw new GoogleOidcError(`Failed to fetch Google JWKS: ${response.status}`); + const body = (await response.json()) as { keys?: Jwk[] }; + + const maxAge = /max-age=(\d+)/.exec(response.headers.get('cache-control') ?? '')?.[1]; + this.jwks = { + keys: Array.isArray(body.keys) ? body.keys : [], + expiresAt: this.now() + (maxAge ? Number(maxAge) * 1000 : DEFAULT_JWKS_TTL_MS), + }; + return this.jwks.keys; + } + + private decodeSegment(segment: string): unknown { + try { + return JSON.parse(Buffer.from(segment, 'base64url').toString('utf8')); + } catch { + throw new GoogleOidcError('Malformed ID token'); + } + } +} diff --git a/src/modules/auth/infrastructure/repositories/user.repository.ts b/src/modules/auth/infrastructure/repositories/user.repository.ts index 96ec7089..0e200661 100644 --- a/src/modules/auth/infrastructure/repositories/user.repository.ts +++ b/src/modules/auth/infrastructure/repositories/user.repository.ts @@ -1,8 +1,7 @@ import { Repository } from './repository'; import { ApiKeyEntity, UserEntity } from '#lib/database/schemas'; import type { CreateUserInput } from '../../domain/entities'; - -import { UserDomain } from '../../domain/user.domain'; +import { UserDomain, type UserAuthProvider } from '../../domain/user.domain'; export class UserRepository extends Repository { async findById(id: string): Promise { @@ -60,6 +59,11 @@ export class UserRepository extends Repository { return row ? this.toDomain(row) : null; } + async findByAuthProvider(provider: string, providerId: string): Promise { + const users = await this.listUsers(); + return users.find((user) => user.hasAuthProvider(provider, providerId)) ?? null; + } + async listUsers(): Promise { const result = await this.db .with({ role: true }) @@ -142,6 +146,32 @@ export class UserRepository extends Repository { .where({ id: userId }); } + async updateAuthProviders(userId: string, authProviders: UserAuthProvider[]): Promise { + await this.db + .update(UserEntity) + .set({ authProviders, updatedAt: new Date().toISOString() }) + .where({ id: userId }); + } + + async activateInvitedUser(userId: string): Promise { + await this.db + .update(UserEntity) + .set({ + status: 'active', + invitationTokenHash: null, + invitationExpiresAt: null, + updatedAt: new Date().toISOString(), + }) + .where({ id: userId }); + } + + async touchLastLogin(userId: string): Promise { + await this.db + .update(UserEntity) + .set({ lastLoginAt: new Date().toISOString() }) + .where({ id: userId }); + } + async setPasswordResetToken( userId: string, passwordResetTokenHash: string, @@ -189,6 +219,8 @@ export class UserRepository extends Repository { status: user.status, invitationExpiresAt: user.invitationExpiresAt ?? null, passwordResetExpiresAt: user.passwordResetExpiresAt ?? null, + authProviders: user.authProviders ?? [], + disabled: user.disabled ?? false, role: user.role, createdAt: user.createdAt, updatedAt: user.updatedAt, 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}