diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5965c71e..c21d274a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -31,6 +31,9 @@ jobs: - name: Check documentation contracts run: node --test scripts/documentation/contracts.test.mjs + - name: Check Docker image contracts + run: node --test scripts/deployment/docker-images.test.mjs + - name: Run ESLint run: npm run lint @@ -106,6 +109,54 @@ jobs: name: playwright-report path: playwright-report/ + ldap-acceptance: + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + postgres: ['15', '17'] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + - run: npm ci --ignore-scripts + - run: npm run install:approved + - name: Verify acceptance orchestration contracts + run: node --test scripts/acceptance/*.test.mjs + - name: Typecheck opt-in AD fixtures without directory access + run: ./node_modules/.bin/tsc --project test/fixtures/ldap/tsconfig.ad.json + working-directory: ./backend + - name: Install fixture scanner + run: | + sudo apt-get update + sudo apt-get install -y clamav + sudo systemctl stop clamav-freshclam || true + sudo freshclam + - name: Install dedicated browser + run: npx playwright install --with-deps chromium + - name: Prepare PostgreSQL image + run: docker pull postgres:${{ matrix.postgres }} + - name: Run live LDAP and recovery matrix plus dedicated browser contracts + run: >- + npm run test:ldap -- --focused --browser --build-fixture + --postgres-image postgres:${{ matrix.postgres }} --postgres-major ${{ matrix.postgres }} + --output-root '${{ runner.temp }}/ldap-evidence' + - name: Retain synthetic LDAP acceptance evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: ldap-acceptance-postgres-${{ matrix.postgres }} + retention-days: 14 + if-no-files-found: error + # Only the synthetic runner output, never container filesystems or AD evidence. + path: | + ${{ runner.temp }}/ldap-evidence/** + !${{ runner.temp }}/ldap-evidence/**/*.key + !${{ runner.temp }}/ldap-evidence/**/fixture-downloads/** + !${{ runner.temp }}/ldap-evidence/**/ca.pem + secret-scan: # The pre-commit hook excludes docs, tests and e2e fixtures. This job scans # them too, so a credential committed under an excluded path is still @@ -128,7 +179,7 @@ jobs: with: node-version-file: '.nvmrc' - name: Audit the reviewed lockfile - run: npm audit --json --audit-level=high > npm-audit.json + run: npm audit --json --audit-level=high --omit=dev > npm-audit.json - uses: actions/upload-artifact@v4 if: always() with: @@ -140,25 +191,41 @@ jobs: strategy: fail-fast: false matrix: - variant: [bookworm, alpine, ubuntu] + include: + - variant: bookworm-core + file: Dockerfile + target: core + profile: core + - variant: bookworm-batteries + file: Dockerfile + target: batteries + profile: batteries + - variant: alpine + file: Dockerfile.alpine + target: "" + profile: bolt + - variant: ubuntu + file: Dockerfile.ubuntu + target: "" + profile: bolt steps: - uses: actions/checkout@v4 - uses: docker/setup-buildx-action@v3 - name: Build and verify shipped image run: | - file=Dockerfile - if [ "${{ matrix.variant }}" != bookworm ]; then file="Dockerfile.${{ matrix.variant }}"; fi - docker build --no-cache -f "$file" -t pabawi:test . - bash scripts/supply-chain/image-smoke.sh pabawi:test + target=() + if [ -n "${{ matrix.target }}" ]; then target=(--target "${{ matrix.target }}"); fi + docker build --no-cache "${target[@]}" -f "${{ matrix.file }}" -t pabawi:test . + bash scripts/supply-chain/image-smoke.sh pabawi:test "${{ matrix.profile }}" mkdir -p artifacts docker run --rm -i --entrypoint node pabawi:test < scripts/supply-chain/dependency-graph.cjs > artifacts/dependencies.json - docker build --no-cache --target backend-deps -f "$file" -t pabawi:deps-repeat . + docker build --no-cache --target backend-deps -f "${{ matrix.file }}" -t pabawi:deps-repeat . docker run --rm -i --entrypoint node pabawi:deps-repeat < scripts/supply-chain/dependency-graph.cjs > artifacts/dependencies-repeat.json cmp artifacts/dependencies.json artifacts/dependencies-repeat.json if [ "${{ matrix.variant }}" = ubuntu ]; then docker run --rm --entrypoint ruby pabawi:test /opt/bolt/test-winrm-rubyzip.rb docker run --rm -i --entrypoint ruby pabawi:test < docker/bolt/dependency-graph.rb > artifacts/ruby-dependencies.json - docker build --no-cache --target bolt-builder -f "$file" -t pabawi:ruby-repeat . + docker build --no-cache --target bolt-builder -f "${{ matrix.file }}" -t pabawi:ruby-repeat . docker run --rm -i --entrypoint ruby pabawi:ruby-repeat < docker/bolt/dependency-graph.rb > artifacts/ruby-dependencies-repeat.json cmp artifacts/ruby-dependencies.json artifacts/ruby-dependencies-repeat.json fi diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index ba534ec3..c2456cef 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -8,6 +8,7 @@ on: env: REGISTRY: ghcr.io IMAGE_NAME: ${{ github.repository }} + DOCKERHUB_IMAGE: example42/pabawi concurrency: group: publish-${{ github.ref }} @@ -20,6 +21,7 @@ jobs: fail-fast: false matrix: arch: [amd64, arm64] + profile: [core, batteries] permissions: contents: read packages: write @@ -40,40 +42,55 @@ jobs: with: context: . platforms: linux/${{ matrix.arch }} + target: ${{ matrix.profile }} load: true push: false tags: pabawi:candidate labels: ${{ steps.meta.outputs.labels }} - cache-from: type=gha,scope=release-${{ matrix.arch }} - cache-to: type=gha,mode=max,scope=release-${{ matrix.arch }} + cache-from: type=gha,scope=release-${{ matrix.profile }}-${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=release-${{ matrix.profile }}-${{ matrix.arch }} - name: Verify release candidate env: DOCKER_DEFAULT_PLATFORM: linux/${{ matrix.arch }} run: | - bash scripts/supply-chain/image-smoke.sh pabawi:candidate + bash scripts/supply-chain/image-smoke.sh pabawi:candidate ${{ matrix.profile }} mkdir -p artifacts docker run --rm -i --entrypoint node pabawi:candidate < scripts/supply-chain/dependency-graph.cjs > artifacts/dependencies.json - name: Scan release candidate - continue-on-error: true - run: bash scripts/supply-chain/scan-image.sh pabawi:candidate artifacts + run: | + ignore_file=() + if [[ "${{ matrix.profile }}" = batteries ]]; then + ignore_file=(scripts/supply-chain/trivy-batteries-ignore.yaml) + fi + bash scripts/supply-chain/scan-image.sh pabawi:candidate artifacts "${ignore_file[@]}" - name: Retain release evidence if: always() uses: actions/upload-artifact@v4 with: - name: release-evidence-${{ matrix.arch }} + name: release-evidence-${{ matrix.profile }}-${{ matrix.arch }} path: artifacts/*.json - uses: docker/login-action@v3 with: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - - name: Push the verified image without rebuilding + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Push the verified image to both registries without rebuilding id: push run: | - tag="${REGISTRY}/${IMAGE_NAME}:${GITHUB_REF_NAME}-${{ matrix.arch }}" - docker tag pabawi:candidate "$tag" - docker push "$tag" - digest=$(docker inspect --format '{{index .RepoDigests 0}}' "$tag") + suffix="" + if [[ "${{ matrix.profile }}" = batteries ]]; then suffix="-batteries"; fi + architecture_tag="${GITHUB_REF_NAME}${suffix}-${{ matrix.arch }}" + ghcr_tag="${REGISTRY}/${IMAGE_NAME}:${architecture_tag}" + dockerhub_tag="${DOCKERHUB_IMAGE}:${architecture_tag}" + docker tag pabawi:candidate "$ghcr_tag" + docker tag pabawi:candidate "$dockerhub_tag" + docker push "$ghcr_tag" + docker push "$dockerhub_tag" + digest=$(docker inspect --format '{{index .RepoDigests 0}}' "$ghcr_tag") echo "digest=${digest#*@}" >> "$GITHUB_OUTPUT" - name: Attest the verified image uses: actions/attest-build-provenance@v1 @@ -94,16 +111,25 @@ jobs: registry: ${{ env.REGISTRY }} username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} + - uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Publish verified architecture images run: | version="${GITHUB_REF_NAME#v}" - image="${REGISTRY}/${IMAGE_NAME}" - tags=(--tag "$image:$version" --tag "$image:sha-${GITHUB_SHA:0:7}") - if [[ "$version" != *-* ]]; then - tags+=(--tag "$image:${version%.*}" --tag "$image:${version%%.*}" --tag "$image:latest") - fi - docker buildx imagetools create "${tags[@]}" \ - "$image:${GITHUB_REF_NAME}-amd64" "$image:${GITHUB_REF_NAME}-arm64" + for image in "${REGISTRY}/${IMAGE_NAME}" "${DOCKERHUB_IMAGE}"; do + core_tags=(--tag "$image:$version" --tag "$image:sha-${GITHUB_SHA:0:7}") + batteries_tags=(--tag "$image:batteries-$version" --tag "$image:batteries-sha-${GITHUB_SHA:0:7}") + if [[ "$version" != *-* ]]; then + core_tags+=(--tag "$image:${version%.*}" --tag "$image:${version%%.*}" --tag "$image:latest") + batteries_tags+=(--tag "$image:batteries-${version%.*}" --tag "$image:batteries-${version%%.*}" --tag "$image:batteries") + fi + docker buildx imagetools create "${core_tags[@]}" \ + "$image:${GITHUB_REF_NAME}-amd64" "$image:${GITHUB_REF_NAME}-arm64" + docker buildx imagetools create "${batteries_tags[@]}" \ + "$image:${GITHUB_REF_NAME}-batteries-amd64" "$image:${GITHUB_REF_NAME}-batteries-arm64" + done create-release: needs: publish-manifest diff --git a/.secrets.baseline b/.secrets.baseline index 6de3310d..779b1085 100644 --- a/.secrets.baseline +++ b/.secrets.baseline @@ -158,6 +158,34 @@ "line_number": 17 } ], + "backend/package.json": [ + { + "type": "Secret Keyword", + "filename": "backend/package.json", + "hashed_secret": "d87f5feaf9e84677eeaccc6fa56767b955f546ef", + "is_verified": false, + "line_number": 10, + "is_secret": false + } + ], + "backend/src/cli/resetUserPassword.ts": [ + { + "type": "Base64 High Entropy String", + "filename": "backend/src/cli/resetUserPassword.ts", + "hashed_secret": "e38670be8612f3c6214bacd1ae73e9ec294ea40e", + "is_verified": false, + "line_number": 32, + "is_secret": false + }, + { + "type": "Base64 High Entropy String", + "filename": "backend/src/cli/resetUserPassword.ts", + "hashed_secret": "4e18791fb60cef39a70028f2ae47ef19e1eccbfe", + "is_verified": false, + "line_number": 33, + "is_secret": false + } + ], "backend/test/UserService.password.test.ts": [ { "type": "Secret Keyword", @@ -1088,6 +1116,16 @@ "line_number": 40 } ], + "backend/test/unit/cli/resetUserPassword.test.ts": [ + { + "type": "Secret Keyword", + "filename": "backend/test/unit/cli/resetUserPassword.test.ts", + "hashed_secret": "1ded3053d0363079a4e681a3b700435d6d880290", + "is_verified": false, + "line_number": 89, + "is_secret": false + } + ], "backend/test/unit/error-handling.test.ts": [ { "type": "Secret Keyword", @@ -1464,5 +1502,5 @@ } ] }, - "generated_at": "2026-09-11T20:46:53Z" + "generated_at": "2026-10-21T18:39:35Z" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 3be0d68f..c5ccdd4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,38 @@ # Changelog +## [1.6.0] - 2026-10-22 + +### Added + +- `reset-password` CLI for account recovery: `npm run reset-password --workspace=backend -- --username admin` + (or `node dist/cli/reset-password.js` in built installs and containers). It + reads the password from a hidden prompt, stdin or `--generate`, applies the + password policy, clears lockouts, revokes all existing sessions and writes a + `cli_password_reset` audit entry. See + [troubleshooting](docs/troubleshooting.md#reset-a-local-users-password-account-recovery). + +### Container images + +- `example42/pabawi` and `ghcr.io/example42/pabawi` now publish a minimal core + image as the default tag family. The core image contains Pabawi but excludes + Bolt, Ansible, Puppet/OpenVox, OpenSSH and the other integration CLIs. +- A batteries image adds Bolt 5.6.0, Ansible 2.14.18, Puppet/OpenVox 8.29.0, + Facter 5.6.1, OpenSSH, Git, curl, rsync and sshpass. It is published under + `batteries`, `batteries-1`, `batteries-1.5`, `batteries-1.5.1` and immutable + commit tags. +- Release CI builds and smoke-tests both profiles for amd64 and arm64, then + publishes the verified images to Docker Hub and GHCR without rebuilding. + Compose, setup and convenience scripts select the batteries image where the + integration toolchain is expected. + +### Security + +- Core and batteries images retain SBOM and vulnerability evidence. Fixable + high or critical findings block publishing, except for a reviewed + batteries-only exception for `CVE-2026-85396` in `rubyzip` 2.4.1. OpenBolt's + current `winrm-fs` dependency prevents a compatible upgrade. The exception + is scoped to the exact gem path and package URL and expires on 2026-12-31. + ## [1.5.0] - 2026-09-14 ### Security: breaking for operators diff --git a/Dockerfile b/Dockerfile index 99d42992..6c86e1d5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -26,8 +26,9 @@ RUN npm ci --workspace=backend --omit=dev --ignore-scripts --no-audit --no-fund # Keep both hoisted and workspace-local packages in their locked locations. RUN mkdir -p backend/node_modules -# Stage 3: Install OpenBolt from OpenVox upstream packages -FROM node:24.21.0-bookworm-slim@sha256:2fe369e969550cde8e867afc3fe370b260140cab4a23d467074295b42163d553 AS bolt-builder +# Stage 3: Build the optional infrastructure toolchain. The default core +# target does not depend on this stage, so BuildKit skips it entirely. +FROM node:24.21.0-bookworm-slim@sha256:2fe369e969550cde8e867afc3fe370b260140cab4a23d467074295b42163d553 AS toolchain-builder # hadolint ignore=DL3008 RUN apt-get update && \ @@ -35,11 +36,13 @@ RUN apt-get update && \ ca-certificates \ curl \ && curl -fsSLO https://apt.voxpupuli.org/openvox8-release-debian12.deb \ - && echo "f10b71b2317c2a919ef1c00a2b5d2d00ac825632323f801601466a9200dc3122 openvox8-release-debian12.deb" | sha256sum -c - \ + && echo "6d1a663202a066a1f676c797ddfd116a141c8fa2f55bd0cd45a8ac8434a3ffeb openvox8-release-debian12.deb" | sha256sum -c - \ && dpkg -i openvox8-release-debian12.deb \ && rm openvox8-release-debian12.deb \ && apt-get update \ - && apt-get install -y --no-install-recommends openbolt=5.6.0-1+debian12 \ + && apt-get install -y --no-install-recommends \ + openbolt=5.6.0-1+debian12 \ + openvox-agent=8.29.0-1+debian12 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* @@ -58,34 +61,36 @@ RUN apt-get update && \ faraday:2.14.3 \ jwt:2.10.3 \ resolv:0.7.2 \ + && /opt/puppetlabs/puppet/bin/gem install --no-document resolv:0.7.2 \ && /opt/puppetlabs/bolt/bin/gem uninstall --force --ignore-dependencies \ concurrent-ruby:1.3.6 faraday:2.14.2 jwt:2.10.2 \ && rm -rf /opt/puppetlabs/bolt/lib/ruby/gems/3.2.0/specifications/default/resolv-0.2.3.gemspec \ /opt/puppetlabs/bolt/lib/ruby/gems/3.2.0/gems/resolv-0.2.3 \ + /opt/puppetlabs/puppet/lib/ruby/gems/3.2.0/specifications/default/resolv-0.2.3.gemspec \ + /opt/puppetlabs/puppet/lib/ruby/gems/3.2.0/gems/resolv-0.2.3 \ && apt-get purge -y make gcc libc6-dev && apt-get autoremove -y \ && rm -rf /var/lib/apt/lists/* -# Stage 4: Production image -FROM node:24.21.0-bookworm-slim@sha256:2fe369e969550cde8e867afc3fe370b260140cab4a23d467074295b42163d553 +# Stage 4: Core production image. This is the default published image and +# contains only Pabawi and the operating-system packages it needs to start. +FROM node:24.21.0-bookworm-slim@sha256:2fe369e969550cde8e867afc3fe370b260140cab4a23d467074295b42163d553 AS core ARG TARGETPLATFORM ARG BUILDPLATFORM # Add metadata labels -LABEL org.opencontainers.image.title="Pabawi" -LABEL org.opencontainers.image.description="Puppet Ansible Bolt Awesome Web Interface" -LABEL org.opencontainers.image.version="1.5.0" +LABEL org.opencontainers.image.title="Pabawi Core" +LABEL org.opencontainers.image.description="Pabawi infrastructure management web interface" +LABEL org.opencontainers.image.version="1.6.0" LABEL org.opencontainers.image.vendor="example42" LABEL org.opencontainers.image.source="https://github.com/example42/pabawi" -# Install only runtime dependencies +# Install only core runtime dependencies. Integration CLIs belong in the +# batteries target below. # hadolint ignore=DL3008 RUN apt-get update && \ apt-get install -y --no-install-recommends \ bash \ - openssh-client \ - git \ - coreutils \ - ansible \ + ca-certificates \ && apt-get install -y --only-upgrade libpcre2-8-0 \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* @@ -95,10 +100,6 @@ RUN apt-get update && \ # dependencies (e.g. brace-expansion, tar, ip-address) don't ship either. RUN rm -rf /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/corepack /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack -# Copy Bolt installation from upstream package builder stage -COPY --from=bolt-builder /opt/puppetlabs /opt/puppetlabs -RUN ln -s /opt/puppetlabs/bolt/bin/bolt /usr/local/bin/bolt - # Create non-root user RUN groupadd -g 1001 pabawi && \ useradd -u 1001 -g pabawi -m -s /bin/bash pabawi @@ -168,3 +169,34 @@ HEALTHCHECK --interval=30s --timeout=3s --start-period=30s --retries=3 \ # Start the application CMD ["node", "dist/server.js"] + +# Stage 5: Optional batteries-included image. It adds every local CLI invoked +# by an integration plus the Puppet/OpenVox operator toolchain. Cloud and API +# integrations use the Node SDKs already present in the core image. +FROM core AS batteries +USER root + +# hadolint ignore=DL3008 +RUN apt-get update && \ + apt-get install -y --no-install-recommends \ + ansible \ + curl \ + git \ + openssh-client \ + rsync \ + sshpass \ + && apt-get clean \ + && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* + +COPY --from=toolchain-builder /opt/puppetlabs /opt/puppetlabs +RUN ln -s /opt/puppetlabs/bolt/bin/bolt /usr/local/bin/bolt \ + && ln -s /opt/puppetlabs/puppet/bin/facter /usr/local/bin/facter \ + && ln -s /opt/puppetlabs/puppet/bin/puppet /usr/local/bin/puppet + +LABEL org.opencontainers.image.title="Pabawi Batteries Included" +LABEL org.opencontainers.image.description="Pabawi with Bolt, Ansible, Puppet/OpenVox, and SSH tooling" + +USER pabawi + +# Keep the default Dockerfile result backward-compatible with the core image. +FROM core AS final diff --git a/Dockerfile.alpine b/Dockerfile.alpine index f8302ae5..184767f7 100644 --- a/Dockerfile.alpine +++ b/Dockerfile.alpine @@ -45,7 +45,7 @@ ARG BUILDPLATFORM # Add metadata labels LABEL org.opencontainers.image.title="Pabawi" LABEL org.opencontainers.image.description="Puppet Ansible Bolt Awesome Web Interface" -LABEL org.opencontainers.image.version="1.5.0" +LABEL org.opencontainers.image.version="1.6.0" LABEL org.opencontainers.image.vendor="example42" LABEL org.opencontainers.image.source="https://github.com/example42/pabawi" diff --git a/Dockerfile.ubuntu b/Dockerfile.ubuntu index b4d3fb93..e0d494a4 100644 --- a/Dockerfile.ubuntu +++ b/Dockerfile.ubuntu @@ -54,7 +54,7 @@ ARG BUILDPLATFORM # Add metadata labels LABEL org.opencontainers.image.title="Pabawi" LABEL org.opencontainers.image.description="Puppet Ansible Bolt Awesome Web Interface" -LABEL org.opencontainers.image.version="1.5.0" +LABEL org.opencontainers.image.version="1.6.0" LABEL org.opencontainers.image.vendor="example42" LABEL org.opencontainers.image.source="https://github.com/example42/pabawi" diff --git a/README.md b/README.md index 2dd5e9e8..50d41f7c 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@

Classic Infrastructures Command & Control Awesomeness

-

Pabawi is a web UI for infrastructure management, inventory, and remote execution.
It integrates with Puppet, Bolt, Ansible, PuppetDB, Hiera, SSH, Proxmox, AWS, and Azure providing a single interface for executing commands, browsing inventory, viewing system facts, provisioning VMs, and tracking operations across your entire environment.
Icing on the cake, all the information you see on Pabawi is exposed with an embedded MCP server usable by your favouring AI agents.

+

A web UI for infrastructure management, inventory, and remote execution across Puppet, Bolt, Ansible, PuppetDB, Hiera, SSH, Checkmk, Proxmox, AWS, and Azure. One interface for running commands, browsing inventory and facts, provisioning VMs, and tracking operations. Everything it sees is also exposed through an embedded MCP server for AI agents.

@@ -17,86 +17,33 @@ [![Docker Image](https://img.shields.io/docker/v/example42/pabawi?label=docker&color=2496ed)](https://hub.docker.com/r/example42/pabawi) [![GitHub Stars](https://img.shields.io/github/stars/example42/pabawi?style=social)](https://github.com/example42/pabawi/stargazers) -## Sponsors +Sponsored by AMS-IX - - - -
Pabawi's main sponsor is AMS-IXAMS-IX
+## Who it's for -## Who is this for? - -- **Sysadmins and DevOps teams** using Puppet, Bolt, Ansible, or SSH to manage physical servers and VMs +- **Sysadmins and DevOps teams** managing physical servers and VMs with Puppet, Bolt, Ansible, or SSH - **Puppet Open Source users** who want a web UI without Puppet Enterprise -- **Mixed-tool environments** — if you use both Puppet and Ansible, Pabawi brings them together in one interface +- **Mixed-tool shops** running both Puppet and Ansible, who want one interface instead of two - **Homelabbers** who just want a web frontend for their servers (SSH-only works fine) If you manage "classic infrastructure" — bare metal, VMs, Kubernetes nodes — Pabawi is built for you. -## Table of Contents - -- [Sponsors](#sponsors) -- [Features](#features) -- [Screenshots](#screenshots) -- [Prerequisites](#prerequisites) -- [Installation](#installation) - - [Quick Start](#quick-start) - - [Manual Setup](#manual-setup) - - [Docker](#docker) -- [Upgrading](#upgrading) -- [Configuration](#configuration) -- [Project Structure](#project-structure) -- [Troubleshooting](#troubleshooting) -- [Development and Contributing](#development-and-contributing) -- [Roadmap](#roadmap) -- [License](#license) -- [Support](#support) -- [Acknowledgments](#acknowledgments) - -## Features - -- **Multi-Source Inventory** — nodes from Bolt, PuppetDB, Ansible, SSH, Proxmox, AWS, Azure, with inventory groups -- **Command Execution** — ad-hoc commands on remote nodes with whitelist security -- **Task Execution** — Bolt tasks with automatic parameter discovery -- **Package Management** — install and manage packages across infrastructure -- **Proxmox Provisioning** — VM and container management alongside config management -- **AWS EC2 Provisioning** — cloud instance lifecycle management -- **Azure VM Provisioning** — Azure VM inventory, provisioning, and lifecycle management (start/stop/restart/deallocate) -- **Execution History** — track operations with re-execution capability -- **RBAC Authentication** — role-based access control, multiple users, audit trail -- **MCP Server** — embedded Model Context Protocol server with read-only infrastructure tools for AI assistants -- **Node Facts** — system information from Puppet agents -- **Puppet Reports** — run reports with metrics and resource changes -- **Catalog Inspection** — compiled catalogs, resource relationships, cross-environment diff -- **Event Tracking** — resource changes and failures over time -- **Hiera Data Browser** — hierarchical configuration data and key usage analysis -- **Node Journal** — timeline of events, actions, and notes per node -- **Global Journal** — cross-node timeline with filtering by node, group, event type, source, and date range -- **Real-time Streaming** — live output for command and task execution -- **Expert Mode** — full command lines and debug output -- **Graceful Degradation** — continues operating when individual integrations are unavailable -- **Request Deduplication** — LRU-cached responses for identical API requests to reduce external calls -- **Input Sanitization** — automatic null byte removal, prototype pollution prevention, and deep nesting protection - -## Screenshots - -Pabawi Screenshots +## What it does -Check this [recording](https://asciinema.org/a/1073835) for a sample MCP session. +- **Inventory & facts** from every connected source, merged and deduplicated across integrations +- **Execution** — ad-hoc commands, Bolt tasks, package management, with a security whitelist, live streaming output, and history/re-run +- **Provisioning** — VM/container lifecycle on Proxmox, AWS EC2, and Azure +- **Puppet observability** — reports, catalog inspection with cross-environment diff, resource event tracking, Hiera data browsing +- **Tracking** — per-node and global journal, audit trail, RBAC with multiple users +- **AI-ready** — embedded MCP server exposing inventory, facts, reports, and catalogs read-only to LLM clients -## Prerequisites +See the [Screenshots](docs/screenshots/pabawi-screenshots.png), a sample [MCP session recording](https://asciinema.org/a/1073835), the [User Guide](docs/user-guide.md) for full feature walkthroughs, and [Architecture](docs/architecture.md) for how it's built. -- **Node.js 24 LTS** (see `.nvmrc`) and **npm 11** (or a container engine for Docker deployment) -- **Bolt CLI** — for Bolt integration ([setup](docs/integrations/bolt.md)) -- **Ansible CLI** — for Ansible integration ([setup](docs/integrations/ansible.md)) -- **Puppet/OpenVox agent** — for [PuppetDB](docs/integrations/puppetdb.md) and [Puppetserver](docs/integrations/puppetserver.md) integrations; provides SSL certs -- **Control repo** — for Hiera integration ([setup](docs/integrations/hiera.md)) +## Installing -All integrations are optional — enable only what you use. +Requires **Node.js 24 LTS** and **npm 11** (or a container engine for Docker). Integration CLIs (Bolt, Ansible, Puppet/OpenVox agent) are only needed for the integrations you enable — see [per-integration setup guides](#integrations). -## Installation - -### Quick Start +**Quick start** (interactive setup script — checks prerequisites, generates `backend/.env`, installs dependencies, starts the app): ```bash git clone https://github.com/example42/pabawi @@ -104,167 +51,61 @@ cd pabawi ./scripts/setup.sh ``` -The interactive setup script will: - -1. **Check prerequisites** — Node.js, npm, and optionally Bolt, Ansible, Puppet/OpenVox CLIs -2. **Generate `backend/.env`** — core settings and integrations with smart defaults based on detected tools and SSL certs -3. **Install dependencies** — `npm run install:all` (installs packages and rebuilds native modules with `--ignore-scripts=false`) -4. **Start the application** — development mode, full-stack build, or exit - -### Manual Setup - -First administrator enrollment requires an installation bootstrap token. -See [Initial setup](docs/initial-setup.md) before exposing a fresh installation. +**Manual setup:** ```bash git clone https://github.com/example42/pabawi cd pabawi - -# Install dependencies (rebuilds native modules like bcrypt, sqlite3) -npm run install:all - -# Create your configuration -cp backend/.env.example backend/.env -# Edit backend/.env with your settings - -# Start in development mode -npm run dev:backend # backend on port 3000 -npm run dev:frontend # frontend on port 5173 - -# Or build and serve everything from the backend -npm run dev:fullstack # port 3000 +npm run install:all # installs deps, rebuilds native modules +cp backend/.env.example backend/.env # then edit backend/.env +npm run dev:fullstack # build + serve everything on port 3000 ``` -### Docker +First admin enrollment requires a bootstrap token — see [Initial Setup](docs/initial-setup.md) before exposing a fresh install. + +**Docker (core image):** ```bash -# Create a working directory for persistent data, certs, and project files mkdir pabawi && cd pabawi - -# Create your configuration file (paths are relative to the container) -vi .env - -# Run the image, mounting the current directory -docker run -d \ - --name pabawi \ - --user "$(id -u):1001" \ +vi .env # paths are relative to the container +docker run -d --name pabawi --user "$(id -u):1001" \ -p 127.0.0.1:3000:3000 \ - -v "$(pwd)/pabawi:/pabawi" \ - --env-file ".env" \ + -v "$(pwd)/pabawi:/pabawi" --env-file ".env" \ example42/pabawi:latest ``` -The application starts at . - -For full Docker and Kubernetes deployment instructions, see the [Docker Deployment Guide](docs/deployment/docker.md) and [Kubernetes Guide](docs/deployment/kubernetes.md). - -## Upgrading - -For existing installations, the upgrade path depends on your deployment method: - -| Method | Command | -|---|---| -| Git / source | `git fetch --tags && git checkout v && npm run install:all && npm run build` | -| Docker | `docker pull example42/pabawi:latest` then recreate the container | -| Docker Compose | `docker compose pull && docker compose up -d` | -| Helm / Kubernetes | `helm upgrade pabawi ./charts/pabawi --set image.tag=` | - -Database migrations run automatically on startup. Always back up your database and review the [CHANGELOG](CHANGELOG.md) for breaking changes before upgrading. - -Full instructions: [Upgrade Guide](docs/upgrading.md). +The core image contains the Pabawi application only. Use +`example42/pabawi:batteries` when Bolt, Ansible, Puppet/OpenVox, or OpenSSH +commands must run inside the container. -## Configuration +Full instructions and Kubernetes/Helm deployment: [Docker Guide](docs/deployment/docker.md), [Kubernetes Guide](docs/deployment/kubernetes.md). -All configuration is in `backend/.env`. The setup script generates this file, or use `backend/.env.example` as a template. +**Upgrading:** `git fetch --tags && git checkout v && npm run install:all && npm run build` (or `docker pull`/`helm upgrade` — see the [Upgrade Guide](docs/upgrading.md)). Migrations run automatically; back up your database first and check the [CHANGELOG](CHANGELOG.md). -The web UI also includes per-integration setup wizards that generate `.env` snippets you can paste into your configuration file. +## Configuring -Key configuration areas: +Everything lives in `backend/.env` — generated by the setup script, templated at `backend/.env.example`, or assembled piece by piece from the in-app per-integration setup wizards. All integrations are optional; enable only what you use. | Area | Variables | |---|---| | Core | `PORT`, `HOST`, `LOG_LEVEL` | | Auth | `JWT_SECRET`, `PABAWI_BOOTSTRAP_TOKEN` | -| Bolt | `BOLT_*` | -| PuppetDB / Puppetserver | `PUPPETDB_*`, `PUPPETSERVER_*` | -| Hiera | `HIERA_*` | -| Ansible | `ANSIBLE_*` | -| SSH | `SSH_*` | -| Proxmox | `PROXMOX_*` | -| AWS | `AWS_*` | -| Azure | `AZURE_*` | +| Integrations | `BOLT_*`, `PUPPETDB_*`, `PUPPETSERVER_*`, `HIERA_*`, `ANSIBLE_*`, `SSH_*`, `CHECKMK_*`, `PROXMOX_*`, `AWS_*`, `AZURE_*` | | Security | `COMMAND_WHITELIST*`, `CONCURRENT_EXECUTION_LIMIT` | | MCP | `MCP_ENABLED` | -Full reference: [Configuration Guide](docs/configuration.md). - -## Project Structure - -```text -pabawi/ -├── frontend/ # Svelte 5 + Vite SPA -│ └── src/ -│ ├── components/ # UI components -│ ├── pages/ # Page components -│ └── lib/ # Utilities and rune-based state -├── backend/ # Node.js + Express + TypeScript -│ └── src/ -│ ├── container/ # DI container (ServiceRegistry) -│ ├── plugins/ # Declarative plugin registry -│ ├── integrations/ # Plugin system (Bolt, PuppetDB, SSH, ...) -│ ├── services/ # ExecutionQueue, RBAC, streaming, auth -│ ├── mcp/ # Embedded MCP server and tool handlers -│ ├── routes/ # Express route factories -│ ├── middleware/ # JWT, RBAC, rate limiting, security headers -│ ├── database/ # SQLite / PostgreSQL adapters + migrations -│ ├── errors/ # Typed error classes -│ └── validation/ # Zod request schemas -├── docs/ # Documentation -│ ├── integrations/ # Per-integration setup guides -│ └── deployment/ # Docker and Kubernetes guides -├── e2e/ # Playwright E2E tests -└── package.json # Root workspace configuration -``` - -See [Architecture](docs/architecture.md) for a detailed description of the plugin system and data flows. - -## Troubleshooting - -See the [Troubleshooting Guide](docs/troubleshooting.md) for common issues with installation, configuration, and integrations. - -## Development and Contributing - -See the [Development Guide](docs/development.md) for setup, testing, and contribution guidelines. - - -### Version History - -See [CHANGELOG](CHANGELOG.md). - - -## License - -Apache License 2.0 — see [LICENSE](LICENSE). - -## Support - -**Documentation** - -- [Architecture](docs/architecture.md) | [Configuration](docs/configuration.md) | [User Guide](docs/user-guide.md) | [API Reference](docs/api.md) -- [Permissions & RBAC](docs/permissions-rbac.md) | [MCP Server](docs/mcp.md) | [Upgrading](docs/upgrading.md) | [Troubleshooting](docs/troubleshooting.md) | [Development](docs/development.md) - -**Integrations** - -- [Bolt](docs/integrations/bolt.md) | [Ansible](docs/integrations/ansible.md) | [SSH](docs/integrations/ssh.md) -- [PuppetDB](docs/integrations/puppetdb.md) | [Puppetserver](docs/integrations/puppetserver.md) | [Hiera](docs/integrations/hiera.md) -- [Proxmox](docs/integrations/proxmox.md) | [AWS](docs/integrations/aws.md) | [Azure](docs/integrations/azure.md) - -**Deployment** +Full reference: [Configuration Guide](docs/configuration.md). Architecture and code layout: [Architecture](docs/architecture.md). -- [Docker](docs/deployment/docker.md) | [Kubernetes](docs/deployment/kubernetes.md) +### Integrations -For help: enable expert mode for diagnostics, or [open a GitHub issue](https://github.com/example42/pabawi/issues) with version info, sanitized config, reproduction steps, and error messages. +[Bolt](docs/integrations/bolt.md) · [Ansible](docs/integrations/ansible.md) · [SSH](docs/integrations/ssh.md) · [PuppetDB](docs/integrations/puppetdb.md) · [Puppetserver](docs/integrations/puppetserver.md) · [Hiera](docs/integrations/hiera.md) · [Checkmk](docs/integrations/checkmk.md) · [Proxmox](docs/integrations/proxmox.md) · [AWS](docs/integrations/aws.md) · [Azure](docs/integrations/azure.md) · [Entra ID SSO](docs/integrations/entra-id.md) -## Acknowledgments +## The usuals -Pabawi builds on: [Puppet/OpenVox](https://puppet.com), [Bolt](https://puppet.com/docs/bolt), [PuppetDB](https://puppet.com/docs/puppetdb), [Svelte 5](https://svelte.dev), [Node.js](https://nodejs.org), [TypeScript](https://www.typescriptlang.org), [SQLite](https://sqlite.org), [PostgreSQL](https://www.postgresql.org). Thanks to all contributors and the Puppet community. +- **Documentation:** [User Guide](docs/user-guide.md) · [Architecture](docs/architecture.md) · [API Reference](docs/api.md) · [Permissions & RBAC](docs/permissions-rbac.md) · [MCP Server](docs/mcp.md) +- **Locked out?** Reset a local password from the shell: `npm run reset-password --workspace=backend -- --username admin` ([details](docs/troubleshooting.md#reset-a-local-users-password-account-recovery)) +- **Troubleshooting:** [Troubleshooting Guide](docs/troubleshooting.md) — for help beyond that, enable expert mode for diagnostics and [open a GitHub issue](https://github.com/example42/pabawi/issues) with version info, sanitized config, and reproduction steps +- **Development & contributing:** [Development Guide](docs/development.md) +- **Version history:** [CHANGELOG](CHANGELOG.md) +- **License:** [Apache License 2.0](LICENSE) +- **Built on:** [Puppet/OpenVox](https://puppet.com), [Bolt](https://puppet.com/docs/bolt), [PuppetDB](https://puppet.com/docs/puppetdb), [Svelte 5](https://svelte.dev), [Node.js](https://nodejs.org), [TypeScript](https://www.typescriptlang.org), [SQLite](https://sqlite.org), [PostgreSQL](https://www.postgresql.org), and the Puppet community diff --git a/backend/.env.example b/backend/.env.example index 09af833d..6427cf3b 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -310,3 +310,47 @@ AZURE_ENABLED=false # CONSOLE_MAX_CONCURRENT_SESSIONS=3 # CONSOLE_HEARTBEAT_INTERVAL_MS=30000 # CONSOLE_VERIFY_UPSTREAM_TLS=true + +# LDAP authentication and read-only directory service. Access requires explicit role grants. +# Operator guide: docs/integrations/ldap.md. Preserve emergency local administrator access. +# Enabling requires complete configuration; directory settings change only after restart. +LDAP_ENABLED=false +# LDAP_DIRECTORY_ID=corporate-directory +# LDAP_DIRECTORY_TYPE=openldap +# LDAP_DISPLAY_NAME=LDAP +# LDAP_LOGIN_HELP_URL= +# LDAP_HOSTNAME=ldap.example.com +# LDAP_PORT=636 +# LDAP_FAILOVER_ENDPOINTS=[] +# LDAP_TLS_MODE=ldaps +# LDAP_CA_FILE= +# LDAP_ALLOW_WILDCARD_CERTIFICATES=false +# LDAP_LOOKUP_USER=cn=pabawi-reader,ou=services,dc=example,dc=com +# LDAP_LOOKUP_PASSWORD= +# LDAP_ANONYMOUS_LOOKUP=false +# LDAP_CONNECT_TIMEOUT_SECONDS=10 +# LDAP_OPERATION_TIMEOUT_SECONDS=10 +# LDAP_REQUEST_TIMEOUT_SECONDS=30 +# LDAP_BASE_DN=dc=example,dc=com +# LDAP_USER_RDN=ou=people +# LDAP_USER_OBJECT_CLASS=inetOrgPerson +# LDAP_USER_LOOKUP_ATTR=uid +# LDAP_USER_ID_ATTR=entryUUID +# LDAP_USER_EMAIL_ATTR=mail +# LDAP_USER_DISPLAY_NAME_ATTR=displayName +# LDAP_USER_GIVEN_NAME_ATTR=givenName +# LDAP_USER_SURNAME_ATTR=sn +# LDAP_USER_ELIGIBILITY_FILTER=(employeeType=active) +# LDAP_GROUP_RDN=ou=groups +# LDAP_GROUP_OBJECT_CLASS=groupOfUniqueNames +# LDAP_GROUP_MEMBER_ATTR=uniqueMember +# LDAP_GROUP_ID_ATTR=entryUUID +# LDAP_GROUP_NAME_ATTR=displayName +# LDAP_GROUP_LOOKUP_ATTR=cn +# LDAP_SEARCH_NESTED_GROUPS=false +# LDAP_DISABLE_MATCHING_RULE_IN_CHAIN=false +# LDAP_NESTED_GROUP_MAX_DEPTH=10 +# LDAP_GROUP_SEARCH_LIMIT=100 +# LDAP_GROUP_TRAVERSAL_LIMIT=1000 +# LDAP_REVALIDATION_INTERVAL_SECONDS=300 +# LDAP_MAX_CONCURRENT_OPERATIONS=10 diff --git a/backend/package.json b/backend/package.json index 4d74cd52..76855546 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,12 +1,13 @@ { "name": "backend", - "version": "1.5.0", + "version": "1.6.0", "description": "Backend API server for Pabawi", "main": "dist/server.js", "scripts": { "dev": "tsx watch src/server.ts", "build": "node ../scripts/compilation/backend.mjs", "start": "node dist/server.js", + "reset-password": "tsx src/cli/reset-password.ts", "test": "vitest --run --passWithNoTests", "test:watch": "vitest", "lint": "eslint src --ext .ts --max-warnings 0", @@ -27,6 +28,7 @@ "express-rate-limit": "^8.2.1", "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", + "ldapts": "9.2.0", "pg": "^8.13.0", "sqlite3": "^6.0.1", "ssh2": "^1.17.0", diff --git a/backend/src/cli/reset-password.ts b/backend/src/cli/reset-password.ts new file mode 100644 index 00000000..248bfe58 --- /dev/null +++ b/backend/src/cli/reset-password.ts @@ -0,0 +1,163 @@ +/** + * Reset a local user's password from the command line (account recovery). + * + * Usage (from the backend directory, with the same environment as the server): + * npm run reset-password -- [--username admin] [--generate | --password-stdin] [--activate] + * node dist/cli/reset-password.js ... (built / Docker image) + * + * The password is never accepted as an argument: it is read from a hidden + * prompt, from stdin (--password-stdin), or generated (--generate). + * Run it on the host that owns the database; shell access is the trust boundary. + */ +import { userInfo } from 'os'; +import { ConfigService } from '../config/ConfigService'; +import { DatabaseService } from '../database/DatabaseService'; +import { AuditLoggingService } from '../services/AuditLoggingService'; +import { AuthenticationService } from '../services/AuthenticationService'; +import { UserService } from '../services/UserService'; +import { generatePassword, resetUserPassword } from './resetUserPassword'; + +interface CliArgs { + username: string; + generate: boolean; + passwordStdin: boolean; + activate: boolean; + help: boolean; +} + +const USAGE = `Usage: reset-password [options] + + --username Account to reset (default: admin) + --generate Generate a random password and print it once + --password-stdin Read the new password from stdin (one line) + --activate Also reactivate the account if it is disabled + -h, --help Show this help + +Without --generate or --password-stdin the password is prompted for twice.`; + +export function parseArgs(argv: string[]): CliArgs { + const args: CliArgs = { + username: 'admin', generate: false, passwordStdin: false, activate: false, help: false, + }; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]; + switch (arg) { + case '--username': { + const value = argv[++i]; + if (!value || value.startsWith('--')) throw new Error('--username requires a value'); + args.username = value; + break; + } + case '--generate': args.generate = true; break; + case '--password-stdin': args.passwordStdin = true; break; + case '--activate': args.activate = true; break; + case '-h': + case '--help': args.help = true; break; + default: throw new Error(`Unknown argument: ${arg}`); + } + } + if (args.generate && args.passwordStdin) { + throw new Error('--generate and --password-stdin are mutually exclusive'); + } + return args; +} + +async function readStdinLine(): Promise { + const chunks: Buffer[] = []; + for await (const chunk of process.stdin) chunks.push(chunk as Buffer); + return Buffer.concat(chunks).toString('utf8').split(/\r?\n/)[0]; +} + +/** Prompt without echoing input. Requires an interactive TTY. */ +function promptHidden(label: string): Promise { + return new Promise((resolve, reject) => { + const stdin = process.stdin; + if (!stdin.isTTY) { + reject(new Error('No TTY available: use --password-stdin or --generate')); + return; + } + process.stderr.write(label); + let value = ''; + stdin.setRawMode(true); + stdin.resume(); + stdin.setEncoding('utf8'); + const onData = (key: string): void => { + for (const ch of key) { + if (ch === '\u0003') { // Ctrl-C + cleanup(); + reject(new Error('Aborted')); + return; + } + if (ch === '\r' || ch === '\n' || ch === '\u0004') { + cleanup(); + process.stderr.write('\n'); + resolve(value); + return; + } + if (ch === '\u007f' || ch === '\b') value = value.slice(0, -1); + else value += ch; + } + }; + const cleanup = (): void => { + stdin.setRawMode(false); + stdin.pause(); + stdin.removeListener('data', onData); + }; + stdin.on('data', onData); + }); +} + +async function obtainPassword(args: CliArgs): Promise<{ password: string; generated: boolean }> { + if (args.generate) return { password: generatePassword(), generated: true }; + if (args.passwordStdin) return { password: await readStdinLine(), generated: false }; + const first = await promptHidden('New password: '); + const second = await promptHidden('Repeat password: '); + if (first !== second) throw new Error('Passwords do not match'); + return { password: first, generated: false }; +} + +async function main(): Promise { + const args = parseArgs(process.argv.slice(2)); + if (args.help) { + process.stdout.write(`${USAGE}\n`); + return; + } + + const { password, generated } = await obtainPassword(args); + + const configService = new ConfigService(); + const config = configService.getConfig(); + + const databaseService = new DatabaseService(config.databasePath, config.dbType, config.databaseUrl); + await databaseService.initialize(); + try { + const db = databaseService.getAdapter(); + const auditLogger = new AuditLoggingService(db); + const authService = new AuthenticationService(db, configService.getJwtSecret(), auditLogger); + const userService = new UserService(db, authService); + + const result = await resetUserPassword( + { db, userService, authService, auditLogger }, + { username: args.username, password, activate: args.activate, invokedBy: userInfo().username }, + ); + + process.stdout.write(`Password reset for "${result.username}". All existing sessions were revoked.\n`); + if (result.reactivated) process.stdout.write('Account was reactivated.\n'); + if (result.federationOnly) { + process.stdout.write('Note: this account had no local password (SSO only); local login is now enabled.\n'); + } + if (generated) process.stdout.write(`Generated password (shown once): ${password}\n`); + } finally { + await databaseService.close(); + } +} + +if (require.main === module) { + main().then( + () => process.exit(0), + (error: unknown) => { + process.stderr.write(`Error: ${error instanceof Error ? error.message : String(error)}\n`); + process.exit(1); + }, + ); +} diff --git a/backend/src/cli/resetUserPassword.ts b/backend/src/cli/resetUserPassword.ts new file mode 100644 index 00000000..45f32047 --- /dev/null +++ b/backend/src/cli/resetUserPassword.ts @@ -0,0 +1,104 @@ +import { randomInt } from 'crypto'; +import type { DatabaseAdapter } from '../database/DatabaseAdapter'; +import type { AuthenticationService } from '../services/AuthenticationService'; +import type { AuditLoggingService } from '../services/AuditLoggingService'; +import type { UserService } from '../services/UserService'; +import { validatePassword } from '../utils/passwordValidation'; + +export interface ResetPasswordDeps { + db: DatabaseAdapter; + userService: UserService; + authService: AuthenticationService; + auditLogger: AuditLoggingService; +} + +export interface ResetPasswordOptions { + username: string; + password: string; + /** Reactivate the account if it is disabled. Off by default. */ + activate?: boolean; + /** OS account that ran the CLI, recorded in the audit log. */ + invokedBy?: string; +} + +export interface ResetPasswordResult { + userId: string; + username: string; + reactivated: boolean; + federationOnly: boolean; +} + +const GENERATED_LENGTH = 20; +const UPPER = 'ABCDEFGHJKLMNPQRSTUVWXYZ'; +const LOWER = 'abcdefghijkmnopqrstuvwxyz'; +const DIGITS = '23456789'; +const SPECIAL = '!@#$%^&*()-_=+'; + +/** + * Generate a random password that satisfies validatePassword(). + * Uses crypto.randomInt, so the output is uniformly random per character. + */ +export function generatePassword(): string { + const all = UPPER + LOWER + DIGITS + SPECIAL; + const pick = (set: string): string => set[randomInt(set.length)]; + const chars = [pick(UPPER), pick(LOWER), pick(DIGITS), pick(SPECIAL)]; + while (chars.length < GENERATED_LENGTH) chars.push(pick(all)); + // Fisher-Yates shuffle so the guaranteed characters are not positional + for (let i = chars.length - 1; i > 0; i--) { + const j = randomInt(i + 1); + [chars[i], chars[j]] = [chars[j], chars[i]]; + } + return chars.join(''); +} + +/** + * Reset a local user's password out of band (CLI recovery path). + * + * Validates the password before touching anything, then: sets the new hash, + * clears lockouts and failed-login counters, rotates the session version so + * every issued access/refresh token stops working, and writes an audit entry. + * The password itself is never logged or audited. + * + * @throws Error if the user does not exist or the password is not acceptable + */ +export async function resetUserPassword( + deps: ResetPasswordDeps, + options: ResetPasswordOptions, +): Promise { + const { db, userService, authService, auditLogger } = deps; + + const user = await userService.getUserByUsername(options.username); + if (!user) { + throw new Error(`User not found: ${options.username}`); + } + + const validation = validatePassword(options.password); + if (!validation.valid) { + throw new Error(`Password validation failed: ${validation.errors.join(', ')}`); + } + + const reactivate = options.activate === true && user.isActive !== 1; + const federationOnly = !user.passwordHash; + + await userService.updateUser(user.id, { + password: options.password, + ...(reactivate ? { isActive: true } : {}), + }); + + // Unlock first, then clear the cumulative counters the unlock does not touch + await authService.unlockAccount(user.username); + await db.execute('DELETE FROM login_attempt_counters WHERE username = ?', [user.username]); + + // updateUser does not rotate the session version; do it explicitly + await authService.revokeAllUserTokens(user.id); + + await auditLogger.logAdminAction('cli_password_reset', user.id, { + source: 'cli', + username: user.username, + invokedBy: options.invokedBy ?? 'unknown', + reactivated: reactivate, + federationOnly, + }); + + return { userId: user.id, username: user.username, reactivated: reactivate, federationOnly }; +} diff --git a/backend/src/config/ConfigService.ts b/backend/src/config/ConfigService.ts index 583901cb..3100465f 100644 --- a/backend/src/config/ConfigService.ts +++ b/backend/src/config/ConfigService.ts @@ -1,3 +1,4 @@ +import { parseLdapConfig } from "./ldap"; import { config as loadDotenv } from "dotenv"; import { AppConfigSchema, @@ -917,6 +918,7 @@ export class ConfigService { mcpEnabled: process.env.MCP_ENABLED === "true", mcpAuthToken: process.env.MCP_AUTH_TOKEN ?? undefined, entraId: this.parseEntraIdConfig() ?? undefined, + ldap: parseLdapConfig(process.env), console: this.consoleConfig, }; @@ -1172,6 +1174,10 @@ export class ConfigService { return null; } + public getLdapConfig(): AppConfig["ldap"] | null { + return this.config.ldap ?? null; + } + /** * Get Entra ID authentication configuration if enabled. * Returns null when ENTRA_ID_ENABLED is not "true". diff --git a/backend/src/config/ldap.ts b/backend/src/config/ldap.ts new file mode 100644 index 00000000..a299085c --- /dev/null +++ b/backend/src/config/ldap.ts @@ -0,0 +1,137 @@ +import { readFileSync } from 'node:fs'; +import { isIP } from 'node:net'; +import { X509Certificate } from 'node:crypto'; +import { parseLdapDn } from './ldapDn'; +import { parseLdapFilter } from './ldapFilter'; +import { z } from 'zod'; + +const attribute = z.string().regex(/^(?:[a-zA-Z][a-zA-Z0-9-]*|[0-9]+(?:\.[0-9]+)+)$/); +const hostname = z.string().max(253).refine(value => + !isIP(value) && value.includes('.') && + value.split('.').every(label => /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(label)), +'Must be an FQDN without protocol, credentials or path'); +const dn = z.string().max(8192).refine(value => { + try { return parseLdapDn(value).length > 0; } catch { return false; } +}, 'Must be a nonempty LDAP DN'); +const relativeDn = z.union([z.literal(''), dn]); +const filter = z.string().max(8192).refine(value => { + if (!value) return true; + try { return !!parseLdapFilter(value); } + catch { return false; } +}, 'Must be a complete LDAP filter'); +const positive = (max: number): z.ZodNumber => z.number().int().min(1).max(max); + +export const LdapConfigSchema = z.object({ + enabled: z.literal(true), + directoryId: z.string().min(1).max(128).regex(/^[a-zA-Z0-9_-]+$/), + directoryType: z.enum(['ad', 'openldap']), + displayName: z.string().min(1).max(200).default('LDAP'), + loginHelpUrl: z.union([z.literal(''), z.string().url().refine(value => { + const url = new URL(value); + return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; + }, 'Must be an HTTP(S) link without credentials')]).default(''), + hostname, + port: positive(65535), + failoverEndpoints: z.array(z.object({ hostname, port: positive(65535) }).strict()).max(4).default([]), + tlsMode: z.enum(['ldaps', 'starttls']).default('ldaps'), + caFile: z.string().default('').refine(value => { + if (!value) return true; + try { + const pem = readFileSync(value, 'utf8'); + const certificates = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----/g); + return !!certificates?.length && certificates.every(cert => !!new X509Certificate(cert)); + } catch { return false; } + }, 'Must be a readable PEM CA bundle'), + allowWildcardCertificates: z.boolean().default(false), + lookupUser: z.union([z.literal(''), dn]).default(''), + lookupPassword: z.string().default(''), + anonymousLookup: z.boolean().default(false), + connectTimeoutSeconds: positive(30).default(10), + operationTimeoutSeconds: positive(30).default(10), + requestTimeoutSeconds: positive(60).default(30), + baseDn: dn, + userRdn: relativeDn.default(''), + userObjectClass: attribute, + userLookupAttr: attribute, + userIdAttr: attribute, + userEmailAttr: attribute.default('mail'), + userDisplayNameAttr: attribute.default('displayName'), + userGivenNameAttr: attribute.default('givenName'), + userSurnameAttr: attribute.default('sn'), + userEligibilityFilter: filter.default(''), + groupRdn: relativeDn.default(''), + groupObjectClass: attribute, + groupMemberAttr: attribute, + groupIdAttr: attribute, + groupNameAttr: attribute, + groupLookupAttr: attribute.default('cn'), + searchNestedGroups: z.boolean().default(false), + disableMatchingRuleInChain: z.boolean().default(false), + nestedGroupMaxDepth: positive(32).default(10), + groupSearchLimit: positive(500).default(100), + groupTraversalLimit: positive(10000).default(1000), + revalidationIntervalSeconds: positive(300).default(300), + maxConcurrentOperations: positive(100).default(10), +}).superRefine((config, context) => { + if (config.anonymousLookup ? !!(config.lookupUser || config.lookupPassword) : !(config.lookupUser && config.lookupPassword)) { + context.addIssue({ code: z.ZodIssueCode.custom, path: ['lookupUser'], + message: 'Anonymous lookup requires absent credentials; authenticated lookup requires DN and nonempty password' }); + } + if (config.directoryType === 'openldap' && !config.userEligibilityFilter) { + context.addIssue({ code: z.ZodIssueCode.custom, path: ['userEligibilityFilter'], + message: 'OpenLDAP requires an explicit positive eligibility filter' }); + } + if (config.groupMemberAttr.toLowerCase() === 'memberuid') { + context.addIssue({ code: z.ZodIssueCode.custom, path: ['groupMemberAttr'], message: 'Only DN-valued membership is supported' }); + } +}); +export type LdapConfig = z.infer; + +export function parseLdapConfig(env: NodeJS.ProcessEnv): LdapConfig | undefined { + const bool = (name: string, value: string | undefined): boolean => { + if (value === undefined || value === 'false') return false; + if (value === 'true') return true; + throw new Error(name + ' must be true or false'); + }; + if (!bool('LDAP_ENABLED', env.LDAP_ENABLED)) return undefined; + const integer = (value: string | undefined): number | undefined => + value === undefined ? undefined : /^\d+$/.test(value) ? Number(value) : NaN; + const ad = env.LDAP_DIRECTORY_TYPE === 'ad'; + let endpoints: unknown = []; + if (env.LDAP_FAILOVER_ENDPOINTS !== undefined) { + try { endpoints = JSON.parse(env.LDAP_FAILOVER_ENDPOINTS) as unknown; } + catch { throw new Error('LDAP_FAILOVER_ENDPOINTS must be a JSON array'); } + } + return LdapConfigSchema.parse({ + enabled: true, directoryId: env.LDAP_DIRECTORY_ID, directoryType: env.LDAP_DIRECTORY_TYPE, + displayName: env.LDAP_DISPLAY_NAME, loginHelpUrl: env.LDAP_LOGIN_HELP_URL, + hostname: env.LDAP_HOSTNAME, + port: env.LDAP_PORT === undefined ? (env.LDAP_TLS_MODE === 'starttls' ? 389 : 636) : integer(env.LDAP_PORT), + failoverEndpoints: endpoints, tlsMode: env.LDAP_TLS_MODE, caFile: env.LDAP_CA_FILE, + allowWildcardCertificates: bool('LDAP_ALLOW_WILDCARD_CERTIFICATES', env.LDAP_ALLOW_WILDCARD_CERTIFICATES), + lookupUser: env.LDAP_LOOKUP_USER, lookupPassword: env.LDAP_LOOKUP_PASSWORD, + anonymousLookup: bool('LDAP_ANONYMOUS_LOOKUP', env.LDAP_ANONYMOUS_LOOKUP), + connectTimeoutSeconds: integer(env.LDAP_CONNECT_TIMEOUT_SECONDS), + operationTimeoutSeconds: integer(env.LDAP_OPERATION_TIMEOUT_SECONDS), + requestTimeoutSeconds: integer(env.LDAP_REQUEST_TIMEOUT_SECONDS), + baseDn: env.LDAP_BASE_DN, userRdn: env.LDAP_USER_RDN, + userObjectClass: env.LDAP_USER_OBJECT_CLASS ?? (ad ? 'user' : 'inetOrgPerson'), + userLookupAttr: env.LDAP_USER_LOOKUP_ATTR ?? (ad ? 'sAMAccountName' : 'uid'), + userIdAttr: env.LDAP_USER_ID_ATTR ?? (ad ? 'objectGUID' : 'entryUUID'), + userEmailAttr: env.LDAP_USER_EMAIL_ATTR, userDisplayNameAttr: env.LDAP_USER_DISPLAY_NAME_ATTR, + userGivenNameAttr: env.LDAP_USER_GIVEN_NAME_ATTR, userSurnameAttr: env.LDAP_USER_SURNAME_ATTR, + userEligibilityFilter: env.LDAP_USER_ELIGIBILITY_FILTER, groupRdn: env.LDAP_GROUP_RDN, + groupObjectClass: env.LDAP_GROUP_OBJECT_CLASS ?? (ad ? 'group' : 'groupOfUniqueNames'), + groupMemberAttr: env.LDAP_GROUP_MEMBER_ATTR ?? (ad ? 'member' : 'uniqueMember'), + groupIdAttr: env.LDAP_GROUP_ID_ATTR ?? (ad ? 'objectGUID' : 'entryUUID'), + groupNameAttr: env.LDAP_GROUP_NAME_ATTR ?? (ad ? 'name' : 'displayName'), + groupLookupAttr: env.LDAP_GROUP_LOOKUP_ATTR, + searchNestedGroups: bool('LDAP_SEARCH_NESTED_GROUPS', env.LDAP_SEARCH_NESTED_GROUPS), + disableMatchingRuleInChain: bool('LDAP_DISABLE_MATCHING_RULE_IN_CHAIN', env.LDAP_DISABLE_MATCHING_RULE_IN_CHAIN), + nestedGroupMaxDepth: integer(env.LDAP_NESTED_GROUP_MAX_DEPTH), + groupSearchLimit: integer(env.LDAP_GROUP_SEARCH_LIMIT), + groupTraversalLimit: integer(env.LDAP_GROUP_TRAVERSAL_LIMIT), + revalidationIntervalSeconds: integer(env.LDAP_REVALIDATION_INTERVAL_SECONDS), + maxConcurrentOperations: integer(env.LDAP_MAX_CONCURRENT_OPERATIONS), + }); +} diff --git a/backend/src/config/ldapDn.ts b/backend/src/config/ldapDn.ts new file mode 100644 index 00000000..f48a1390 --- /dev/null +++ b/backend/src/config/ldapDn.ts @@ -0,0 +1,94 @@ +import { TextDecoder } from 'node:util'; +import { BerReader } from 'ldapts'; + +export type ParsedLdapDn = readonly (readonly string[])[]; +const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); +const attribute = /^(?:[a-zA-Z][a-zA-Z0-9-]*|(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*))+)$/; +const hexPair = /^[0-9a-f]{2}$/i; +const escaped = new Set([' ', '"', '#', '+', ',', ';', '<', '=', '>', '\\']); + +function invalid(): never { throw new SyntaxError('Invalid LDAP distinguished name'); } + +/** RFC 4514 syntax. Values stay exact because schema-specific matching belongs to the directory. */ +export function parseLdapDn(input: string): ParsedLdapDn { + if (Buffer.byteLength(input) > 8192) invalid(); + if (!input) return []; + const rdns: string[][] = []; + let offset = 0; + while (offset < input.length) { + const assertions: string[] = []; + for (;;) { + const start = offset; + while (offset < input.length && !['=', ',', '+'].includes(input[offset])) offset++; + const name = input.slice(start, offset); + if (!attribute.test(name) || input[offset++] !== '=') invalid(); + let value: string; + if (input[offset] === '#') { + const begin = ++offset; + while (offset < input.length && ![',', '+'].includes(input[offset])) offset++; + const hex = input.slice(begin, offset); + if (!/^(?:[0-9a-f]{2})+$/i.test(hex)) invalid(); + const bytes = Buffer.from(hex, 'hex'); + // Preserve opaque BER bytes; never guess an unknown attribute's value syntax. + const tag = bytes[0]; + if (tag === 0 || tag % 32 === 31) invalid(); + try { + const reader = new BerReader(bytes); + if (reader.readString(tag, true) === null || reader.remain !== 0) invalid(); + } catch { invalid(); } + value = JSON.stringify(['ber', bytes.toString('hex')]); + } else { + const bytes: number[] = []; + let first = true; + let unescapedTrailingSpace = false; + while (offset < input.length && ![',', '+'].includes(input[offset])) { + const character = input[offset++]; + if (character === '\\') { + const pair = input.slice(offset, offset + 2); + if (hexPair.test(pair)) { + bytes.push(Number.parseInt(pair, 16)); + offset += 2; + } else { + const literal = input[offset++]; + if (!escaped.has(literal)) invalid(); + bytes.push(literal.charCodeAt(0)); + } + unescapedTrailingSpace = false; + } else { + if ('"<>;'.includes(character) || character === '\0' || (first && (character === ' ' || character === '#'))) invalid(); + const code = input.codePointAt(offset - 1) ?? invalid(); + if (code >= 0xd800 && code <= 0xdfff) invalid(); + const literal = String.fromCodePoint(code); + if (literal.length === 2) offset++; + bytes.push(...Buffer.from(literal)); + unescapedTrailingSpace = character === ' '; + } + first = false; + } + if (unescapedTrailingSpace) invalid(); + try { value = JSON.stringify(['text', utf8.decode(Buffer.from(bytes))]); } + catch { invalid(); } + } + const assertion = JSON.stringify([name.toLowerCase(), value]); + if (assertions.includes(assertion)) invalid(); + assertions.push(assertion); + if (input[offset] !== '+') break; + offset++; + } + rdns.push(assertions.sort()); + if (offset === input.length) break; + if (input[offset++] !== ',' || offset === input.length) invalid(); + } + return rdns; +} + +export function ldapDnEquals(left: string, right: string): boolean { + return JSON.stringify(parseLdapDn(left)) === JSON.stringify(parseLdapDn(right)); +} + +export function ldapDnWithinScope(dn: string, base: string): boolean { + const entry = parseLdapDn(dn); + const scope = parseLdapDn(base); + return entry.length > 0 && scope.length > 0 && entry.length >= scope.length && + JSON.stringify(entry.slice(entry.length - scope.length)) === JSON.stringify(scope); +} diff --git a/backend/src/config/ldapFilter.ts b/backend/src/config/ldapFilter.ts new file mode 100644 index 00000000..c56ee2d8 --- /dev/null +++ b/backend/src/config/ldapFilter.ts @@ -0,0 +1,47 @@ +import { + AndFilter, ApproximateFilter, EqualityFilter, ExtensibleFilter, FilterParser, + GreaterThanEqualsFilter, LessThanEqualsFilter, NotFilter, OrFilter, SubstringFilter, +} from 'ldapts'; +import type { Filter } from 'ldapts'; + +export function parseLdapFilter(input: string): Filter { + let depth = 0; + for (let index = 0; index < input.length; index++) { + const char = input[index]; + if (char.charCodeAt(0) === 0) throw new SyntaxError('Invalid LDAP filter character'); + if (char === '\\') { + if (!/^[0-9a-f]{2}$/i.test(input.slice(index + 1, index + 3))) throw new SyntaxError('Invalid LDAP filter escape'); + index += 2; + } else if (char === '(') depth++; + else if (char === ')') { + depth--; + if (depth < 0 || (depth === 0 && index !== input.length - 1)) throw new SyntaxError('Invalid LDAP filter structure'); + } + } + if (depth !== 0 || !input.startsWith('(') || !input.endsWith(')') || /\([&|!]\)/.test(input)) { + throw new SyntaxError('Invalid LDAP filter structure'); + } + // ldapts parses hex escapes as Latin-1 characters. Normalize all input to + // escaped UTF-8 octets, then restore assertion values before BER serialization. + const octets = Array.from(input, char => char.charCodeAt(0) <= 127 ? char : + Array.from(Buffer.from(char), byte => '\\' + byte.toString(16).padStart(2, '0')).join('')).join(''); + const parsed = FilterParser.parseString(octets); + const text = (value: string): string => new TextDecoder('utf-8', { fatal: true }).decode(Buffer.from(value, 'latin1')); + const restore = (filter: Filter): void => { + if (filter instanceof AndFilter || filter instanceof OrFilter) { + for (const child of filter.filters) restore(child); + } else if (filter instanceof NotFilter) restore(filter.filter); + else if (filter instanceof EqualityFilter) { + if (typeof filter.value === 'string') filter.value = Buffer.from(filter.value, 'latin1'); + } else if (filter instanceof SubstringFilter) { + filter.initial = text(filter.initial); + filter.any = filter.any.map(text); + filter.final = text(filter.final); + } else if (filter instanceof ApproximateFilter || filter instanceof GreaterThanEqualsFilter || + filter instanceof LessThanEqualsFilter || filter instanceof ExtensibleFilter) { + filter.value = text(filter.value); + } + }; + restore(parsed); + return parsed; +} diff --git a/backend/src/config/schema.ts b/backend/src/config/schema.ts index 00099588..b940816e 100644 --- a/backend/src/config/schema.ts +++ b/backend/src/config/schema.ts @@ -1,3 +1,5 @@ +import { LdapConfigSchema } from "./ldap"; +export { LdapConfigSchema, type LdapConfig } from "./ldap"; import { z } from "zod"; /** @@ -473,6 +475,7 @@ export const AppConfigSchema = z.object({ mcpEnabled: z.boolean().default(false), mcpAuthToken: z.string().optional(), entraId: EntraIdConfigSchema.optional(), + ldap: LdapConfigSchema.optional(), }); export type AppConfig = z.infer; diff --git a/backend/src/container/DIContainer.ts b/backend/src/container/DIContainer.ts index 1e312998..788e3bbc 100644 --- a/backend/src/container/DIContainer.ts +++ b/backend/src/container/DIContainer.ts @@ -2,12 +2,37 @@ import { LoggerService } from "../services/LoggerService"; import { ExpertModeService } from "../services/ExpertModeService"; import { ConfigService } from "../config/ConfigService"; import type { EntraIdService } from "../services/EntraIdService"; +import type { LdapDirectoryService } from "../services/LdapDirectoryService"; +import type { LdapMappingService } from "../services/LdapMappingService"; +import type { LdapAuthenticationService } from "../services/LdapAuthenticationService"; +import { InvalidAuthenticationContextError } from "../services/AuthenticationService"; +import { AuthenticationService } from "../services/AuthenticationService"; +import { AuditLoggingService } from "../services/AuditLoggingService"; +import type { DatabaseAdapter } from "../database/DatabaseAdapter"; export interface ServiceRegistry { logger: LoggerService; expertMode: ExpertModeService; config: ConfigService; + authentication: AuthenticationService; entraId?: EntraIdService; + ldapDirectory?: LdapDirectoryService; + ldapMappings?: LdapMappingService; + ldapAuthentication?: LdapAuthenticationService; +} + +export function resolveAuthenticationService(db: DatabaseAdapter, container: DIContainer): AuthenticationService { + if (!container.has('authentication')) { + container.register('authentication', new AuthenticationService( + db, container.resolve('config').getJwtSecret(), new AuditLoggingService(db), + undefined, async (userId, identityId, directoryId, version, force) => { + const ldap = container.has('ldapAuthentication') ? container.resolve('ldapAuthentication') : undefined; + if (!ldap) throw new InvalidAuthenticationContextError(); + await ldap.assertEligible(userId, identityId, directoryId, version, force); + }, + )); + } + return container.resolve('authentication'); } export class DIContainer { diff --git a/backend/src/database/migrations/031_external_identity_boundaries.postgres.sql b/backend/src/database/migrations/031_external_identity_boundaries.postgres.sql new file mode 100644 index 00000000..8b179ac8 --- /dev/null +++ b/backend/src/database/migrations/031_external_identity_boundaries.postgres.sql @@ -0,0 +1,170 @@ +ALTER TABLE users DROP CONSTRAINT users_email_key; +ALTER TABLE users ALTER COLUMN email DROP NOT NULL; +ALTER TABLE users ADD COLUMN local_auth_enabled INTEGER NOT NULL DEFAULT 1 CHECK (local_auth_enabled IN (0, 1)); +ALTER TABLE users ADD COLUMN display_name TEXT; +UPDATE users SET local_auth_enabled = 0 WHERE password_hash IS NULL; +ALTER TABLE users ADD CONSTRAINT users_local_email_required CHECK (local_auth_enabled = 0 OR (email IS NOT NULL AND length(trim(email)) > 0)); +ALTER TABLE users ADD CONSTRAINT users_local_password_scope CHECK (local_auth_enabled = 1 OR password_hash IS NULL); +ALTER TABLE federated_identities DROP CONSTRAINT federated_identities_provider_subject_key; +ALTER TABLE federated_identities ADD CONSTRAINT federated_identity_scope UNIQUE(provider, issuer, subject); +ALTER TABLE federated_identities ADD CONSTRAINT federated_identity_owner UNIQUE(id, user_id); +ALTER TABLE federated_identities ADD CONSTRAINT federated_identity_directory UNIQUE(id, provider, issuer); +DROP INDEX idx_federated_identities_lookup; +CREATE INDEX idx_federated_identities_lookup ON federated_identities(provider, issuer, subject); +DROP VIEW effective_user_roles; + +CREATE UNIQUE INDEX idx_users_local_email ON users(email) WHERE local_auth_enabled = 1; + +CREATE TABLE ldap_directory_state ( + directory_id TEXT PRIMARY KEY, + mapping_revision BIGINT NOT NULL DEFAULT 0 CHECK (mapping_revision >= 0), + config_revision TEXT NOT NULL DEFAULT '' +); + +CREATE TABLE ldap_identity_metadata ( + identity_id TEXT PRIMARY KEY, + provider TEXT NOT NULL DEFAULT 'ldap' CHECK (provider = 'ldap'), + directory_id TEXT NOT NULL REFERENCES ldap_directory_state(directory_id), + login_name TEXT NOT NULL, + dn TEXT NOT NULL, + FOREIGN KEY (identity_id, provider, directory_id) + REFERENCES federated_identities(id, provider, issuer) ON DELETE CASCADE +); + +CREATE INDEX idx_ldap_identity_directory ON ldap_identity_metadata(directory_id); + +CREATE UNIQUE INDEX idx_ldap_identity_scope ON ldap_identity_metadata(identity_id, directory_id); + +CREATE TABLE external_group_mappings ( + id TEXT PRIMARY KEY, + directory_id TEXT NOT NULL REFERENCES ldap_directory_state(directory_id), + group_subject TEXT NOT NULL, + group_dn TEXT NOT NULL, + group_name TEXT NOT NULL, + role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE, + enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE(directory_id, group_subject, role_id), + UNIQUE(id, role_id, directory_id) +); + +CREATE TABLE federated_user_roles_new ( + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE, + identity_id TEXT NOT NULL, + source_key TEXT NOT NULL CHECK (length(source_key) > 0), + mapping_id TEXT, + directory_id TEXT, + PRIMARY KEY (identity_id, role_id, source_key), + FOREIGN KEY (identity_id, user_id) REFERENCES federated_identities(id, user_id) ON DELETE CASCADE, + FOREIGN KEY (identity_id, directory_id) REFERENCES ldap_identity_metadata(identity_id, directory_id) ON DELETE CASCADE, + FOREIGN KEY (mapping_id, role_id, directory_id) REFERENCES external_group_mappings(id, role_id, directory_id) ON DELETE CASCADE, + CHECK ((mapping_id IS NULL AND directory_id IS NULL) OR (mapping_id IS NOT NULL AND directory_id IS NOT NULL)) +); + +-- Detached historical grants have no provable identity owner. Preserve access. +INSERT INTO user_roles (user_id, role_id, assigned_at) +SELECT f.user_id, f.role_id, CAST(CURRENT_TIMESTAMP AS TEXT) FROM federated_user_roles f +WHERE NOT EXISTS (SELECT 1 FROM federated_identities i WHERE i.user_id = f.user_id AND i.provider = 'entra-id') +ON CONFLICT(user_id, role_id) DO NOTHING; + +INSERT INTO federated_user_roles_new (user_id, role_id, identity_id, source_key) +SELECT f.user_id, f.role_id, i.id, 'legacy' +FROM federated_user_roles f JOIN federated_identities i ON i.user_id = f.user_id AND i.provider = 'entra-id'; + +DROP TABLE federated_user_roles; + +ALTER TABLE federated_user_roles_new RENAME TO federated_user_roles; + +CREATE INDEX idx_federated_roles_user ON federated_user_roles(user_id, role_id); + +CREATE INDEX idx_federated_roles_mapping ON federated_user_roles(mapping_id); + +CREATE UNIQUE INDEX idx_federated_roles_mapping_identity ON federated_user_roles(identity_id, mapping_id) WHERE mapping_id IS NOT NULL; + +CREATE VIEW effective_user_roles AS +SELECT user_id, role_id FROM user_roles +UNION SELECT user_id, role_id FROM federated_user_roles; + +CREATE TABLE ldap_validation_state ( + identity_id TEXT PRIMARY KEY REFERENCES ldap_identity_metadata(identity_id) ON DELETE CASCADE, + last_validated_at BIGINT, + validation_generation BIGINT NOT NULL DEFAULT 0 CHECK (validation_generation >= 0), + mapping_revision BIGINT NOT NULL DEFAULT 0 CHECK (mapping_revision >= 0), + config_revision TEXT NOT NULL, + CHECK (last_validated_at IS NULL OR last_validated_at >= 0) +); + +CREATE TABLE ldap_validation_leases ( + identity_id TEXT PRIMARY KEY REFERENCES ldap_identity_metadata(identity_id) ON DELETE CASCADE, + lease_owner TEXT, + lease_expires_at BIGINT, + fencing_generation BIGINT NOT NULL DEFAULT 0 CHECK (fencing_generation >= 0), + CHECK ((lease_owner IS NULL AND lease_expires_at IS NULL) OR (lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL)) +); + +CREATE INDEX idx_ldap_lease_expiry ON ldap_validation_leases(lease_expires_at); + +CREATE TRIGGER authz_federated_roles AFTER INSERT OR UPDATE OR DELETE ON federated_user_roles +FOR EACH STATEMENT EXECUTE FUNCTION pabawi_authorization_changed(); +CREATE FUNCTION pabawi_revoke_local_scope_sessions() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.local_auth_enabled IS DISTINCT FROM OLD.local_auth_enabled THEN + NEW.session_version := replace(gen_random_uuid()::text, '-', ''); + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER revoke_local_scope_sessions BEFORE UPDATE OF local_auth_enabled ON users +FOR EACH ROW EXECUTE FUNCTION pabawi_revoke_local_scope_sessions(); + + +CREATE FUNCTION pabawi_ldap_mapping_insert() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE ldap_directory_state SET mapping_revision = mapping_revision + 1 + WHERE directory_id IN (SELECT NEW.directory_id); + UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id IN (SELECT NEW.directory_id)); + UPDATE authorization_state SET revision = replace(gen_random_uuid()::text, '-', '') WHERE id = 1; + RETURN NULL; +END; +$$; +CREATE TRIGGER ldap_mapping_insert AFTER INSERT ON external_group_mappings +FOR EACH ROW EXECUTE FUNCTION pabawi_ldap_mapping_insert(); + +CREATE FUNCTION pabawi_ldap_mapping_update() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE ldap_directory_state SET mapping_revision = mapping_revision + 1 + WHERE directory_id IN (SELECT OLD.directory_id UNION SELECT NEW.directory_id); + UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id IN (SELECT OLD.directory_id UNION SELECT NEW.directory_id)); + UPDATE authorization_state SET revision = replace(gen_random_uuid()::text, '-', '') WHERE id = 1; + RETURN NULL; +END; +$$; +CREATE TRIGGER ldap_mapping_update AFTER UPDATE ON external_group_mappings +FOR EACH ROW EXECUTE FUNCTION pabawi_ldap_mapping_update(); + +-- PostgreSQL checks composite foreign keys before AFTER UPDATE withdrawal. +CREATE FUNCTION pabawi_ldap_mapping_withdraw() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + DELETE FROM federated_user_roles WHERE mapping_id = OLD.id; + RETURN NEW; +END; +$$; +CREATE TRIGGER ldap_mapping_withdraw BEFORE UPDATE ON external_group_mappings +FOR EACH ROW EXECUTE FUNCTION pabawi_ldap_mapping_withdraw(); + +CREATE FUNCTION pabawi_ldap_mapping_delete() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + UPDATE ldap_directory_state SET mapping_revision = mapping_revision + 1 + WHERE directory_id IN (SELECT OLD.directory_id); + UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id IN (SELECT OLD.directory_id)); + UPDATE authorization_state SET revision = replace(gen_random_uuid()::text, '-', '') WHERE id = 1; + RETURN NULL; +END; +$$; +CREATE TRIGGER ldap_mapping_delete AFTER DELETE ON external_group_mappings +FOR EACH ROW EXECUTE FUNCTION pabawi_ldap_mapping_delete(); diff --git a/backend/src/database/migrations/031_external_identity_boundaries.sqlite.sql b/backend/src/database/migrations/031_external_identity_boundaries.sqlite.sql new file mode 100644 index 00000000..6959fe15 --- /dev/null +++ b/backend/src/database/migrations/031_external_identity_boundaries.sqlite.sql @@ -0,0 +1,232 @@ +-- pabawi:sqlite-foreign-keys-off +-- Preserve account IDs, session versions, and all referencing rows during rebuilds. +DROP VIEW effective_user_roles; +-- pabawi:statement-breakpoint +CREATE TABLE users_new ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + email TEXT, + password_hash TEXT, + local_auth_enabled INTEGER NOT NULL DEFAULT 1 CHECK (local_auth_enabled IN (0, 1)), + display_name TEXT, + first_name TEXT NOT NULL, + last_name TEXT NOT NULL, + is_active INTEGER NOT NULL DEFAULT 1, + is_admin INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + last_login_at TEXT, + session_version TEXT NOT NULL DEFAULT '0', + CHECK (local_auth_enabled = 0 OR (email IS NOT NULL AND length(trim(email)) > 0)), + CHECK (local_auth_enabled = 1 OR password_hash IS NULL) +); +-- pabawi:statement-breakpoint +INSERT INTO users_new (id, username, email, password_hash, local_auth_enabled, first_name, last_name, + is_active, is_admin, created_at, updated_at, last_login_at, session_version) +SELECT id, username, email, password_hash, CASE WHEN password_hash IS NULL THEN 0 ELSE 1 END, + first_name, last_name, is_active, is_admin, created_at, updated_at, last_login_at, session_version FROM users; +-- pabawi:statement-breakpoint +DROP TABLE users; +-- pabawi:statement-breakpoint +ALTER TABLE users_new RENAME TO users; +-- pabawi:statement-breakpoint +CREATE INDEX idx_users_username ON users(username); +-- pabawi:statement-breakpoint +CREATE INDEX idx_users_email ON users(email); +-- pabawi:statement-breakpoint +CREATE INDEX idx_users_active ON users(is_active); +-- pabawi:statement-breakpoint +CREATE TABLE federated_identities_new ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + subject TEXT NOT NULL, + issuer TEXT NOT NULL, + email TEXT, + id_token TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE(provider, issuer, subject), + UNIQUE(id, user_id), + UNIQUE(id, provider, issuer) +); +-- pabawi:statement-breakpoint +INSERT INTO federated_identities_new SELECT * FROM federated_identities; +-- pabawi:statement-breakpoint +DROP TABLE federated_identities; +-- pabawi:statement-breakpoint +ALTER TABLE federated_identities_new RENAME TO federated_identities; +-- pabawi:statement-breakpoint +CREATE INDEX idx_federated_identities_user ON federated_identities(user_id); +-- pabawi:statement-breakpoint +CREATE INDEX idx_federated_identities_lookup ON federated_identities(provider, issuer, subject); +-- pabawi:statement-breakpoint +CREATE UNIQUE INDEX idx_users_local_email ON users(email) WHERE local_auth_enabled = 1; +-- pabawi:statement-breakpoint +CREATE TABLE ldap_directory_state ( + directory_id TEXT PRIMARY KEY, + mapping_revision BIGINT NOT NULL DEFAULT 0 CHECK (mapping_revision >= 0), + config_revision TEXT NOT NULL DEFAULT '' +); +-- pabawi:statement-breakpoint +CREATE TABLE ldap_identity_metadata ( + identity_id TEXT PRIMARY KEY, + provider TEXT NOT NULL DEFAULT 'ldap' CHECK (provider = 'ldap'), + directory_id TEXT NOT NULL REFERENCES ldap_directory_state(directory_id), + login_name TEXT NOT NULL, + dn TEXT NOT NULL, + FOREIGN KEY (identity_id, provider, directory_id) + REFERENCES federated_identities(id, provider, issuer) ON DELETE CASCADE +); +-- pabawi:statement-breakpoint +CREATE INDEX idx_ldap_identity_directory ON ldap_identity_metadata(directory_id); +-- pabawi:statement-breakpoint +CREATE UNIQUE INDEX idx_ldap_identity_scope ON ldap_identity_metadata(identity_id, directory_id); +-- pabawi:statement-breakpoint +CREATE TABLE external_group_mappings ( + id TEXT PRIMARY KEY, + directory_id TEXT NOT NULL REFERENCES ldap_directory_state(directory_id), + group_subject TEXT NOT NULL, + group_dn TEXT NOT NULL, + group_name TEXT NOT NULL, + role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE, + enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + UNIQUE(directory_id, group_subject, role_id), + UNIQUE(id, role_id, directory_id) +); +-- pabawi:statement-breakpoint +CREATE TABLE federated_user_roles_new ( + user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + role_id TEXT NOT NULL REFERENCES roles(id) ON DELETE CASCADE, + identity_id TEXT NOT NULL, + source_key TEXT NOT NULL CHECK (length(source_key) > 0), + mapping_id TEXT, + directory_id TEXT, + PRIMARY KEY (identity_id, role_id, source_key), + FOREIGN KEY (identity_id, user_id) REFERENCES federated_identities(id, user_id) ON DELETE CASCADE, + FOREIGN KEY (identity_id, directory_id) REFERENCES ldap_identity_metadata(identity_id, directory_id) ON DELETE CASCADE, + FOREIGN KEY (mapping_id, role_id, directory_id) REFERENCES external_group_mappings(id, role_id, directory_id) ON DELETE CASCADE, + CHECK ((mapping_id IS NULL AND directory_id IS NULL) OR (mapping_id IS NOT NULL AND directory_id IS NOT NULL)) +); +-- pabawi:statement-breakpoint +-- Detached historical grants have no provable identity owner. Preserve access. +INSERT INTO user_roles (user_id, role_id, assigned_at) +SELECT f.user_id, f.role_id, CAST(CURRENT_TIMESTAMP AS TEXT) FROM federated_user_roles f +WHERE NOT EXISTS (SELECT 1 FROM federated_identities i WHERE i.user_id = f.user_id AND i.provider = 'entra-id') +ON CONFLICT(user_id, role_id) DO NOTHING; +-- pabawi:statement-breakpoint +INSERT INTO federated_user_roles_new (user_id, role_id, identity_id, source_key) +SELECT f.user_id, f.role_id, i.id, 'legacy' +FROM federated_user_roles f JOIN federated_identities i ON i.user_id = f.user_id AND i.provider = 'entra-id'; +-- pabawi:statement-breakpoint +DROP TABLE federated_user_roles; +-- pabawi:statement-breakpoint +ALTER TABLE federated_user_roles_new RENAME TO federated_user_roles; +-- pabawi:statement-breakpoint +CREATE INDEX idx_federated_roles_user ON federated_user_roles(user_id, role_id); +-- pabawi:statement-breakpoint +CREATE INDEX idx_federated_roles_mapping ON federated_user_roles(mapping_id); +-- pabawi:statement-breakpoint +CREATE UNIQUE INDEX idx_federated_roles_mapping_identity ON federated_user_roles(identity_id, mapping_id) WHERE mapping_id IS NOT NULL; +-- pabawi:statement-breakpoint +CREATE VIEW effective_user_roles AS +SELECT user_id, role_id FROM user_roles +UNION SELECT user_id, role_id FROM federated_user_roles; +-- pabawi:statement-breakpoint +CREATE TABLE ldap_validation_state ( + identity_id TEXT PRIMARY KEY REFERENCES ldap_identity_metadata(identity_id) ON DELETE CASCADE, + last_validated_at BIGINT, + validation_generation BIGINT NOT NULL DEFAULT 0 CHECK (validation_generation >= 0), + mapping_revision BIGINT NOT NULL DEFAULT 0 CHECK (mapping_revision >= 0), + config_revision TEXT NOT NULL, + CHECK (last_validated_at IS NULL OR last_validated_at >= 0) +); +-- pabawi:statement-breakpoint +CREATE TABLE ldap_validation_leases ( + identity_id TEXT PRIMARY KEY REFERENCES ldap_identity_metadata(identity_id) ON DELETE CASCADE, + lease_owner TEXT, + lease_expires_at BIGINT, + fencing_generation BIGINT NOT NULL DEFAULT 0 CHECK (fencing_generation >= 0), + CHECK ((lease_owner IS NULL AND lease_expires_at IS NULL) OR (lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL)) +); +-- pabawi:statement-breakpoint +CREATE INDEX idx_ldap_lease_expiry ON ldap_validation_leases(lease_expires_at); +-- pabawi:statement-breakpoint +-- Explicit statement boundaries keep SQLite trigger bodies intact. +CREATE TRIGGER revoke_user_sessions AFTER UPDATE OF password_hash, is_active, is_admin ON users +WHEN NEW.password_hash IS NOT OLD.password_hash OR NEW.is_active IS NOT OLD.is_active OR NEW.is_admin IS NOT OLD.is_admin +BEGIN + UPDATE users SET session_version = lower(hex(randomblob(16))) WHERE id = NEW.id; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER authz_users_insert AFTER INSERT ON users +BEGIN + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER authz_users_update AFTER UPDATE OF is_active, is_admin ON users +BEGIN + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER authz_users_delete AFTER DELETE ON users +BEGIN + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER authz_federated_roles_insert AFTER INSERT ON federated_user_roles +BEGIN + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER authz_federated_roles_update AFTER UPDATE ON federated_user_roles +BEGIN + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER authz_federated_roles_delete AFTER DELETE ON federated_user_roles +BEGIN + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER revoke_local_scope_sessions AFTER UPDATE OF local_auth_enabled ON users +WHEN NEW.local_auth_enabled IS NOT OLD.local_auth_enabled +BEGIN + UPDATE users SET session_version = lower(hex(randomblob(16))) WHERE id = NEW.id; +END; + +-- pabawi:statement-breakpoint +CREATE TRIGGER ldap_mapping_insert AFTER INSERT ON external_group_mappings +BEGIN + UPDATE ldap_directory_state SET mapping_revision = mapping_revision + 1 + WHERE directory_id IN (SELECT NEW.directory_id); + UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id IN (SELECT NEW.directory_id)); + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER ldap_mapping_update AFTER UPDATE ON external_group_mappings +BEGIN + UPDATE ldap_directory_state SET mapping_revision = mapping_revision + 1 + WHERE directory_id IN (SELECT OLD.directory_id UNION SELECT NEW.directory_id); + UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id IN (SELECT OLD.directory_id UNION SELECT NEW.directory_id)); + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; +-- pabawi:statement-breakpoint +-- Withdraw before a role/scope edit changes the referenced composite key. +CREATE TRIGGER ldap_mapping_withdraw BEFORE UPDATE ON external_group_mappings +BEGIN + DELETE FROM federated_user_roles WHERE mapping_id = OLD.id; +END; +-- pabawi:statement-breakpoint +CREATE TRIGGER ldap_mapping_delete AFTER DELETE ON external_group_mappings +BEGIN + UPDATE ldap_directory_state SET mapping_revision = mapping_revision + 1 + WHERE directory_id IN (SELECT OLD.directory_id); + UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id IN (SELECT OLD.directory_id)); + UPDATE authorization_state SET revision = lower(hex(randomblob(16))) WHERE id = 1; +END; diff --git a/backend/src/database/migrations/032_provider_bound_sessions.postgres.sql b/backend/src/database/migrations/032_provider_bound_sessions.postgres.sql new file mode 100644 index 00000000..e1e7b79c --- /dev/null +++ b/backend/src/database/migrations/032_provider_bound_sessions.postgres.sql @@ -0,0 +1,4 @@ +-- Provider ownership cannot be inferred for legacy sessions. Require a fresh login once. +UPDATE users SET session_version = replace(gen_random_uuid()::text, '-', ''); +UPDATE oauth_state_store SET expires_at = '1970-01-01T00:00:00.000Z'; +UPDATE oauth_auth_codes SET expires_at = '1970-01-01T00:00:00.000Z'; diff --git a/backend/src/database/migrations/032_provider_bound_sessions.sqlite.sql b/backend/src/database/migrations/032_provider_bound_sessions.sqlite.sql new file mode 100644 index 00000000..bda78fcb --- /dev/null +++ b/backend/src/database/migrations/032_provider_bound_sessions.sqlite.sql @@ -0,0 +1,4 @@ +-- Provider ownership cannot be inferred for legacy sessions. Require a fresh login once. +UPDATE users SET session_version = lower(hex(randomblob(16))); +UPDATE oauth_state_store SET expires_at = '1970-01-01T00:00:00.000Z'; +UPDATE oauth_auth_codes SET expires_at = '1970-01-01T00:00:00.000Z'; diff --git a/backend/src/database/migrations/033_ldap_validation_decisions.postgres.sql b/backend/src/database/migrations/033_ldap_validation_decisions.postgres.sql new file mode 100644 index 00000000..b966c2f6 --- /dev/null +++ b/backend/src/database/migrations/033_ldap_validation_decisions.postgres.sql @@ -0,0 +1,4 @@ +-- Retain ordering even when a positive revocation clears successful freshness. +ALTER TABLE ldap_validation_state ADD COLUMN decision_started_at BIGINT CHECK (decision_started_at IS NULL OR decision_started_at >= 0); +ALTER TABLE ldap_validation_state ADD COLUMN decision_sequence BIGINT NOT NULL DEFAULT 0 CHECK (decision_sequence >= 0); +ALTER TABLE ldap_directory_state ADD COLUMN validation_sequence BIGINT NOT NULL DEFAULT 0 CHECK (validation_sequence >= 0); diff --git a/backend/src/database/migrations/033_ldap_validation_decisions.sqlite.sql b/backend/src/database/migrations/033_ldap_validation_decisions.sqlite.sql new file mode 100644 index 00000000..b966c2f6 --- /dev/null +++ b/backend/src/database/migrations/033_ldap_validation_decisions.sqlite.sql @@ -0,0 +1,4 @@ +-- Retain ordering even when a positive revocation clears successful freshness. +ALTER TABLE ldap_validation_state ADD COLUMN decision_started_at BIGINT CHECK (decision_started_at IS NULL OR decision_started_at >= 0); +ALTER TABLE ldap_validation_state ADD COLUMN decision_sequence BIGINT NOT NULL DEFAULT 0 CHECK (decision_sequence >= 0); +ALTER TABLE ldap_directory_state ADD COLUMN validation_sequence BIGINT NOT NULL DEFAULT 0 CHECK (validation_sequence >= 0); diff --git a/backend/src/database/migrations/034_console_authentication_context.postgres.sql b/backend/src/database/migrations/034_console_authentication_context.postgres.sql new file mode 100644 index 00000000..6d20c39a --- /dev/null +++ b/backend/src/database/migrations/034_console_authentication_context.postgres.sql @@ -0,0 +1,2 @@ +-- Legacy reservations have no provable provider context and fail closed on upgrade. +ALTER TABLE console_sessions ADD COLUMN auth_context TEXT; diff --git a/backend/src/database/migrations/034_console_authentication_context.sqlite.sql b/backend/src/database/migrations/034_console_authentication_context.sqlite.sql new file mode 100644 index 00000000..6d20c39a --- /dev/null +++ b/backend/src/database/migrations/034_console_authentication_context.sqlite.sql @@ -0,0 +1,2 @@ +-- Legacy reservations have no provable provider context and fail closed on upgrade. +ALTER TABLE console_sessions ADD COLUMN auth_context TEXT; diff --git a/backend/src/integrations/puppetdb/CircuitBreaker.ts b/backend/src/integrations/puppetdb/CircuitBreaker.ts index 42fff2a7..2b976d92 100644 --- a/backend/src/integrations/puppetdb/CircuitBreaker.ts +++ b/backend/src/integrations/puppetdb/CircuitBreaker.ts @@ -165,6 +165,9 @@ export class CircuitBreaker { // Service has recovered, close the circuit this.reset(); this.transitionTo("closed"); + } else if (this.state === "closed") { + // Only consecutive failures trip the breaker; a success clears the streak + this.failureCount = 0; } } diff --git a/backend/src/integrations/puppetdb/PuppetDBService.ts b/backend/src/integrations/puppetdb/PuppetDBService.ts index 9654b7d2..587eedc7 100644 --- a/backend/src/integrations/puppetdb/PuppetDBService.ts +++ b/backend/src/integrations/puppetdb/PuppetDBService.ts @@ -656,8 +656,9 @@ export class PuppetDBService const envGroups = this.createEnvironmentGroups(envResult as PuppetDBNode[]); groups.push(...envGroups); } - } catch { - this.log("Failed to query nodes for environment grouping", "warn"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + this.log(`Failed to query nodes for environment grouping: ${detail}`, "warn"); } // Query 2: Group by OS family (from facts) @@ -673,8 +674,9 @@ export class PuppetDBService const osGroups = this.createOSFamilyGroups(osResult as { certname: string; "os.family": string }[]); groups.push(...osGroups); } - } catch { - this.log("Failed to query nodes for OS family grouping", "warn"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + this.log(`Failed to query nodes for OS family grouping: ${detail}`, "warn"); } // Cache the result diff --git a/backend/src/mcp/McpServiceUser.ts b/backend/src/mcp/McpServiceUser.ts index 144962c1..bf4c45eb 100644 --- a/backend/src/mcp/McpServiceUser.ts +++ b/backend/src/mcp/McpServiceUser.ts @@ -16,9 +16,9 @@ export interface McpServiceUserResult { /** * Idempotent provisioning of the mcp-service user at startup. * - * If the user already exists, looks up the existing role and returns IDs. - * If not, creates the user, an "MCP Service" built-in role with all read - * permissions, and assigns the role to the user. + * Repairs missing users, roles, and assignments after incomplete provisioning. + * New roles receive all read permissions; existing roles retain their permissions + * because administrators may have customized machine access. */ export async function provisionMcpServiceUser( userService: UserService, @@ -37,11 +37,9 @@ export async function provisionMcpServiceUser( const roles = await userService.getUserRoles(existing.id); const mcpRole = roles.find((r) => r.name === MCP_ROLE_NAME); - if (!mcpRole) { - throw new Error('MCP service user exists but MCP Service role not found'); + if (mcpRole) { + return { userId: existing.id, roleId: mcpRole.id }; } - - return { userId: existing.id, roleId: mcpRole.id }; } logger.info('Provisioning MCP service user', { @@ -51,7 +49,7 @@ export async function provisionMcpServiceUser( // Create user with random password (never used for login) const password = `Mcp!${randomUUID()}`; // pragma: allowlist secret - const user = await userService.createUser({ + const user = existing ?? await userService.createUser({ username: MCP_USERNAME, email: `${MCP_USERNAME}@localhost`, password, @@ -61,21 +59,22 @@ export async function provisionMcpServiceUser( isAdmin: false, }); - // Create built-in role - const role = await roleService.createRole({ - name: MCP_ROLE_NAME, - description: 'Built-in role for MCP server with read-only access', - isBuiltIn: true, - }); + let role = await roleService.getRoleByName(MCP_ROLE_NAME); + if (!role) { + role = await roleService.createRole({ + name: MCP_ROLE_NAME, + description: 'Built-in role for MCP server with read-only access', + isBuiltIn: true, + }); - // Assign all read permissions to the role - const readPermissions = await permissionService.listPermissions({ - action: 'read', - limit: 1000, - }); + const readPermissions = await permissionService.listPermissions({ + action: 'read', + limit: 1000, + }); - for (const perm of readPermissions.items) { - await roleService.assignPermissionToRole(role.id, perm.id); + for (const perm of readPermissions.items) { + await roleService.assignPermissionToRole(role.id, perm.id); + } } // Assign role to user diff --git a/backend/src/middleware/authMiddleware.ts b/backend/src/middleware/authMiddleware.ts index cdc7ec33..8a8bb4d1 100644 --- a/backend/src/middleware/authMiddleware.ts +++ b/backend/src/middleware/authMiddleware.ts @@ -1,6 +1,6 @@ import type { Request, Response, NextFunction } from "express"; -import { AuthenticationService } from "../services/AuthenticationService"; -import type { DatabaseAdapter } from "../database/DatabaseAdapter"; +import type { AuthenticationService } from "../services/AuthenticationService"; +import { ldapAuthenticationFailure } from "../services/LdapAuthenticationService"; import { ERROR_CODES, sendAuthenticationError, sendDatabaseError, isDatabaseConnectionError } from "../utils/errorHandling"; // Express.Request.user augmentation is defined in src/types/express.d.ts @@ -13,9 +13,7 @@ import { ERROR_CODES, sendAuthenticationError, sendDatabaseError, isDatabaseConn * * Requirements: 5.1, 6.6, 16.1, 16.5 */ -export function createAuthMiddleware(db: DatabaseAdapter, jwtSecret?: string) { - const authService = new AuthenticationService(db, jwtSecret); - +export function createAuthMiddleware(authService: AuthenticationService) { return async (req: Request, res: Response, next: NextFunction): Promise => { try { // Extract token from Authorization header @@ -66,12 +64,19 @@ export function createAuthMiddleware(db: DatabaseAdapter, jwtSecret?: string) { iat: payload.iat, exp: payload.exp }; + req.authContext = payload.authContext; + req.authSessionVersion = payload.sessionVersion; req.revalidateAuth = async (): Promise => { await authService.verifyToken(token); }; // Continue to next middleware next(); } catch (error) { + const failure = ldapAuthenticationFailure(error); + if (failure) { + res.status(failure.status).json({ error: { code: failure.code, message: failure.message } }); + return; + } // Check for database connection errors (Requirement 16.5) if (isDatabaseConnectionError(error)) { sendDatabaseError(res, error, "Authentication service temporarily unavailable"); diff --git a/backend/src/middleware/securityMiddleware.ts b/backend/src/middleware/securityMiddleware.ts index 88a5c45c..192ce13d 100644 --- a/backend/src/middleware/securityMiddleware.ts +++ b/backend/src/middleware/securityMiddleware.ts @@ -141,7 +141,8 @@ export function inputSanitizationMiddleware( ): void { try { // Sanitize request body - if (req.body && typeof req.body === "object") { + // LDAP login has a strict bounded schema. Preserve directory login values as well as passwords. + if (req.body && typeof req.body === "object" && !(req.method === 'POST' && req.path === '/api/auth/ldap/login')) { req.body = sanitizeObject(req.body); } diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts index 013fe763..40d4ae33 100644 --- a/backend/src/routes/auth.ts +++ b/backend/src/routes/auth.ts @@ -2,10 +2,8 @@ import { PermissionService } from "../services/PermissionService"; import { Router, type Request, type Response } from "express"; import { z } from "zod"; import { asyncHandler } from "./asyncHandler"; -import { UserService } from "../services/UserService"; -import { AuthenticationService } from "../services/AuthenticationService"; +import { FederatedAccountError, UserService } from "../services/UserService"; import { SetupService } from "../services/SetupService"; -import { AuditLoggingService } from "../services/AuditLoggingService"; import type { DatabaseService } from "../database/DatabaseService"; import { sendValidationError, @@ -20,8 +18,10 @@ import { } from "../utils/errorHandling"; import { ZodError } from "zod"; import { createAuthMiddleware } from "../middleware/authMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; import type { EntraIdService } from "../services/EntraIdService"; +import { ldapAuthenticationFailure } from "../services/LdapAuthenticationService"; +import { AuditLoggingService } from "../services/AuditLoggingService"; /** * Zod schema for user registration @@ -75,13 +75,10 @@ export function createAuthRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const configService = container.resolve("config"); - const jwtSecret = configService.getJwtSecret(); - const auditLogger = new AuditLoggingService(databaseService.getAdapter()); - const authService = new AuthenticationService(databaseService.getAdapter(), jwtSecret, auditLogger); + const authService = resolveAuthenticationService(databaseService.getAdapter(), container); const userService = new UserService(databaseService.getAdapter(), authService); const setupService = new SetupService(databaseService.getAdapter()); - const authMiddleware = createAuthMiddleware(databaseService.getAdapter(), jwtSecret); + const authMiddleware = createAuthMiddleware(authService); router.get("/permissions", asyncHandler(authMiddleware), asyncHandler(async (req, res) => { const userId = req.user?.userId; if (!userId) { @@ -119,11 +116,49 @@ export function createAuthRouter( if (entraIdService) { providers.entraId = entraIdService.getProviderInfo(); } + if (container.has('ldapAuthentication')) { + const config = container.resolve('config').getLdapConfig(); + if (config) providers.ldap = { enabled: true, name: config.displayName, loginHelpUrl: config.loginHelpUrl }; + } res.status(200).json(providers); }), ); + const ldapLoginSchema = z.object({ + username: z.string().min(1).max(1024).refine(value => Buffer.byteLength(value) <= 1024), + password: z.string().min(1).max(4096).refine(value => Buffer.byteLength(value) <= 4096), + }).strict(); + router.post('/ldap/login', asyncHandler(async (req, res): Promise => { + res.setHeader('Cache-Control', 'no-store'); + const ldap = container.has('ldapAuthentication') ? container.resolve('ldapAuthentication') : undefined; + const config = ldap ? container.resolve('config').getLdapConfig() : undefined; + if (!ldap || !config) { res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Not found' } }); return; } + const parsed = ldapLoginSchema.safeParse(req.body); + if (!parsed.success) { + res.status(400).json({ error: { code: 'VALIDATION_ERROR', message: 'Invalid LDAP login request' } }); return; + } + const { username, password } = parsed.data; + const audit = new AuditLoggingService(databaseService.getAdapter()); + if (await authService.isLdapLoginLocked(config.directoryId, username)) { + res.status(429).json({ error: { code: 'RATE_LIMITED', message: 'Too many authentication attempts' } }); return; + } + try { + const proof = await ldap.authenticate(username, password); + const tokens = await authService.generateTokenPair(proof.user, + { provider: 'ldap', identityId: proof.identityId, directoryId: proof.directoryId }, proof.sessionVersion); + await authService.recordLdapLoginOutcome(config.directoryId, username, true); + await audit.logAuthenticationAttempt('ldap:' + config.directoryId, true, proof.user.id, req.ip, req.headers['user-agent']); + res.json({ ...tokens, user: userService.toUserDTO(proof.user) }); + } catch (error) { + const failure = ldapAuthenticationFailure(error); + if (failure?.code === 'INVALID_CREDENTIALS') await authService.recordLdapLoginOutcome(config.directoryId, username, false, req.ip); + await audit.logAuthenticationAttempt('ldap:' + config.directoryId, false, null, req.ip, req.headers['user-agent'], failure?.code ?? 'INTERNAL_ERROR'); + if (!failure) throw error; + res.status(failure.status).json({ error: { code: failure.code, message: failure.message } }); + } + })); + /** * POST /api/auth/register * Register a new user account @@ -544,9 +579,9 @@ export function createAuthRouter( } // Return error response - res.status(statusCode).json({ + res.status(authResult.errorStatus ?? statusCode).json({ error: { - code: statusCode === 400 ? "INVALID_REFRESH_TOKEN" : "REFRESH_TOKEN_EXPIRED", + code: authResult.errorCode ?? (statusCode === 400 ? "INVALID_REFRESH_TOKEN" : "REFRESH_TOKEN_EXPIRED"), message: authResult.error ?? "Token refresh failed", }, }); @@ -672,6 +707,8 @@ export function createAuthRouter( return; } + await userService.requireLocalProfileOwnership(user.id); + // Verify current password const isCurrentPasswordValid = await authService.verifyPassword( validatedData.currentPassword, @@ -728,6 +765,10 @@ export function createAuthRouter( message: "Password changed successfully. Please log in again with your new password.", }); } catch (error) { + if (error instanceof FederatedAccountError && error.code === 'DIRECTORY_ACCOUNT_READ_ONLY') { + res.status(403).json({ error: { code: error.code, message: error.message } }); + return; + } // Handle Zod validation errors (Requirement 16.3) if (error instanceof ZodError) { logger.warn("Password change validation failed", { diff --git a/backend/src/routes/console.ts b/backend/src/routes/console.ts index 9b0980fb..a091b9ba 100644 --- a/backend/src/routes/console.ts +++ b/backend/src/routes/console.ts @@ -9,7 +9,7 @@ import { PermissionService } from "../services/PermissionService"; import type { ConsoleSessionManager } from "../services/ConsoleSessionManager"; import { ConsoleAccountError, ConsoleCapacityError } from "../services/ConsoleSessionManager"; import type { ConsoleConnectionBroker } from "../services/ConsoleConnectionBroker"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; import { asyncHandler } from "./asyncHandler"; @@ -37,10 +37,8 @@ export function createConsoleRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const config = container.resolve("config"); - const jwtSecret = config.getJwtSecret(); - const authMiddleware = createAuthMiddleware(db, jwtSecret); + const authMiddleware = createAuthMiddleware(resolveAuthenticationService(db, container)); const rbacMiddleware = createRbacMiddleware(db); const permissionService = new PermissionService(db); @@ -134,7 +132,7 @@ export function createConsoleRouter( asyncHandler(rbacMiddleware("console", "access")), asyncHandler(async (req: Request, res: Response): Promise => { const userId = req.user?.userId; - if (!userId) { + if (!userId || !req.authContext || !req.authSessionVersion) { res.status(401).json({ error: { code: "UNAUTHORIZED", message: "Authentication required" }, }); @@ -211,6 +209,7 @@ export function createConsoleRouter( try { reservation = await sessionManager.reserveSession({ userId, nodeId: resolvedNodeId, provider: providerName, transport, + authContext: req.authContext, sessionVersion: req.authSessionVersion, }); } catch (error) { if (error instanceof ConsoleCapacityError) { diff --git a/backend/src/routes/entraIdAuth.ts b/backend/src/routes/entraIdAuth.ts index db6a0739..ab9e923e 100644 --- a/backend/src/routes/entraIdAuth.ts +++ b/backend/src/routes/entraIdAuth.ts @@ -5,7 +5,7 @@ import { z } from "zod"; import { asyncHandler } from "./asyncHandler"; import { type EntraIdService, EntraIdError, ENTRA_ID_ERROR_CODES } from "../services/EntraIdService"; import type { DatabaseService } from "../database/DatabaseService"; -import type { DIContainer } from "../container/DIContainer"; +import { type DIContainer, resolveAuthenticationService } from "../container/DIContainer"; import { createAuthMiddleware } from "../middleware/authMiddleware"; import { createRbacMiddleware } from "../middleware/rbacMiddleware"; @@ -286,7 +286,7 @@ export function createEntraIdAuthRouter( ); router.post("/enroll", - asyncHandler(createAuthMiddleware(db, container.resolve("config").getJwtSecret())), + asyncHandler(createAuthMiddleware(resolveAuthenticationService(db, container))), asyncHandler(createRbacMiddleware(db)("rbac", "admin")), asyncHandler(createRbacMiddleware(db)("users", "admin")), asyncHandler(async (req, res) => { diff --git a/backend/src/routes/groups.ts b/backend/src/routes/groups.ts index 24d2d00b..d0925b5f 100644 --- a/backend/src/routes/groups.ts +++ b/backend/src/routes/groups.ts @@ -10,7 +10,7 @@ import { sendValidationError, ERROR_CODES } from "../utils/errorHandling"; import { ZodError } from "zod"; import { createAuthMiddleware } from "../middleware/authMiddleware"; import { createRbacMiddleware } from "../middleware/rbacMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; /** * Zod schema for pagination query parameters @@ -45,12 +45,10 @@ export function createGroupsRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const configService = container.resolve("config"); - const jwtSecret = configService.getJwtSecret(); const groupService = new GroupService(databaseService.getAdapter()); const auditLogger = new AuditLoggingService(databaseService.getAdapter()); const permissionService = new PermissionService(databaseService.getAdapter()); - const authMiddleware = createAuthMiddleware(databaseService.getAdapter(), jwtSecret); + const authMiddleware = createAuthMiddleware(resolveAuthenticationService(databaseService.getAdapter(), container)); const rbacMiddleware = createRbacMiddleware(databaseService.getAdapter()); /** diff --git a/backend/src/routes/journal.ts b/backend/src/routes/journal.ts index 89279507..180af87f 100644 --- a/backend/src/routes/journal.ts +++ b/backend/src/routes/journal.ts @@ -20,9 +20,11 @@ import { JournalEventTypeSchema, JournalSourceSchema, type JournalEntry } from " import type { IntegrationManager } from "../integrations/IntegrationManager"; import type { DatabaseService } from "../database/DatabaseService"; import { sendValidationError, ERROR_CODES } from "../utils/errorHandling"; +import { SessionAuthorization } from "../services/SessionAuthorization"; +import { PermissionService } from "../services/PermissionService"; import { createAuthMiddleware } from "../middleware/authMiddleware"; import { createRbacMiddleware } from "../middleware/rbacMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; /** * Filter journal entries by date range (post-collection). @@ -130,9 +132,8 @@ export function createJournalRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const configService = container.resolve("config"); const journalService = new JournalService(databaseService.getAdapter()); - const authMiddleware = createAuthMiddleware(databaseService.getAdapter(), configService.getJwtSecret()); + const authMiddleware = createAuthMiddleware(resolveAuthenticationService(databaseService.getAdapter(), container)); const rbacMiddleware = createRbacMiddleware(databaseService.getAdapter()); const db = databaseService.getAdapter(); @@ -219,9 +220,18 @@ export function createJournalRouter( res.setHeader("X-Accel-Buffering", "no"); res.flushHeaders(); + const authorization = new SessionAuthorization(async () => { + if (!req.revalidateAuth || !req.user) throw new Error('Authentication required'); + await req.revalidateAuth(); + if (!await new PermissionService(db).hasPermission(req.user.userId, 'journal', 'read')) { + throw new Error('Journal permission revoked'); + } + }, () => { res.end(); }); + res.on('close', () => { authorization.close(); }); + function send(eventName: string, data: unknown): void { if (res.writableEnded) return; - res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`); + authorization.run(() => { if (!res.writableEnded) res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`); }); } const heartbeat = setInterval(() => { @@ -247,7 +257,7 @@ export function createJournalRouter( send("source_error", { source: "global", message: "Group not found" }); clearInterval(heartbeat); send("complete", {}); - res.end(); + await authorization.finish(() => { res.end(); }); return; } nodeIds = group.nodes; @@ -357,7 +367,7 @@ export function createJournalRouter( clearInterval(heartbeat); if (!res.writableEnded) { send("complete", {}); - res.end(); + await authorization.finish(() => { res.end(); }); } } })(); @@ -400,9 +410,18 @@ export function createJournalRouter( res.setHeader("X-Accel-Buffering", "no"); res.flushHeaders(); + const authorization = new SessionAuthorization(async () => { + if (!req.revalidateAuth || !req.user) throw new Error('Authentication required'); + await req.revalidateAuth(); + if (!await new PermissionService(db).hasPermission(req.user.userId, 'journal', 'read')) { + throw new Error('Journal permission revoked'); + } + }, () => { res.end(); }); + res.on('close', () => { authorization.close(); }); + function send(eventName: string, data: unknown): void { if (res.writableEnded) return; - res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`); + authorization.run(() => { if (!res.writableEnded) res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`); }); } // Heartbeat to prevent proxies from closing idle connections @@ -616,11 +635,11 @@ export function createJournalRouter( } } - await Promise.all(tasks).finally(() => { + await Promise.all(tasks).finally(async () => { clearInterval(heartbeat); if (!res.writableEnded) { send("complete", {}); - res.end(); + await authorization.finish(() => { res.end(); }); } }); })(); diff --git a/backend/src/routes/ldapAdministration.ts b/backend/src/routes/ldapAdministration.ts new file mode 100644 index 00000000..3b95c4e8 --- /dev/null +++ b/backend/src/routes/ldapAdministration.ts @@ -0,0 +1,146 @@ +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { Router, type Request, type Response, type NextFunction } from 'express'; +import rateLimit from 'express-rate-limit'; +import { z } from 'zod'; +import type { DatabaseService } from '../database/DatabaseService'; +import { type DIContainer, resolveAuthenticationService } from '../container/DIContainer'; +import type { LdapDirectoryGroup, LdapDirectoryService } from '../services/LdapDirectoryService'; +import { LdapDirectoryError } from '../services/LdapDirectoryService'; +import { LdapAdministrationError, type LdapAuditActor, type LdapMappingService } from '../services/LdapMappingService'; +import { createAuthMiddleware } from '../middleware/authMiddleware'; +import { createRbacMiddleware } from '../middleware/rbacMiddleware'; +import { createRateLimitMiddleware } from '../middleware/securityMiddleware'; +import { asyncHandler } from './asyncHandler'; + +const text = z.string().min(1).max(1024).refine(value => Buffer.byteLength(value) <= 1024); +const subject = z.string().uuid(); +const searchSchema = z.object({ query: text, cursor: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict(); +const createSchema = z.object({ groupSubject: subject, roleId: z.string().min(1).max(128) }).strict(); +const updateSchema = z.object({ roleId: z.string().min(1).max(128).optional(), enabled: z.boolean().optional() }) + .strict().refine(value => value.roleId !== undefined || value.enabled !== undefined); +const diagnosticSchema = z.object({ username: text.optional(), groupSubjects: z.array(subject).max(20).optional() }) + .strict().refine(value => !value.groupSubjects?.length || value.username !== undefined); + +function actor(req: Request): LdapAuditActor { + assert(req.user, 'LDAP administration requires an authenticated audit actor'); + return { userId: req.user.userId, ip: req.ip, userAgent: req.headers['user-agent'] }; +} + +function directoryStatus(code: string): number { + if (code === 'BUSY') return 429; + if (['INVALID_IDENTITY', 'INELIGIBLE', 'IDENTITY_CHANGED'].includes(code)) return 422; + return 503; +} + +export function createLdapAdministrationRouter(database: DatabaseService, container: DIContainer): Router { + const router = Router(); + const db = database.getAdapter(); + const logger = container.resolve('logger'); + const services = (): { directory: LdapDirectoryService; mappings: LdapMappingService } => { + const directory = container.resolve('ldapDirectory'); + const mappings = container.resolve('ldapMappings'); + assert(directory && mappings, 'LDAP administration requires configured services'); + return { directory, mappings }; + }; + const guards = [ + asyncHandler(createAuthMiddleware(resolveAuthenticationService(db, container))), + asyncHandler(createRbacMiddleware(db)('rbac', 'admin')), + createRateLimitMiddleware(), + (_req: Request, res: Response, next: NextFunction): void => { + res.setHeader('Cache-Control', 'no-store'); + if (!container.has('ldapDirectory') || !container.has('ldapMappings')) { + res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Not found' } }); + return; + } + next(); + }, + ]; + const diagnosticsLimit = rateLimit({ + windowMs: 60_000, limit: 10, keyGenerator: req => actor(req).userId, + standardHeaders: true, legacyHeaders: false, + message: { error: { code: 'RATE_LIMITED', message: 'LDAP diagnostic limit reached' } }, + }); + interface Page { groups: LdapDirectoryGroup[]; offset: number; query: string; actorId: string; expires: number } + const pages = new Map(); + const pageSize = 50; + const page = (snapshot: Page): { items: LdapDirectoryGroup[]; nextCursor: string | null } => { + const items = snapshot.groups.slice(snapshot.offset, snapshot.offset + pageSize); + let nextCursor: string | null = null; + if (snapshot.offset + items.length < snapshot.groups.length) { + nextCursor = randomBytes(32).toString('hex'); + for (const [key, value] of pages) if (value.expires <= Date.now()) pages.delete(key); + while (pages.size >= 64) { const oldest = pages.keys().next().value; if (oldest) pages.delete(oldest); } + pages.set(nextCursor, { ...snapshot, offset: snapshot.offset + items.length }); + } + return { items, nextCursor }; + }; + + router.get('/groups', ...guards, asyncHandler(async (req, res): Promise => { + const input = searchSchema.parse(req.query); + const userId = actor(req).userId; + if (input.cursor) { + const snapshot = pages.get(input.cursor); + if (!snapshot || snapshot.expires <= Date.now() || snapshot.query !== input.query || snapshot.actorId !== userId) { + throw new LdapAdministrationError('INVALID_CURSOR'); + } + res.json(page(snapshot)); + } else { + const groups = await services().directory.searchGroups(input.query); + res.json(page({ groups, offset: 0, query: input.query, actorId: userId, expires: Date.now() + 60_000 })); + } + })); + + router.get('/mappings', ...guards, asyncHandler(async (req, res): Promise => { + z.object({}).strict().parse(req.query); + res.json({ items: await services().mappings.list() }); + })); + + router.post('/mappings', ...guards, asyncHandler(async (req, res): Promise => { + const input = createSchema.parse(req.body); + const mapping = await services().mappings.create(input.groupSubject, input.roleId, actor(req)); + res.status(201).json(mapping); + })); + + router.put('/mappings/:id', ...guards, asyncHandler(async (req, res): Promise => { + const input = updateSchema.parse(req.body); + res.json(await services().mappings.update(req.params.id, input, actor(req))); + })); + + router.delete('/mappings/:id', ...guards, asyncHandler(async (req, res): Promise => { + await services().mappings.remove(req.params.id, actor(req)); + res.sendStatus(204); + })); + + router.post('/test', ...guards, diagnosticsLimit, asyncHandler(async (req, res): Promise => { + const input = diagnosticSchema.parse(req.body); + const mappings = await services().mappings.list(); + const mapped = new Set(mappings.filter(mapping => mapping.enabled).map(mapping => mapping.groupSubject)); + if (input.groupSubjects?.some(value => !mapped.has(value.toLowerCase()))) { + res.status(400).json({ error: { code: 'INVALID_GROUP_SELECTION', message: 'Select enabled mapped groups' } }); + return; + } + const result = await services().directory.diagnose(input); + const failure = result.stages.find(stage => stage.status === 'failed'); + res.status(failure ? directoryStatus(failure.code ?? 'UNAVAILABLE') : 200).json(result); + })); + + router.use((error: unknown, _req: Request, res: Response, _next: NextFunction): void => { + if (error instanceof z.ZodError) { + res.status(400).json({ error: { code: 'VALIDATION_ERROR', message: 'Invalid LDAP administration request' } }); + return; + } + if (error instanceof LdapAdministrationError) { + const status = error.code === 'NOT_FOUND' ? 404 : error.code === 'INVALID_CURSOR' ? 400 : 409; + res.status(status).json({ error: { code: error.code, message: 'LDAP administration request failed' } }); + return; + } + if (error instanceof LdapDirectoryError) { + res.status(directoryStatus(error.code)).json({ error: { code: error.code, message: 'LDAP directory operation failed' } }); + return; + } + logger.error('LDAP administration request failed', { component: 'LdapAdministrationRouter', operation: 'request' }); + res.status(500).json({ error: { code: 'INTERNAL_SERVER_ERROR', message: 'LDAP administration request failed' } }); + }); + return router; +} diff --git a/backend/src/routes/permissions.ts b/backend/src/routes/permissions.ts index eb75ba96..e70d7da7 100644 --- a/backend/src/routes/permissions.ts +++ b/backend/src/routes/permissions.ts @@ -9,7 +9,7 @@ import { sendValidationError, ERROR_CODES } from "../utils/errorHandling"; import { ZodError } from "zod"; import { createAuthMiddleware } from "../middleware/authMiddleware"; import { createRbacMiddleware } from "../middleware/rbacMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; /** * Zod schema for pagination query parameters @@ -38,11 +38,9 @@ export function createPermissionsRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const configService = container.resolve("config"); - const jwtSecret = configService.getJwtSecret(); const auditLogger = new AuditLoggingService(databaseService.getAdapter()); const permissionService = new PermissionService(databaseService.getAdapter()); - const authMiddleware = createAuthMiddleware(databaseService.getAdapter(), jwtSecret); + const authMiddleware = createAuthMiddleware(resolveAuthenticationService(databaseService.getAdapter(), container)); const rbacMiddleware = createRbacMiddleware(databaseService.getAdapter()); /** diff --git a/backend/src/routes/roles.ts b/backend/src/routes/roles.ts index 54366cea..40b87bac 100644 --- a/backend/src/routes/roles.ts +++ b/backend/src/routes/roles.ts @@ -10,7 +10,7 @@ import { sendValidationError, ERROR_CODES } from "../utils/errorHandling"; import { ZodError } from "zod"; import { createAuthMiddleware } from "../middleware/authMiddleware"; import { createRbacMiddleware } from "../middleware/rbacMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; /** * Zod schema for pagination query parameters @@ -46,12 +46,10 @@ export function createRolesRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const configService = container.resolve("config"); - const jwtSecret = configService.getJwtSecret(); const roleService = new RoleService(databaseService.getAdapter()); const auditLogger = new AuditLoggingService(databaseService.getAdapter()); const permissionService = new PermissionService(databaseService.getAdapter()); - const authMiddleware = createAuthMiddleware(databaseService.getAdapter(), jwtSecret); + const authMiddleware = createAuthMiddleware(resolveAuthenticationService(databaseService.getAdapter(), container)); const rbacMiddleware = createRbacMiddleware(databaseService.getAdapter()); /** diff --git a/backend/src/routes/setup.ts b/backend/src/routes/setup.ts index 6252da88..9926b81c 100644 --- a/backend/src/routes/setup.ts +++ b/backend/src/routes/setup.ts @@ -3,9 +3,7 @@ import { tokensEqual } from "../utils/tokensEqual"; import { z } from "zod"; import { asyncHandler } from "./asyncHandler"; import { UserService } from "../services/UserService"; -import { AuthenticationService } from "../services/AuthenticationService"; import { SetupService } from "../services/SetupService"; -import { AuditLoggingService } from "../services/AuditLoggingService"; import type { DatabaseService } from "../database/DatabaseService"; import { sendValidationError, @@ -19,7 +17,7 @@ import { } from "../utils/errorHandling"; import { ZodError } from "zod"; import { createAuthRateLimitMiddleware } from "../middleware/securityMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; /** * Zod schema for initial setup @@ -66,9 +64,7 @@ export function createSetupRouter( const router = Router(); const logger = container.resolve("logger"); const configService = container.resolve("config"); - const jwtSecret = configService.getJwtSecret(); - const auditLogger = new AuditLoggingService(databaseService.getAdapter()); - const authService = new AuthenticationService(databaseService.getAdapter(), jwtSecret, auditLogger); + const authService = resolveAuthenticationService(databaseService.getAdapter(), container); const userService = new UserService(databaseService.getAdapter(), authService); const setupService = new SetupService(databaseService.getAdapter()); diff --git a/backend/src/routes/users.ts b/backend/src/routes/users.ts index 56167047..b0efcf63 100644 --- a/backend/src/routes/users.ts +++ b/backend/src/routes/users.ts @@ -3,15 +3,14 @@ import { AuditLoggingService } from "../services/AuditLoggingService"; import { Router, type Request, type Response } from "express"; import { z } from "zod"; import { asyncHandler } from "./asyncHandler"; -import { UserService } from "../services/UserService"; -import { AuthenticationService } from "../services/AuthenticationService"; +import { FederatedAccountError, UserService } from "../services/UserService"; import { PermissionService } from "../services/PermissionService"; import type { DatabaseService } from "../database/DatabaseService"; import { sendValidationError, ERROR_CODES } from "../utils/errorHandling"; import { ZodError } from "zod"; import { createAuthMiddleware } from "../middleware/authMiddleware"; import { createRbacMiddleware } from "../middleware/rbacMiddleware"; -import { type DIContainer, createDefaultContainer } from "../container/DIContainer"; +import { type DIContainer, createDefaultContainer, resolveAuthenticationService } from "../container/DIContainer"; /** * Zod schema for pagination query parameters @@ -55,13 +54,11 @@ export function createUsersRouter( ): Router { const router = Router(); const logger = container.resolve("logger"); - const configService = container.resolve("config"); - const jwtSecret = configService.getJwtSecret(); - const authService = new AuthenticationService(databaseService.getAdapter(), jwtSecret); + const authService = resolveAuthenticationService(databaseService.getAdapter(), container); const userService = new UserService(databaseService.getAdapter(), authService); const auditLogger = new AuditLoggingService(databaseService.getAdapter()); const permissionService = new PermissionService(databaseService.getAdapter()); - const authMiddleware = createAuthMiddleware(databaseService.getAdapter(), jwtSecret); + const authMiddleware = createAuthMiddleware(authService); const rbacMiddleware = createRbacMiddleware(databaseService.getAdapter()); /** @@ -239,7 +236,11 @@ export function createUsersRouter( }); // Convert users to DTOs (remove passwords) - const userDTOs = result.items.map(user => userService.toUserDTO(user)); + const metadata = await userService.getAdministrationMetadata( + result.items, container.resolve('config').getLdapConfig() ?? undefined); + const userDTOs = result.items.map(user => ({ + ...userService.toUserDTO(user), authentication: metadata.get(user.id), + })); // Calculate total pages const totalPages = Math.ceil(result.total / validatedQuery.limit); @@ -351,9 +352,15 @@ export function createUsersRouter( }, }); + const metadata = await userService.getAdministrationMetadata( + [user], container.resolve('config').getLdapConfig() ?? undefined); + const roleSources = await userService.getUserRoleSources(userId); + // Return user with groups and roles res.status(200).json({ ...userDTO, + authentication: metadata.get(userId), + roleSources, groups: groups, roles: roles, }); @@ -477,6 +484,10 @@ export function createUsersRouter( // Return updated user res.status(200).json(userDTO); } catch (error) { + if (error instanceof FederatedAccountError && error.code === 'DIRECTORY_ACCOUNT_READ_ONLY') { + res.status(403).json({ error: { code: error.code, message: error.message } }); + return; + } // Handle user not found if (error instanceof Error && error.message === 'User not found') { logger.warn("User not found for update", { diff --git a/backend/src/server.ts b/backend/src/server.ts index d55ecc7e..f0153c29 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -18,6 +18,10 @@ import { createLogsRouter } from "./routes/logs"; import { createConfigRouter } from "./routes/config"; import { asyncHandler } from "./routes/asyncHandler"; import { createAuthRouter } from "./routes/auth"; +import { createLdapAdministrationRouter } from "./routes/ldapAdministration"; +import { LdapAuthenticationService } from "./services/LdapAuthenticationService"; +import { LdapDirectoryService } from "./services/LdapDirectoryService"; +import { LdapMappingService } from "./services/LdapMappingService"; import { createSetupRouter } from "./routes/setup"; import { createUsersRouter } from "./routes/users"; import { createGroupsRouter } from "./routes/groups"; @@ -66,10 +70,9 @@ import { LoggerService } from "./services/LoggerService"; import { LogBufferService } from "./services/LogBufferService"; import { ExpertModeService } from "./services/ExpertModeService"; import { PerformanceMonitorService } from "./services/PerformanceMonitorService"; -import { DIContainer } from "./container/DIContainer"; +import { DIContainer, resolveAuthenticationService } from "./container/DIContainer"; import { PuppetRunHistoryService } from "./services/PuppetRunHistoryService"; import { JournalService, type LiveSource } from "./services/journal/JournalService"; -import { AuthenticationService } from "./services/AuthenticationService"; import { UserService } from "./services/UserService"; import { RoleService } from "./services/RoleService"; import { PermissionService } from "./services/PermissionService"; @@ -600,16 +603,31 @@ async function startServer(): Promise { res.status(overall === "ok" ? 200 : 503).json({ status: overall, message: "Backend API is running", - version: "1.5.0", + version: "1.6.0", checks: { database: dbError ? { status: dbStatus, error: dbError } : { status: dbStatus }, }, }); })); + const authService = resolveAuthenticationService(databaseService.getAdapter(), container); + // Setup routes (no authentication required - only accessible when setup is incomplete) app.use("/api/setup", createSetupRouter(databaseService, container)); + const ldapConfig = configService.getLdapConfig(); + if (ldapConfig) { + const directory = new LdapDirectoryService(ldapConfig, logger); + container.register("ldapDirectory", directory); + const mappings = new LdapMappingService(databaseService.getAdapter(), ldapConfig.directoryId, directory); + container.register("ldapMappings", mappings); + const ldapAuthentication = new LdapAuthenticationService(databaseService.getAdapter(), ldapConfig, directory, + mappings, new UserService(databaseService.getAdapter(), authService)); + await ldapAuthentication.initialize(); + container.register('ldapAuthentication', ldapAuthentication); + } + app.use("/api/auth/ldap", createLdapAdministrationRouter(databaseService, container)); + // Authentication routes with stricter rate limiting const authRateLimitMiddleware = createAuthRateLimitMiddleware(); app.use("/api/auth", authRateLimitMiddleware, createRefreshRateLimitMiddleware(), createAuthRouter(databaseService, container)); @@ -625,11 +643,6 @@ async function startServer(): Promise { try { const auditLogger = new AuditLoggingService(databaseService.getAdapter()); - const authService = new AuthenticationService( - databaseService.getAdapter(), - configService.getJwtSecret(), - auditLogger, - ); const userService = new UserService(databaseService.getAdapter(), authService); const roleService = new RoleService(databaseService.getAdapter()); @@ -680,7 +693,7 @@ async function startServer(): Promise { // Create authentication and RBAC middleware instances // Wrap async middleware with asyncHandler to satisfy Express's void return expectation - const authMiddleware = asyncHandler(createAuthMiddleware(databaseService.getAdapter(), configService.getJwtSecret())); + const authMiddleware = asyncHandler(createAuthMiddleware(authService)); const rawRbacMiddleware = createRbacMiddleware(databaseService.getAdapter()); const rbacMiddleware = (resource: string, action: string): express.RequestHandler => asyncHandler(rawRbacMiddleware(resource, action)); @@ -695,9 +708,8 @@ async function startServer(): Promise { let inventoryAuthMiddleware = authMiddleware; const lifecycleToken = configService.getLifecycleToken(); if (lifecycleToken) { - const lifecycleAuthService = new AuthenticationService(databaseService.getAdapter(), configService.getJwtSecret()); const { userId: lifecycleUserId } = await provisionLifecycleServiceUser( - new UserService(databaseService.getAdapter(), lifecycleAuthService), + new UserService(databaseService.getAdapter(), authService), new RoleService(databaseService.getAdapter()), new PermissionService(databaseService.getAdapter()), logger, @@ -827,7 +839,6 @@ async function startServer(): Promise { }); try { - const authService = new AuthenticationService(databaseService.getAdapter(), configService.getJwtSecret()); const userService = new UserService(databaseService.getAdapter(), authService); const roleService = new RoleService(databaseService.getAdapter()); const permissionService = new PermissionService(databaseService.getAdapter()); @@ -881,6 +892,7 @@ async function startServer(): Promise { consoleConfig, logger, auditLoggingService, + authService, consoleConnectionBroker, // Every termination path goes through the manager, which has no plugin // registry of its own; without this bridge a provider keeps its session diff --git a/backend/src/services/AuthenticationService.ts b/backend/src/services/AuthenticationService.ts index 609a1599..04895f37 100644 --- a/backend/src/services/AuthenticationService.ts +++ b/backend/src/services/AuthenticationService.ts @@ -5,6 +5,7 @@ import crypto from 'crypto'; import type { AuditLoggingService } from './AuditLoggingService'; import { performanceMonitor } from './PerformanceMonitor'; import { LoggerService } from './LoggerService'; +import { ldapAuthenticationFailure } from './LdapAuthenticationService'; /** * Authentication result returned after successful authentication @@ -15,12 +16,43 @@ export interface AuthResult { refreshToken?: string; user?: UserDTO; error?: string; + errorStatus?: number; + errorCode?: string; +} + +export type AuthenticationContext = + | { provider: 'local'; identityId: null } + | { provider: 'entra-id'; identityId: string } + | { provider: 'ldap'; identityId: string; directoryId: string }; + +export type LdapSessionEligibility = (userId: string, identityId: string, directoryId: string, + expectedVersion: string, force: boolean) => Promise; + +export class InvalidAuthenticationContextError extends Error { + readonly code = 'INVALID_TOKEN'; + + constructor() { + super('Invalid token'); + this.name = 'InvalidAuthenticationContextError'; + } +} + +export function isAuthenticationContext(value: unknown): value is AuthenticationContext { + if (typeof value !== 'object' || value === null) return false; + const context = value as Record; + if (context.provider === 'ldap') return Object.keys(context).length === 3 && + typeof context.identityId === 'string' && context.identityId.length > 0 && + typeof context.directoryId === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(context.directoryId); + if (Object.keys(context).length !== 2) return false; + return (context.provider === 'local' && context.identityId === null) || + (context.provider === 'entra-id' && typeof context.identityId === 'string' && context.identityId.length > 0); } /** * JWT token payload structure */ export interface TokenPayload { + authContext: AuthenticationContext; userId: string; username: string; roles: string[]; @@ -37,7 +69,8 @@ export interface TokenPayload { export interface UserDTO { id: string; username: string; - email: string; + email: string | null; + displayName: string | null; firstName: string; lastName: string; isActive: boolean; @@ -53,8 +86,9 @@ export interface UserDTO { interface User { id: string; username: string; - email: string; - passwordHash: string; + email: string | null; + displayName: string | null; + passwordHash: string | null; sessionVersion: string; firstName: string; lastName: string; @@ -69,6 +103,7 @@ interface User { * Refresh token payload structure */ interface RefreshTokenPayload { + authContext: AuthenticationContext; userId: string; username: string; type: 'refresh'; @@ -115,6 +150,7 @@ export class AuthenticationService { jwtSecret?: string, auditLogger?: AuditLoggingService, bcryptCostFactor?: number, + private readonly ldapEligibility?: LdapSessionEligibility, ) { this.db = db; this.auditLogger = auditLogger; @@ -265,7 +301,7 @@ export class AuthenticationService { await this.clearFailedLoginAttempts(username); // Generate tokens - const { token, refreshToken } = await this.generateTokenPair(user, sessionVersion); + const { token, refreshToken } = await this.generateTokenPair(user, { provider: 'local', identityId: null }, sessionVersion); // Update last login timestamp await this.updateLastLogin(user.id); @@ -319,10 +355,11 @@ export class AuthenticationService { } } - public async generateTokenPair(user: Pick, expectedVersion?: string): Promise<{ token: string; refreshToken: string }> { - const version = expectedVersion ?? await this.getActiveSessionVersion(user.id); - const token = await this.generateToken(user, version); - const refreshToken = await this.generateRefreshToken(user, version); + public async generateTokenPair(user: Pick, context: AuthenticationContext, expectedVersion?: string): Promise<{ token: string; refreshToken: string }> { + const version = await this.assertSessionEligible(user.id, context, expectedVersion); + const token = await this.generateToken(user, context, version); + const refreshToken = await this.generateRefreshToken(user, context, version); + await this.assertSessionEligible(user.id, context, version); return { token, refreshToken }; } @@ -332,13 +369,13 @@ export class AuthenticationService { * @param user - User object * @returns JWT access token string */ - public async generateToken(user: Pick, expectedVersion?: string): Promise { - const sessionVersion = await this.getActiveSessionVersion(user.id); - if (expectedVersion !== undefined && expectedVersion !== sessionVersion) throw new Error('Token has been revoked'); + public async generateToken(user: Pick, context: AuthenticationContext, expectedVersion?: string): Promise { + const sessionVersion = await this.assertSessionEligible(user.id, context, expectedVersion); // Fetch user roles for token const roles = await this.getUserRoles(user.id); const payload: TokenPayload = { + authContext: context, userId: user.id, username: user.username, roles: roles, @@ -362,10 +399,10 @@ export class AuthenticationService { * @param user - User object * @returns JWT refresh token string */ - public async generateRefreshToken(user: Pick, expectedVersion?: string): Promise { - const sessionVersion = await this.getActiveSessionVersion(user.id); - if (expectedVersion !== undefined && expectedVersion !== sessionVersion) throw new Error('Token has been revoked'); + public async generateRefreshToken(user: Pick, context: AuthenticationContext, expectedVersion?: string): Promise { + const sessionVersion = await this.assertSessionEligible(user.id, context, expectedVersion); const payload = { + authContext: context, userId: user.id, username: user.username, type: 'refresh', @@ -401,9 +438,7 @@ export class AuthenticationService { !Array.isArray(payload.roles) || !payload.roles.every((role: unknown) => typeof role === 'string')) { throw new Error('Invalid token'); } - if (payload.sessionVersion !== await this.getActiveSessionVersion(payload.userId)) { - throw new Error('Token has been revoked'); - } + await this.assertSessionEligible(payload.userId, payload.authContext, payload.sessionVersion); // Check if token is revoked const isRevoked = await this.isTokenRevoked(token); @@ -451,9 +486,7 @@ export class AuthenticationService { return { success: false, error: 'Invalid refresh token' }; } - if (payload.sessionVersion !== await this.getActiveSessionVersion(payload.userId)) { - return { success: false, error: 'Refresh token has been revoked' }; - } + await this.assertSessionEligible(payload.userId, payload.authContext, payload.sessionVersion, true); // Reuse detection: a revoked refresh token being presented is treated // as compromise — revoke the entire token family for this user. @@ -478,7 +511,7 @@ export class AuthenticationService { // Order matters — revoke first so a concurrent reuse will see the revoked state. await this.revokeToken(refreshToken); - const { token: newAccessToken, refreshToken: newRefreshToken } = await this.generateTokenPair(user, payload.sessionVersion); + const { token: newAccessToken, refreshToken: newRefreshToken } = await this.generateTokenPair(user, payload.authContext, payload.sessionVersion); return { success: true, @@ -492,6 +525,11 @@ export class AuthenticationService { } else if (error instanceof jwt.JsonWebTokenError) { return { success: false, error: 'Invalid refresh token' }; } + if (error instanceof Error && error.message === 'Token has been revoked') { + return { success: false, error: 'Refresh token has been revoked' }; + } + const failure = ldapAuthenticationFailure(error); + if (failure) return { success: false, error: failure.message, errorStatus: failure.status, errorCode: failure.code }; return { success: false, error: error instanceof Error && error.message === 'User not found or inactive' ? error.message : 'Token refresh failed' }; } } @@ -513,8 +551,8 @@ export class AuthenticationService { * @param hash - Bcrypt hash * @returns True if password matches hash */ - public async comparePassword(password: string, hash: string): Promise { - return bcrypt.compare(password, hash); + public async comparePassword(password: string, hash: string | null): Promise { + return hash === null ? false : bcrypt.compare(password, hash); } /** @@ -524,7 +562,7 @@ export class AuthenticationService { * @param hash - Bcrypt hash * @returns True if password matches hash */ - public async verifyPassword(password: string, hash: string): Promise { + public async verifyPassword(password: string, hash: string | null): Promise { return this.comparePassword(password, hash); } @@ -570,17 +608,37 @@ export class AuthenticationService { ); } - private async getActiveSessionVersion(userId: string): Promise { - const user = await this.db.queryOne<{ isActive: number; sessionVersion: string }>( - 'SELECT is_active AS "isActive", session_version AS "sessionVersion" FROM users WHERE id = ?', + /** Common account/provider eligibility boundary for token and transport checks. */ + public async assertSessionEligible(userId: string, context: AuthenticationContext, expectedVersion?: string, force = false): Promise { + if (!isAuthenticationContext(context)) throw new InvalidAuthenticationContextError(); + const user = await this.db.queryOne<{ isActive: number; sessionVersion: string; localAuthEnabled: number }>( + 'SELECT is_active AS "isActive", session_version AS "sessionVersion", local_auth_enabled AS "localAuthEnabled" FROM users WHERE id = ?', [userId], ); if (user?.isActive !== 1) throw new Error('User not found or inactive'); + if (expectedVersion !== undefined && expectedVersion !== user.sessionVersion) throw new Error('Token has been revoked'); + if (context.provider === 'local') { + if (user.localAuthEnabled !== 1) throw new InvalidAuthenticationContextError(); + } else { + const identity = await this.db.queryOne<{ id: string }>( + 'SELECT id FROM federated_identities WHERE id = ? AND user_id = ? AND provider = ?', + [context.identityId, userId, context.provider], + ); + if (!identity) throw new InvalidAuthenticationContextError(); + if (context.provider === 'ldap') { + if (!this.ldapEligibility) throw new InvalidAuthenticationContextError(); + await this.ldapEligibility(userId, context.identityId, context.directoryId, user.sessionVersion, force); + const current = await this.db.queryOne<{ sessionVersion: string; isActive: number }>( + 'SELECT session_version AS "sessionVersion", is_active AS "isActive" FROM users WHERE id = ?', [userId]); + if (current?.isActive !== 1 || current.sessionVersion !== user.sessionVersion) throw new Error('Token has been revoked'); + } + } return user.sessionVersion; } private isSessionPayload(payload: string | jwt.JwtPayload): payload is jwt.JwtPayload & (TokenPayload | RefreshTokenPayload) { return typeof payload !== 'string' && + isAuthenticationContext(payload.authContext) && typeof payload.userId === 'string' && payload.userId.length > 0 && typeof payload.username === 'string' && payload.username.length > 0 && typeof payload.jti === 'string' && payload.jti.length > 0 && @@ -631,6 +689,7 @@ export class AuthenticationService { return this.db.queryOne( `SELECT id, username, email, password_hash AS "passwordHash", + display_name AS "displayName", session_version AS "sessionVersion", first_name AS "firstName", last_name AS "lastName", @@ -639,7 +698,7 @@ export class AuthenticationService { created_at AS "createdAt", updated_at AS "updatedAt", last_login_at AS "lastLoginAt" - FROM users WHERE username = ?`, + FROM users WHERE username = ? AND local_auth_enabled = 1`, [username] ); } @@ -651,6 +710,7 @@ export class AuthenticationService { return this.db.queryOne( `SELECT id, username, email, password_hash AS "passwordHash", + display_name AS "displayName", session_version AS "sessionVersion", first_name AS "firstName", last_name AS "lastName", @@ -786,6 +846,20 @@ export class AuthenticationService { } } + private ldapLoginKey(directoryId: string, login: string): string { + return 'ldap:' + crypto.createHash('sha256').update(JSON.stringify(['ldap', directoryId, login])).digest('hex'); + } + + public async isLdapLoginLocked(directoryId: string, login: string): Promise { + return (await this.checkAccountLockout(this.ldapLoginKey(directoryId, login))).isLocked; + } + + public async recordLdapLoginOutcome(directoryId: string, login: string, success: boolean, ip?: string): Promise { + const key = this.ldapLoginKey(directoryId, login); + if (success) await this.clearFailedLoginAttempts(key); + else await this.recordFailedLoginAttempt(key, 'INVALID_CREDENTIALS', ip); + } + /** * Record a failed login attempt and apply lockout if necessary * @@ -826,7 +900,7 @@ export class AuthenticationService { `INSERT INTO login_attempt_counters (username, cumulative_failed_attempts, last_failed_at) VALUES (?, 1, ?) ON CONFLICT(username) DO UPDATE SET - cumulative_failed_attempts = cumulative_failed_attempts + 1, + cumulative_failed_attempts = login_attempt_counters.cumulative_failed_attempts + 1, last_failed_at = excluded.last_failed_at`, [username, timestamp] ); @@ -1018,6 +1092,7 @@ export class AuthenticationService { id: user.id, username: user.username, email: user.email, + displayName: user.displayName, firstName: user.firstName, lastName: user.lastName, isActive: user.isActive === 1, diff --git a/backend/src/services/ConsoleSessionManager.ts b/backend/src/services/ConsoleSessionManager.ts index 79360214..3c085262 100644 --- a/backend/src/services/ConsoleSessionManager.ts +++ b/backend/src/services/ConsoleSessionManager.ts @@ -1,4 +1,5 @@ import { PermissionService } from "./PermissionService"; +import { isAuthenticationContext, type AuthenticationService, type AuthenticationContext } from './AuthenticationService'; import { randomBytes, randomUUID } from "crypto"; import type { ConsoleConfig } from "../config/schema"; @@ -110,6 +111,7 @@ export class ConsoleSessionManager { private config: ConsoleConfig, private logger: LoggerService, private auditLogger: AuditLoggingService, + private authentication: Pick, private broker?: ConsoleConnectionBroker, private providerCleanup?: ConsoleProviderCleanup, ) { @@ -117,13 +119,18 @@ export class ConsoleSessionManager { } async assertSessionAuthorized(sessionId: string): Promise { - const session = await this.db.queryOne<{ userId: string }>( - `SELECT c.user_id AS "userId" FROM console_sessions c JOIN users u ON u.id = c.user_id + const session = await this.db.queryOne<{ userId: string; authContext: string | null; sessionVersion: string }>( + `SELECT c.user_id AS "userId", c.auth_context AS "authContext", c.session_version AS "sessionVersion" + FROM console_sessions c JOIN users u ON u.id = c.user_id WHERE c.id = ? AND c.state IN ('creating', 'active') AND u.is_active = 1 AND c.session_version = u.session_version`, [sessionId], ); - if (!session || !await this.permissionService.hasPermission(session.userId, 'console', 'access')) { + if (!session?.authContext) throw new ConsoleAccountError('Console session authorization revoked'); + const context: unknown = JSON.parse(session.authContext); + if (!isAuthenticationContext(context)) throw new ConsoleAccountError('Console session authorization revoked'); + await this.authentication.assertSessionEligible(session.userId, context, session.sessionVersion); + if (!await this.permissionService.hasPermission(session.userId, 'console', 'access')) { throw new Error('Console session authorization revoked'); } } @@ -155,7 +162,10 @@ export class ConsoleSessionManager { nodeId: string; provider: string; transport: ConsoleTransport; + authContext: AuthenticationContext; + sessionVersion: string; }): Promise { + await this.authentication.assertSessionEligible(request.userId, request.authContext, request.sessionVersion); const sessionId = randomUUID(); const token = this.generateToken(); const now = new Date().toISOString(); @@ -166,8 +176,8 @@ export class ConsoleSessionManager { // explicit row lock. const account = await this.db.queryOne<{ sessionVersion: string }>( `SELECT session_version AS "sessionVersion" FROM users - WHERE id = ? AND is_active = 1${this.db.getDialect() === "postgres" ? " FOR UPDATE" : ""}`, - [request.userId], + WHERE id = ? AND is_active = 1 AND session_version = ?${this.db.getDialect() === "postgres" ? " FOR UPDATE" : ""}`, + [request.userId, request.sessionVersion], ); if (!account) throw new ConsoleAccountError("User not found or inactive"); @@ -186,11 +196,11 @@ export class ConsoleSessionManager { `INSERT INTO console_sessions ( id, user_id, node_id, provider, transport, state, token, token_created_at, token_consumed, - started_at, last_heartbeat_at, session_version - ) VALUES (?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?)`, + started_at, last_heartbeat_at, session_version, auth_context + ) VALUES (?, ?, ?, ?, ?, 'creating', ?, ?, 0, ?, ?, ?, ?)`, [ sessionId, request.userId, request.nodeId, request.provider, request.transport, - token, now, now, now, account.sessionVersion, + token, now, now, now, account.sessionVersion, JSON.stringify(request.authContext), ], ); }); diff --git a/backend/src/services/EntraIdService.ts b/backend/src/services/EntraIdService.ts index 8fcd04dd..64d012c8 100644 --- a/backend/src/services/EntraIdService.ts +++ b/backend/src/services/EntraIdService.ts @@ -5,7 +5,7 @@ import jwt from 'jsonwebtoken'; import type { DatabaseAdapter } from '../database/DatabaseAdapter'; import type { EntraIdConfig } from '../config/schema'; import type { AuthenticationService } from './AuthenticationService'; -import type { UserService, User } from './UserService'; +import { FederatedAccountError, type UserService, type User } from './UserService'; import type { UserDTO } from './UserService'; import type { RoleService } from './RoleService'; import type { AuditLoggingService } from './AuditLoggingService'; @@ -277,7 +277,12 @@ export class EntraIdService { const user = await this.provisionUser(claims); // 9. Sync group-to-role mapping - await this.syncGroupRoles(user.id, claims.groupsUnavailable ? [] : claims.groups); + const identity = await this.db.queryOne<{ id: string }>( + 'SELECT id FROM federated_identities WHERE user_id = ? AND provider = ? AND issuer = ? AND subject = ?', + [user.id, 'entra-id', claims.iss, claims.sub], + ); + if (!identity) throw new EntraIdError(ENTRA_ID_ERROR_CODES.PROVISIONING_FAILED, 'Authenticating identity is missing'); + await this.syncGroupRoles(identity.id, claims.groupsUnavailable ? [] : claims.groups); if (claims.groupsUnavailable && this.config.groupMapping) { throw new EntraIdError(ENTRA_ID_ERROR_CODES.GROUPS_UNAVAILABLE, "Complete group membership is required for login"); } @@ -285,6 +290,7 @@ export class EntraIdService { // 10. Issue session tokens and generate auth code const authCodeEntry = await this.issueSessionTokens( user, + identity.id, tokenResponse.id_token, browserBinding, ); @@ -334,7 +340,7 @@ export class EntraIdService { return existingUser; } - if (claims.email && await this.userService.findByEmail(claims.email)) { + if (claims.email && (await this.userService.findAllByEmail(claims.email)).length > 0) { const winner = await this.userService.findByFederatedIdentity('entra-id', claims.sub, claims.iss); if (winner) { this.requireActiveUser(winner); @@ -345,7 +351,16 @@ export class EntraIdService { // 6. No match — create new federated user try { - const newUser = await this.userService.createFederatedUser(claims); + const newUser = await this.userService.createFederatedUser({ + provider: 'entra-id', issuer: claims.iss, subject: claims.sub, + username: /^[a-zA-Z0-9_]{3,50}$/.test(claims.preferred_username) + ? claims.preferred_username + : claims.email.split('@')[0].replace(/[^a-zA-Z0-9_]/g, '_').slice(0, 50), + email: claims.email || null, displayName: null, + firstName: claims.given_name || '', lastName: claims.family_name || '', + defaultRole: 'configured', + }); + this.requireActiveUser(newUser); this.logger.info('New federated user created', { ...logMeta, @@ -359,6 +374,9 @@ export class EntraIdService { this.requireActiveUser(winner); return winner; } + if (err instanceof FederatedAccountError && err.code === 'IDENTITY_COLLISION') { + throw new EntraIdError(ENTRA_ID_ERROR_CODES.IDENTITY_COLLISION, err.message); + } const message = err instanceof Error ? err.message : String(err); this.logger.error('Failed to create federated user', { ...logMeta, @@ -391,6 +409,7 @@ export class EntraIdService { */ private async issueSessionTokens( user: User, + identityId: string, idToken: string, browserBinding: string, ): Promise { @@ -398,7 +417,7 @@ export class EntraIdService { this.requireActiveUser(user); // 1. Generate Pabawi JWT tokens - const { token: accessToken, refreshToken } = await this.authService.generateTokenPair(user); + const { token: accessToken, refreshToken } = await this.authService.generateTokenPair(user, { provider: 'entra-id', identityId }); // 2. Generate single-use authorization code (32 bytes of entropy) const authCode = randomBytes(32).toString('hex'); @@ -784,20 +803,26 @@ export class EntraIdService { } /** Replace only provider-owned grants, including grants from removed mappings. */ - async syncGroupRoles(userId: string, groups: string[] | undefined): Promise { + async syncGroupRoles(identityId: string, groups: string[] | undefined): Promise { await this.db.withTransaction(async () => { + const identity = await this.db.queryOne<{ userId: string }>( + `SELECT user_id AS "userId" FROM federated_identities WHERE id = ? AND provider = 'entra-id' AND issuer = ?`, + [identityId, `https://login.microsoftonline.com/${this.config.tenantId}/v2.0`], + ); + if (!identity) throw new EntraIdError(ENTRA_ID_ERROR_CODES.PROVISIONING_FAILED, 'Authenticating identity is missing'); + const { userId } = identity; // Serialize reconciliation of this account across PostgreSQL connections. await this.db.execute('UPDATE users SET updated_at = updated_at WHERE id = ?', [userId]); await this.db.execute(`DELETE FROM user_roles WHERE user_id = ? AND role_id IN (SELECT role_id FROM legacy_federated_user_roles WHERE user_id = ?)`, [userId, userId]); - await this.db.execute('DELETE FROM federated_user_roles WHERE user_id = ?', [userId]); + await this.db.execute('DELETE FROM federated_user_roles WHERE identity_id = ?', [identityId]); const normalizedGroups = new Set((groups ?? []).map(group => group.toLowerCase())); for (const [group, roleName] of Object.entries(this.config.groupMapping ?? {})) { if (!normalizedGroups.has(group.toLowerCase())) continue; const role = await this.db.queryOne<{ id: string }>('SELECT id FROM roles WHERE LOWER(name) = LOWER(?)', [roleName]); if (!role) throw new EntraIdError(ENTRA_ID_ERROR_CODES.PROVISIONING_FAILED, 'Group mapping references an unknown role'); - await this.db.execute(`INSERT INTO federated_user_roles (user_id, role_id) VALUES (?, ?) - ON CONFLICT(user_id, role_id) DO NOTHING`, [userId, role.id]); + await this.db.execute(`INSERT INTO federated_user_roles (user_id, role_id, identity_id, source_key) VALUES (?, ?, ?, ?) + ON CONFLICT(identity_id, role_id, source_key) DO NOTHING`, [userId, role.id, identityId, `group:${group.toLowerCase()}`]); } }); } diff --git a/backend/src/services/GroupService.ts b/backend/src/services/GroupService.ts index 2e1e90bd..fd0fbdee 100644 --- a/backend/src/services/GroupService.ts +++ b/backend/src/services/GroupService.ts @@ -74,7 +74,7 @@ export interface PaginatedResult { export interface User { id: string; username: string; - email: string; + email: string | null; firstName: string; lastName: string; isActive: number; diff --git a/backend/src/services/LdapAuthenticationService.ts b/backend/src/services/LdapAuthenticationService.ts new file mode 100644 index 00000000..f519cbc9 --- /dev/null +++ b/backend/src/services/LdapAuthenticationService.ts @@ -0,0 +1,354 @@ +import { createHash, randomBytes, randomUUID } from 'node:crypto'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { setTimeout as delay } from 'node:timers/promises'; +import type { LdapConfig } from '../config/ldap'; +import type { DatabaseAdapter } from '../database/DatabaseAdapter'; +import type { LdapDirectoryResult, LdapDirectoryService } from './LdapDirectoryService'; +import { LdapDirectoryError } from './ldap/LdapDirectoryError'; +import { LdapAdministrationError, type LdapMappingService, type LdapMappingRevision } from './LdapMappingService'; +import type { UserService, User } from './UserService'; +import { AuditLoggingService } from './AuditLoggingService'; + +export class LdapAuthenticationError extends Error { + constructor(public readonly code: 'DENIED' | 'STALE_VALIDATION' | 'INVALID_CONTEXT') { + super('LDAP authentication failed: ' + code); + this.name = 'LdapAuthenticationError'; + } +} + +export function ldapAuthenticationFailure(error: unknown): { status: number; code: string; message: string } | undefined { + if (error instanceof LdapAuthenticationError) { + if (error.code === 'INVALID_CONTEXT') return { status: 401, code: 'INVALID_TOKEN', message: 'Invalid token' }; + if (error.code === 'DENIED') return { status: 403, code: 'LDAP_ACCESS_DENIED', message: 'Directory access denied' }; + } else if (error instanceof LdapDirectoryError) { + if (['INVALID_CREDENTIALS', 'INELIGIBLE'].includes(error.code)) { + return { status: 401, code: 'INVALID_CREDENTIALS', message: 'Invalid credentials' }; + } + if (error.code === 'BUSY') return { status: 429, code: 'LDAP_BUSY', message: 'Directory capacity limit reached' }; + } else if (!(error instanceof LdapAdministrationError)) return undefined; + return { status: 503, code: 'LDAP_UNAVAILABLE', message: 'Directory authentication temporarily unavailable' }; +} + +export interface LdapAuthenticationProof { + user: User; + identityId: string; + directoryId: string; + sessionVersion: string; +} +interface Identity { id: string; userId: string; subject: string; sessionVersion: string; isActive: number } +interface ValidationState { + lastValidatedAt: number | string | null; generation: number | string; + mappingRevision: number | string; configRevision: string; decisionStartedAt: number | string | null; + decisionSequence: number | string; +} +interface Snapshot { + revision: LdapMappingRevision; + mappings: { id: string; groupSubject: string; roleId: string }[]; + startedAt: number; + sequence: string; +} +interface Lease { owner: string; generation: string } + +/** Directory proof and database publication. This service never handles JWTs. */ +export class LdapAuthenticationService { + private readonly configRevision: string; + private readonly flights = new Map>(); + private readonly audit: AuditLoggingService; + private readonly clock: string; + + constructor( + private readonly db: DatabaseAdapter, + private readonly config: LdapConfig, + private readonly directory: Pick, + private readonly mappings: LdapMappingService, + private readonly users: UserService, + ) { + this.configRevision = createHash('sha256').update(JSON.stringify(config)) + .update(config.caFile ? readFileSync(config.caFile) : '').digest('hex'); + this.audit = new AuditLoggingService(db); + this.clock = db.getDialect() === 'postgres' + ? 'CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)' + : "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)"; + } + + /** Call once at startup. Older processes cannot silently reinstate their configuration. */ + public async initialize(): Promise { + await this.mappings.revision(); + await this.db.withTransaction(async () => { + const changed = await this.db.execute(`UPDATE ldap_directory_state SET config_revision = ? + WHERE directory_id = ? AND config_revision <> ?`, + [this.configRevision, this.config.directoryId, this.configRevision]); + if (changed.changes) { + await this.db.execute(`UPDATE ldap_validation_state SET last_validated_at = NULL + WHERE identity_id IN (SELECT identity_id FROM ldap_identity_metadata WHERE directory_id = ?)`, [this.config.directoryId]); + } + }); + } + + public async authenticate(loginName: string, password: string): Promise { + const snapshot = await this.snapshot(); + const result = await this.directory.authenticate(loginName, password, this.subjects(snapshot)); + const proof = await this.users.withFederatedUser({ ...result.user, provider: 'ldap', issuer: this.config.directoryId, + defaultRole: 'none' }, async user => { + await this.mappings.lockRevision(snapshot.revision); + const identity = await this.identityBySubject(result.user.subject); + if (identity?.userId !== user.id) throw new LdapAuthenticationError('INVALID_CONTEXT'); + await this.lockAccount(identity); + await this.assertNewerDecision(identity.id, snapshot.sequence); + // Credential proofs cannot be shared. Fence any older lookup-only work before publishing this login. + const lease = await this.claim(identity.id, true); + if (!lease) throw new LdapAuthenticationError('STALE_VALIDATION'); + const allowed = await this.publish(identity, snapshot, lease, result); + await this.release(identity.id, lease); + if (!allowed) return null; + await this.db.execute('UPDATE users SET last_login_at = ? WHERE id = ?', [new Date().toISOString(), user.id]); + const current = await this.users.getUserById(user.id); + assert(current); + return { user: current, identityId: identity.id, + directoryId: this.config.directoryId, sessionVersion: identity.sessionVersion }; + }); + // A proven zero-role account remains committed for subsequent manual assignment. + if (!proof) throw new LdapAuthenticationError('DENIED'); + return proof; + } + + public async assertEligible(userId: string, identityId: string, directoryId: string, + expectedVersion: string, force = false): Promise { + if (directoryId !== this.config.directoryId) throw new LdapAuthenticationError('INVALID_CONTEXT'); + const identity = await this.identity(identityId, userId, expectedVersion); + if (!force && await this.fresh(identity.id)) { + await this.requireRoles(identity); + if (await this.fresh(identity.id)) return; + } + const flightKey = JSON.stringify([identity.id, identity.sessionVersion]); + let flight = this.flights.get(flightKey); + if (!flight) { + flight = this.validate(identity); + this.flights.set(flightKey, flight); + const release = (): void => { if (this.flights.get(flightKey) === flight) this.flights.delete(flightKey); }; + void flight.then(release, release); + } + await flight; + // Never let a caller that joined work from another session version inherit its result. + await this.identity(identityId, userId, expectedVersion); + await this.requireRoles(identity); + if (!await this.fresh(identityId)) throw new LdapAuthenticationError('STALE_VALIDATION'); + } + + private async validate(identity: Identity): Promise { + const initial = await this.state(identity.id); + const deadline = performance.now() + this.config.requestTimeoutSeconds * 1000; + let lease: Lease | null = null; + let snapshot: Snapshot; + for (;;) { + snapshot = await this.snapshot(); + const acquired = await this.mappings.withRevision(snapshot.revision, async () => { + const current = await this.state(identity.id); + if (BigInt(current.generation) > BigInt(initial.generation) && await this.fresh(identity.id)) return { coalesced: true }; + return { coalesced: false, lease: await this.claim(identity.id) }; + }); + if (acquired.coalesced) return; + lease = acquired.lease ?? null; + if (lease) break; + if (performance.now() >= deadline) throw new LdapDirectoryError('BUSY'); + await delay(25); + await this.identity(identity.id, identity.userId, identity.sessionVersion); + // Only an overlapping remote validation can satisfy a forced refresh. + const state = await this.state(identity.id); + if (BigInt(state.generation) > BigInt(initial.generation) && await this.fresh(identity.id)) return; + } + try { + let result: LdapDirectoryResult; + try { + result = await this.directory.revalidate(identity.subject, this.subjects(snapshot)); + } catch (error) { + if (error instanceof LdapDirectoryError && error.code === 'INELIGIBLE') { + await this.mappings.withRevision(snapshot.revision, async () => { + await this.lockAccount(identity); + await this.fence(identity.id, lease); + await this.revoke(identity, snapshot, 'INELIGIBLE'); + await this.fence(identity.id, lease); + }); + throw new LdapAuthenticationError('DENIED'); + } + throw error; + } + if (result.user.subject !== identity.subject) throw new LdapAuthenticationError('INVALID_CONTEXT'); + const allowed = await this.users.withFederatedUser({ ...result.user, provider: 'ldap', issuer: this.config.directoryId, + defaultRole: 'none' }, async () => { + await this.mappings.lockRevision(snapshot.revision); + await this.lockAccount(identity); + return this.publish(identity, snapshot, lease, result); + }); + if (!allowed) throw new LdapAuthenticationError('DENIED'); + } finally { + await this.release(identity.id, lease); + } + } + + private async snapshot(): Promise { + await this.mappings.revision(); + const decision = await this.db.withTransaction(async () => { + const locked = await this.db.execute(`UPDATE ldap_directory_state SET validation_sequence = validation_sequence + 1 + WHERE directory_id = ? AND config_revision = ?`, [this.config.directoryId, this.configRevision]); + if (locked.changes !== 1) throw new LdapAuthenticationError('STALE_VALIDATION'); + const row = await this.db.queryOne<{ mappingRevision: number | string; sequence: number | string }>( + 'SELECT mapping_revision AS "mappingRevision", validation_sequence AS sequence FROM ldap_directory_state WHERE directory_id = ?', + [this.config.directoryId]); + assert(row); + return { revision: { directoryId: this.config.directoryId, mappingRevision: String(row.mappingRevision), configRevision: this.configRevision }, + sequence: String(row.sequence), startedAt: await this.now() }; + }); + const mappings = (await this.mappings.list()).filter(mapping => mapping.enabled); + return { ...decision, mappings }; + } + + private subjects(snapshot: Snapshot): string[] { return [...new Set(snapshot.mappings.map(mapping => mapping.groupSubject))]; } + + private async now(): Promise { + const row = await this.db.queryOne<{ now: string | number }>(`SELECT ${this.clock} AS "now"`); + assert(row); + return Number(row.now); + } + + private async identityBySubject(subject: string): Promise { + return this.db.queryOne(`SELECT i.id, i.user_id AS "userId", i.subject, + u.session_version AS "sessionVersion", u.is_active AS "isActive" + FROM federated_identities i JOIN ldap_identity_metadata m ON m.identity_id = i.id AND m.directory_id = i.issuer + JOIN users u ON u.id = i.user_id WHERE i.provider = 'ldap' AND i.issuer = ? AND i.subject = ?`, + [this.config.directoryId, subject]); + } + + private async identity(id: string, userId: string, version: string): Promise { + const identity = await this.db.queryOne(`SELECT i.id, i.user_id AS "userId", i.subject, + u.session_version AS "sessionVersion", u.is_active AS "isActive" + FROM federated_identities i JOIN ldap_identity_metadata m ON m.identity_id = i.id AND m.directory_id = i.issuer + JOIN users u ON u.id = i.user_id WHERE i.id = ? AND i.user_id = ? AND i.provider = 'ldap' AND i.issuer = ?`, + [id, userId, this.config.directoryId]); + if (identity?.isActive !== 1 || identity.sessionVersion !== version) throw new LdapAuthenticationError('INVALID_CONTEXT'); + return identity; + } + + private async lockAccount(identity: Identity): Promise { + const locked = await this.db.execute('UPDATE users SET session_version = session_version WHERE id = ? AND session_version = ?', + [identity.userId, identity.sessionVersion]); + if (locked.changes !== 1) throw new LdapAuthenticationError('INVALID_CONTEXT'); + } + + private async state(id: string): Promise { + const state = await this.db.queryOne(`SELECT last_validated_at AS "lastValidatedAt", + validation_generation AS generation, mapping_revision AS "mappingRevision", config_revision AS "configRevision", + decision_started_at AS "decisionStartedAt", decision_sequence AS "decisionSequence" FROM ldap_validation_state WHERE identity_id = ?`, [id]); + if (!state) throw new LdapAuthenticationError('INVALID_CONTEXT'); + return state; + } + + private async fresh(id: string): Promise { + const row = await this.db.queryOne<{ fresh: number }>(`SELECT 1 AS fresh FROM ldap_validation_state v + JOIN ldap_identity_metadata m ON m.identity_id = v.identity_id + JOIN ldap_directory_state d ON d.directory_id = m.directory_id + WHERE v.identity_id = ? AND v.last_validated_at IS NOT NULL AND v.last_validated_at <= ${this.clock} + AND v.last_validated_at + ? > ${this.clock} AND v.mapping_revision = d.mapping_revision + AND v.config_revision = d.config_revision AND d.config_revision = ?`, + [id, this.config.revalidationIntervalSeconds * 1000, this.configRevision]); + return row?.fresh === 1; + } + + private async claim(id: string, replace = false): Promise { + await this.db.execute('INSERT INTO ldap_validation_leases (identity_id) VALUES (?) ON CONFLICT DO NOTHING', [id]); + const owner = randomUUID(); + const updated = await this.db.execute(`UPDATE ldap_validation_leases SET lease_owner = ?, + lease_expires_at = ${this.clock} + ?, fencing_generation = fencing_generation + 1 + WHERE identity_id = ?${replace ? '' : ` AND (lease_owner IS NULL OR lease_expires_at <= ${this.clock})`}`, + [owner, this.config.requestTimeoutSeconds * 1000, id]); + if (!updated.changes) return null; + const row = await this.db.queryOne<{ generation: number | string }>( + 'SELECT fencing_generation AS generation FROM ldap_validation_leases WHERE identity_id = ?', [id]); + assert(row); + return { owner, generation: String(row.generation) }; + } + + private async fence(id: string, lease: Lease): Promise { + const locked = await this.db.execute(`UPDATE ldap_validation_leases SET fencing_generation = fencing_generation + WHERE identity_id = ? AND lease_owner = ? AND fencing_generation = ? AND lease_expires_at > ${this.clock}`, + [id, lease.owner, lease.generation]); + if (locked.changes !== 1) throw new LdapAuthenticationError('STALE_VALIDATION'); + } + + private async release(id: string, lease: Lease): Promise { + await this.db.execute(`UPDATE ldap_validation_leases SET lease_owner = NULL, lease_expires_at = NULL + WHERE identity_id = ? AND lease_owner = ? AND fencing_generation = ?`, [id, lease.owner, lease.generation]); + } + + private async assertNewerDecision(id: string, sequence: string): Promise { + const state = await this.state(id); + if (BigInt(state.decisionSequence) > BigInt(sequence)) { + throw new LdapAuthenticationError('STALE_VALIDATION'); + } + } + + private async publish(identity: Identity, snapshot: Snapshot, lease: Lease, result: LdapDirectoryResult): Promise { + await this.fence(identity.id, lease); + await this.assertNewerDecision(identity.id, snapshot.sequence); + if (snapshot.startedAt + this.config.revalidationIntervalSeconds * 1000 <= await this.now()) { + throw new LdapAuthenticationError('STALE_VALIDATION'); + } + const before = await this.db.query<{ source_key: string }>('SELECT source_key FROM federated_user_roles WHERE identity_id = ?', [identity.id]); + const selected = snapshot.mappings.filter(mapping => result.groupSubjects.includes(mapping.groupSubject)); + const keys = new Set(selected.map(mapping => 'mapping:' + mapping.id)); + for (const row of before) { + if (!keys.has(row.source_key)) await this.db.execute('DELETE FROM federated_user_roles WHERE identity_id = ? AND source_key = ?', [identity.id, row.source_key]); + } + for (const mapping of selected) { + await this.db.execute(`INSERT INTO federated_user_roles (user_id, role_id, identity_id, source_key, mapping_id, directory_id) + VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`, + [identity.userId, mapping.roleId, identity.id, 'mapping:' + mapping.id, mapping.id, this.config.directoryId]); + } + const active = await this.db.queryOne<{ active: number }>('SELECT is_active AS active FROM users WHERE id = ?', [identity.userId]); + if (active?.active !== 1 || !await this.hasRoles(identity.userId)) { + await this.revoke(identity, snapshot, active?.active === 1 ? 'NO_ROLES' : 'SUSPENDED'); + return false; + } + await this.db.execute(`UPDATE ldap_validation_state SET last_validated_at = ?, decision_started_at = ?, + decision_sequence = ?, validation_generation = validation_generation + 1, mapping_revision = ?, config_revision = ? WHERE identity_id = ?`, + [snapshot.startedAt, snapshot.startedAt, snapshot.sequence, snapshot.revision.mappingRevision, this.configRevision, identity.id]); + if (before.length !== keys.size || before.some(row => !keys.has(row.source_key))) { + await this.audit.logAdminAction('ldapEntitlementsChanged', identity.userId, + { directoryId: this.config.directoryId, identityId: identity.id, mappingIds: selected.map(mapping => mapping.id) }); + } + // Database/audit work consumes the same freshness budget as directory I/O. + if (!await this.fresh(identity.id)) throw new LdapAuthenticationError('STALE_VALIDATION'); + await this.fence(identity.id, lease); + return true; + } + + private async hasRoles(userId: string): Promise { + return !!await this.db.queryOne(`SELECT role_id FROM effective_user_roles WHERE user_id = ? + UNION SELECT gr.role_id FROM group_roles gr JOIN user_groups ug ON ug.group_id = gr.group_id WHERE ug.user_id = ?`, [userId, userId]); + } + + private async requireRoles(identity: Identity): Promise { + if (await this.hasRoles(identity.userId)) return; + const snapshot = await this.snapshot(); + const denied = await this.mappings.withRevision(snapshot.revision, async () => { + await this.lockAccount(identity); + if (await this.hasRoles(identity.userId)) return false; + await this.revoke(identity, snapshot, 'NO_ROLES'); + return true; + }); + if (denied) throw new LdapAuthenticationError('DENIED'); + } + + private async revoke(identity: Identity, decision: Pick, reason: string): Promise { + await this.assertNewerDecision(identity.id, decision.sequence); + await this.db.execute('DELETE FROM federated_user_roles WHERE identity_id = ?', [identity.id]); + await this.db.execute(`UPDATE ldap_validation_state SET last_validated_at = NULL, decision_started_at = ?, + decision_sequence = ?, validation_generation = validation_generation + 1 WHERE identity_id = ?`, + [decision.startedAt, decision.sequence, identity.id]); + await this.db.execute('UPDATE users SET session_version = ? WHERE id = ? AND session_version = ?', + [randomBytes(16).toString('hex'), identity.userId, identity.sessionVersion]); + await this.audit.logAdminAction('ldapSessionRevoked', identity.userId, + { directoryId: this.config.directoryId, identityId: identity.id, reason }); + } +} diff --git a/backend/src/services/LdapDirectoryService.ts b/backend/src/services/LdapDirectoryService.ts new file mode 100644 index 00000000..adc419e3 --- /dev/null +++ b/backend/src/services/LdapDirectoryService.ts @@ -0,0 +1,386 @@ +import { ldapDnEquals, ldapDnWithinScope, parseLdapDn } from '../config/ldapDn'; +import { + AndFilter, OrFilter, EqualityFilter, ExtensibleFilter, SubstringFilter, + InappropriateMatchingError, InvalidCredentialsError, + SizeLimitExceededError, TimeLimitExceededError, UnavailableCriticalExtensionError, +} from 'ldapts'; +import type { Entry, Filter, SearchOptions } from 'ldapts'; +import type { LdapConfig } from '../config/ldap'; +import { parseLdapFilter } from '../config/ldapFilter'; +import type { LoggerService } from './LoggerService'; +import { LdapDirectoryError } from './ldap/LdapDirectoryError'; +import { canonicalUuid, guidToSubject, subjectToGuid } from './ldap/identity'; +import { adPolicyAttributes, attributeValues, checkAdEligibility, textAttribute } from './ldap/policy'; +import { openLdapConnection } from './ldap/transport'; +import type { LdapConnection, LdapConnector, LdapEndpoint } from './ldap/transport'; + +export { LdapDirectoryError } from './ldap/LdapDirectoryError'; + +export interface LdapDirectoryUser { + subject: string; dn: string; loginName: string; displayName: string; + email: string | null; firstName: string; lastName: string; +} +export interface LdapDirectoryGroup { subject: string; dn: string; name: string } +export interface LdapDirectoryResult { user: LdapDirectoryUser; groupSubjects: string[] } +export interface LdapDiagnosticStage { + stage: 'tls' | 'lookup' | 'identity' | 'eligibility' | 'groups'; + status: 'passed' | 'failed'; durationMs: number; code?: string; +} +export interface LdapDiagnostics { + authenticated: false; stages: LdapDiagnosticStage[]; groupSubjects?: string[]; +} +interface Transaction { + signal: AbortSignal; endpoint: LdapEndpoint; lookup: LdapConnection; + connections: LdapConnection[]; +} + +function safeDirectoryError(error: unknown): LdapDirectoryError { + if (error instanceof LdapDirectoryError) return error; + if (error instanceof InvalidCredentialsError) return new LdapDirectoryError('INVALID_CREDENTIALS'); + if (error instanceof SizeLimitExceededError) return new LdapDirectoryError('LIMIT_EXCEEDED'); + if (error instanceof TimeLimitExceededError) return new LdapDirectoryError('TIMEOUT'); + return new LdapDirectoryError('UNAVAILABLE'); +} + +export class LdapDirectoryService { + private active = 0; + private readonly userBase: string; + private readonly groupBase: string; + private readonly eligibilityFilter: Filter | undefined; + + constructor( + private readonly config: LdapConfig, + private readonly logger: LoggerService, + private readonly connect: LdapConnector = openLdapConnection, + ) { + this.eligibilityFilter = config.userEligibilityFilter ? parseLdapFilter(config.userEligibilityFilter) : undefined; + this.userBase = [config.userRdn, config.baseDn].filter(Boolean).join(','); + this.groupBase = [config.groupRdn, config.baseDn].filter(Boolean).join(','); + } + + public async authenticate(loginName: string, password: string, mappedGroups: readonly string[] = []): Promise { + if (!loginName || !password || Buffer.byteLength(loginName) > 1024 || Buffer.byteLength(password) > 4096) { + throw new LdapDirectoryError('INVALID_CREDENTIALS'); + } + return this.transaction('authenticate', async tx => { + const before = await this.user(tx, this.equality(this.config.userLookupAttr, loginName), true); + const userBind = await this.connect(this.config, tx.endpoint, tx.signal); + if (tx.signal.aborted) { userBind.close(); throw new LdapDirectoryError('TIMEOUT'); } + tx.connections.push(userBind); + tx.signal.throwIfAborted(); + await userBind.bind(before.dn, password); + userBind.close(); + // A reused login or moved locator must not substitute another immutable identity after bind. + let after: LdapDirectoryUser; + try { after = await this.user(tx, this.subjectFilter(this.config.userIdAttr, before.subject), false); } + catch (error) { + if (error instanceof LdapDirectoryError && error.code === 'INELIGIBLE') throw new LdapDirectoryError('IDENTITY_CHANGED'); + throw error; + } + if (before.subject !== after.subject || before.loginName !== after.loginName || + !ldapDnEquals(before.dn, after.dn)) { + throw new LdapDirectoryError('IDENTITY_CHANGED'); + } + return { user: after, groupSubjects: await this.memberships(tx, after.dn, mappedGroups) }; + }); + } + + public async revalidate(subject: string, mappedGroups: readonly string[] = []): Promise { + const identityFilter = this.subjectFilter(this.config.userIdAttr, subject); + return this.transaction('revalidate', async tx => { + const user = await this.user(tx, identityFilter, false); + if (user.subject !== canonicalUuid(subject)) throw new LdapDirectoryError('IDENTITY_CHANGED'); + return { user, groupSubjects: await this.memberships(tx, user.dn, mappedGroups) }; + }); + } + + public async searchGroups(query: string): Promise { + if (!query || Buffer.byteLength(query) > 1024) throw new LdapDirectoryError('LIMIT_EXCEEDED'); + return this.transaction('searchGroups', async tx => { + const filter = this.and(this.equality('objectClass', this.config.groupObjectClass), + new OrFilter({ filters: [...new Set([this.config.groupLookupAttr, this.config.groupNameAttr])] + .map(attribute => new SubstringFilter({ attribute, any: [query] })) })); + const entries = await this.search(tx, this.groupBase, filter, this.groupAttributes(), this.config.groupSearchLimit); + return entries.map(entry => this.group(entry)); + }); + } + + public async resolveGroup(subject: string): Promise { + const filter = this.subjectFilter(this.config.groupIdAttr, subject); + return this.transaction('resolveGroup', async tx => this.resolveGroupInTransaction(tx, filter)); + } + + public async diagnose(input: { username?: string; groupSubjects?: string[] }): Promise { + const started = Date.now(); + const stages: LdapDiagnosticStage[] = []; + const result: LdapDiagnostics = { authenticated: false, stages }; + try { + await this.transaction('diagnose', async tx => { + const username = input.username; + if (username === undefined) return; + if (!username || Buffer.byteLength(username) > 1024) throw new LdapDirectoryError('LIMIT_EXCEEDED'); + const subject = await this.diagnosticStage(stages, 'identity', async () => { + const entries = await this.search(tx, this.userBase, + this.and(this.equality('objectClass', this.config.userObjectClass), this.equality(this.config.userLookupAttr, username)), + [this.config.userIdAttr], 2); + if (entries.length !== 1) throw new LdapDirectoryError('INVALID_IDENTITY'); + if (!this.inScope(entries[0].dn, this.userBase)) throw new LdapDirectoryError('INCOMPLETE_RESULT'); + return this.identity(entries[0], this.config.userIdAttr); + }); + const user = await this.diagnosticStage(stages, 'eligibility', () => this.user(tx, this.subjectFilter(this.config.userIdAttr, subject), false)); + const groups = input.groupSubjects; + if (groups?.length) { + result.groupSubjects = await this.diagnosticStage(stages, 'groups', async () => { + for (const subject of groups) await this.resolveGroupInTransaction(tx, this.subjectFilter(this.config.groupIdAttr, subject)); + return this.memberships(tx, user.dn, groups); + }); + } + }, stages); + } catch (error) { + const code = safeDirectoryError(error).code; + const failed = stages.find(stage => stage.status === 'failed'); + if (failed) { + failed.code = code; + failed.durationMs = Math.max(failed.durationMs, Date.now() - started - stages.filter(stage => stage.status === 'passed') + .reduce((sum, stage) => sum + stage.durationMs, 0)); + } else stages.push({ stage: 'lookup', status: 'failed', durationMs: Date.now() - started, code }); + delete result.groupSubjects; + } + // Aborted protocol promises can settle later; their bookkeeping must not change the returned report. + return { ...result, stages: stages.map(stage => ({ ...stage })) }; + } + + private async diagnosticStage(stages: LdapDiagnosticStage[], stage: LdapDiagnosticStage['stage'], work: () => Promise): Promise { + const started = Date.now(); + const entry: LdapDiagnosticStage = { stage, status: 'failed', durationMs: 0, code: 'TIMEOUT' }; + stages.push(entry); + try { + const result = await work(); + entry.status = 'passed'; + entry.durationMs = Date.now() - started; + delete entry.code; + return result; + } catch (error) { + entry.code = safeDirectoryError(error).code; + entry.durationMs = Date.now() - started; + throw error; + } + } + + private async transaction(operation: string, work: (tx: Transaction) => Promise, stages?: LdapDiagnosticStage[]): Promise { + if (this.active >= this.config.maxConcurrentOperations) throw new LdapDirectoryError('BUSY'); + this.active++; + const started = Date.now(); + const controller = new AbortController(); + const connections: LdapConnection[] = []; + let timer: ReturnType | undefined; + const deadline = new Promise((_resolve, reject) => { + timer = setTimeout(() => { controller.abort(); reject(new LdapDirectoryError('TIMEOUT')); }, + this.config.requestTimeoutSeconds * 1000); + }); + const run = async (): Promise => { + let lookup: LdapConnection | undefined; + let selected: LdapEndpoint | undefined; + const endpoints = [{ hostname: this.config.hostname, port: this.config.port }, ...this.config.failoverEndpoints]; + const establish = async (): Promise => { + for (const [index, endpoint] of endpoints.entries()) { + controller.signal.throwIfAborted(); + try { + const connection = await this.connect(this.config, endpoint, controller.signal); + if (controller.signal.aborted) { connection.close(); controller.signal.throwIfAborted(); } + lookup = connection; + connections.push(connection); + selected = endpoint; + if (index > 0) this.logger.info('LDAP endpoint failover', { + component: 'LdapDirectoryService', operation, metadata: { directoryId: this.config.directoryId, endpointIndex: index }, + }); + break; + } catch (error) { + if (controller.signal.aborted) throw new LdapDirectoryError('TIMEOUT'); + const code = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined; + const transient = code && ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN', 'ENOTFOUND'].includes(code); + if (!transient && !(error instanceof LdapDirectoryError && error.code === 'TIMEOUT')) { + throw new LdapDirectoryError('UNAVAILABLE'); + } + } + } + if (!lookup || !selected) throw new LdapDirectoryError('UNAVAILABLE'); + }; + if (stages) await this.diagnosticStage(stages, 'tls', establish); + else await establish(); + if (!lookup || !selected) throw new LdapDirectoryError('UNAVAILABLE'); + // Failover ends before any credential-bearing bind. User passwords are never retried. + const lookupConnection = lookup; + const bind = async (): Promise => { + try { await lookupConnection.bind(this.config.lookupUser, this.config.lookupPassword); } + catch (error) { + // A service credential failure says nothing about the submitted user's password. + if (error instanceof InvalidCredentialsError) throw new LdapDirectoryError('UNAVAILABLE'); + throw error; + } + }; + if (stages) await this.diagnosticStage(stages, 'lookup', bind); + else await bind(); + return work({ signal: controller.signal, endpoint: selected, lookup, connections }); + }; + try { + const result = await Promise.race([run(), deadline]); + this.logger.debug('LDAP operation completed', { + component: 'LdapDirectoryService', operation, metadata: { directoryId: this.config.directoryId, durationMs: Date.now() - started }, + }); + return result; + } catch (error) { + const safeError = controller.signal.aborted ? new LdapDirectoryError('TIMEOUT') : safeDirectoryError(error); + this.logger.warn('LDAP operation failed', { + component: 'LdapDirectoryService', operation, metadata: { directoryId: this.config.directoryId, + reason: safeError.code, durationMs: Date.now() - started }, + }); + throw safeError; + } finally { + if (timer) clearTimeout(timer); + controller.abort(); + for (const connection of connections) connection.close(); + this.active--; + } + } + + private equality(attribute: string, value: string | Buffer): EqualityFilter { + return new EqualityFilter({ attribute, value }); + } + + private subjectFilter(attribute: string, subject: string): Filter { + return this.equality(attribute, this.config.directoryType === 'ad' ? subjectToGuid(subject) : canonicalUuid(subject)); + } + + private and(...filters: (Filter | undefined)[]): Filter { + return new AndFilter({ filters: filters.filter((filter): filter is Filter => filter !== undefined) }); + } + + private async search(tx: Transaction, base: string, filter: Filter, attributes: string[], limit: number): Promise { + tx.signal.throwIfAborted(); + const options: SearchOptions = { + scope: 'sub', derefAliases: 'never', filter, attributes, sizeLimit: limit, + paged: false, timeLimit: this.config.operationTimeoutSeconds, + explicitBufferAttributes: this.config.directoryType === 'ad' ? [this.config.userIdAttr, this.config.groupIdAttr] : [], + }; + const result = await tx.lookup.search(base, options); + tx.signal.throwIfAborted(); + if (result.searchReferences.length) throw new LdapDirectoryError('INCOMPLETE_RESULT'); + if (result.searchEntries.length > limit) throw new LdapDirectoryError('LIMIT_EXCEEDED'); + return result.searchEntries; + } + + private identity(entry: Entry, attribute: string): string { + const values = attributeValues(entry, attribute); + if (values.length !== 1) throw new LdapDirectoryError('INVALID_IDENTITY'); + const value = values[0]; + if (this.config.directoryType === 'ad') { + if (!Buffer.isBuffer(value)) throw new LdapDirectoryError('INVALID_IDENTITY'); + return guidToSubject(value); + } + if (typeof value !== 'string') throw new LdapDirectoryError('INVALID_IDENTITY'); + return canonicalUuid(value); + } + + private async user(tx: Transaction, identityFilter: Filter, credentials: boolean): Promise { + const c = this.config; + const entries = await this.search(tx, this.userBase, + this.and(this.equality('objectClass', c.userObjectClass), identityFilter, this.eligibilityFilter), + [c.userIdAttr, c.userLookupAttr, c.userEmailAttr, c.userDisplayNameAttr, c.userGivenNameAttr, c.userSurnameAttr, + ...(c.directoryType === 'ad' ? adPolicyAttributes : [])], 2); + if (entries.length !== 1) throw new LdapDirectoryError(credentials ? 'INVALID_CREDENTIALS' + : entries.length === 0 ? 'INELIGIBLE' : 'INCOMPLETE_RESULT'); + const entry = entries[0]; + const subject = this.identity(entry, c.userIdAttr); + if (c.directoryType === 'ad') checkAdEligibility(entry); + const loginName = textAttribute(entry, c.userLookupAttr, true); + if (!loginName || !this.inScope(entry.dn, this.userBase)) throw new LdapDirectoryError('INVALID_IDENTITY'); + return { subject, dn: entry.dn, loginName, + email: textAttribute(entry, c.userEmailAttr), + displayName: textAttribute(entry, c.userDisplayNameAttr) ?? loginName, + firstName: textAttribute(entry, c.userGivenNameAttr) ?? '', + lastName: textAttribute(entry, c.userSurnameAttr) ?? '' }; + } + + private groupAttributes(): string[] { + const c = this.config; + return [c.groupIdAttr, c.groupNameAttr, c.groupLookupAttr, + ...(c.directoryType === 'openldap' ? [c.groupMemberAttr] : [])]; + } + + private inScope(dn: string, base: string): boolean { + return ldapDnWithinScope(dn, base); + } + + private group(entry: Entry): LdapDirectoryGroup { + if (!this.inScope(entry.dn, this.groupBase)) throw new LdapDirectoryError('INCOMPLETE_RESULT'); + if (this.config.directoryType === 'openldap') { + for (const member of attributeValues(entry, this.config.groupMemberAttr)) { + if (typeof member !== 'string' || /#'[01]*'B$/i.test(member)) { + throw new LdapDirectoryError('INCOMPLETE_RESULT'); + } + try { if (parseLdapDn(member).length === 0) throw new LdapDirectoryError('INCOMPLETE_RESULT'); } + catch { throw new LdapDirectoryError('INCOMPLETE_RESULT'); } + } + } + const name = textAttribute(entry, this.config.groupNameAttr) ?? textAttribute(entry, this.config.groupLookupAttr, true); + if (!name) throw new LdapDirectoryError('INVALID_IDENTITY'); + return { subject: this.identity(entry, this.config.groupIdAttr), dn: entry.dn, name }; + } + + private async resolveGroupInTransaction(tx: Transaction, filter: Filter): Promise { + const entries = await this.search(tx, this.groupBase, + this.and(this.equality('objectClass', this.config.groupObjectClass), filter), this.groupAttributes(), 2); + if (entries.length !== 1) throw new LdapDirectoryError('INVALID_IDENTITY'); + return this.group(entries[0]); + } + + private async memberships(tx: Transaction, userDn: string, subjects: readonly string[]): Promise { + if (subjects.length > this.config.groupTraversalLimit) throw new LdapDirectoryError('LIMIT_EXCEEDED'); + const mapped = new Set(subjects.map(canonicalUuid)); + if (!mapped.size) return []; + const c = this.config; + const visited: LdapDirectoryGroup[] = []; + const visitedSubjects = new Set(); + const frontier = [{ dn: userDn, depth: 0 }]; + // Reverse membership searches avoid downloading AD ranged member lists entirely. + for (const current of frontier) { + const parents = await this.search(tx, this.groupBase, + this.and(this.equality('objectClass', c.groupObjectClass), this.equality(c.groupMemberAttr, current.dn)), + this.groupAttributes(), c.groupTraversalLimit - visited.length + 1); + for (const entry of parents) { + const group = this.group(entry); + if (visitedSubjects.has(group.subject)) { + if (!visited.some(previous => previous.subject === group.subject && ldapDnEquals(previous.dn, group.dn))) { + throw new LdapDirectoryError('IDENTITY_CHANGED'); + } + continue; + } + if (visited.length >= c.groupTraversalLimit || (c.searchNestedGroups && current.depth >= c.nestedGroupMaxDepth)) { + throw new LdapDirectoryError('LIMIT_EXCEEDED'); + } + visitedSubjects.add(group.subject); + visited.push(group); + if (c.searchNestedGroups) frontier.push({ dn: group.dn, depth: current.depth + 1 }); + } + if (!c.searchNestedGroups) break; + } + const result = visited.filter(group => mapped.has(group.subject)).map(group => group.subject); + if (c.directoryType === 'ad' && c.searchNestedGroups && !c.disableMatchingRuleInChain) { + // Bounded traversal proves scope and completeness first. The AD rule is only a checked optimization. + try { + const entries = await this.search(tx, this.groupBase, + this.and(this.equality('objectClass', c.groupObjectClass), + new ExtensibleFilter({ matchType: c.groupMemberAttr, rule: '1.2.840.113556.1.4.1941', value: userDn })), + this.groupAttributes(), c.groupTraversalLimit); + const chain = new Set(entries.map(entry => this.group(entry).subject)); + if (chain.size !== visitedSubjects.size || [...visitedSubjects].some(subject => !chain.has(subject))) { + throw new LdapDirectoryError('INCOMPLETE_RESULT'); + } + } catch (error) { + if (!(error instanceof InappropriateMatchingError || error instanceof UnavailableCriticalExtensionError)) throw error; + } + } + return result; + } +} diff --git a/backend/src/services/LdapMappingService.ts b/backend/src/services/LdapMappingService.ts new file mode 100644 index 00000000..3b2b3b44 --- /dev/null +++ b/backend/src/services/LdapMappingService.ts @@ -0,0 +1,136 @@ +import { randomUUID } from 'node:crypto'; +import type { DatabaseAdapter } from '../database/DatabaseAdapter'; +import type { LdapDirectoryService } from './LdapDirectoryService'; +import { AuditLoggingService } from './AuditLoggingService'; +import { canonicalUuid } from './ldap/identity'; + +export class LdapAdministrationError extends Error { + constructor(public readonly code: 'NOT_FOUND' | 'CONFLICT' | 'STALE_REVISION' | 'INVALID_CURSOR') { + super('LDAP administration failed: ' + code); + this.name = 'LdapAdministrationError'; + } +} + +export interface LdapMapping { + id: string; directoryId: string; groupSubject: string; groupDn: string; groupName: string; + roleId: string; roleName: string; enabled: boolean; createdAt: string; updatedAt: string; + source: 'ldap'; +} +interface MappingRow extends Omit { enabled: number } +export interface LdapMappingRevision { directoryId: string; mappingRevision: string; configRevision: string } +export interface LdapAuditActor { userId: string; ip?: string; userAgent?: string } + +const columns = `m.id, m.directory_id AS "directoryId", m.group_subject AS "groupSubject", + m.group_dn AS "groupDn", m.group_name AS "groupName", m.role_id AS "roleId", r.name AS "roleName", + m.enabled, m.created_at AS "createdAt", m.updated_at AS "updatedAt"`; + +export class LdapMappingService { + private readonly audit: AuditLoggingService; + + constructor( + private readonly db: DatabaseAdapter, + private readonly directoryId: string, + private readonly directory: Pick, + ) { this.audit = new AuditLoggingService(db); } + + public async revision(): Promise { + await this.db.execute('INSERT INTO ldap_directory_state (directory_id) VALUES (?) ON CONFLICT DO NOTHING', [this.directoryId]); + const row = await this.db.queryOne<{ mapping_revision: string | number; config_revision: string }>( + 'SELECT mapping_revision, config_revision FROM ldap_directory_state WHERE directory_id = ?', [this.directoryId]); + if (!row) throw new LdapAdministrationError('STALE_REVISION'); + return { directoryId: this.directoryId, mappingRevision: String(row.mapping_revision), configRevision: row.config_revision }; + } + + // The directory row serializes mapping edits with publication of validation results on both adapters. + // Callers supply only database work; directory I/O must finish before acquiring this lock. + public async withRevision(revision: LdapMappingRevision, work: () => Promise): Promise { + return this.db.withTransaction(async () => { + await this.lockRevision(revision); + return work(); + }); + } + + /** Caller owns the surrounding transaction, including provisioning and lease fencing. */ + public async lockRevision(revision: LdapMappingRevision): Promise { + if (revision.directoryId !== this.directoryId) throw new LdapAdministrationError('STALE_REVISION'); + const locked = await this.db.execute(`UPDATE ldap_directory_state SET mapping_revision = mapping_revision + WHERE directory_id = ? AND mapping_revision = ? AND config_revision = ?`, + [this.directoryId, revision.mappingRevision, revision.configRevision]); + if (locked.changes !== 1) throw new LdapAdministrationError('STALE_REVISION'); + } + + public async list(): Promise { + const rows = await this.db.query(`SELECT ${columns} FROM external_group_mappings m + JOIN roles r ON r.id = m.role_id WHERE m.directory_id = ? ORDER BY m.group_name, m.role_id, m.id`, [this.directoryId]); + return rows.map(row => ({ ...row, enabled: row.enabled === 1, source: 'ldap' })); + } + + public async get(id: string): Promise { + const row = await this.db.queryOne(`SELECT ${columns} FROM external_group_mappings m + JOIN roles r ON r.id = m.role_id WHERE m.id = ? AND m.directory_id = ?`, [id, this.directoryId]); + if (!row) throw new LdapAdministrationError('NOT_FOUND'); + return { ...row, enabled: row.enabled === 1, source: 'ldap' }; + } + + public async create(groupSubject: string, roleId: string, actor: LdapAuditActor): Promise { + const revision = await this.revision(); + const group = await this.directory.resolveGroup(canonicalUuid(groupSubject)); + return this.withRevision(revision, async () => { + await this.checkRoleAndDuplicate(group.subject, roleId); + const id = randomUUID(); + const now = new Date().toISOString(); + await this.db.execute(`INSERT INTO external_group_mappings + (id, directory_id, group_subject, group_dn, group_name, role_id, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, [id, this.directoryId, group.subject, group.dn, group.name, roleId, now, now]); + const mapping = await this.get(id); + await this.record('createLdapMapping', mapping, actor); + return mapping; + }); + } + + public async update(id: string, input: { roleId?: string; enabled?: boolean }, actor: LdapAuditActor): Promise { + const revision = await this.revision(); + const previous = await this.get(id); + // Withdrawal remains available during an outage. Granting or changing a role requires fresh identity proof. + const group = input.enabled === false && input.roleId === undefined ? null + : await this.directory.resolveGroup(previous.groupSubject); + return this.withRevision(revision, async () => { + const roleId = input.roleId ?? previous.roleId; + await this.checkRoleAndDuplicate(previous.groupSubject, roleId, id); + await this.db.execute(`UPDATE external_group_mappings SET group_dn = ?, group_name = ?, role_id = ?, enabled = ?, updated_at = ? + WHERE id = ? AND directory_id = ?`, [group?.dn ?? previous.groupDn, group?.name ?? previous.groupName, + roleId, (input.enabled ?? previous.enabled) ? 1 : 0, new Date().toISOString(), id, this.directoryId]); + const mapping = await this.get(id); + await this.record('updateLdapMapping', mapping, actor); + return mapping; + }); + } + + public async remove(id: string, actor: LdapAuditActor): Promise { + const revision = await this.revision(); + await this.withRevision(revision, async () => { + const mapping = await this.get(id); + await this.db.execute('DELETE FROM external_group_mappings WHERE id = ? AND directory_id = ?', [id, this.directoryId]); + await this.record('deleteLdapMapping', mapping, actor); + }); + } + + private async checkRoleAndDuplicate(subject: string, roleId: string, exceptId = ''): Promise { + // Keep role deletion from racing the insert on PostgreSQL; SQLite already holds its writer lock. + const suffix = this.db.getDialect() === 'postgres' ? ' FOR KEY SHARE' : ''; + if (!await this.db.queryOne('SELECT id FROM roles WHERE id = ?' + suffix, [roleId])) { + throw new LdapAdministrationError('NOT_FOUND'); + } + if (await this.db.queryOne(`SELECT id FROM external_group_mappings + WHERE directory_id = ? AND group_subject = ? AND role_id = ? AND id <> ?`, [this.directoryId, subject, roleId, exceptId])) { + throw new LdapAdministrationError('CONFLICT'); + } + } + + private async record(action: string, mapping: LdapMapping, actor: LdapAuditActor): Promise { + await this.audit.logAdminAction(action, actor.userId, { + directoryId: this.directoryId, mappingId: mapping.id, groupSubject: mapping.groupSubject, + roleId: mapping.roleId, enabled: mapping.enabled, + }, actor.ip, actor.userAgent); + } +} diff --git a/backend/src/services/RoleService.ts b/backend/src/services/RoleService.ts index 22daa661..a126e519 100644 --- a/backend/src/services/RoleService.ts +++ b/backend/src/services/RoleService.ts @@ -159,7 +159,7 @@ export class RoleService { * @param name - Role name * @returns Role or null if not found */ - private async getRoleByName(name: string): Promise { + public async getRoleByName(name: string): Promise { return this.db.queryOne( `SELECT ${ROLE_COLUMNS} FROM roles WHERE name = ?`, [name] diff --git a/backend/src/services/SessionAuthorization.ts b/backend/src/services/SessionAuthorization.ts index 1e2c2b98..89893f19 100644 --- a/backend/src/services/SessionAuthorization.ts +++ b/backend/src/services/SessionAuthorization.ts @@ -45,4 +45,10 @@ export class SessionAuthorization { this.closed = true; clearInterval(this.timer); } + + async finish(action: () => void): Promise { + await this.pending; + this.deliver(action); + this.close(); + } } diff --git a/backend/src/services/UserService.ts b/backend/src/services/UserService.ts index a82a8d32..36b5f4fd 100644 --- a/backend/src/services/UserService.ts +++ b/backend/src/services/UserService.ts @@ -1,9 +1,9 @@ +import assert from 'node:assert/strict'; import type { DatabaseAdapter } from '../database/DatabaseAdapter'; -import { randomUUID } from 'crypto'; +import { createHash, randomUUID } from 'crypto'; import type { AuthenticationService } from './AuthenticationService'; import { SetupService } from './SetupService'; import { validatePassword } from '../utils/passwordValidation'; -import type { IdTokenClaims } from './EntraIdService'; /** * User model from database @@ -11,8 +11,10 @@ import type { IdTokenClaims } from './EntraIdService'; export interface User { id: string; username: string; - email: string; - passwordHash: string; + email: string | null; + passwordHash: string | null; + localAuthEnabled: number; + displayName: string | null; firstName: string; lastName: string; isActive: number; @@ -32,6 +34,8 @@ export interface User { */ const USER_COLUMNS = `id, username, email, password_hash AS "passwordHash", + local_auth_enabled AS "localAuthEnabled", + display_name AS "displayName", first_name AS "firstName", last_name AS "lastName", is_active AS "isActive", @@ -65,7 +69,8 @@ const FEDERATED_IDENTITY_COLUMNS = `id, export interface UserDTO { id: string; username: string; - email: string; + email: string | null; + displayName: string | null; firstName: string; lastName: string; isActive: boolean; @@ -75,9 +80,17 @@ export interface UserDTO { lastLoginAt: string | null; } -/** - * Create user data transfer object - */ +export interface UserAdministrationMetadata { + profileReadOnly: boolean; + sources: { provider: 'local' | 'ldap' | 'entra-id'; name: string; directoryId?: string; loginName?: string }[]; +} + +export interface UserRoleSource { + roleId: string; source: 'manual' | 'ldap' | 'entra-id'; + directoryId?: string; groupName?: string; +} + +/** Create user data transfer object. */ export interface CreateUserDTO { username: string; email: string; @@ -159,6 +172,37 @@ export interface FederatedIdentity { updatedAt: string; } +export interface ExternalProfile { + email: string | null; + displayName: string | null; + firstName: string; + lastName: string; +} + +export type FederatedProvisioningInput = ExternalProfile & { + issuer: string; + subject: string; +} & ({ + provider: 'entra-id'; + username: string; + defaultRole: 'configured'; +} | { + provider: 'ldap'; + loginName: string; + dn: string; + defaultRole: 'none'; +}); + +export class FederatedAccountError extends Error { + constructor( + readonly code: 'IDENTITY_COLLISION' | 'DIRECTORY_ACCOUNT_READ_ONLY' | 'INVALID_EXTERNAL_IDENTITY', + message: string, + ) { + super(message); + this.name = 'FederatedAccountError'; + } +} + /** * User service for managing user accounts, profiles, and user-group/role relationships * @@ -188,6 +232,9 @@ export class UserService { * @throws Error if username or email already exists */ public async createUser(data: CreateUserDTO): Promise { + if (data.username.toLowerCase().startsWith('ldap:')) { + throw new Error('Username uses a reserved directory namespace'); + } // Validate username uniqueness const existingUsername = await this.getUserByUsername(data.username); if (existingUsername) { @@ -195,7 +242,7 @@ export class UserService { } // Validate email uniqueness - const existingEmail = await this.getUserByEmail(data.email); + const existingEmail = await this.findLocalByEmail(data.email); if (existingEmail) { throw new Error('Email already exists'); } @@ -280,14 +327,14 @@ export class UserService { } /** - * Get user by email + * Resolve only the unique local credential scope. * * @param email - Email address * @returns User or null if not found */ - private async getUserByEmail(email: string): Promise { + public async findLocalByEmail(email: string): Promise { return this.db.queryOne( - `SELECT ${USER_COLUMNS} FROM users WHERE email = ?`, + `SELECT ${USER_COLUMNS} FROM users WHERE email = ? AND local_auth_enabled = 1`, [email] ); } @@ -307,10 +354,15 @@ export class UserService { throw new Error('User not found'); } + if (data.password !== undefined || data.email !== undefined || + data.firstName !== undefined || data.lastName !== undefined) { + await this.requireLocalProfileOwnership(id); + } + // Validate email uniqueness if email is being updated - if (data.email && data.email !== user.email) { - const existingEmail = await this.getUserByEmail(data.email); - if (existingEmail) { + if (data.email && data.email !== user.email && user.localAuthEnabled === 1) { + const existingEmail = await this.findLocalByEmail(data.email); + if (existingEmail && existingEmail.id !== id) { throw new Error('Email already exists'); } } @@ -335,6 +387,15 @@ export class UserService { } if (data.password !== undefined) { + if (user.localAuthEnabled === 0) { + const entraIdentity = await this.db.queryOne<{ id: string }>( + `SELECT id FROM federated_identities WHERE user_id = ? AND provider = 'entra-id' + AND NOT EXISTS (SELECT 1 FROM federated_identities WHERE user_id = ? AND provider = 'ldap')`, + [id, id] + ); + if (!entraIdentity) throw new Error('Directory accounts cannot have local passwords'); + updates.push('local_auth_enabled = 1'); + } // Validate password complexity const passwordValidation = validatePassword(data.password); if (!passwordValidation.valid) { @@ -651,6 +712,7 @@ export class UserService { id: user.id, username: user.username, email: user.email, + displayName: user.displayName, firstName: user.firstName, lastName: user.lastName, isActive: user.isActive === 1, @@ -661,108 +723,154 @@ export class UserService { }; } - /** - * Derive a valid username from IdToken claims. - * - * If preferred_username matches ^[a-zA-Z0-9_]{3,50}$, use it directly. - * Otherwise, derive from the email local-part by replacing disallowed - * characters with underscores and truncating to 50 characters. - */ - private deriveUsername(claims: IdTokenClaims): string { - const validUsernamePattern = /^[a-zA-Z0-9_]{3,50}$/; - - if (claims.preferred_username && validUsernamePattern.test(claims.preferred_username)) { - return claims.preferred_username; + public async getAdministrationMetadata( + users: User[], directory?: { directoryId: string; displayName: string }, + ): Promise> { + const result = new Map(users.map(user => [user.id, { + profileReadOnly: false, + sources: user.localAuthEnabled === 1 ? [{ provider: 'local', name: 'Local' }] : [], + }])); + if (users.length === 0) return result; + const rows = await this.db.query<{ userId: string; provider: string; issuer: string; loginName: string | null }>( + 'SELECT f.user_id AS "userId", f.provider, f.issuer, m.login_name AS "loginName" ' + + 'FROM federated_identities f LEFT JOIN ldap_identity_metadata m ON m.identity_id = f.id ' + + 'WHERE f.user_id IN (' + users.map(() => '?').join(',') + ') ORDER BY f.provider, f.issuer, f.id', + users.map(user => user.id)); + for (const row of rows) { + const metadata = result.get(row.userId); + if (!metadata) continue; + if (row.provider === 'ldap') { + metadata.profileReadOnly = true; + metadata.sources.push({ + provider: 'ldap', name: directory?.directoryId === row.issuer ? directory.displayName : 'LDAP', + directoryId: row.issuer, ...(row.loginName === null ? {} : { loginName: row.loginName }), + }); + } else if (row.provider === 'entra-id') { + metadata.sources.push({ provider: 'entra-id', name: 'Microsoft Entra ID' }); + } } + return result; + } - const localPart = claims.email.split('@')[0]; - const sanitized = localPart.replace(/[^a-zA-Z0-9_]/g, '_'); - return sanitized.slice(0, 50); + public async getUserRoleSources(userId: string): Promise { + const manual = await this.db.query<{ roleId: string }>( + 'SELECT role_id AS "roleId" FROM user_roles WHERE user_id = ?', [userId]); + const external = await this.db.query<{ roleId: string; source: 'ldap' | 'entra-id'; directoryId: string | null; groupName: string | null }>( + 'SELECT g.role_id AS "roleId", f.provider AS source, m.directory_id AS "directoryId", m.group_name AS "groupName" ' + + 'FROM federated_user_roles g JOIN federated_identities f ON f.id = g.identity_id ' + + 'LEFT JOIN external_group_mappings m ON m.id = g.mapping_id WHERE g.user_id = ?', [userId]); + const legacy = await this.db.query<{ roleId: string }>( + 'SELECT role_id AS "roleId" FROM legacy_federated_user_roles WHERE user_id = ?', [userId]); + return [ + ...manual.map(row => ({ roleId: row.roleId, source: 'manual' as const })), + ...external.map(row => ({ roleId: row.roleId, source: row.source, + ...(row.directoryId === null ? {} : { directoryId: row.directoryId }), + ...(row.groupName === null ? {} : { groupName: row.groupName }) })), + ...legacy.map(row => ({ roleId: row.roleId, source: 'entra-id' as const })), + ]; + } + + /** Reject directory-owned writes even for administrators and legacy mixed accounts. */ + public async requireLocalProfileOwnership(userId: string): Promise { + const identity = await this.db.queryOne<{ id: string }>( + "SELECT id FROM federated_identities WHERE user_id = ? AND provider = 'ldap'", + [userId], + ); + if (identity) { + throw new FederatedAccountError('DIRECTORY_ACCOUNT_READ_ONLY', + 'Directory profile fields are read-only; directory accounts cannot have local passwords'); + } } /** - * Create a new user from federated identity (SSO) claims. - * - * Creates the user with null password_hash, is_active=1, assigns the - * default viewer role, and creates a federated_identities record linking - * the user to the external IdP. - * - * @param claims - Validated ID token claims from the identity provider - * @returns Created user - * @throws Error if username uniqueness constraint is violated + * Owns the provisioning transaction. Call only after proving the external identity. + * No token is issued here, including when a committed account has no effective roles. */ - public async createFederatedUser(claims: IdTokenClaims): Promise { - const username = this.deriveUsername(claims); - - // Use a transaction to ensure atomicity — no partial records - return this.db.withTransaction(async () => { - // Check username uniqueness - const existingUsername = await this.getUserByUsername(username); - if (existingUsername) { - throw new Error( - `Account creation failed: derived username "${username}" already exists` - ); - } + public async createFederatedUser(input: FederatedProvisioningInput): Promise { + return this.withFederatedUser(input, user => Promise.resolve(user)); + } - // Check email uniqueness (a separate user with this email should not exist; - // collisions must never implicitly link the existing account) - const existingEmail = await this.getUserByEmail(claims.email); - if (existingEmail) { - throw new Error( - `Account creation failed: email "${claims.email}" already exists` - ); - } + /** Publish provider-owned authorization in the same transaction as account/profile changes. + * The callback performs database work only and must not open another transaction. + */ + public async withFederatedUser(input: FederatedProvisioningInput, publish: (user: User) => Promise): Promise { + if (!input.issuer.trim() || !input.subject.trim() || + (input.provider === 'ldap' && (!input.loginName.trim() || !input.dn.trim())) || + (input.provider === 'entra-id' && input.username.toLowerCase().startsWith('ldap:'))) { + throw new FederatedAccountError('INVALID_EXTERNAL_IDENTITY', 'Invalid external identity or provisioning policy'); + } + // Hash a structured tuple so separators and mutable directory locators cannot collide. + const username = input.provider === 'ldap' + ? 'ldap:' + createHash('sha256').update(JSON.stringify([input.provider, input.issuer, input.subject])).digest('hex') + : input.username; - const userId = randomUUID(); + return this.db.withTransaction(async () => { const now = new Date().toISOString(); - - // Insert user with null password_hash (federation-only) + // Preserve SetupService's fallback when the row is absent and lock every provisioning writer. await this.db.execute( - `INSERT INTO users (id, username, email, password_hash, first_name, last_name, is_active, is_admin, created_at, updated_at) - VALUES (?, ?, ?, NULL, ?, ?, 1, 0, ?, ?)`, - [ - userId, - username, - claims.email, - claims.given_name || '', - claims.family_name || '', - now, - now - ] + `INSERT INTO config (key, value, updated_at) VALUES ('default_new_user_role', 'role-viewer-001', ?) + ON CONFLICT(key) DO UPDATE SET value = config.value`, [now], ); - - // Assign default viewer role - const defaultRoleId = await this.setupService.getDefaultNewUserRole(); - if (defaultRoleId) { + const existing = await this.findByFederatedIdentity(input.provider, input.subject, input.issuer); + let userId: string; + let identityId: string; + if (existing) { + if (input.provider === 'entra-id') return publish(existing); + userId = existing.id; + const identity = await this.db.queryOne<{ id: string }>( + 'SELECT id FROM federated_identities WHERE provider = ? AND issuer = ? AND subject = ?', + [input.provider, input.issuer, input.subject], + ); + assert(identity); + identityId = identity.id; await this.db.execute( - `INSERT INTO user_roles (user_id, role_id, assigned_at) VALUES (?, ?, ?)`, - [userId, defaultRoleId, now] + 'UPDATE users SET email = ?, display_name = ?, first_name = ?, last_name = ?, updated_at = ? WHERE id = ?', + [input.email, input.displayName, input.firstName, input.lastName, now, userId], ); + await this.db.execute('UPDATE federated_identities SET email = ?, updated_at = ? WHERE id = ?', + [input.email, now, identityId]); + } else { + if (await this.getUserByUsername(username)) { + throw new FederatedAccountError('IDENTITY_COLLISION', 'Account creation failed: derived username already exists'); + } + if (input.provider === 'entra-id' && input.email && (await this.findAllByEmail(input.email)).length > 0) { + throw new FederatedAccountError('IDENTITY_COLLISION', 'Existing accounts require explicit administrative enrollment'); + } + userId = randomUUID(); + identityId = randomUUID(); + await this.db.execute( + `INSERT INTO users (id, username, email, password_hash, local_auth_enabled, display_name, + first_name, last_name, is_active, is_admin, created_at, updated_at) + VALUES (?, ?, ?, NULL, 0, ?, ?, ?, 1, 0, ?, ?)`, + [userId, username, input.email, input.displayName, input.firstName, input.lastName, now, now], + ); + await this.db.execute( + `INSERT INTO federated_identities (id, user_id, provider, issuer, subject, email, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + [identityId, userId, input.provider, input.issuer, input.subject, input.email, now, now], + ); + if (input.defaultRole === 'configured') { + const roleId = await this.setupService.getDefaultNewUserRole(); + if (roleId) await this.db.execute( + 'INSERT INTO user_roles (user_id, role_id, assigned_at) VALUES (?, ?, ?)', [userId, roleId, now]); + } } - - // Create federated identity record - const federatedId = randomUUID(); - await this.db.execute( - `INSERT INTO federated_identities (id, user_id, provider, subject, issuer, email, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, - [ - federatedId, - userId, - 'entra-id', - claims.sub, - claims.iss, - claims.email, - now, - now - ] - ); - - const user = await this.getUserById(userId); - if (!user) { - throw new Error('Failed to create federated user'); + if (input.provider === 'ldap') { + await this.db.execute('INSERT INTO ldap_directory_state (directory_id) VALUES (?) ON CONFLICT DO NOTHING', [input.issuer]); + await this.db.execute( + `INSERT INTO ldap_identity_metadata (identity_id, directory_id, login_name, dn) VALUES (?, ?, ?, ?) + ON CONFLICT(identity_id) DO UPDATE SET login_name = excluded.login_name, dn = excluded.dn`, + [identityId, input.issuer, input.loginName, input.dn], + ); + // Provisioning alone proves no session freshness. Revalidation owns these revisions later. + await this.db.execute( + `INSERT INTO ldap_validation_state (identity_id, config_revision) VALUES (?, '') + ON CONFLICT(identity_id) DO NOTHING`, [identityId], + ); } - - return user; + const user = await this.getUserById(userId); + assert(user); + return publish(user); }); } @@ -785,6 +893,10 @@ export class UserService { issuer: string, email: string | null, ): Promise { + if (provider === 'ldap') { + throw new FederatedAccountError('DIRECTORY_ACCOUNT_READ_ONLY', 'LDAP identities cannot be linked to existing accounts'); + } + await this.requireLocalProfileOwnership(userId); const id = randomUUID(); const now = new Date().toISOString(); @@ -841,14 +953,13 @@ export class UserService { } /** - * Public wrapper around the private getUserByEmail method. - * Used by EntraIdService for email-match account linking during SSO. - * - * @param email - Email address to search for - * @returns User or null if not found + * External contact email is not an identity key. Callers must handle all matches. */ - public async findByEmail(email: string): Promise { - return this.getUserByEmail(email); + public async findAllByEmail(email: string): Promise { + return this.db.query( + `SELECT ${USER_COLUMNS} FROM users WHERE email = ? ORDER BY id`, + [email] + ); } } diff --git a/backend/src/services/ldap/LdapDirectoryError.ts b/backend/src/services/ldap/LdapDirectoryError.ts new file mode 100644 index 00000000..d248f56d --- /dev/null +++ b/backend/src/services/ldap/LdapDirectoryError.ts @@ -0,0 +1,10 @@ +export type LdapDirectoryErrorCode = + | 'INVALID_CREDENTIALS' | 'INELIGIBLE' | 'IDENTITY_CHANGED' | 'INVALID_IDENTITY' + | 'POLICY_UNREADABLE' | 'INCOMPLETE_RESULT' | 'LIMIT_EXCEEDED' | 'BUSY' | 'TIMEOUT' | 'UNAVAILABLE'; + +export class LdapDirectoryError extends Error { + constructor(public readonly code: LdapDirectoryErrorCode) { + super('LDAP directory operation failed: ' + code); + this.name = 'LdapDirectoryError'; + } +} diff --git a/backend/src/services/ldap/identity.ts b/backend/src/services/ldap/identity.ts new file mode 100644 index 00000000..5e060fe5 --- /dev/null +++ b/backend/src/services/ldap/identity.ts @@ -0,0 +1,28 @@ +import { LdapDirectoryError } from './LdapDirectoryError'; + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export function canonicalUuid(value: string): string { + if (!uuid.test(value) || value === '00000000-0000-0000-0000-000000000000') { + throw new LdapDirectoryError('INVALID_IDENTITY'); + } + return value.toLowerCase(); +} + +export function guidToSubject(value: Buffer): string { + if (value.length !== 16) throw new LdapDirectoryError('INVALID_IDENTITY'); + const bytes = Buffer.from(value); + bytes.subarray(0, 4).reverse(); + bytes.subarray(4, 6).reverse(); + bytes.subarray(6, 8).reverse(); + const hex = bytes.toString('hex'); + return canonicalUuid([hex.slice(0, 8), hex.slice(8, 12), hex.slice(12, 16), hex.slice(16, 20), hex.slice(20)].join('-')); +} + +export function subjectToGuid(value: string): Buffer { + const bytes = Buffer.from(canonicalUuid(value).replaceAll('-', ''), 'hex'); + bytes.subarray(0, 4).reverse(); + bytes.subarray(4, 6).reverse(); + bytes.subarray(6, 8).reverse(); + return bytes; +} diff --git a/backend/src/services/ldap/policy.ts b/backend/src/services/ldap/policy.ts new file mode 100644 index 00000000..773d549f --- /dev/null +++ b/backend/src/services/ldap/policy.ts @@ -0,0 +1,44 @@ +import type { Entry } from 'ldapts'; +import { LdapDirectoryError } from './LdapDirectoryError'; + +export const adPolicyAttributes = [ + 'userAccountControl', 'msDS-User-Account-Control-Computed', + 'accountExpires', 'pwdLastSet', 'msDS-UserPasswordExpiryTimeComputed', +]; + +export function attributeValues(entry: Entry, name: string): (string | Buffer)[] { + const key = Object.keys(entry).find(key => key.toLowerCase() === name.toLowerCase()); + if (!key) return []; + const value = entry[key]; + return Array.isArray(value) ? value : [value]; +} + +export function textAttribute(entry: Entry, name: string, required = false): string | null { + const values = attributeValues(entry, name); + if (values.length === 0 && !required) return null; + if (values.length !== 1 || typeof values[0] !== 'string' || !values[0]) { + throw new LdapDirectoryError('POLICY_UNREADABLE'); + } + return values[0]; +} + +export function checkAdEligibility(entry: Entry, now = Date.now()): void { + const number = (name: string): bigint => { + const text = textAttribute(entry, name, true); + if (!text || !/^\d+$/.test(text)) throw new LdapDirectoryError('POLICY_UNREADABLE'); + const value = BigInt(text); + if (value > 9223372036854775807n) throw new LdapDirectoryError('POLICY_UNREADABLE'); + return value; + }; + const uac = number('userAccountControl'); + const computed = number('msDS-User-Account-Control-Computed'); + const expires = number('accountExpires'); + const passwordSet = number('pwdLastSet'); + const passwordExpiry = number('msDS-UserPasswordExpiryTimeComputed'); + const filetime = (BigInt(now) + 11644473600000n) * 10000n; + const expired = (value: bigint): boolean => value !== 0n && value !== 9223372036854775807n && value <= filetime; + if ((uac & 2n) !== 0n || (computed & (16n | 8388608n)) !== 0n || + expired(expires) || passwordSet === 0n || passwordExpiry === 0n || expired(passwordExpiry)) { + throw new LdapDirectoryError('INELIGIBLE'); + } +} diff --git a/backend/src/services/ldap/transport.ts b/backend/src/services/ldap/transport.ts new file mode 100644 index 00000000..46278e96 --- /dev/null +++ b/backend/src/services/ldap/transport.ts @@ -0,0 +1,152 @@ +import { readFileSync } from 'node:fs'; +import { connect as tcpConnect } from 'node:net'; +import type { Socket } from 'node:net'; +import { connect as tlsConnect, checkServerIdentity, getCACertificates } from 'node:tls'; +import type { ConnectionOptions, PeerCertificate, TLSSocket } from 'node:tls'; +import { Client, MessageParser, MessageResponseStatus, SearchResponse, SearchEntry, StatusCodeParser, PagedResultsControl } from 'ldapts'; +import type { SearchOptions, SearchResult } from 'ldapts'; +import type { LdapConfig } from '../../config/ldap'; +import { LdapDirectoryError } from './LdapDirectoryError'; + +export interface LdapEndpoint { hostname: string; port: number } +export interface LdapConnection { + bind(dn: string, password: string): Promise; + search(base: string, options: SearchOptions): Promise; + close(): void; +} +export type LdapConnector = (config: LdapConfig, endpoint: LdapEndpoint, signal: AbortSignal) => Promise; + +export function verifyLdapHostname(host: string, certificate: PeerCertificate, allowWildcard: boolean): Error | undefined { + const normalError = checkServerIdentity(host, certificate); + if (normalError || allowWildcard) return normalError; + // Only reject wildcard identities that could match this endpoint, not unrelated SANs. + const identities = certificate.subjectaltname + ? certificate.subjectaltname.split(', ').filter(value => value.startsWith('DNS:')).map(value => value.slice(4)) + : [certificate.subject.CN].flat(); + const wildcardUsed = identities.some(identity => !!identity && identity.includes('*') && + !checkServerIdentity(host, { subjectaltname: 'DNS:' + identity } as PeerCertificate)); + return wildcardUsed ? new LdapDirectoryError('UNAVAILABLE') : undefined; +} + +export const openLdapConnection: LdapConnector = async (config, endpoint, signal) => { + const sockets = new Set(); + let client: Client | undefined; + let closed = false; + const close = (): void => { + if (closed) return; + closed = true; + signal.removeEventListener('abort', close); + // Unbind clears library credential references; destruction also interrupts pending operations. + if (client) void client.unbind().catch(() => undefined); + for (const socket of sockets) socket.destroy(); + sockets.clear(); + }; + const track = (socket: T): T => { + sockets.add(socket); + socket.once('close', () => sockets.delete(socket)); + return socket; + }; + signal.addEventListener('abort', close, { once: true }); + const tlsOptions: ConnectionOptions = { + minVersion: 'TLSv1.2', rejectUnauthorized: true, servername: endpoint.hostname, + checkServerIdentity: (host, certificate) => verifyLdapHostname(host, certificate, config.allowWildcardCertificates), + ...(config.caFile ? { ca: [...getCACertificates('default'), readFileSync(config.caFile, 'utf8')] } : {}), + }; + try { + signal.throwIfAborted(); + const socket = config.tlsMode === 'ldaps' + ? track(tlsConnect({ ...tlsOptions, host: endpoint.hostname, port: endpoint.port })) + : track(tcpConnect({ host: endpoint.hostname, port: endpoint.port })); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => { close(); reject(new LdapDirectoryError('TIMEOUT')); }, + config.connectTimeoutSeconds * 1000); + const abort = (): void => { done(new LdapDirectoryError('TIMEOUT')); }; + signal.addEventListener('abort', abort, { once: true }); + const done = (error?: Error): void => { + clearTimeout(timer); + signal.removeEventListener('abort', abort); + socket.removeListener('error', done); + if (error) reject(error); else resolve(); + }; + socket.once('error', done); + socket.once(config.tlsMode === 'ldaps' ? 'secureConnect' : 'connect', () => { done(); }); + }); + let secureTransport: Socket = socket; + let supplied = false; + const existingSocket = (): Socket => { + signal.throwIfAborted(); + if (closed || supplied) throw new LdapDirectoryError('UNAVAILABLE'); + supplied = true; + return socket; + }; + const secureSocket = (options: ConnectionOptions): TLSSocket => { + signal.throwIfAborted(); + if (closed) throw new LdapDirectoryError('UNAVAILABLE'); + if (config.tlsMode === 'ldaps') return existingSocket() as TLSSocket; + if (options.socket !== socket) throw new LdapDirectoryError('UNAVAILABLE'); + secureTransport = track(tlsConnect(options)); + return secureTransport as TLSSocket; + }; + client = new Client({ + url: (config.tlsMode === 'ldaps' ? 'ldaps://' : 'ldap://') + endpoint.hostname + ':' + String(endpoint.port), + connectTimeout: config.connectTimeoutSeconds * 1000, + timeout: config.operationTimeoutSeconds * 1000, strictDN: true, autoRebind: false, + // ldapts 9.2 uses (port, host, options) for LDAPS and (options) for StartTLS. + createConnection: existingSocket, + createSecureConnection: ((portOrOptions: number | ConnectionOptions): TLSSocket => + secureSocket(typeof portOrOptions === 'number' ? tlsOptions : portOrOptions)), + ...(config.tlsMode === 'ldaps' ? { tlsOptions } : {}), + }); + if (config.tlsMode === 'starttls') await client.startTLS(tlsOptions); + signal.throwIfAborted(); + const connectedClient = client; + // ldapts suppresses sizeLimitExceeded when a request specifies sizeLimit. + // Observe the server status so truncated authentication data can never be accepted. + const parser = new MessageParser(); + let searchError: Error | undefined; + const readSearchError = (): Error | undefined => searchError; + let searchLimit = 0; + let entryCount = 0; + parser.on('error', () => { searchError = new LdapDirectoryError('INCOMPLETE_RESULT'); close(); }); + parser.on('message', message => { + if (message instanceof SearchEntry && ++entryCount > searchLimit) { + searchError = new LdapDirectoryError('LIMIT_EXCEEDED'); + close(); + } + if (message instanceof SearchResponse && message.controls?.some(control => + control instanceof PagedResultsControl && !!control.value?.cookie?.length)) { + searchError = new LdapDirectoryError('INCOMPLETE_RESULT'); + } + if (message instanceof SearchResponse && message.status !== MessageResponseStatus.Success) { + searchError = StatusCodeParser.parse(message); + } + }); + secureTransport.prependListener('data', (data: Buffer) => { parser.read(data, new Map()); }); + return { + bind: async (dn, password): Promise => { + signal.throwIfAborted(); + if (closed) throw new LdapDirectoryError('UNAVAILABLE'); + await connectedClient.bind(dn, password); + signal.throwIfAborted(); + }, + search: async (base, options): Promise => { + signal.throwIfAborted(); + if (closed) throw new LdapDirectoryError('UNAVAILABLE'); + searchError = undefined; + entryCount = 0; + searchLimit = options.sizeLimit ?? 0; + let result: SearchResult; + try { result = await connectedClient.search(base, options); } + catch (error) { throw readSearchError() ?? error; } + const serverError = readSearchError(); + if (serverError) throw serverError; + signal.throwIfAborted(); + return result; + }, + close, + }; + } catch (error) { + close(); + throw error; + } +}; diff --git a/backend/src/types/express.d.ts b/backend/src/types/express.d.ts index 15c545b2..0def278d 100644 --- a/backend/src/types/express.d.ts +++ b/backend/src/types/express.d.ts @@ -1,4 +1,5 @@ import type { ExecutionRecord } from "../database/ExecutionRepository"; +import type { AuthenticationContext } from "../services/AuthenticationService"; /** * Centralized Express.Request augmentation for Pabawi. @@ -22,6 +23,8 @@ declare global { exp: number; }; mcpAuthMethod?: 'jwt' | 'static'; + authContext?: AuthenticationContext; + authSessionVersion?: string; revalidateAuth?: () => Promise; /** Execution snapshot checked by the mutation authorization middleware. */ authorizedExecution?: ExecutionRecord; diff --git a/backend/src/types/node-tls.d.ts b/backend/src/types/node-tls.d.ts new file mode 100644 index 00000000..71b15eb3 --- /dev/null +++ b/backend/src/types/node-tls.d.ts @@ -0,0 +1,6 @@ +import 'node:tls'; + +// The supported Node 24 runtime exposes this API; the repository uses Node 20 types. +declare module 'node:tls' { + export function getCACertificates(type?: 'default' | 'system' | 'bundled' | 'extra'): string[]; +} diff --git a/backend/test/AuthenticationService.test.ts b/backend/test/AuthenticationService.test.ts index aecdcbb2..660a3397 100644 --- a/backend/test/AuthenticationService.test.ts +++ b/backend/test/AuthenticationService.test.ts @@ -174,7 +174,7 @@ describe('AuthenticationService', () => { }); it('should generate valid JWT access token', async () => { - const token = await authService.generateToken(testUser); + const token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); expect(token).toBeDefined(); expect(typeof token).toBe('string'); @@ -182,7 +182,7 @@ describe('AuthenticationService', () => { }); it('should generate valid JWT refresh token', async () => { - const refreshToken = await authService.generateRefreshToken(testUser); + const refreshToken = await authService.generateRefreshToken(testUser, { provider: 'local', identityId: null }); expect(refreshToken).toBeDefined(); expect(typeof refreshToken).toBe('string'); @@ -190,7 +190,7 @@ describe('AuthenticationService', () => { }); it('should include user information in token payload', async () => { - const token = await authService.generateToken(testUser); + const token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); const payload = await authService.verifyToken(token); expect(payload.userId).toBe(testUser.id); @@ -200,7 +200,7 @@ describe('AuthenticationService', () => { }); it('should include expiration time in token', async () => { - const token = await authService.generateToken(testUser); + const token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); const payload = await authService.verifyToken(token); expect(payload.exp).toBeDefined(); @@ -213,7 +213,7 @@ describe('AuthenticationService', () => { }); it('should include token ID (jti) for revocation tracking', async () => { - const token = await authService.generateToken(testUser); + const token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); const payload = await authService.verifyToken(token); expect(payload.jti).toBeDefined(); @@ -237,7 +237,7 @@ describe('AuthenticationService', () => { `, [userId, 'testuser', 'test@example.com', passwordHash, 'Test', 'User', 1, 0, now, now]); testUser = await db.queryOne('SELECT * FROM users WHERE username = ?', ['testuser']); - validToken = await authService.generateToken(testUser); + validToken = await authService.generateToken(testUser, { provider: 'local', identityId: null }); }); it('should verify valid token', async () => { @@ -280,7 +280,7 @@ describe('AuthenticationService', () => { `, [userId, 'testuser', 'test@example.com', passwordHash, 'Test', 'User', 1, 0, now, now]); testUser = await db.queryOne('SELECT * FROM users WHERE username = ?', ['testuser']); - refreshToken = await authService.generateRefreshToken(testUser); + refreshToken = await authService.generateRefreshToken(testUser, { provider: 'local', identityId: null }); }); it('should generate new access token from valid refresh token', async () => { @@ -293,7 +293,7 @@ describe('AuthenticationService', () => { }); it('should reject access token used as refresh token', async () => { - const accessToken = await authService.generateToken(testUser); + const accessToken = await authService.generateToken(testUser, { provider: 'local', identityId: null }); const result = await authService.refreshToken(accessToken); expect(result.success).toBe(false); @@ -332,7 +332,7 @@ describe('AuthenticationService', () => { `, [userId, 'testuser', 'test@example.com', passwordHash, 'Test', 'User', 1, 0, now, now]); testUser = await db.queryOne('SELECT * FROM users WHERE username = ?', ['testuser']); - token = await authService.generateToken(testUser); + token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); }); it('should revoke specific token', async () => { @@ -349,8 +349,8 @@ describe('AuthenticationService', () => { }); it('should revoke all user tokens', async () => { - const token1 = await authService.generateToken(testUser); - const token2 = await authService.generateToken(testUser); + const token1 = await authService.generateToken(testUser, { provider: 'local', identityId: null }); + const token2 = await authService.generateToken(testUser, { provider: 'local', identityId: null }); await authService.revokeAllUserTokens(testUser.id); @@ -390,7 +390,7 @@ describe('AuthenticationService', () => { }); it('should include user roles in token payload', async () => { - const token = await authService.generateToken(testUser); + const token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); const payload = await authService.verifyToken(token); expect(payload.roles).toBeDefined(); @@ -426,7 +426,7 @@ describe('AuthenticationService', () => { VALUES (?, ?, ?) `, [groupId, roleId, now]); - const token = await authService.generateToken(testUser); + const token = await authService.generateToken(testUser, { provider: 'local', identityId: null }); const payload = await authService.verifyToken(token); expect(payload.roles).toContain('GroupRole'); diff --git a/backend/test/UserService.password.test.ts b/backend/test/UserService.password.test.ts index 45199802..44c6ccf8 100644 --- a/backend/test/UserService.password.test.ts +++ b/backend/test/UserService.password.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import { SQLiteAdapter } from '../src/database/SQLiteAdapter'; import { UserService } from '../src/services/UserService'; import { AuthenticationService } from '../src/services/AuthenticationService'; +import { initializeTestSchema } from './helpers/schema'; describe('UserService - Password Validation Integration', () => { let db: SQLiteAdapter; @@ -15,9 +16,7 @@ describe('UserService - Password Validation Integration', () => { await db.initialize(); // Initialize schema - await initializeSchema(db); - - await db.execute('CREATE VIEW effective_user_roles AS SELECT user_id, role_id FROM user_roles'); + await initializeTestSchema(db); authService = new AuthenticationService(db, testJwtSecret); userService = new UserService(db, authService); @@ -182,112 +181,3 @@ describe('UserService - Password Validation Integration', () => { }); }); }); - - -// Helper function to initialize database schema -async function initializeSchema(db: SQLiteAdapter): Promise { - const schema = ` - CREATE TABLE users ( - id TEXT PRIMARY KEY, - username TEXT NOT NULL UNIQUE, - email TEXT NOT NULL UNIQUE, - password_hash TEXT NOT NULL, - session_version TEXT NOT NULL DEFAULT '0', - first_name TEXT NOT NULL, - last_name TEXT NOT NULL, - is_active INTEGER NOT NULL DEFAULT 1, - is_admin INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - last_login_at TEXT - ); - - CREATE TABLE groups ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - description TEXT NOT NULL, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - - CREATE TABLE roles ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - description TEXT NOT NULL, - is_built_in INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - - CREATE TABLE permissions ( - id TEXT PRIMARY KEY, - resource TEXT NOT NULL, - action TEXT NOT NULL, - description TEXT NOT NULL, - created_at TEXT NOT NULL, - UNIQUE(resource, action) - ); - - CREATE TABLE user_groups ( - user_id TEXT NOT NULL, - group_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (user_id, group_id), - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, - FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE - ); - - CREATE TABLE user_roles ( - user_id TEXT NOT NULL, - role_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (user_id, role_id), - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, - FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE - ); - - CREATE TABLE group_roles ( - group_id TEXT NOT NULL, - role_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (group_id, role_id), - FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE, - FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE - ); - - CREATE TABLE role_permissions ( - role_id TEXT NOT NULL, - permission_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (role_id, permission_id), - FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE, - FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE - ); - - CREATE TABLE revoked_tokens ( - token TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - revoked_at TEXT NOT NULL, - expires_at TEXT NOT NULL, - FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE - ); - - CREATE TABLE config ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TEXT NOT NULL - ); - - INSERT INTO config (key, value, updated_at) VALUES - ('allow_self_registration', 'false', datetime('now')), - ('default_new_user_role', 'role-viewer-001', datetime('now')); - - INSERT INTO roles (id, name, description, is_built_in, created_at, updated_at) VALUES - ('role-viewer-001', 'Viewer', 'Default viewer role', 1, datetime('now'), datetime('now')); - `; - - const statements = schema.split(';').map(s => s.trim()).filter(s => s.length > 0); - for (const statement of statements) { - await db.execute(statement); - } -} diff --git a/backend/test/config/LdapConfig.test.ts b/backend/test/config/LdapConfig.test.ts new file mode 100644 index 00000000..0a134361 --- /dev/null +++ b/backend/test/config/LdapConfig.test.ts @@ -0,0 +1,90 @@ +import { BerWriter } from 'ldapts'; +import { parseLdapFilter } from '../../src/config/ldapFilter'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { parseLdapConfig } from '../../src/config/ldap'; +import { ConfigService } from '../../src/config/ConfigService'; + +const enabled = { + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory-1', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'localhost.localdomain', LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_LOOKUP_USER: 'cn=reader,dc=example,dc=test', LDAP_LOOKUP_PASSWORD: 'fixture-reader', // pragma: allowlist secret + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', +}; +afterEach(() => vi.unstubAllEnvs()); + +describe('LDAP configuration', () => { + it('ignores directory settings while disabled but rejects malformed enabled flags', () => { + expect(parseLdapConfig({ LDAP_HOSTNAME: 'invalid' })).toBeUndefined(); + expect(parseLdapConfig({ LDAP_ENABLED: 'false', LDAP_PORT: 'no' })).toBeUndefined(); + expect(() => parseLdapConfig({ LDAP_ENABLED: 'yes' })).toThrow('LDAP_ENABLED'); + }); + + it('selects OpenLDAP and AD presets and TLS ports', () => { + expect(parseLdapConfig(enabled)).toMatchObject({ + directoryId: 'directory-1', directoryType: 'openldap', userObjectClass: 'inetOrgPerson', + userIdAttr: 'entryUUID', groupObjectClass: 'groupOfUniqueNames', groupMemberAttr: 'uniqueMember', + port: 636, maxConcurrentOperations: 10, requestTimeoutSeconds: 30, + }); + expect(parseLdapConfig({ ...enabled, LDAP_DIRECTORY_TYPE: 'ad', LDAP_TLS_MODE: 'starttls', + LDAP_USER_ELIGIBILITY_FILTER: '' })).toMatchObject({ + port: 389, userIdAttr: 'objectGUID', groupObjectClass: 'group', groupMemberAttr: 'member', + userLookupAttr: 'sAMAccountName', + }); + }); + + it.each([ + ['LDAP_DIRECTORY_ID', 'bad/scope'], ['LDAP_DIRECTORY_TYPE', 'freeipa'], + ['LDAP_HOSTNAME', 'ldap://host.example'], ['LDAP_HOSTNAME', '127.0.0.1'], + ['LDAP_HOSTNAME', 'host'], ['LDAP_HOSTNAME', 'reader@host.example'], + ['LDAP_HOSTNAME', 'host.example/path'], ['LDAP_HOSTNAME', 'a..test'], + ['LDAP_PORT', '0'], ['LDAP_PORT', '65536'], ['LDAP_PORT', '389x'], ['LDAP_PORT', ''], + ['LDAP_FAILOVER_ENDPOINTS', '{}'], ['LDAP_FAILOVER_ENDPOINTS', 'invalid'], + ['LDAP_FAILOVER_ENDPOINTS', '[{"hostname":"other.example","port":636,"tlsMode":"plain"}]'], + ['LDAP_FAILOVER_ENDPOINTS', JSON.stringify(Array.from({ length: 5 }, () => ({ hostname: 'other.example', port: 636 })))], + ['LDAP_TLS_MODE', 'plain'], ['LDAP_CA_FILE', '/tmp/pabawi-missing-directory-ca.pem'], + ['LDAP_BASE_DN', 'bad DN'], ['LDAP_BASE_DN', ''], ['LDAP_USER_RDN', 'bad'], + ['LDAP_LOOKUP_USER', 'bad DN'], ['LDAP_LOOKUP_PASSWORD', ''], + ['LDAP_ANONYMOUS_LOOKUP', 'true'], ['LDAP_ALLOW_WILDCARD_CERTIFICATES', '1'], + ['LDAP_USER_ID_ATTR', 'uid)(objectClass=*'], ['LDAP_GROUP_LOOKUP_ATTR', 'cn;unsafe'], + ['LDAP_USER_ELIGIBILITY_FILTER', ''], ['LDAP_USER_ELIGIBILITY_FILTER', '(&(uid=*)'], + ['LDAP_GROUP_MEMBER_ATTR', 'memberUid'], ['LDAP_LOGIN_HELP_URL', 'javascript:alert(1)'], + ['LDAP_LOGIN_HELP_URL', 'https://user:pass@example.test/'], // pragma: allowlist secret (synthetic invalid URL) + ['LDAP_CONNECT_TIMEOUT_SECONDS', '31'], ['LDAP_OPERATION_TIMEOUT_SECONDS', '0'], + ['LDAP_REQUEST_TIMEOUT_SECONDS', '61'], ['LDAP_NESTED_GROUP_MAX_DEPTH', '33'], + ['LDAP_GROUP_SEARCH_LIMIT', '501'], ['LDAP_GROUP_TRAVERSAL_LIMIT', '10001'], + ['LDAP_REVALIDATION_INTERVAL_SECONDS', '301'], ['LDAP_MAX_CONCURRENT_OPERATIONS', '101'], + ])('rejects malformed %s', (name, value) => { + expect(() => parseLdapConfig({ ...enabled, [name]: value })).toThrow(); + }); + + it('requires consistent explicit anonymous configuration', () => { + expect(parseLdapConfig({ ...enabled, LDAP_LOOKUP_USER: undefined, LDAP_LOOKUP_PASSWORD: undefined, + LDAP_ANONYMOUS_LOOKUP: 'true' })).toMatchObject({ anonymousLookup: true, lookupUser: '', lookupPassword: '' }); + }); + + it('accepts parsed escaped DNs, OID attributes and complete filters', () => { + expect(parseLdapConfig({ ...enabled, LDAP_USER_RDN: 'ou=People\\, staff', + LDAP_USER_ID_ATTR: '1.3.6.1.1.16.4', LDAP_USER_ELIGIBILITY_FILTER: '(&(employeeType=active)(uid=*))' })).toBeDefined(); + }); + + it('preserves configured binary and UTF-8 filter assertion bytes', () => { + for (const filter of ['(displayName=é)', '(displayName=\\c3\\a9)', '(displayName=*\\c3\\a9*)']) { + const writer = new BerWriter(); + parseLdapFilter(filter).write(writer); + expect(writer.buffer.includes(Buffer.from('é', 'utf8'))).toBe(true); + } + const writer = new BerWriter(); + parseLdapFilter('(objectGUID=\\ff\\00\\80)').write(writer); + expect(writer.buffer.includes(Buffer.from([255, 0, 128]))).toBe(true); + }); + + it('validates enabled config at startup without attempting network access', () => { + for (const [key, value] of Object.entries(enabled)) vi.stubEnv(key, value); + vi.stubEnv('JWT_SECRET', 'pabawi-ldap-config-fixture-secret-long'); // pragma: allowlist secret + vi.stubEnv('LDAP_HOSTNAME', 'unreachable.invalid'); + const service = new ConfigService(); + expect(service.getLdapConfig()).toMatchObject({ enabled: true, hostname: 'unreachable.invalid' }); + vi.stubEnv('LDAP_TLS_MODE', 'plain'); + expect(() => new ConfigService()).toThrow('tlsMode'); + }); +}); diff --git a/backend/test/config/LdapDn.test.ts b/backend/test/config/LdapDn.test.ts new file mode 100644 index 00000000..427ef343 --- /dev/null +++ b/backend/test/config/LdapDn.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest'; +import fc from 'fast-check'; +import { ldapDnEquals, ldapDnWithinScope, parseLdapDn } from '../../src/config/ldapDn'; + +describe('project-owned RFC 4514 DN parsing and conservative comparison', () => { + it('recognizes root, OIDs, empty values and unordered multi-valued RDNs', () => { + expect(parseLdapDn('')).toEqual([]); + expect(parseLdapDn('cn=,dc=example')).toHaveLength(2); + expect(parseLdapDn('1.2.840.113556.1.4.656=opaque')).toHaveLength(1); + expect(ldapDnEquals('CN=Alice+uid=a,dc=example', 'UID=a+cn=Alice,DC=example')).toBe(true); + expect(ldapDnEquals('cn=Alice,dc=example', 'cn=alice,dc=example')).toBe(false); + expect(ldapDnEquals('cn=Alice,dc=example', 'cn=Alice,dc=Example')).toBe(false); + expect(ldapDnEquals('cn=Alice+uid=a,dc=example', 'cn=Alice,dc=example')).toBe(false); + }); + + it('decodes escaped UTF-8 bytes and separators without losing value boundaries', () => { + expect(ldapDnEquals(String.raw`cn=Jos\c3\a9\, Admin,dc=example`, String.raw`cn=José\2c Admin,dc=example`)).toBe(true); + expect(ldapDnEquals(String.raw`cn=\ Alice\ ,dc=example`, String.raw`cn=\20Alice\20,dc=example`)).toBe(true); + expect(ldapDnEquals(String.raw`cn=\#a\+b\=c\\d,dc=example`, String.raw`cn=\23a\2bb=c\5cd,dc=example`)).toBe(true); + expect(ldapDnEquals(String.raw`cn=a\00b,dc=example`, String.raw`cn=a\00b,dc=example`)).toBe(true); + expect(ldapDnEquals('cn=😀,dc=example', String.raw`cn=\f0\9f\98\80,dc=example`)).toBe(true); + expect(ldapDnEquals('cn=\ufeffa', 'cn=a')).toBe(false); + expect(ldapDnEquals(String.raw`cn=a\2cb,dc=example`, 'cn=a,cn=b,dc=example')).toBe(false); + }); + + it('preserves complete BER hex values without equating opaque bytes to text', () => { + expect(ldapDnEquals('1.2.3=#0402ABCD', '1.2.3=#0402abcd')).toBe(true); + expect(ldapDnEquals('cn=#0c0141', 'cn=A')).toBe(false); + expect(ldapDnEquals('1.2.3=#040200ff', '1.2.3=#040200fe')).toBe(false); + }); + + it('checks parsed suffixes rather than textual endings or case-folded values', () => { + expect(ldapDnWithinScope('uid=a,ou=People,dc=example', 'ou=People,dc=example')).toBe(true); + expect(ldapDnWithinScope('OU=People,DC=example', 'ou=People,dc=example')).toBe(true); + expect(ldapDnWithinScope('uid=a,ou=people,dc=example', 'ou=People,dc=example')).toBe(false); + expect(ldapDnWithinScope(String.raw`cn=outside\,ou=People,dc=example`, 'ou=People,dc=example')).toBe(false); + expect(ldapDnWithinScope('uid=a,dc=notexample', 'dc=example')).toBe(false); + expect(ldapDnWithinScope('', 'dc=example')).toBe(false); + expect(ldapDnWithinScope('dc=example', '')).toBe(false); + }); + + it.each(['bad', 'cn', '=a', 'cn=a,', 'cn=a+', 'cn=a,,dc=x', 'cn=a++uid=b', 'cn= a', 'cn=a ', + 'cn="a"', 'cn=a;b', 'cn=ab', 'cn=a\0b', 'cn=\ud800', 'cn=\udc00', + 'cn=a' + String.fromCharCode(92), String.raw`cn=\q`, String.raw`cn=\c3\28`, String.raw`cn=\ff`, + 'cn=#', 'cn=#1', 'cn=#zz', 'cn=#04', 'cn=#0402ff', 'cn=#0400ffff', 'cn=#04800000', 'cn=#0000', + 'cn=a+CN=a', '01.2=a', '1..2=a', 'cn;binary=a'])('rejects malformed or ambiguous input %j', value => { + expect(() => parseLdapDn(value)).toThrow(SyntaxError); + }); + + it('bounds input size and preserves randomly generated UTF-8 values across octet escaping', () => { + expect(() => parseLdapDn('cn=' + 'x'.repeat(8192))).toThrow(); + fc.assert(fc.property(fc.array(fc.integer({ min: 0x21, max: 0x10ffff }) + .filter(code => code < 0xd800 || code > 0xdfff), { minLength: 1, maxLength: 20 }), codes => { + const value = String.fromCodePoint(...codes); + const encoded = [...Buffer.from(value)].map(byte => '\\' + byte.toString(16).padStart(2, '0')).join(''); + const literal = [...value].map(character => ['#', '"', '+', ',', ';', '<', '=', '>', String.fromCharCode(92)].includes(character) ? String.fromCharCode(92) + character : character).join(''); + expect(ldapDnEquals('cn=' + encoded, 'CN=' + literal)).toBe(true); + expect(ldapDnWithinScope('uid=a,cn=' + encoded, 'cn=' + encoded)).toBe(true); + }), { numRuns: 200 }); + }); +}); diff --git a/backend/test/database/BatchLifecycleMigration.test.ts b/backend/test/database/BatchLifecycleMigration.test.ts index b0b124a6..bc50d574 100644 --- a/backend/test/database/BatchLifecycleMigration.test.ts +++ b/backend/test/database/BatchLifecycleMigration.test.ts @@ -42,7 +42,7 @@ for (const dialect of ['sqlite', 'postgres'] as const) { const batch = await db.queryOne>("SELECT * FROM batch_executions WHERE id = 'batch'"); const runner = new MigrationRunner(db, migrations); // Every migration from 029 onwards has to leave the populated history below intact. - expect(await runner.runPendingMigrations()).toBe(2); + expect(await runner.runPendingMigrations()).toBe(6); expect(await db.queryOne("SELECT * FROM executions WHERE id = 'child'")).toMatchObject({ ...original, created_at: original!.started_at, user_id: 'actor', cancellation_requested_at: null, }); diff --git a/backend/test/database/authorization-state.test.ts b/backend/test/database/authorization-state.test.ts index 7b1cfc2e..7ef017e1 100644 --- a/backend/test/database/authorization-state.test.ts +++ b/backend/test/database/authorization-state.test.ts @@ -34,8 +34,8 @@ for (const dialect of ['sqlite', 'postgres'] as const) { await writer.execute("INSERT INTO user_roles VALUES ('user', 'role-viewer-001', 'now')"); const permissions = new PermissionService(reader); const auth = new AuthenticationService(reader, 'database-session-revocation-test-secret'); - const token = await auth.generateToken({ id: 'user', username: 'user' }); - const refresh = await auth.generateRefreshToken({ id: 'user', username: 'user' }); + const token = await auth.generateToken({ id: 'user', username: 'user' }, { provider: 'local', identityId: null }); + const refresh = await auth.generateRefreshToken({ id: 'user', username: 'user' }, { provider: 'local', identityId: null }); expect(await permissions.hasPermission('user', 'executions', 'read')).toBe(true); await writer.execute("DELETE FROM user_roles WHERE user_id = 'user'"); expect(await permissions.hasPermission('user', 'executions', 'read')).toBe(false); @@ -51,7 +51,7 @@ for (const dialect of ['sqlite', 'postgres'] as const) { expect(await permissions.hasPermission('user', 'executions', 'read')).toBe(false); await expect(auth.verifyToken(token)).rejects.toThrow('revoked'); expect((await auth.refreshToken(refresh)).success).toBe(false); - const fresh = await auth.generateToken({ id: 'user', username: 'user' }); + const fresh = await auth.generateToken({ id: 'user', username: 'user' }, { provider: 'local', identityId: null }); await writer.execute("UPDATE users SET password_hash = 'new-hash' WHERE id = 'user'"); await expect(auth.verifyToken(fresh)).rejects.toThrow('revoked'); const transactionPermissions = new PermissionService(writer); @@ -59,7 +59,7 @@ for (const dialect of ['sqlite', 'postgres'] as const) { let rolledBackToken = ''; await expect(writer.withTransaction(async () => { await writer.execute("UPDATE users SET is_admin = 1 WHERE id = 'user'"); - rolledBackToken = await writerAuth.generateToken({ id: 'user', username: 'user' }); + rolledBackToken = await writerAuth.generateToken({ id: 'user', username: 'user' }, { provider: 'local', identityId: null }); expect(await transactionPermissions.hasPermission('user', 'executions', 'read')).toBe(true); throw new Error('rollback cached revision'); })).rejects.toThrow('rollback cached revision'); diff --git a/backend/test/database/external-identity-boundaries.test.ts b/backend/test/database/external-identity-boundaries.test.ts new file mode 100644 index 00000000..9f61b4c4 --- /dev/null +++ b/backend/test/database/external-identity-boundaries.test.ts @@ -0,0 +1,353 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { copyFileSync, mkdirSync, mkdtempSync, readdirSync, rmSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import { MigrationRunner } from '../../src/database/MigrationRunner'; +import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; +import { UserService } from '../../src/services/UserService'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { PermissionService } from '../../src/services/PermissionService'; +import { EntraIdService, type IdTokenClaims } from '../../src/services/EntraIdService'; +import { RoleService } from '../../src/services/RoleService'; +import { AuditLoggingService } from '../../src/services/AuditLoggingService'; +import { LoggerService } from '../../src/services/LoggerService'; + +const migrations = join(__dirname, '../../src/database/migrations'); +const databaseUrl = process.env.TEST_DATABASE_URL; +const issuer = 'https://login.microsoftonline.com/tenant/v2.0'; +const fixturePassword = 'ValidPass123!'; // pragma: allowlist secret +const fixtureClientSecret = 'fixture'; // pragma: allowlist secret +const claims: IdTokenClaims = { sub: 'subject', iss: issuer, aud: 'client', exp: 9999999999, + nonce: 'nonce', email: 'entra@example.test', preferred_username: 'entrauser', given_name: 'Entra', family_name: 'User' }; + +async function externalUser(db: DatabaseAdapter, id: string, email: string | null = null): Promise { + await db.execute(`INSERT INTO users + (id, username, email, password_hash, local_auth_enabled, first_name, last_name, created_at, updated_at) + VALUES (?, ?, ?, NULL, 0, '', '', 'now', 'now')`, [id, `ldap:${id}`, email]); +} + +async function identity(db: DatabaseAdapter, id: string, user: string, provider = 'ldap', scope = 'directory'): Promise { + await db.execute(`INSERT INTO federated_identities (id, user_id, provider, issuer, subject, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, 'now', 'now')`, [id, user, provider, scope, id]); +} + +async function ldapIdentity(db: DatabaseAdapter, id = 'ldap', user = 'external'): Promise { + await identity(db, id, user); + await db.execute(`INSERT INTO ldap_directory_state (directory_id) VALUES ('directory') ON CONFLICT DO NOTHING`); + await db.execute(`INSERT INTO ldap_identity_metadata (identity_id, directory_id, login_name, dn) + VALUES (?, 'directory', 'login', 'uid=login,dc=example')`, [id]); +} + +async function mapping(db: DatabaseAdapter, id: string): Promise { + await db.execute(`INSERT INTO external_group_mappings + (id, directory_id, group_subject, group_dn, group_name, role_id, created_at, updated_at) + VALUES (?, 'directory', ?, ?, ?, 'role-viewer-001', 'now', 'now')`, [id, id, `cn=${id},dc=example`, id]); +} + +async function grant(db: DatabaseAdapter, mappingId: string): Promise { + await db.execute(`INSERT INTO federated_user_roles (user_id, role_id, identity_id, source_key, mapping_id, directory_id) + VALUES ('external', 'role-viewer-001', 'ldap', ?, ?, 'directory')`, [`mapping:${mappingId}`, mappingId]); +} + +for (const dialect of ['sqlite', 'postgres'] as const) { + describe.skipIf(dialect === 'postgres' && !databaseUrl)(`${dialect}: external identity boundaries`, () => { + let dir: string; + let url: string; + let control: PostgresAdapter | undefined; + let database: DatabaseService; + let db: DatabaseAdapter; + let reader: DatabaseAdapter; + let users: UserService; + let auth: AuthenticationService; + let entra: EntraIdService; + let schema: string; + + beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), 'pabawi-ldap-schema-')); + schema = `ldap_${randomUUID().replaceAll('-', '')}`; + url = ''; + if (dialect === 'postgres' && databaseUrl) { + control = new PostgresAdapter(databaseUrl); + await control.initialize(); + await control.execute(`CREATE SCHEMA ${schema}`); + const scoped = new URL(databaseUrl); + scoped.searchParams.set('options', `-csearch_path=${schema}`); + url = scoped.toString(); + } + database = new DatabaseService(join(dir, 'live.db'), dialect, url); + await database.initialize(); + db = database.getAdapter(); + reader = dialect === 'sqlite' ? new SQLiteAdapter(join(dir, 'live.db')) : new PostgresAdapter(url); + await reader.initialize(); + auth = new AuthenticationService(db, 'external-identity-fixture-secret'); + users = new UserService(db, auth); + entra = new EntraIdService(db, { enabled: true, tenantId: 'tenant', clientId: 'client', clientSecret: fixtureClientSecret, + redirectUri: 'http://localhost/callback', scopes: ['openid'], groupMapping: { A: 'Viewer', B: 'Viewer' }, jwksCacheTtlMs: 1000 }, + auth, users, new RoleService(db), new AuditLoggingService(db), new LoggerService()); + }); + + afterEach(async () => { + await reader?.close(); + await database?.close(); + if (control) { + await control.execute(`DROP SCHEMA ${schema} CASCADE`); + await control.close(); + control = undefined; + } + rmSync(dir, { recursive: true, force: true }); + }); + + it('allows null and duplicate external emails while local lookup and uniqueness remain unambiguous', async () => { + await externalUser(db, 'one'); + await externalUser(db, 'two'); + await externalUser(db, 'three', 'shared@example.test'); + await externalUser(db, 'four', 'shared@example.test'); + expect((await users.getUserById('one'))?.passwordHash).toBeNull(); + expect(users.toUserDTO((await users.getUserById('one'))!).email).toBeNull(); + expect(await users.findLocalByEmail('shared@example.test')).toBeNull(); + const local = await users.createUser({ username: 'local', email: 'shared@example.test', password: fixturePassword, firstName: 'Local', lastName: 'User' }); + expect((await users.findLocalByEmail('shared@example.test'))?.id).toBe(local.id); + expect(await users.findAllByEmail('shared@example.test')).toHaveLength(3); + await expect(users.createUser({ username: 'another', email: 'shared@example.test', password: fixturePassword, firstName: '', lastName: '' })).rejects.toThrow('Email already exists'); + await expect(db.execute(`INSERT INTO users (id, username, email, first_name, last_name, created_at, updated_at) + VALUES ('duplicate', 'duplicate', 'shared@example.test', '', '', 'now', 'now')`)).rejects.toThrow(); + await expect(db.execute(`UPDATE users SET email = NULL WHERE id = ?`, [local.id])).rejects.toThrow(); + await expect(db.execute(`UPDATE users SET password_hash = ? WHERE id = 'one'`, ['hash'])).rejects.toThrow(); + expect((await auth.authenticate('local', fixturePassword)).success).toBe(true); + expect((await auth.authenticate('ldap:one', fixturePassword)).success).toBe(false); + await expect(users.createUser({ username: 'LDAP:reserved', email: 'reserved@example.test', password: fixturePassword, firstName: '', lastName: '' })).rejects.toThrow('reserved'); + }); + + it('preserves Entra collision rejection with any email match and permits missing contact email', async () => { + await externalUser(db, 'one', claims.email); + await externalUser(db, 'two', claims.email); + await expect(entra.provisionUser(claims)).rejects.toMatchObject({ code: 'IDENTITY_COLLISION' }); + expect(await db.query('SELECT id FROM federated_identities')).toEqual([]); + for (const name of ['first', 'second']) { + const user = await entra.provisionUser({ ...claims, sub: name, email: '', preferred_username: name }); + expect(user.email).toBeNull(); + expect(user.localAuthEnabled).toBe(0); + expect(await users.getUserRoles(user.id)).toHaveLength(1); + } + }); + + it('keys identities by provider, issuer and subject and preserves identity during locator changes', async () => { + await externalUser(db, 'external'); + await ldapIdentity(db); + await identity(db, 'other', 'external', 'ldap', 'other-directory'); + await db.execute(`UPDATE federated_identities SET subject = 'ldap' WHERE id = 'other'`); + await expect(identity(db, 'third', 'external')).resolves.toBeUndefined(); + await expect(db.execute(`UPDATE federated_identities SET subject = 'ldap' WHERE id = 'third'`)).rejects.toThrow(); + expect((await users.findByFederatedIdentity('ldap', 'ldap', 'directory'))?.id).toBe('external'); + const originalVersion = await db.queryOne('SELECT session_version FROM users WHERE id = ?', ['external']); + await db.execute(`UPDATE ldap_identity_metadata SET login_name = 'renamed', dn = 'uid=renamed,ou=moved,dc=example' WHERE identity_id = 'ldap'`); + await db.execute(`UPDATE users SET display_name = 'Single Display Name', first_name = '', last_name = '', email = NULL, updated_at = 'later' WHERE id = 'external'`); + expect(await db.queryOne('SELECT session_version FROM users WHERE id = ?', ['external'])).toEqual(originalVersion); + expect((await users.getUserById('external'))?.displayName).toBe('Single Display Name'); + await externalUser(db, 'replacement'); + await ldapIdentity(db, 'new-object', 'replacement'); + expect((await users.findByFederatedIdentity('ldap', 'new-object', 'directory'))?.id).toBe('replacement'); + await expect(db.execute(`UPDATE ldap_identity_metadata SET directory_id = 'other-directory' WHERE identity_id = 'ldap'`)).rejects.toThrow(); + }); + + it('preserves explicit Entra password administration and rejects local credentials for LDAP identities', async () => { + const user = await entra.provisionUser(claims); + expect((await auth.authenticate(user.username, fixturePassword)).success).toBe(false); + await users.updateUser(user.id, { password: fixturePassword }); + expect((await users.getUserById(user.id))?.localAuthEnabled).toBe(1); + expect((await auth.authenticate(user.username, fixturePassword)).success).toBe(true); + expect((await entra.provisionUser(claims)).id).toBe(user.id); + await externalUser(db, 'external'); + await ldapIdentity(db); + await expect(users.updateUser('external', { password: fixturePassword })).rejects.toThrow('cannot have local passwords'); + expect((await users.getUserById('external'))?.passwordHash).toBeNull(); + await expect(auth.generateTokenPair({ id: 'external', username: 'ldap:external' }, { provider: 'local', identityId: null })) + .rejects.toThrow('Invalid token'); + const contactless = await entra.provisionUser({ ...claims, sub: 'contactless', email: '', preferred_username: 'contactless' }); + const contactlessIdentity = await db.queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [contactless.id]); + const { refreshToken } = await auth.generateTokenPair(contactless, { provider: 'entra-id', identityId: contactlessIdentity!.id }); + expect((await auth.refreshToken(refreshToken)).user?.email).toBeNull(); + }); + + it('serializes concurrent Entra email collision checks after removal of the global email index', async () => { + const readerAuth = new AuthenticationService(reader, 'external-identity-fixture-secret'); + const otherEntra = new EntraIdService(reader, { enabled: true, tenantId: 'tenant', clientId: 'client', clientSecret: fixtureClientSecret, + redirectUri: 'http://localhost/callback', scopes: ['openid'], groupMapping: null, jwksCacheTtlMs: 1000 }, + readerAuth, new UserService(reader, readerAuth), new RoleService(reader), new AuditLoggingService(reader), new LoggerService()); + const results = await Promise.allSettled([entra, otherEntra].map((service, index) => service.provisionUser({ + ...claims, sub: `subject-${String(index)}`, preferred_username: `user_${String(index)}`, + }))); + expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1); + expect(results.filter(result => result.status === 'rejected')).toHaveLength(1); + expect(await users.findAllByEmail(claims.email)).toHaveLength(1); + expect(await db.query('SELECT id FROM federated_identities')).toHaveLength(1); + }); + + it('deduplicates effective roles while preserving mapping, manual and other identity provenance', async () => { + await externalUser(db, 'external'); + await ldapIdentity(db); + await identity(db, 'entra', 'external', 'entra-id', issuer); + await identity(db, 'another-entra', 'external', 'entra-id', issuer); + await db.execute(`INSERT INTO federated_user_roles (user_id, role_id, identity_id, source_key) + VALUES ('external', 'role-viewer-001', 'another-entra', 'other-source')`); + await mapping(db, 'one'); + await mapping(db, 'two'); + await grant(db, 'one'); + await grant(db, 'two'); + await entra.syncGroupRoles('entra', ['A', 'B']); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(5); + expect(await users.getUserRoles('external')).toHaveLength(1); + await entra.syncGroupRoles('entra', []); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(3); + await db.execute(`INSERT INTO user_roles VALUES ('external', 'role-viewer-001', 'now')`); + const permissions = new PermissionService(reader); + expect(await permissions.hasPermission('external', 'executions', 'read')).toBe(true); + await db.execute(`DELETE FROM external_group_mappings WHERE id = 'one'`); + expect(await db.query(`SELECT mapping_id FROM federated_user_roles WHERE identity_id = 'ldap'`)).toEqual([{ mapping_id: 'two' }]); + expect(await permissions.hasPermission('external', 'executions', 'read')).toBe(true); + await db.execute(`UPDATE external_group_mappings SET enabled = 0 WHERE id = 'two'`); + expect(await db.query(`SELECT * FROM federated_user_roles WHERE identity_id = 'ldap'`)).toEqual([]); + await db.execute(`DELETE FROM federated_identities WHERE id = 'another-entra'`); + expect(await permissions.hasPermission('external', 'executions', 'read')).toBe(true); + await db.execute(`DELETE FROM user_roles WHERE user_id = 'external'`); + expect(await permissions.hasPermission('external', 'executions', 'read')).toBe(false); + await expect(entra.syncGroupRoles('ldap', ['A'])).rejects.toThrow('identity is missing'); + }); + + it('enforces grant ownership and invalidates persisted validation on mapping changes across connections', async () => { + await externalUser(db, 'external'); + await externalUser(db, 'other-user'); + await ldapIdentity(db); + await mapping(db, 'one'); + await grant(db, 'one'); + await db.execute(`INSERT INTO ldap_validation_state + (identity_id, last_validated_at, validation_generation, mapping_revision, config_revision) + VALUES ('ldap', 1000, 3, 1, 'config')`); + await db.execute(`INSERT INTO ldap_validation_leases (identity_id, lease_owner, lease_expires_at, fencing_generation) + VALUES ('ldap', 'process', 2000, 4)`); + await expect(db.execute(`UPDATE federated_user_roles SET user_id = 'other-user'`)).rejects.toThrow(); + await expect(db.execute(`UPDATE federated_user_roles SET directory_id = 'other-directory'`)).rejects.toThrow(); + const before = await reader.queryOne<{ revision: string }>('SELECT revision FROM authorization_state'); + await db.execute(`UPDATE external_group_mappings SET group_dn = 'cn=moved,dc=example' WHERE id = 'one'`); + expect(String((await reader.queryOne<{ mapping_revision: string }>('SELECT mapping_revision FROM ldap_directory_state'))?.mapping_revision)).toBe('2'); + expect(await reader.queryOne('SELECT last_validated_at FROM ldap_validation_state')).toEqual({ last_validated_at: null }); + expect(await reader.queryOne('SELECT revision FROM authorization_state')).not.toEqual(before); + expect(await reader.query('SELECT * FROM federated_user_roles')).toEqual([]); + await grant(db, 'one'); + await db.execute(`UPDATE external_group_mappings SET role_id = 'role-operator-001' WHERE id = 'one'`); + expect(await reader.query('SELECT * FROM federated_user_roles')).toEqual([]); + await expect(db.withTransaction(async () => { + await db.execute(`DELETE FROM external_group_mappings WHERE id = 'one'`); + throw new Error('rollback mapping'); + })).rejects.toThrow('rollback mapping'); + expect(String((await reader.queryOne<{ mapping_revision: string }>('SELECT mapping_revision FROM ldap_directory_state'))?.mapping_revision)).toBe('3'); + await db.execute(`DELETE FROM users WHERE id = 'external'`); + for (const table of ['federated_identities', 'ldap_identity_metadata', 'ldap_validation_state', 'ldap_validation_leases']) { + expect(await db.query(`SELECT * FROM ${table}`)).toEqual([]); + } + if (dialect === 'sqlite') expect(await db.query('PRAGMA foreign_key_check')).toEqual([]); + }); + + it('upgrades a populated migration-030 database preserving enrollments and relationships with intentional session invalidation', async () => { + // Use a second isolated schema/file so the fixture really predates migration 031. + const partial = join(dir, 'migrations'); + mkdirSync(partial); + for (const file of readdirSync(migrations)) { + if (file.slice(0, 3) <= '030') copyFileSync(join(migrations, file), join(partial, file)); + } + const upgradeSchema = `${schema}_upgrade`; + if (control) await control.execute(`CREATE SCHEMA ${upgradeSchema}`); + const upgradeUrl = new URL(url || 'postgresql://localhost/unused'); + upgradeUrl.searchParams.set('options', `-csearch_path=${upgradeSchema}`); + const old = dialect === 'sqlite' ? new SQLiteAdapter(join(dir, 'upgrade.db')) : new PostgresAdapter(upgradeUrl.toString()); + await old.initialize(); + try { + await new MigrationRunner(old, partial).runPendingMigrations(); + for (const [id, password] of [['local', 'hash'], ['enrolled', 'hash'], ['federated', null], ['detached', null]]) { + await old.execute(`INSERT INTO users (id, username, email, password_hash, first_name, last_name, created_at, updated_at, session_version) + VALUES (?, ?, ?, ?, '', '', 'now', 'now', 'abc123')`, [id, id, `${id}@example.test`, password]); + } + for (const user of ['enrolled', 'federated']) { + await identity(old, `${user}-identity`, user, 'entra-id', issuer); + await old.execute(`INSERT INTO federated_user_roles VALUES (?, 'role-viewer-001')`, [user]); + } + await old.execute(`INSERT INTO federated_user_roles VALUES ('detached', 'role-viewer-001')`); + await old.execute(`INSERT INTO user_roles VALUES ('enrolled', 'role-operator-001', 'now')`); + await old.execute(`INSERT INTO legacy_federated_user_roles VALUES ('enrolled', 'role-operator-001')`); + await old.execute(`INSERT INTO groups VALUES ('group', 'group', '', 'now', 'now')`); + await old.execute(`INSERT INTO user_groups VALUES ('enrolled', 'group', 'now')`); + await old.execute(`INSERT INTO revoked_tokens VALUES ('token', 'enrolled', 'now', 'later')`); + await old.execute(`INSERT INTO audit_logs (id, timestamp, event_type, "action", user_id, result) + VALUES ('audit', 'now', 'auth', 'login_success', 'enrolled', 'success')`); + await old.execute(`INSERT INTO journal_entries (id, node_id, node_uri, event_type, source, "action", summary, user_id, timestamp) + VALUES ('journal', 'n1', 'ssh://n1', 'note', 'user', 'note', 'fixture', 'enrolled', 'now')`); + const tables = ['federated_identities', 'user_groups', 'legacy_federated_user_roles', 'revoked_tokens', 'audit_logs', 'journal_entries']; + const before = await Promise.all(tables.map(table => old.query(`SELECT * FROM ${table}`))); + const accountColumns = 'id, username, email, password_hash, is_active, is_admin, first_name, last_name, created_at, updated_at, last_login_at'; + const accountsBefore = await old.query(`SELECT ${accountColumns} FROM users ORDER BY id`); + const permissionsBefore = await old.query('SELECT * FROM effective_user_roles ORDER BY user_id, role_id'); + await new MigrationRunner(old).runPendingMigrations(); + expect(await old.query(`SELECT ${accountColumns} FROM users ORDER BY id`)).toEqual(accountsBefore); + expect(await old.query("SELECT id FROM users WHERE session_version = 'abc123'")).toEqual([]); + expect(await Promise.all(tables.map(table => old.query(`SELECT * FROM ${table}`)))).toEqual(before); + expect(await old.query('SELECT * FROM effective_user_roles ORDER BY user_id, role_id')).toEqual(permissionsBefore); + expect(await old.query('SELECT user_id, identity_id, source_key FROM federated_user_roles ORDER BY user_id')).toEqual([ + { user_id: 'enrolled', identity_id: 'enrolled-identity', source_key: 'legacy' }, + { user_id: 'federated', identity_id: 'federated-identity', source_key: 'legacy' }, + ]); + expect(await old.query('SELECT id, local_auth_enabled FROM users ORDER BY id')).toEqual([ + { id: 'detached', local_auth_enabled: 0 }, { id: 'enrolled', local_auth_enabled: 1 }, + { id: 'federated', local_auth_enabled: 0 }, { id: 'local', local_auth_enabled: 1 }, + ]); + const oldAuth = new AuthenticationService(old, 'upgrade-fixture-secret'); + const token = await oldAuth.generateToken({ id: 'enrolled', username: 'enrolled' }, { provider: 'local', identityId: null }); + await old.execute(`UPDATE users SET display_name = 'Changed' WHERE id = 'enrolled'`); + await expect(oldAuth.verifyToken(token)).resolves.toBeDefined(); + await old.execute(`UPDATE users SET password_hash = ? WHERE id = 'enrolled'`, ['changed']); + await expect(oldAuth.verifyToken(token)).rejects.toThrow('revoked'); + expect((await new MigrationRunner(old).getStatus()).pending).toEqual([]); + if (dialect === 'sqlite') { + expect(await old.query('PRAGMA foreign_key_check')).toEqual([]); + expect(await old.query('PRAGMA integrity_check')).toEqual([{ integrity_check: 'ok' }]); + } + } finally { + await old.close(); + if (control) await control.execute(`DROP SCHEMA ${upgradeSchema} CASCADE`); + } + }); + }); +} + +describe('SQLite migration 031 rollback', () => { + it('restores the pre-upgrade schema and foreign keys after a rebuild fails', async () => { + const dir = mkdtempSync(join(tmpdir(), 'pabawi-ldap-rollback-')); + const db = new SQLiteAdapter(join(dir, 'live.db')); + await db.initialize(); + try { + for (const file of readdirSync(migrations)) { + if (file.slice(0, 3) <= '030') copyFileSync(join(migrations, file), join(dir, file)); + } + await new MigrationRunner(db, dir).runPendingMigrations(); + await db.execute(`INSERT INTO users (id, username, email, password_hash, first_name, last_name, created_at, updated_at) + VALUES ('user', 'user', 'user@example.test', 'hash', '', '', 'now', 'now')`); + await identity(db, 'entra', 'user', 'entra-id', issuer); + await db.execute(`INSERT INTO federated_user_roles VALUES ('user', 'role-viewer-001')`); + const filename = '031_external_identity_boundaries.sqlite.sql'; + writeFileSync(join(dir, filename), `${readFileSync(join(migrations, filename), 'utf8')}\n-- pabawi:statement-breakpoint\nINSERT INTO missing_table VALUES (1);`); + await expect(new MigrationRunner(db, dir).runPendingMigrations()).rejects.toThrow('missing_table'); + expect(await db.query('PRAGMA foreign_keys')).toEqual([{ foreign_keys: 1 }]); + expect(await db.query('SELECT * FROM effective_user_roles')).toEqual([{ user_id: 'user', role_id: 'role-viewer-001' }]); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([{ user_id: 'user', role_id: 'role-viewer-001' }]); + expect(await db.query("SELECT * FROM migrations WHERE id = '031'")).toEqual([]); + await new MigrationRunner(db).runPendingMigrations(); + expect(await db.query('PRAGMA foreign_key_check')).toEqual([]); + } finally { + await db.close(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/backend/test/database/federated-provisioning.test.ts b/backend/test/database/federated-provisioning.test.ts new file mode 100644 index 00000000..4e6427af --- /dev/null +++ b/backend/test/database/federated-provisioning.test.ts @@ -0,0 +1,185 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { UserService, type FederatedProvisioningInput } from '../../src/services/UserService'; +import { resetUserPassword } from '../../src/cli/resetUserPassword'; +import { AuditLoggingService } from '../../src/services/AuditLoggingService'; + +const fixturePassword = 'ValidPass123!'; // pragma: allowlist secret +const ldap: FederatedProvisioningInput = { + provider: 'ldap', issuer: 'directory', subject: 'immutable-subject', + loginName: 'alice', dn: 'uid=alice,dc=example', email: 'shared@example.test', + displayName: 'Alice', firstName: 'Alice', lastName: '', defaultRole: 'none', +}; +const entra: FederatedProvisioningInput = { + provider: 'entra-id', issuer: 'tenant', subject: 'subject', username: 'entra', + email: 'entra@example.test', displayName: null, firstName: 'Entra', lastName: '', defaultRole: 'configured', +}; + +for (const dialect of ['sqlite', 'postgres'] as const) { + describe.skipIf(dialect === 'postgres' && !process.env.TEST_DATABASE_URL)(`${dialect} shared external provisioning`, () => { + let directory: string; + let schema: string; + let control: PostgresAdapter | undefined; + let database: DatabaseService; + let db: DatabaseAdapter; + let reader: DatabaseAdapter; + let auth: AuthenticationService; + let users: UserService; + let other: UserService; + + beforeEach(async () => { + directory = mkdtempSync(join(tmpdir(), 'pabawi-provisioning-')); + schema = `provision_${randomUUID().replaceAll('-', '')}`; + let url = ''; + if (dialect === 'postgres') { + control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute(`CREATE SCHEMA ${schema}`); + const scoped = new URL(process.env.TEST_DATABASE_URL!); + scoped.searchParams.set('options', `-csearch_path=${schema}`); + url = scoped.toString(); + } + const file = join(directory, 'live.db'); + database = new DatabaseService(file, dialect, url); + await database.initialize(); + db = database.getAdapter(); + reader = dialect === 'sqlite' ? new SQLiteAdapter(file) : new PostgresAdapter(url); + await reader.initialize(); + auth = new AuthenticationService(db, 'external-provisioning-fixture-secret', undefined, 4); + users = new UserService(db, auth); + other = new UserService(reader, new AuthenticationService(reader, 'external-provisioning-fixture-secret', undefined, 4)); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await reader?.close(); + await database?.close(); + if (control) { + await control.execute(`DROP SCHEMA ${schema} CASCADE`); + await control.close(); + control = undefined; + } + rmSync(directory, { recursive: true, force: true }); + }); + + it('converges concurrent first logins across connections without roles, credentials or tokens', async () => { + await db.execute("DELETE FROM config WHERE key = 'default_new_user_role'"); + const tokenSpy = vi.spyOn(auth, 'generateTokenPair'); + const accounts = await Promise.all(Array.from({ length: 12 }, (_, i) => (i % 2 ? users : other).createFederatedUser(ldap))); + expect(new Set(accounts.map(user => user.id)).size).toBe(1); + expect(accounts[0]).toMatchObject({ localAuthEnabled: 0, passwordHash: null, isAdmin: 0, isActive: 1 }); + expect(accounts[0].username).toMatch(/^ldap:[a-f0-9]{64}$/); + for (const table of ['users', 'federated_identities', 'ldap_identity_metadata', 'ldap_validation_state']) { + expect(await db.query(`SELECT * FROM ${table}`)).toHaveLength(1); + } + expect(await users.getUserRoles(accounts[0].id)).toEqual([]); + expect(await db.queryOne('SELECT last_validated_at, validation_generation, config_revision FROM ldap_validation_state')) + .toMatchObject({ last_validated_at: null, config_revision: '' }); + expect(await db.query('SELECT * FROM oauth_auth_codes')).toEqual([]); + expect(tokenSpy).not.toHaveBeenCalled(); + expect((await auth.authenticate(accounts[0].username, fixturePassword)).success).toBe(false); + await users.assignRoleToUser(accounts[0].id, 'role-viewer-001'); + const returning = await users.createFederatedUser(ldap); + expect(returning.id).toBe(accounts[0].id); + expect(await users.getUserRoles(returning.id)).toHaveLength(1); + }); + + it('refreshes directory profile and locators without reactivating, changing manual grants or rotating sessions', async () => { + const user = await users.createFederatedUser(ldap); + const originalVersion = await db.queryOne('SELECT session_version FROM users WHERE id = ?', [user.id]); + await users.createFederatedUser({ ...ldap, displayName: 'Updated Directory Name' }); + expect(await db.queryOne('SELECT session_version FROM users WHERE id = ?', [user.id])).toEqual(originalVersion); + await expect(auth.generateToken(user, { provider: 'local', identityId: null })).rejects.toThrow('Invalid token'); + await users.assignRoleToUser(user.id, 'role-viewer-001'); + await users.updateUser(user.id, { isActive: false, isAdmin: true }); + const version = await db.queryOne('SELECT session_version FROM users WHERE id = ?', [user.id]); + const result = await users.createFederatedUser({ ...ldap, loginName: 'renamed', dn: 'uid=renamed,ou=moved,dc=example', + email: null, displayName: 'Unsplit Full Name', firstName: '', lastName: '' }); + expect(result).toMatchObject({ id: user.id, username: user.username, email: null, displayName: 'Unsplit Full Name', + firstName: '', lastName: '', isActive: 0, isAdmin: 1, passwordHash: null }); + expect(await db.queryOne('SELECT session_version FROM users WHERE id = ?', [user.id])).toEqual(version); + expect(await users.getUserRoles(user.id)).toHaveLength(1); + expect(await db.queryOne('SELECT login_name, dn FROM ldap_identity_metadata')) + .toEqual({ login_name: 'renamed', dn: 'uid=renamed,ou=moved,dc=example' }); + }); + + it('never links matching local, Entra or LDAP contacts and scopes immutable subjects by directory', async () => { + const local = await users.createUser({ username: 'alice', email: ldap.email!, password: fixturePassword, firstName: 'Local', lastName: 'User' }); + const external = await users.createFederatedUser(ldap); + const replacement = await users.createFederatedUser({ ...ldap, subject: 'replacement' }); + const anotherDirectory = await users.createFederatedUser({ ...ldap, issuer: 'another-directory' }); + const noEmail = await users.createFederatedUser({ ...ldap, subject: 'no-email', email: null }); + const federated = await users.createFederatedUser({ ...entra, username: 'another', subject: 'another' }); + const sameContact = await users.createFederatedUser({ ...ldap, subject: 'entra-contact', email: federated.email }); + expect(new Set([local, external, replacement, anotherDirectory, noEmail, sameContact].map(user => user.id)).size).toBe(6); + expect(new Set([external, replacement, anotherDirectory].map(user => user.username)).size).toBe(3); + expect(await users.findLocalByEmail(ldap.email!)).toMatchObject({ id: local.id }); + await expect(users.linkFederatedIdentity(local.id, 'ldap', 'subject', 'directory', null)) + .rejects.toMatchObject({ code: 'DIRECTORY_ACCOUNT_READ_ONLY' }); + await expect(users.linkFederatedIdentity(external.id, 'entra-id', 'subject', 'tenant', null)) + .rejects.toMatchObject({ code: 'DIRECTORY_ACCOUNT_READ_ONLY' }); + }); + + it('enforces profile ownership and CLI password rejection even for a legacy mixed account', async () => { + const user = await users.createFederatedUser(ldap); + for (const update of [{ email: 'changed@example.test' }, { firstName: 'Changed' }, { lastName: 'Changed' }, { password: fixturePassword }]) { + await expect(users.updateUser(user.id, update)).rejects.toMatchObject({ code: 'DIRECTORY_ACCOUNT_READ_ONLY' }); + } + await db.execute('UPDATE users SET local_auth_enabled = 1, password_hash = ? WHERE id = ?', + [await auth.hashPassword(fixturePassword), user.id]); + await expect(users.updateUser(user.id, { password: fixturePassword })).rejects.toMatchObject({ code: 'DIRECTORY_ACCOUNT_READ_ONLY' }); + await expect(resetUserPassword({ db, userService: users, authService: auth, auditLogger: new AuditLoggingService(db) }, + { username: user.username, password: fixturePassword, activate: true })).rejects.toMatchObject({ code: 'DIRECTORY_ACCOUNT_READ_ONLY' }); + expect((await users.getUserById(user.id))?.email).toBe(ldap.email); + }); + + it('preserves Entra defaults, returning profiles and explicitly enrolled local credentials', async () => { + const user = await users.createFederatedUser(entra); + expect(await users.getUserRoles(user.id)).toHaveLength(1); + const returning = await users.createFederatedUser({ ...entra, email: 'changed@example.test', firstName: 'Changed' }); + expect(returning).toMatchObject({ id: user.id, email: entra.email, firstName: entra.firstName }); + const local = await users.createUser({ username: 'local', email: 'local@example.test', password: fixturePassword, firstName: 'Local', lastName: 'User' }); + await users.linkFederatedIdentity(local.id, 'entra-id', 'enrolled', 'tenant', local.email); + const enrolled = await users.createFederatedUser({ ...entra, subject: 'enrolled', username: 'unused' }); + expect(enrolled).toMatchObject({ id: local.id, passwordHash: local.passwordHash, localAuthEnabled: 1 }); + }); + + it('serializes Entra contact collisions inside the shared transaction', async () => { + const results = await Promise.allSettled([users, other].map((service, i) => service.createFederatedUser({ + ...entra, subject: `subject-${String(i)}`, username: `entra_${String(i)}`, + }))); + expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1); + expect(results.find(result => result.status === 'rejected')).toMatchObject({ reason: { code: 'IDENTITY_COLLISION' } }); + expect(await db.query('SELECT * FROM users')).toHaveLength(1); + }); + + it('rolls back account and identity if metadata creation fails', async () => { + const execute = db.execute.bind(db); + vi.spyOn(db, 'execute').mockImplementation(async (sql, params) => { + if (sql.includes('INSERT INTO ldap_identity_metadata')) throw new Error('metadata write failed'); + return execute(sql, params); + }); + await expect(users.createFederatedUser(ldap)).rejects.toThrow('metadata write failed'); + for (const table of ['users', 'federated_identities', 'ldap_directory_state', 'ldap_validation_state', 'user_roles']) { + expect(await db.query(`SELECT * FROM ${table}`)).toEqual([]); + } + vi.restoreAllMocks(); + await expect(users.createFederatedUser(ldap)).resolves.toMatchObject({ localAuthEnabled: 0 }); + }); + + it('rejects missing immutable identity or locators without creating accounts', async () => { + for (const input of [{ ...ldap, subject: '' }, { ...ldap, issuer: ' ' }, { ...ldap, loginName: '' }, { ...ldap, dn: '' }]) { + await expect(users.createFederatedUser(input)).rejects.toMatchObject({ code: 'INVALID_EXTERNAL_IDENTITY' }); + } + expect(await db.query('SELECT * FROM users')).toEqual([]); + }); + }); +} diff --git a/backend/test/database/ldap-authentication.test.ts b/backend/test/database/ldap-authentication.test.ts new file mode 100644 index 00000000..0d165eba --- /dev/null +++ b/backend/test/database/ldap-authentication.test.ts @@ -0,0 +1,492 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { fork, type ChildProcess } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { UserService } from '../../src/services/UserService'; +import { LdapAuthenticationService, type LdapAuthenticationProof } from '../../src/services/LdapAuthenticationService'; +import { LdapMappingService } from '../../src/services/LdapMappingService'; +import { LdapDirectoryError, type LdapDirectoryResult } from '../../src/services/LdapDirectoryService'; +import { parseLdapConfig } from '../../src/config/ldap'; + +const password = 'directory-password-fixture'; // pragma: allowlist secret +const subject = '00112233-4455-6677-8899-aabbccddeeff'; +const groupSubject = '10112233-4455-6677-8899-aabbccddeeff'; +const otherGroup = '20112233-4455-6677-8899-aabbccddeeff'; +const viewer = 'role-viewer-001'; +const config = parseLdapConfig({ LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'ldap.example.test', LDAP_ANONYMOUS_LOOKUP: 'true', LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)' })!; +const result: LdapDirectoryResult = { user: { subject, dn: 'uid=a,dc=example,dc=test', loginName: 'a', displayName: 'A', + email: null, firstName: '', lastName: '' }, groupSubjects: [groupSubject] }; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} + +for (const dialect of ['sqlite', 'postgres'] as const) { + describe.skipIf(dialect === 'postgres' && !process.env.TEST_DATABASE_URL)(`${dialect} atomic LDAP authentication and freshness`, () => { + let folder: string; + let databaseUrl: string; + const children: ChildProcess[] = []; + let schema: string; + let control: PostgresAdapter | undefined; + let database: DatabaseService; + let db: DatabaseAdapter; + let reader: DatabaseAdapter; + let users: UserService; + let mappings: LdapMappingService; + let auth: AuthenticationService; + let service: LdapAuthenticationService; + let other: LdapAuthenticationService; + let directory: { authenticate: ReturnType; revalidate: ReturnType }; + + beforeEach(async () => { + folder = mkdtempSync(join(tmpdir(), 'pabawi-ldap-auth-')); + schema = `ldapauth_${randomUUID().replaceAll('-', '')}`; + let url = ''; + if (dialect === 'postgres') { + control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute(`CREATE SCHEMA ${schema}`); + const scoped = new URL(process.env.TEST_DATABASE_URL!); + scoped.searchParams.set('options', `-csearch_path=${schema}`); + url = scoped.toString(); + } + databaseUrl = url; + const file = join(folder, 'live.db'); + database = new DatabaseService(file, dialect, url); + await database.initialize(); + db = database.getAdapter(); + reader = dialect === 'sqlite' ? new SQLiteAdapter(file) : new PostgresAdapter(url); + await reader.initialize(); + auth = new AuthenticationService(db, 'ldap-authentication-fixture-jwt-secret'); + users = new UserService(db, auth); + directory = { authenticate: vi.fn().mockResolvedValue(result), revalidate: vi.fn().mockResolvedValue(result) }; + const resolveGroup = async (subject: string) => ({ subject, dn: 'cn=operators,dc=example,dc=test', name: 'Operators' }); + mappings = new LdapMappingService(db, config.directoryId, { resolveGroup }); + service = new LdapAuthenticationService(db, config, directory, mappings, users); + other = new LdapAuthenticationService(reader, config, directory, + new LdapMappingService(reader, config.directoryId, { resolveGroup }), + new UserService(reader, new AuthenticationService(reader, 'ldap-authentication-fixture-jwt-secret'))); + await service.initialize(); + await other.initialize(); + await db.execute(`INSERT INTO users (id, username, email, first_name, last_name, created_at, updated_at) + VALUES ('administrator', 'administrator', 'admin@example.test', '', '', 'now', 'now')`); + await mappings.create(groupSubject, viewer, { userId: 'administrator' }); + }); + + afterEach(async () => { + for (const child of children.splice(0)) { + if (child.exitCode === null && child.signalCode === null) { + const exited = once(child, 'exit'); + child.kill(); + await exited; + } + } + vi.restoreAllMocks(); + await reader?.close(); + await database?.close(); + if (control) { + await control.execute(`DROP SCHEMA ${schema} CASCADE`); + await control.close(); + control = undefined; + } + rmSync(folder, { recursive: true, force: true }); + }); + + async function login(): Promise { return service.authenticate('a', password); } + async function validate(proof: LdapAuthenticationProof, force = false, instance = service): Promise { + return instance.assertEligible(proof.user.id, proof.identityId, proof.directoryId, proof.sessionVersion, force); + } + async function state() { return db.queryOne('SELECT * FROM ldap_validation_state'); } + async function expire(): Promise { await db.execute('UPDATE ldap_validation_state SET last_validated_at = 1'); } + + it('publishes account, profile, exact grant provenance and freshness together, without JWT issuance', async () => { + const token = vi.spyOn(auth, 'generateTokenPair'); + const proof = await login(); + expect(proof.user).toMatchObject({ email: null, passwordHash: null, localAuthEnabled: 0, displayName: 'A' }); + expect(directory.authenticate).toHaveBeenCalledWith('a', password, [groupSubject]); + expect(await users.getUserRoles(proof.user.id)).toHaveLength(1); + expect(await db.query('SELECT identity_id, mapping_id, directory_id FROM federated_user_roles')) + .toEqual([{ identity_id: proof.identityId, mapping_id: (await mappings.list())[0].id, directory_id: 'directory' }]); + const saved = await state(); + expect(saved).toMatchObject({ identity_id: proof.identityId }); + expect(Number((saved as { last_validated_at: number }).last_validated_at)).toBeGreaterThan(0); + expect(token).not.toHaveBeenCalled(); + expect(await db.queryOne('SELECT lease_owner, lease_expires_at FROM ldap_validation_leases')) + .toEqual({ lease_owner: null, lease_expires_at: null }); + }); + + it('failed credentials cannot provision or alter existing freshness and grants', async () => { + directory.authenticate.mockRejectedValueOnce(new LdapDirectoryError('INVALID_CREDENTIALS')); + await expect(login()).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + expect(await db.query('SELECT * FROM federated_identities')).toEqual([]); + await login(); + const before = await state(); + directory.authenticate.mockRejectedValueOnce(new LdapDirectoryError('INVALID_CREDENTIALS')); + await expect(login()).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + expect(await state()).toEqual(before); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + }); + + it('commits a proven zero-role account, denies access and permits a later manually assigned login', async () => { + directory.authenticate.mockResolvedValue({ ...result, groupSubjects: [] }); + await expect(login()).rejects.toMatchObject({ code: 'DENIED' }); + const identity = await db.queryOne<{ user_id: string }>('SELECT user_id FROM federated_identities'); + expect(identity).not.toBeNull(); + expect(await state()).toMatchObject({ last_validated_at: null }); + await users.assignRoleToUser(identity!.user_id, viewer); + const proof = await login(); + expect(proof.user.id).toBe(identity!.user_id); + await expect(validate(proof)).resolves.toBeUndefined(); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([]); + }); + + it('never reactivates local suspension or restores sessions on profile refresh', async () => { + const proof = await login(); + await users.updateUser(proof.user.id, { isActive: false }); + await expect(login()).rejects.toMatchObject({ code: 'DENIED' }); + await expect(validate(proof)).rejects.toMatchObject({ code: 'INVALID_CONTEXT' }); + expect((await users.getUserById(proof.user.id))?.isActive).toBe(0); + expect(await state()).toMatchObject({ last_validated_at: null }); + }); + + it('reuses persisted fresh checks across processes while every forced refresh queries LDAP', async () => { + const proof = await login(); + await validate(proof); + await validate(proof, false, other); + expect(directory.revalidate).not.toHaveBeenCalled(); + await validate(proof, true); + await validate(proof, true, other); + expect(directory.revalidate).toHaveBeenCalledTimes(2); + }); + + it('blocks expired freshness on transient errors without extending timestamps or erasing grants, then recovers', async () => { + const proof = await login(); + await expire(); + const before = await state(); + directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('UNAVAILABLE')); + await expect(validate(proof)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + expect(await state()).toEqual(before); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + await expect(validate(proof, false, other)).resolves.toBeUndefined(); + expect(directory.revalidate).toHaveBeenCalledTimes(2); + }); + + it('does not change grants or freshness for incomplete, limited, timed-out or malformed directory work', async () => { + const proof = await login(); + const before = await state(); + const grants = await db.query('SELECT * FROM federated_user_roles'); + for (const code of ['INCOMPLETE_RESULT', 'LIMIT_EXCEEDED', 'TIMEOUT', 'POLICY_UNREADABLE', 'IDENTITY_CHANGED'] as const) { + directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError(code)); + await expect(validate(proof, true)).rejects.toMatchObject({ code }); + expect(await state()).toEqual(before); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual(grants); + } + }); + + it('positive revocation is terminal for old versions even after directory recovery and a new login', async () => { + const proof = await login(); + directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('INELIGIBLE')); + await expect(validate(proof, true)).rejects.toMatchObject({ code: 'DENIED' }); + expect(await state()).toMatchObject({ last_validated_at: null }); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([]); + await expect(validate(proof)).rejects.toMatchObject({ code: 'INVALID_CONTEXT' }); + const fresh = await login(); + expect(fresh.sessionVersion).not.toBe(proof.sessionVersion); + await expect(validate(fresh)).resolves.toBeUndefined(); + await expect(validate(proof, false, other)).rejects.toMatchObject({ code: 'INVALID_CONTEXT' }); + }); + + it('preserves manual and duplicate mapped grants, then revokes when the last explicit role is removed', async () => { + await mappings.create(otherGroup, viewer, { userId: 'administrator' }); + directory.authenticate.mockResolvedValueOnce({ ...result, groupSubjects: [groupSubject, otherGroup] }); + const proof = await login(); + await users.assignRoleToUser(proof.user.id, viewer); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(2); + await validate(proof, true); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + directory.revalidate.mockResolvedValue({ ...result, groupSubjects: [] }); + await validate(proof, true); + expect(await users.getUserRoles(proof.user.id)).toHaveLength(1); + await db.execute('DELETE FROM user_roles WHERE user_id = ?', [proof.user.id]); + await expect(validate(proof)).rejects.toMatchObject({ code: 'DENIED' }); + await expect(validate(proof)).rejects.toMatchObject({ code: 'INVALID_CONTEXT' }); + }); + + + function validationWorker(proof: LdapAuthenticationProof, response = result) { + const child = fork(join(__dirname, '../fixtures/ldap/validation-worker.ts'), [], { + execArgv: ['--import', 'tsx'], stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }); + children.push(child); + const exited = once(child, 'exit'); + let stderr = ''; + child.stderr!.on('data', chunk => { stderr += String(chunk); }); + let readingResolve!: (pid: number) => void; + let doneResolve!: (code: string) => void; + let readingReject!: (error: Error) => void; + let doneReject!: (error: Error) => void; + const reading = new Promise((resolve, reject) => { readingResolve = resolve; readingReject = reject; }); + const done = new Promise((resolve, reject) => { doneResolve = resolve; doneReject = reject; }); + child.on('message', (message: { type: string; pid: number; code: string }) => { + if (message.type === 'reading') readingResolve(message.pid); + if (message.type === 'done') doneResolve(message.code); + }); + child.on('error', error => { readingReject(error); doneReject(error); }); + child.on('exit', () => { + const error = new Error('Validation worker exited before its expected message: ' + stderr); + readingReject(error); + doneReject(error); + }); + // Attach handlers immediately so a failed worker cannot produce an unhandled rejection. + void reading.catch(() => undefined); + void done.catch(() => undefined); + child.send({ databasePath: join(folder, 'live.db'), dialect, databaseUrl, config, proof, result: response }); + return { child, reading, done: done.then(async code => { await exited; return code; }) }; + } + + it('coalesces an overlapping forced check with a separate operating-system process', async () => { + const proof = await login(); + const worker = validationWorker(proof); + expect(await worker.reading).not.toBe(process.pid); + const sequence = await db.queryOne<{ validation_sequence: string | number }>('SELECT validation_sequence FROM ldap_directory_state'); + const local = validate(proof, true); + await vi.waitFor(async () => { + const current = await db.queryOne<{ validation_sequence: string | number }>('SELECT validation_sequence FROM ldap_directory_state'); + expect(BigInt(current!.validation_sequence)).toBeGreaterThan(BigInt(sequence!.validation_sequence)); + }); + expect(directory.revalidate).not.toHaveBeenCalled(); + worker.child.send('release'); + expect(await worker.done).toBe('ok'); + await local; + expect(directory.revalidate).not.toHaveBeenCalled(); + expect(Number((await state() as { last_validated_at: string | number }).last_validated_at)).toBeGreaterThan(0); + }, 15000); + + it('fences a delayed result from a separate process after lease replacement', async () => { + const proof = await login(); + const worker = validationWorker(proof, { ...result, user: { ...result.user, displayName: 'Stale worker' }, groupSubjects: [] }); + await worker.reading; + await db.execute('UPDATE ldap_validation_leases SET lease_expires_at = 1'); + await validate(proof, true); + const before = await state(); + worker.child.send('release'); + expect(await worker.done).toBe('STALE_VALIDATION'); + expect(await state()).toEqual(before); + expect((await users.getUserById(proof.user.id))?.displayName).toBe('A'); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + }, 15000); + + it('rejects a separate-process result after a mapping revision changes', async () => { + const proof = await login(); + const worker = validationWorker(proof); + await worker.reading; + await mappings.update((await mappings.list())[0].id, { enabled: false }, { userId: 'administrator' }); + const before = await state(); + worker.child.send('release'); + expect(await worker.done).toBe('STALE_REVISION'); + expect(await state()).toEqual(before); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([]); + }, 15000); + + it('coalesces simultaneous validation and refresh checks inside a process', async () => { + const proof = await login(); + const pending = deferred(); + directory.revalidate.mockReturnValueOnce(pending.promise); + const checks = Array.from({ length: 8 }, () => validate(proof, true)); + await vi.waitFor(() => expect(directory.revalidate).toHaveBeenCalledOnce()); + pending.resolve(result); + await Promise.all(checks); + expect(directory.revalidate).toHaveBeenCalledOnce(); + }); + + it('coalesces overlapping validations through a database lease across independent connections', async () => { + const proof = await login(); + const pending = deferred(); + directory.revalidate.mockReturnValueOnce(pending.promise); + const first = validate(proof, true); + await vi.waitFor(() => expect(directory.revalidate).toHaveBeenCalledOnce()); + const second = validate(proof, true, other); + await new Promise(resolve => setTimeout(resolve, 60)); + expect(directory.revalidate).toHaveBeenCalledOnce(); + pending.resolve(result); + await Promise.all([first, second]); + expect(directory.revalidate).toHaveBeenCalledOnce(); + }); + + it('fences an expired worker after another process publishes a newer decision', async () => { + const proof = await login(); + const pending = deferred(); + directory.revalidate.mockReturnValueOnce(pending.promise); + const first = validate(proof, true).catch(error => error as Error); + await vi.waitFor(() => expect(directory.revalidate).toHaveBeenCalledOnce()); + await reader.execute('UPDATE ldap_validation_leases SET lease_expires_at = 1'); + await validate(proof, true, other); + const before = await state(); + pending.resolve({ ...result, user: { ...result.user, displayName: 'Stale profile' }, groupSubjects: [] }); + expect(await first).toMatchObject({ code: 'STALE_VALIDATION' }); + expect(await state()).toEqual(before); + expect((await users.getUserById(proof.user.id))?.displayName).toBe('A'); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + }); + + it('does not let an old positive denial revoke a newer successful login', async () => { + const proof = await login(); + const pending = deferred(); + directory.revalidate.mockReturnValueOnce(pending.promise); + const first = validate(proof, true).catch(error => error as Error); + await vi.waitFor(() => expect(directory.revalidate).toHaveBeenCalledOnce()); + const fresh = await other.authenticate('a', password); + pending.reject(new LdapDirectoryError('INELIGIBLE')); + expect(await first).toMatchObject({ code: 'STALE_VALIDATION' }); + await expect(validate(fresh)).resolves.toBeUndefined(); + }); + + it('prevents publication after a mapping edit during directory I/O', async () => { + const proof = await login(); + const pending = deferred(); + directory.revalidate.mockReturnValueOnce(pending.promise); + const first = validate(proof, true).catch(error => error as Error); + await vi.waitFor(() => expect(directory.revalidate).toHaveBeenCalledOnce()); + await mappings.remove((await mappings.list())[0].id, { userId: 'administrator' }); + pending.resolve(result); + expect(await first).toMatchObject({ code: 'STALE_REVISION' }); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([]); + expect(await state()).toMatchObject({ last_validated_at: null }); + }); + + it('rolls back first provisioning and profile changes if freshness publication fails', async () => { + const execute = db.execute.bind(db); + vi.spyOn(db, 'execute').mockImplementation(async (sql, params) => { + if (sql.includes('UPDATE ldap_validation_state SET last_validated_at = ?')) throw new Error('publication failed'); + return execute(sql, params); + }); + await expect(login()).rejects.toThrow('publication failed'); + for (const table of ['federated_identities', 'ldap_identity_metadata', 'ldap_validation_state', 'ldap_validation_leases', 'federated_user_roles']) { + expect(await db.query(`SELECT * FROM ${table}`)).toEqual([]); + } + expect(await db.query('SELECT id FROM users')).toEqual([{ id: 'administrator' }]); + }); + + it('rejects changed directory configuration in an older process and invalidates persisted freshness', async () => { + const proof = await login(); + const newer = new LdapAuthenticationService(reader, { ...config, userEligibilityFilter: '(employeeType=approved)' }, directory, + new LdapMappingService(reader, config.directoryId, { resolveGroup: async () => { throw new Error('unused'); } }), + new UserService(reader, auth)); + await newer.initialize(); + expect(await state()).toMatchObject({ last_validated_at: null }); + await expect(validate(proof)).rejects.toMatchObject({ code: 'STALE_VALIDATION' }); + await expect(validate(proof, true, newer)).resolves.toBeUndefined(); + await expect(validate(proof)).rejects.toMatchObject({ code: 'STALE_VALIDATION' }); + }); + + it('binds validation to exact identity, user, directory and session version', async () => { + const proof = await login(); + for (const args of [ + ['administrator', proof.identityId, 'directory', proof.sessionVersion], + [proof.user.id, 'foreign-identity', 'directory', proof.sessionVersion], + [proof.user.id, proof.identityId, 'foreign-directory', proof.sessionVersion], + [proof.user.id, proof.identityId, 'directory', 'invalid-version'], + ] as const) { + await expect(service.assertEligible(...args)).rejects.toMatchObject({ code: 'INVALID_CONTEXT' }); + } + expect(directory.revalidate).not.toHaveBeenCalled(); + }); + + it('does not emit an audit event for unchanged periodic revalidation', async () => { + const proof = await login(); + const events = await db.query('SELECT action, details FROM audit_logs'); + await validate(proof, true); + expect(await db.query('SELECT action, details FROM audit_logs')).toEqual(events); + }); + + it('enforces the exact freshness deadline using a controlled database clock', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + const start = 1_800_000_000_000; + vi.setSystemTime(start); + const expression = dialect === 'postgres' ? 'CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)' + : "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)"; + const query = db.queryOne.bind(db); + const execute = db.execute.bind(db); + vi.spyOn(db, 'queryOne').mockImplementation((sql, params) => query(sql.replaceAll(expression, String(Date.now())), params)); + vi.spyOn(db, 'execute').mockImplementation((sql, params) => execute(sql.replaceAll(expression, String(Date.now())), params)); + try { + const proof = await login(); + vi.setSystemTime(start + 299_999); + await validate(proof); + expect(directory.revalidate).not.toHaveBeenCalled(); + vi.setSystemTime(start + 300_000); + directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('UNAVAILABLE')); + await expect(validate(proof)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + const saved = await state() as { last_validated_at: number | string }; + expect(Number(saved.last_validated_at)).toBe(start); + await expect(validate(proof)).resolves.toBeUndefined(); + expect(directory.revalidate).toHaveBeenCalledTimes(2); + const pending = deferred(); + directory.authenticate.mockReturnValueOnce(pending.promise); + const staleLogin = login().catch(error => error as Error); + await vi.waitFor(() => expect(directory.authenticate).toHaveBeenCalledTimes(2)); + // Equal timestamps still have an unambiguous persisted decision order. + directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('INELIGIBLE')); + await expect(validate(proof, true)).rejects.toMatchObject({ code: 'DENIED' }); + pending.resolve(result); + expect(await staleLogin).toMatchObject({ code: 'STALE_VALIDATION' }); + } finally { vi.useRealTimers(); } + }); + + it('cannot turn a slow credential transaction into fresh state at completion time', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + const start = 1_800_000_000_000; + vi.setSystemTime(start); + const expression = dialect === 'postgres' ? 'CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)' + : "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)"; + const query = db.queryOne.bind(db); + const execute = db.execute.bind(db); + vi.spyOn(db, 'queryOne').mockImplementation((sql, params) => query(sql.replaceAll(expression, String(Date.now())), params)); + vi.spyOn(db, 'execute').mockImplementation((sql, params) => execute(sql.replaceAll(expression, String(Date.now())), params)); + directory.authenticate.mockImplementationOnce(async () => { vi.setSystemTime(start + 300_000); return result; }); + try { + await expect(login()).rejects.toMatchObject({ code: 'STALE_VALIDATION' }); + expect(await db.query('SELECT * FROM federated_identities')).toEqual([]); + } finally { vi.useRealTimers(); } + }); + + it('converges concurrent credential proofs from independent connections to one account and identity', async () => { + const attempts = await Promise.allSettled(Array.from({ length: 12 }, (_, i) => (i % 2 ? service : other).authenticate('a', password))); + const completed = attempts.filter(attempt => attempt.status === 'fulfilled'); + expect(completed.length).toBeGreaterThan(0); + expect(new Set(completed.map(attempt => attempt.value.user.id)).size).toBe(1); + expect(await db.query('SELECT * FROM federated_identities')).toHaveLength(1); + expect(await db.query('SELECT * FROM ldap_validation_state')).toHaveLength(1); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + for (const attempt of attempts) if (attempt.status === 'rejected') expect(attempt.reason).toMatchObject({ code: 'STALE_VALIDATION' }); + }); + + it('rejects a credential proof that started before a newer positive revocation', async () => { + const proof = await login(); + const pending = deferred(); + directory.authenticate.mockReturnValueOnce(pending.promise); + const first = login().catch(error => error as Error); + await vi.waitFor(() => expect(directory.authenticate).toHaveBeenCalledTimes(2)); + await new Promise(resolve => setTimeout(resolve, 3)); + directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('INELIGIBLE')); + await expect(validate(proof, true, other)).rejects.toMatchObject({ code: 'DENIED' }); + pending.resolve(result); + expect(await first).toMatchObject({ code: 'STALE_VALIDATION' }); + expect(await state()).toMatchObject({ last_validated_at: null }); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([]); + }); + }); +} diff --git a/backend/test/database/ldap-mappings.test.ts b/backend/test/database/ldap-mappings.test.ts new file mode 100644 index 00000000..481305c1 --- /dev/null +++ b/backend/test/database/ldap-mappings.test.ts @@ -0,0 +1,253 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { UserService } from '../../src/services/UserService'; +import { PermissionService } from '../../src/services/PermissionService'; +import { LdapMappingService, type LdapMapping } from '../../src/services/LdapMappingService'; +import { LdapDirectoryError } from '../../src/services/LdapDirectoryService'; + +const groupSubject = '10112233-4455-6677-8899-aabbccddeeff'; +const anotherGroup = '20112233-4455-6677-8899-aabbccddeeff'; +const group = { subject: groupSubject, dn: 'cn=operators,dc=example', name: 'Operators' }; +const actor = { userId: 'administrator' }; +const viewer = 'role-viewer-001'; + +for (const dialect of ['sqlite', 'postgres'] as const) { + describe.skipIf(dialect === 'postgres' && !process.env.TEST_DATABASE_URL)(`${dialect} LDAP mapping administration`, () => { + let directory: string; + let schema: string; + let control: PostgresAdapter | undefined; + let database: DatabaseService; + let db: DatabaseAdapter; + let reader: DatabaseAdapter; + let mappings: LdapMappingService; + let other: LdapMappingService; + let resolveGroup: ReturnType; + let userId: string; + let identityId: string; + + beforeEach(async () => { + directory = mkdtempSync(join(tmpdir(), 'pabawi-ldap-mappings-')); + schema = `mapping_${randomUUID().replaceAll('-', '')}`; + let url = ''; + if (dialect === 'postgres') { + control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute(`CREATE SCHEMA ${schema}`); + const scoped = new URL(process.env.TEST_DATABASE_URL!); + scoped.searchParams.set('options', `-csearch_path=${schema}`); + url = scoped.toString(); + } + const file = join(directory, 'live.db'); + database = new DatabaseService(file, dialect, url); + await database.initialize(); + db = database.getAdapter(); + reader = dialect === 'sqlite' ? new SQLiteAdapter(file) : new PostgresAdapter(url); + await reader.initialize(); + const users = new UserService(db, new AuthenticationService(db, 'ldap-mapping-fixture-jwt-secret-for-tests')); + userId = (await users.createFederatedUser({ provider: 'ldap', issuer: 'directory', subject: 'user-subject', + loginName: 'alice', dn: 'uid=alice,dc=example', displayName: 'Alice', email: null, + firstName: '', lastName: '', defaultRole: 'none' })).id; + identityId = (await db.queryOne<{ id: string }>("SELECT id FROM federated_identities WHERE user_id = ?", [userId]))!.id; + await db.execute(`INSERT INTO users (id, username, email, first_name, last_name, created_at, updated_at) + VALUES ('administrator', 'administrator', 'admin@example.test', '', '', 'now', 'now')`); + resolveGroup = vi.fn().mockImplementation(async (subject: string) => ({ ...group, subject })); + mappings = new LdapMappingService(db, 'directory', { resolveGroup }); + other = new LdapMappingService(reader, 'directory', { resolveGroup }); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await reader?.close(); + await database?.close(); + if (control) { + await control.execute(`DROP SCHEMA ${schema} CASCADE`); + await control.close(); + control = undefined; + } + rmSync(directory, { recursive: true, force: true }); + }); + + async function grant(mapping: LdapMapping, adapter = db): Promise { + await adapter.execute(`INSERT INTO federated_user_roles + (user_id, role_id, identity_id, source_key, mapping_id, directory_id) VALUES (?, ?, ?, ?, ?, 'directory')`, + [userId, mapping.roleId, identityId, `mapping:${mapping.id}`, mapping.id]); + } + async function validate(): Promise { + await db.execute('UPDATE ldap_validation_state SET last_validated_at = 1234, mapping_revision = ? WHERE identity_id = ?', + [(await mappings.revision()).mappingRevision, identityId]); + } + + it('returns current source labels and independent manual/mapped grant provenance for administration', async () => { + const users = new UserService(db, new AuthenticationService(db, 'administration-metadata-fixture-signing-secret')); + const user = await users.getUserById(userId); + expect(user).not.toBeNull(); + const metadata = await users.getAdministrationMetadata([user!], { directoryId: 'directory', displayName: 'Corporate' }); + expect(metadata.get(userId)).toEqual({ profileReadOnly: true, sources: [ + { provider: 'ldap', name: 'Corporate', directoryId: 'directory', loginName: 'alice' }, + ] }); + expect(await users.getAdministrationMetadata([])).toEqual(new Map()); + const mapping = await mappings.create(groupSubject, viewer, actor); + await grant(mapping); + await users.assignRoleToUser(userId, viewer); + expect(await users.getUserRoleSources(userId)).toEqual([ + { roleId: viewer, source: 'manual' }, + { roleId: viewer, source: 'ldap', directoryId: 'directory', groupName: 'Operators' }, + ]); + await users.removeRoleFromUser(userId, viewer); + expect(await users.getUserRoleSources(userId)).toEqual([ + { roleId: viewer, source: 'ldap', directoryId: 'directory', groupName: 'Operators' }, + ]); + expect(await users.getUserRoles(userId)).toHaveLength(1); + }); + + it('persists authoritative immutable identity, source, role and atomic audit without granting access', async () => { + const mapping = await mappings.create(groupSubject.toUpperCase(), viewer, actor); + expect(resolveGroup).toHaveBeenCalledWith(groupSubject); + expect(mapping).toMatchObject({ source: 'ldap', directoryId: 'directory', groupSubject, + groupDn: group.dn, groupName: group.name, roleId: viewer, roleName: 'Viewer', enabled: true }); + expect(await other.list()).toEqual([mapping]); + expect(await db.query('SELECT * FROM federated_user_roles')).toEqual([]); + expect((await mappings.revision()).mappingRevision).toBe('1'); + const audit = await db.queryOne<{ details: string; action: string; user_id: string }>('SELECT details, "action", user_id FROM audit_logs'); + expect(audit).toMatchObject({ action: 'createLdapMapping', user_id: actor.userId }); + expect(JSON.parse(audit!.details)).toEqual({ directoryId: 'directory', mappingId: mapping.id, groupSubject, roleId: viewer, enabled: true }); + expect(audit!.details).not.toContain(group.dn); + }); + + it('rejects duplicate mappings and absent roles without advancing revision', async () => { + await mappings.create(groupSubject, viewer, actor); + const revision = await mappings.revision(); + await expect(mappings.create(groupSubject, viewer, actor)).rejects.toMatchObject({ code: 'CONFLICT' }); + await expect(mappings.create(anotherGroup, 'absent', actor)).rejects.toMatchObject({ code: 'NOT_FOUND' }); + expect(await mappings.revision()).toEqual(revision); + expect(await db.query('SELECT * FROM audit_logs')).toHaveLength(1); + expect(await mappings.create(groupSubject, 'role-operator-001', actor)).toMatchObject({ groupSubject }); + }); + + it('withdraws only attributable grants and invalidates timestamp and permission caches across adapters', async () => { + const one = await mappings.create(groupSubject, viewer, actor); + const two = await mappings.create(anotherGroup, viewer, actor); + await grant(one); await grant(two); await validate(); + await db.execute(`INSERT INTO user_roles (user_id, role_id, assigned_at) VALUES (?, ?, 'now')`, [userId, viewer]); + await db.execute(`INSERT INTO federated_identities (id, user_id, provider, issuer, subject, created_at, updated_at) + VALUES ('entra', ?, 'entra-id', 'tenant', 'subject', 'now', 'now')`, [userId]); + await db.execute(`INSERT INTO federated_user_roles (user_id, role_id, identity_id, source_key) VALUES (?, ?, 'entra', 'source')`, [userId, viewer]); + const permissions = new PermissionService(reader); + expect(await permissions.hasPermission(userId, 'executions', 'read')).toBe(true); + const authorization = await reader.queryOne('SELECT revision FROM authorization_state'); + await mappings.update(one.id, { enabled: false }, actor); + expect(await reader.queryOne('SELECT last_validated_at FROM ldap_validation_state')).toEqual({ last_validated_at: null }); + expect(await reader.queryOne('SELECT revision FROM authorization_state')).not.toEqual(authorization); + expect(await reader.query('SELECT mapping_id FROM federated_user_roles WHERE identity_id = ?', [identityId])).toEqual([{ mapping_id: two.id }]); + await mappings.remove(two.id, actor); + expect(await permissions.hasPermission(userId, 'executions', 'read')).toBe(true); + expect(await reader.query('SELECT identity_id FROM federated_user_roles')).toEqual([{ identity_id: 'entra' }]); + await db.execute('DELETE FROM federated_identities WHERE id = ?', ['entra']); + expect(await permissions.hasPermission(userId, 'executions', 'read')).toBe(true); + await db.execute('DELETE FROM user_roles WHERE user_id = ?', [userId]); + expect(await permissions.hasPermission(userId, 'executions', 'read')).toBe(false); + }); + + it('refreshes labels by immutable subject on replacement and withdraws old role grants', async () => { + const mapping = await mappings.create(groupSubject, viewer, actor); + await grant(mapping); await validate(); + resolveGroup.mockResolvedValue({ ...group, dn: 'cn=renamed,dc=example', name: 'Renamed' }); + expect(await mappings.update(mapping.id, { roleId: 'role-operator-001' }, actor)) + .toMatchObject({ groupSubject, groupName: 'Renamed', groupDn: 'cn=renamed,dc=example', roleId: 'role-operator-001' }); + expect(resolveGroup).toHaveBeenLastCalledWith(groupSubject); + expect(await reader.query('SELECT * FROM federated_user_roles')).toEqual([]); + }); + + it('allows outage withdrawal but prevents new, changed or reenabled grants and rolls back no-op failures', async () => { + const mapping = await mappings.create(groupSubject, viewer, actor); + await grant(mapping); + resolveGroup.mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + const before = await mappings.revision(); + await expect(mappings.create(anotherGroup, viewer, actor)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + await expect(mappings.update(mapping.id, { roleId: 'role-operator-001' }, actor)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + expect(await mappings.revision()).toEqual(before); + expect(await db.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + await mappings.update(mapping.id, { enabled: false }, actor); + await expect(mappings.update(mapping.id, { enabled: true }, actor)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + await mappings.remove(mapping.id, actor); + expect(await reader.query('SELECT * FROM federated_user_roles')).toEqual([]); + expect(await mappings.list()).toEqual([]); + }); + + it.each(['disable', 'replace', 'delete', 'insert'] as const)('fences stale validation after mapping %s without resurrecting grants', async mutation => { + const mapping = await mappings.create(groupSubject, viewer, actor); + const stale = await other.revision(); + if (mutation === 'disable') await mappings.update(mapping.id, { enabled: false }, actor); + if (mutation === 'replace') await mappings.update(mapping.id, { roleId: 'role-operator-001' }, actor); + if (mutation === 'delete') await mappings.remove(mapping.id, actor); + if (mutation === 'insert') await mappings.create(anotherGroup, viewer, actor); + let published = false; + await expect(other.withRevision(stale, async () => { + published = true; + await grant(mapping, reader); + await reader.execute('UPDATE ldap_validation_state SET last_validated_at = 9999'); + })).rejects.toMatchObject({ code: 'STALE_REVISION' }); + expect(published).toBe(false); + expect(await reader.query('SELECT * FROM federated_user_roles')).toEqual([]); + expect(await reader.queryOne('SELECT last_validated_at FROM ldap_validation_state')).toEqual({ last_validated_at: null }); + }); + + it('serializes an edit queued while a validation transaction owns the directory revision', async () => { + const mapping = await mappings.create(groupSubject, viewer, actor); + const revision = await mappings.revision(); + let edit: Promise | undefined; + await mappings.withRevision(revision, async () => { + await grant(mapping); + edit = other.update(mapping.id, { enabled: false }, actor); + await db.execute('UPDATE ldap_validation_state SET last_validated_at = 1234'); + }); + await edit; + expect(await reader.query('SELECT * FROM federated_user_roles')).toEqual([]); + expect(await reader.queryOne('SELECT last_validated_at FROM ldap_validation_state')).toEqual({ last_validated_at: null }); + }); + + it('rejects an administration result whose revision changed during directory I/O', async () => { + const mapping = await mappings.create(groupSubject, viewer, actor); + resolveGroup.mockImplementationOnce(async () => { + await other.remove(mapping.id, actor); + return group; + }); + await expect(mappings.update(mapping.id, { enabled: true }, actor)).rejects.toMatchObject({ code: 'STALE_REVISION' }); + expect(await mappings.list()).toEqual([]); + }); + + it('rolls back withdrawal, revision invalidation and mutation when audit persistence fails', async () => { + const mapping = await mappings.create(groupSubject, viewer, actor); + await grant(mapping); await validate(); + const revision = await mappings.revision(); + const execute = db.execute.bind(db); + vi.spyOn(db, 'execute').mockImplementation(async (sql, params) => { + if (sql.includes('INSERT INTO audit_logs')) throw new Error('audit unavailable'); + return execute(sql, params); + }); + await expect(mappings.remove(mapping.id, actor)).rejects.toThrow('audit unavailable'); + expect(await mappings.revision()).toEqual(revision); + expect(await mappings.get(mapping.id)).toMatchObject({ enabled: true }); + expect(await reader.query('SELECT * FROM federated_user_roles')).toHaveLength(1); + expect(String((await reader.queryOne<{ last_validated_at: string | number }>('SELECT last_validated_at FROM ldap_validation_state'))?.last_validated_at)).toBe('1234'); + }); + + it('rejects other directory ownership and changed configuration revisions', async () => { + const mapping = await mappings.create(groupSubject, viewer, actor); + const wrong = new LdapMappingService(reader, 'another-directory', { resolveGroup }); + await expect(wrong.get(mapping.id)).rejects.toMatchObject({ code: 'NOT_FOUND' }); + const revision = await mappings.revision(); + await expect(wrong.withRevision(revision, async () => {})).rejects.toMatchObject({ code: 'STALE_REVISION' }); + await db.execute("UPDATE ldap_directory_state SET config_revision = 'changed' WHERE directory_id = 'directory'"); + await expect(other.withRevision(revision, async () => {})).rejects.toMatchObject({ code: 'STALE_REVISION' }); + }); + }); +} diff --git a/backend/test/database/ldap-upgrade-recovery.test.ts b/backend/test/database/ldap-upgrade-recovery.test.ts new file mode 100644 index 00000000..6a9e34a7 --- /dev/null +++ b/backend/test/database/ldap-upgrade-recovery.test.ts @@ -0,0 +1,192 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { appendFileSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; +import { homedir, tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { spawn } from 'node:child_process'; +import jwt from 'jsonwebtoken'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import { MigrationRunner } from '../../src/database/MigrationRunner'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { UserService } from '../../src/services/UserService'; +import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; + +const migrations = join(__dirname, '../../src/database/migrations'); +const secret = 'upgrade-rehearsal-signing-secret-key'; // pragma: allowlist secret +const password = 'RestoreFixture123!'; // pragma: allowlist secret +const cleanups: (() => Promise)[] = []; +afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); }); + +async function command(args: string[], input?: Buffer): Promise { + const output: Buffer[] = []; + const errors: Buffer[] = []; + const child = spawn('docker', args, { stdio: ['pipe', 'pipe', 'pipe'] }); + child.stdout.on('data', value => output.push(value)); + child.stderr.on('data', value => errors.push(value)); + child.stdin.end(input); + let failure: Error | undefined; + child.on('error', error => { failure = error; }); + const status = await new Promise(resolveExit => child.on('close', code => { resolveExit(code ?? 1); })); + const log = join(homedir(), '.agents/logs/pabawi.jsonl'); + mkdirSync(join(homedir(), '.agents/logs'), { recursive: true }); + const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; + appendFileSync(log, JSON.stringify({ + ts: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), agent: 'codex', actor: 'agent', cwd: process.cwd(), + cmd: ['docker', ...args].map(quote).join(' '), reason: 'rehearse isolated PostgreSQL backup and restoration', + result: status === 0 ? 'ok' : 'fail', note: 'exit ' + status, + }) + '\n'); + if (failure || status !== 0) throw failure ?? new Error(Buffer.concat(errors).toString()); + return Buffer.concat(output); +} + +async function seed(db: DatabaseAdapter, partial: string) { + await new MigrationRunner(db, partial).runPendingMigrations(); + const hash = await new AuthenticationService(db, secret).hashPassword(password); + for (const id of ['local', 'enrolled']) { + await db.execute("INSERT INTO users (id, username, email, password_hash, first_name, last_name, is_active, is_admin, created_at, updated_at, session_version) VALUES (?, ?, ?, ?, '', '', 1, 0, 'now', 'now', 'pre-upgrade-version')", + [id, id, id + '@example.test', hash]); + await db.execute("INSERT INTO user_roles VALUES (?, 'role-viewer-001', 'now')", [id]); + } + await db.execute("INSERT INTO federated_identities (id, user_id, provider, subject, issuer, created_at, updated_at) VALUES ('identity', 'enrolled', 'entra-id', 'subject', 'issuer', 'now', 'now')"); + await db.execute("INSERT INTO federated_user_roles VALUES ('enrolled', 'role-operator-001')"); + await db.execute("INSERT INTO groups VALUES ('group', 'Operators', '', 'now', 'now')"); + await db.execute("INSERT INTO user_groups VALUES ('enrolled', 'group', 'now')"); + await db.execute('INSERT INTO audit_logs (id, timestamp, event_type, "action", user_id, result) ' + + "VALUES ('audit', 'now', 'auth', 'login_success', 'enrolled', 'success')"); +} + +async function snapshot(db: DatabaseAdapter) { + const tables = ['migrations', 'users', 'federated_identities', 'federated_user_roles', 'user_roles', 'user_groups', 'groups', 'audit_logs']; + return Object.fromEntries(await Promise.all(tables.map(async table => [ + table, await db.query('SELECT * FROM ' + table + ' ORDER BY 1, 2'), + ]))); +} + +async function upgradeAndVerify(database: DatabaseService) { + await database.initialize(); + const db = database.getAdapter(); + const auth = new AuthenticationService(db, secret); + const users = new UserService(db, auth); + expect((await new MigrationRunner(db).getStatus()).pending).toEqual([]); + expect(await db.queryOne("SELECT id FROM migrations WHERE id = '034'")).toEqual({ id: '034' }); + expect(await db.query("SELECT id FROM users WHERE session_version = 'pre-upgrade-version'")).toEqual([]); + expect(await db.query('SELECT id, user_id, provider, subject, issuer FROM federated_identities')) + .toEqual([{ id: 'identity', user_id: 'enrolled', provider: 'entra-id', subject: 'subject', issuer: 'issuer' }]); + expect(await db.query('SELECT user_id, role_id FROM effective_user_roles ORDER BY user_id, role_id')).toEqual([ + { user_id: 'enrolled', role_id: 'role-operator-001' }, { user_id: 'enrolled', role_id: 'role-viewer-001' }, + { user_id: 'local', role_id: 'role-viewer-001' }, + ]); + expect(await db.query('SELECT user_id, group_id FROM user_groups')).toEqual([{ user_id: 'enrolled', group_id: 'group' }]); + expect(await db.queryOne("SELECT user_id FROM audit_logs WHERE id = 'audit'")).toEqual({ user_id: 'enrolled' }); + const user = (await users.getUserById('enrolled'))!; + const legacy = jwt.sign({ userId: user.id, username: user.username, sessionVersion: 'pre-upgrade-version' }, secret, { expiresIn: '1h' }); + await expect(auth.verifyToken(legacy)).rejects.toThrow(); + expect((await auth.refreshToken(legacy)).success).toBe(false); + const pair = await auth.authenticate('local', password); + expect(pair.success).toBe(true); + const entra = await auth.generateTokenPair(user, { provider: 'entra-id', identityId: 'identity' }); + await expect(auth.verifyToken(entra.token)).resolves.toMatchObject({ userId: 'enrolled' }); + expect((await auth.refreshToken(entra.refreshToken)).success).toBe(true); + const version = (await users.getUserById('local'))!.sessionVersion; + await database.close(); + await database.initialize(); + const restarted = new AuthenticationService(database.getAdapter(), secret); + await expect(restarted.verifyToken(pair.token!)).resolves.toMatchObject({ userId: 'local' }); + expect((await new UserService(database.getAdapter(), restarted).getUserById('local'))!.sessionVersion).toBe(version); + if (db.getDialect() === 'sqlite') { + expect(await database.getAdapter().query('PRAGMA integrity_check')).toEqual([{ integrity_check: 'ok' }]); + expect(await database.getAdapter().query('PRAGMA foreign_key_check')).toEqual([]); + } +} + +for (const dialect of ['sqlite', 'postgres'] as const) { + describe.skipIf(dialect === 'postgres' && !(process.env.TEST_DATABASE_URL && process.env.TEST_LDAP_POSTGRES_CONTAINER))( + dialect + ' LDAP backup, upgrade and restore rehearsal', () => { + it('backs up populated pre-LDAP state, upgrades once, restores the old snapshot and repeats the upgrade', async () => { + const dir = mkdtempSync(join(process.env.TEST_LDAP_EVIDENCE_DIR ?? tmpdir(), 'upgrade-recovery-')); + const partial = join(dir, 'migrations-through-030'); + mkdirSync(partial); + for (const file of readdirSync(migrations).filter(file => file.endsWith('.sql') && file.slice(0, 3) <= '030')) { + copyFileSync(join(migrations, file), join(partial, file)); + } + const sourcePath = join(dir, 'source.db'); + const backupPath = join(dir, 'pre-upgrade.db'); + let sourceUrl = ''; + let restoreUrl = ''; + let source: DatabaseAdapter; + if (dialect === 'postgres') { + const key = randomUUID().replaceAll('-', ''); + const sourceName = 'ldap_recovery_' + key; + const restoreName = 'ldap_restored_' + key; + const control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute('CREATE DATABASE ' + sourceName); + await control.execute('CREATE DATABASE ' + restoreName); + await control.close(); + const sourceAddress = new URL(process.env.TEST_DATABASE_URL!); + sourceAddress.pathname = '/' + sourceName; + sourceAddress.search = ''; + const restoreAddress = new URL(sourceAddress); + restoreAddress.pathname = '/' + restoreName; + sourceUrl = sourceAddress.toString(); + restoreUrl = restoreAddress.toString(); + source = new PostgresAdapter(sourceUrl); + } else { + source = new SQLiteAdapter(sourcePath); + } + await source.initialize(); + cleanups.push(() => source.close()); + if (dialect === 'sqlite') await source.execute('PRAGMA wal_autocheckpoint = 0'); + await seed(source, partial); + const before = await snapshot(source); + if (dialect === 'sqlite') { + expect(statSync(sourcePath + '-wal').size).toBeGreaterThan(0); + await source.execute('VACUUM INTO ?', [backupPath]); + } else { + const dump = await command(['exec', process.env.TEST_LDAP_POSTGRES_CONTAINER!, 'pg_dump', '-U', 'postgres', + '--format=custom', '--no-owner', '--dbname=' + new URL(sourceUrl).pathname.slice(1)]); + writeFileSync(join(dir, 'pre-upgrade.dump'), dump); + } + await source.close(); + const upgraded = new DatabaseService(sourcePath, dialect, sourceUrl); + cleanups.push(() => upgraded.close()); + await upgradeAndVerify(upgraded); + + const failureDir = join(dir, 'candidate-migrations'); + mkdirSync(failureDir); + for (const file of readdirSync(migrations).filter(file => file.endsWith('.sql'))) { + copyFileSync(join(migrations, file), join(failureDir, file)); + } + writeFileSync(join(failureDir, '035_rehearsal_failure.sql'), "CREATE TABLE rehearsal_partial (id TEXT);\nINSERT INTO missing_rehearsal_table VALUES (1);"); + await expect(new MigrationRunner(upgraded.getAdapter(), failureDir).runPendingMigrations()).rejects.toThrow(); + expect(await upgraded.getAdapter().queryOne("SELECT id FROM migrations WHERE id = '035'")).toBeNull(); + if (dialect === 'sqlite') { + expect(await upgraded.getAdapter().queryOne("SELECT name FROM sqlite_master WHERE name = 'rehearsal_partial'")).toBeNull(); + } else { + expect(await upgraded.getAdapter().queryOne("SELECT tablename FROM pg_tables WHERE schemaname = 'public' AND tablename = 'rehearsal_partial'")).toBeNull(); + await command(['exec', '-i', process.env.TEST_LDAP_POSTGRES_CONTAINER!, 'pg_restore', '-U', 'postgres', + '--exit-on-error', '--single-transaction', '--no-owner', '--dbname=' + new URL(restoreUrl).pathname.slice(1)], + readFileSync(join(dir, 'pre-upgrade.dump'))); + } + const restoredPath = join(dir, 'restored.db'); + if (dialect === 'sqlite') copyFileSync(backupPath, restoredPath); + const restored: DatabaseAdapter = dialect === 'sqlite' ? new SQLiteAdapter(restoredPath) : new PostgresAdapter(restoreUrl); + await restored.initialize(); + cleanups.push(() => restored.close()); + expect(await snapshot(restored)).toEqual(before); + expect(await restored.queryOne("SELECT id FROM migrations WHERE id = '031'")).toBeNull(); + await restored.close(); + const redeployed = new DatabaseService(restoredPath, dialect, restoreUrl); + cleanups.push(() => redeployed.close()); + await upgradeAndVerify(redeployed); + writeFileSync(join(dir, 'result.json'), JSON.stringify({ dialect, passed: true, + source: dialect === 'sqlite' ? sourcePath : new URL(sourceUrl).pathname.slice(1), + restored: dialect === 'sqlite' ? restoredPath : new URL(restoreUrl).pathname.slice(1), + checks: ['populated-030-snapshot', 'committed-WAL-or-pg-dump', 'upgrade-through-034', + 'legacy-reauthentication', 'local-and-Entra-login', 'restart-no-repeated-invalidation', + 'failed-migration-rollback', 'restored-original-snapshot', 'successful-repeat-upgrade'] }, null, 2)); + }, 30000); + }); +} diff --git a/backend/test/database/migration-016-convergence.test.ts b/backend/test/database/migration-016-convergence.test.ts index 4da4ae2b..ea213735 100644 --- a/backend/test/database/migration-016-convergence.test.ts +++ b/backend/test/database/migration-016-convergence.test.ts @@ -40,10 +40,10 @@ describe("I02: migration 016 feature convergence", () => { } const retainedTables = variant === "fresh" ? [] : ["users", "user_roles", ...(variant === "entra" ? ["federated_identities", "oauth_state_store", "oauth_auth_codes"] : [])]; const before = await Promise.all(retainedTables.map(table => db.query(table === "users" ? 'SELECT id, username, email, password_hash, first_name, last_name, is_active, is_admin, created_at, updated_at, last_login_at FROM users' : `SELECT * FROM ${table}`))); - // New nullable browser bindings intentionally invalidate legacy in-flight logins. + // Provider context requires reauthentication, including pending OAuth exchanges. if (variant === "entra") { for (const rows of before.slice(3)) { - for (const row of rows) Object.assign(row as object, { browser_binding: null }); + for (const row of rows) Object.assign(row as object, { browser_binding: null, expires_at: '1970-01-01T00:00:00.000Z' }); } } const runner = new MigrationRunner(db, migrationsDir); diff --git a/backend/test/database/migration-integration.test.ts b/backend/test/database/migration-integration.test.ts index ba55483f..a59995ff 100644 --- a/backend/test/database/migration-integration.test.ts +++ b/backend/test/database/migration-integration.test.ts @@ -28,8 +28,8 @@ describe('Migration Integration Test', () => { it('should apply all migrations on initialization', async () => { const status = await dbService.getMigrationStatus(); - // Should have applied all migrations (000 through 030, no 012 in source) - expect(status.applied).toHaveLength(30); + // Should have applied all migrations (000 through 034, no 012 in source) + expect(status.applied).toHaveLength(34); expect(status.applied[0].id).toBe('000'); expect(status.applied[1].id).toBe('001'); expect(status.applied[2].id).toBe('002'); @@ -52,7 +52,7 @@ describe('Migration Integration Test', () => { expect(status.applied[19].id).toBe('020'); expect(status.applied[20].id).toBe('021'); expect(status.applied[21].id).toBe('022'); - expect(status.applied.at(-1)?.id).toBe('030'); + expect(status.applied.at(-1)?.id).toBe('034'); expect(status.pending).toHaveLength(0); }); @@ -93,8 +93,8 @@ describe('Migration Integration Test', () => { const status = await dbService2.getMigrationStatus(); - // Should still have 30 applied, 0 pending - expect(status.applied).toHaveLength(30); + // Should still have 32 applied, 0 pending + expect(status.applied).toHaveLength(34); expect(status.pending).toHaveLength(0); await dbService2.close(); diff --git a/backend/test/database/provider-bound-sessions.test.ts b/backend/test/database/provider-bound-sessions.test.ts new file mode 100644 index 00000000..9e3f7f2d --- /dev/null +++ b/backend/test/database/provider-bound-sessions.test.ts @@ -0,0 +1,220 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { copyFileSync, mkdtempSync, readdirSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import jwt from 'jsonwebtoken'; +import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; +import { MigrationRunner } from '../../src/database/MigrationRunner'; +import { AuthenticationService, type AuthenticationContext } from '../../src/services/AuthenticationService'; +import { UserService } from '../../src/services/UserService'; + +const secret = 'provider-context-fixture-signing-key'; // pragma: allowlist secret +const password = 'ProviderTest123!'; // pragma: allowlist secret +const localContext: AuthenticationContext = { provider: 'local', identityId: null }; +const migrations = join(__dirname, '../../src/database/migrations'); + +for (const dialect of ['sqlite', 'postgres'] as const) { + describe.skipIf(dialect === 'postgres' && !process.env.TEST_DATABASE_URL)(`${dialect}: provider-bound sessions`, () => { + let db: DatabaseAdapter; + let control: PostgresAdapter | undefined; + let schema: string; + let auth: AuthenticationService; + let users: UserService; + + beforeEach(async () => { + schema = `sessions_${randomUUID().replaceAll('-', '')}`; + if (dialect === 'postgres') { + control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute(`CREATE SCHEMA ${schema}`); + const scoped = new URL(process.env.TEST_DATABASE_URL!); + scoped.searchParams.set('options', `-csearch_path=${schema}`); + db = new PostgresAdapter(scoped.toString()); + } else { + db = new SQLiteAdapter(':memory:'); + } + await db.initialize(); + auth = new AuthenticationService(db, secret, undefined, 4); + users = new UserService(db, auth); + }); + + afterEach(async () => { + await db?.close(); + if (control) { + await control.execute(`DROP SCHEMA ${schema} CASCADE`); + await control.close(); + control = undefined; + } + }); + + async function fixture(): Promise<{ user: { id: string; username: string }; context: AuthenticationContext }> { + await new MigrationRunner(db).runPendingMigrations(); + const user = await users.createUser({ username: 'alice', email: 'alice@example.test', password, + firstName: 'Alice', lastName: 'Test' }); + await users.linkFederatedIdentity(user.id, 'entra-id', 'immutable-subject', 'https://issuer.example.test', user.email); + const identity = await db.queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [user.id]); + expect(identity).not.toBeNull(); + return { user, context: { provider: 'entra-id', identityId: identity!.id } }; + } + + function replaceContext(token: string, context: unknown): string { + const payload = jwt.decode(token) as jwt.JwtPayload; + if (context === undefined) delete payload.authContext; + else payload.authContext = context; + return jwt.sign(payload, secret, { algorithm: 'HS256' }); + } + + it('issues and rotates explicit local and Entra context without guessing an enrolled account provider', async () => { + const { user, context } = await fixture(); + const local = await auth.authenticate(user.username, password); + expect(local.success).toBe(true); + expect(await auth.verifyToken(local.token!)).toMatchObject({ authContext: localContext }); + const federated = await auth.generateTokenPair(user, context); + for (const [pair, expected] of [[local, localContext], [federated, context]] as const) { + expect(jwt.decode(pair.refreshToken!)).toMatchObject({ authContext: expected, type: 'refresh' }); + const rotated = await auth.refreshToken(pair.refreshToken!); + expect(rotated.success).toBe(true); + expect(await auth.verifyToken(rotated.token!)).toMatchObject({ userId: user.id, authContext: expected }); + expect(jwt.decode(rotated.refreshToken!)).toMatchObject({ authContext: expected, type: 'refresh' }); + expect(rotated.refreshToken).not.toBe(pair.refreshToken); + } + }); + + + it('counts local and provider-scoped LDAP failures and applies temporary lockout on both adapters', async () => { + const { user } = await fixture(); + for (let attempt = 0; attempt < 5; attempt++) { + expect((await auth.authenticate(user.username, 'incorrect')).success).toBe(false); + await auth.recordLdapLoginOutcome('directory', user.username, false); + } + expect((await auth.authenticate(user.username, password)).error).toMatch(/temporarily locked/i); + expect(await auth.isLdapLoginLocked('directory', user.username)).toBe(true); + expect(await auth.isLdapLoginLocked('another-directory', user.username)).toBe(false); + expect(await auth.isLdapLoginLocked('directory', 'another-user')).toBe(false); + const counters = await db.query<{ username: string; cumulative_failed_attempts: number }>( + 'SELECT username, cumulative_failed_attempts FROM login_attempt_counters'); + expect(counters).toHaveLength(2); + expect(counters.find(row => row.username === user.username)?.cumulative_failed_attempts).toBe(6); + expect(counters.find(row => row.username !== user.username)?.cumulative_failed_attempts).toBe(5); + await auth.recordLdapLoginOutcome('directory', user.username, true); + expect(await auth.isLdapLoginLocked('directory', user.username)).toBe(false); + expect((await auth.authenticate(user.username, password)).success).toBe(false); + }); + + it('rejects signed malformed, legacy, mismatched and premature LDAP context for access and refresh', async () => { + const { user, context } = await fixture(); + const pair = await auth.generateTokenPair(user, context); + const other = await users.createUser({ username: 'other', email: 'other@example.test', password, + firstName: '', lastName: '' }); + await users.linkFederatedIdentity(other.id, 'entra-id', 'immutable-subject', 'https://other-issuer.example.test', other.email); + const otherIdentity = await db.queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [other.id]); + const invalid = [undefined, null, 'local', {}, { provider: 'local' }, + { provider: 'local', identityId: context.identityId }, { provider: 'entra-id', identityId: null }, + { provider: 'entra-id', identityId: '' }, { provider: 'entra-id', identityId: 42 }, + { provider: 'entra-id', identityId: 'missing' }, { provider: 'entra-id', identityId: otherIdentity!.id }, + { ...context, directoryId: 'forged' }, { provider: 'unknown', identityId: null }, + { provider: 'ldap', identityId: context.identityId, directoryId: 'directory' }]; + for (const value of invalid) { + await expect(auth.verifyToken(replaceContext(pair.token, value))).rejects.toThrow('Invalid token'); + expect((await auth.refreshToken(replaceContext(pair.refreshToken, value))).success).toBe(false); + } + // Untrusted changes also fail signature validation before database context resolution. + const [header, body, signature] = pair.token.split('.'); + const changed = JSON.parse(Buffer.from(body, 'base64url').toString()) as Record; + changed.authContext = localContext; + await expect(auth.verifyToken(`${header}.${Buffer.from(JSON.stringify(changed)).toString('base64url')}.${signature}`)) + .rejects.toThrow('Invalid token'); + await expect(auth.verifyToken(pair.token)).resolves.toMatchObject({ authContext: context }); + }); + + it('checks identity ownership at issuance and does not treat external accounts as local', async () => { + await new MigrationRunner(db).runPendingMigrations(); + const user = await users.createFederatedUser({ provider: 'entra-id', issuer: 'tenant', subject: 'subject', + username: 'external', email: null, firstName: '', lastName: '', displayName: null, defaultRole: 'configured' }); + for (const issue of [auth.generateToken.bind(auth), auth.generateRefreshToken.bind(auth), auth.generateTokenPair.bind(auth)]) { + await expect(issue(user, localContext)).rejects.toThrow('Invalid token'); + await expect(issue(user, { provider: 'entra-id', identityId: 'missing' })).rejects.toThrow('Invalid token'); + await expect(issue(user, { provider: 'ldap', identityId: 'missing', directoryId: 'directory' } as unknown as AuthenticationContext)) + .rejects.toThrow('Invalid token'); + } + const identity = await db.queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [user.id]); + const pair = await auth.generateTokenPair(user, { provider: 'entra-id', identityId: identity!.id }); + expect((await auth.refreshToken(pair.refreshToken)).user?.email).toBeNull(); + }); + + it('fails after identity deletion while independent local sessions remain valid', async () => { + const { user, context } = await fixture(); + const local = await auth.generateTokenPair(user, localContext); + const federated = await auth.generateTokenPair(user, context); + await db.execute('DELETE FROM federated_identities WHERE id = ?', [context.identityId]); + await expect(auth.verifyToken(federated.token)).rejects.toThrow('Invalid token'); + expect((await auth.refreshToken(federated.refreshToken)).success).toBe(false); + await expect(auth.verifyToken(local.token)).resolves.toMatchObject({ authContext: localContext }); + expect((await auth.refreshToken(local.refreshToken)).success).toBe(true); + }); + + it('rejects disabled local scope and preserves explicitly enrolled Entra access', async () => { + const { user, context } = await fixture(); + const old = await auth.generateTokenPair(user, localContext); + await db.execute('UPDATE users SET local_auth_enabled = 0, password_hash = NULL WHERE id = ?', [user.id]); + await expect(auth.verifyToken(old.token)).rejects.toThrow('revoked'); + expect((await auth.refreshToken(old.refreshToken)).success).toBe(false); + await expect(auth.generateTokenPair(user, localContext)).rejects.toThrow('Invalid token'); + const pair = await auth.generateTokenPair(user, context); + await expect(auth.verifyToken(pair.token)).resolves.toMatchObject({ authContext: context }); + await auth.revokeAllUserTokens(user.id); + await expect(auth.verifyToken(pair.token)).rejects.toThrow('revoked'); + expect((await auth.refreshToken(pair.refreshToken)).success).toBe(false); + }); + + it('invalidates legacy sessions once on upgrade while preserving identities, grants and account data', async () => { + const partial = mkdtempSync(join(tmpdir(), 'pabawi-provider-migrations-')); + for (const file of readdirSync(migrations).filter(file => file.endsWith('.sql') && file < '032')) { + copyFileSync(join(migrations, file), join(partial, file)); + } + await new MigrationRunner(db, partial).runPendingMigrations(); + const user = await users.createUser({ username: 'alice', email: 'alice@example.test', password, + firstName: 'Alice', lastName: 'Test' }); + await users.linkFederatedIdentity(user.id, 'entra-id', 'subject', 'issuer', user.email); + const identity = await db.queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [user.id]); + const context: AuthenticationContext = { provider: 'entra-id', identityId: identity!.id }; + const local = await auth.generateTokenPair(user, localContext); + const federated = await auth.generateTokenPair(user, context); + const legacy = replaceContext(local.token, undefined); + const legacyRefresh = replaceContext(local.refreshToken, undefined); + const now = new Date().toISOString(); + const future = new Date(Date.now() + 600_000).toISOString(); + await db.execute(`INSERT INTO oauth_state_store (state, nonce, code_verifier, created_at, expires_at) + VALUES ('state', 'nonce', 'verifier', ?, ?)`, [now, future]); + await db.execute(`INSERT INTO oauth_auth_codes (code, access_token, refresh_token, user_id, created_at, expires_at) + VALUES ('code', ?, ?, ?, ?, ?)`, [local.token, local.refreshToken, user.id, now, future]); + await db.execute(`INSERT INTO console_sessions (id, user_id, node_id, provider, transport, state, started_at, session_version) + VALUES ('console', ?, 'node', 'proxmox', 'websocket-vnc', 'active', ?, ?)`, [user.id, now, (jwt.decode(local.token) as jwt.JwtPayload).sessionVersion]); + const accountColumns = 'id, username, email, password_hash, local_auth_enabled, first_name, last_name, is_active, is_admin, created_at, updated_at'; + const account = await db.query(`SELECT ${accountColumns} FROM users`); + const tables = ['federated_identities', 'user_roles', 'effective_user_roles']; + const before = await Promise.all(tables.map(table => db.query(`SELECT * FROM ${table}`))); + expect(await new MigrationRunner(db).runPendingMigrations()).toBe(3); + expect(await db.query(`SELECT ${accountColumns} FROM users`)).toEqual(account); + expect(await Promise.all(tables.map(table => db.query(`SELECT * FROM ${table}`)))).toEqual(before); + for (const pair of [local, federated, { token: legacy, refreshToken: legacyRefresh }]) { + await expect(auth.verifyToken(pair.token)).rejects.toThrow(); + expect((await auth.refreshToken(pair.refreshToken)).success).toBe(false); + } + for (const table of ['oauth_state_store', 'oauth_auth_codes']) { + expect(await db.query(`SELECT * FROM ${table} WHERE expires_at > ?`, [now])).toEqual([]); + } + expect(await db.query('SELECT c.id FROM console_sessions c JOIN users u ON c.user_id = u.id WHERE c.session_version = u.session_version')).toEqual([]); + const newLocal = await auth.authenticate(user.username, password); + const newFederated = await auth.generateTokenPair(user, context); + expect(newLocal.success).toBe(true); + expect(await new MigrationRunner(db).runPendingMigrations()).toBe(0); + await expect(auth.verifyToken(newLocal.token!)).resolves.toMatchObject({ authContext: localContext }); + await expect(auth.verifyToken(newFederated.token)).resolves.toMatchObject({ authContext: context }); + if (dialect === 'sqlite') expect(await db.query('PRAGMA foreign_key_check')).toEqual([]); + }); + }); +} diff --git a/backend/test/database/rbac-schema.test.ts b/backend/test/database/rbac-schema.test.ts index 1b30ae6a..f5abece3 100644 --- a/backend/test/database/rbac-schema.test.ts +++ b/backend/test/database/rbac-schema.test.ts @@ -31,7 +31,10 @@ describe('RBAC Database Schema', () => { expect(result).toBeDefined(); expect(result.sql).toContain('id TEXT PRIMARY KEY'); expect(result.sql).toContain('username TEXT NOT NULL UNIQUE'); - expect(result.sql).toContain('email TEXT NOT NULL UNIQUE'); + expect(result.sql).toContain('email TEXT'); + expect(result.sql).toContain('local_auth_enabled INTEGER NOT NULL DEFAULT 1'); + const index = await db.queryOne<{ sql: string }>("SELECT sql FROM sqlite_master WHERE name = 'idx_users_local_email'"); + expect(index?.sql).toContain('UNIQUE INDEX idx_users_local_email ON users(email) WHERE local_auth_enabled = 1'); expect(result.sql).toContain('password_hash TEXT'); expect(result.sql).toContain('is_active INTEGER NOT NULL DEFAULT 1'); expect(result.sql).toContain('is_admin INTEGER NOT NULL DEFAULT 0'); diff --git a/backend/test/database/sso-concurrency.test.ts b/backend/test/database/sso-concurrency.test.ts index 01c3783c..e886ba3d 100644 --- a/backend/test/database/sso-concurrency.test.ts +++ b/backend/test/database/sso-concurrency.test.ts @@ -48,13 +48,15 @@ for (const dialect of ['sqlite', 'postgres'] as const) { const users = await Promise.all(services.map(service => service.provisionUser(claims))); expect(new Set(users.map(user => user.id)).size).toBe(1); expect(await adapters[0].query('SELECT * FROM federated_identities')).toHaveLength(1); + const identity = await adapters[0].queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [users[0].id]); + expect(identity).not.toBeNull(); await adapters[0].execute('DELETE FROM user_roles WHERE user_id = ?', [users[0].id]); const permissions = new PermissionService(adapters[1]); - await Promise.all(services.map(service => service.syncGroupRoles(users[0].id, ['a']))); + await Promise.all(services.map(service => service.syncGroupRoles(identity!.id, ['a']))); expect(await permissions.hasPermission(users[0].id, 'executions', 'read')).toBe(true); - await services[0].syncGroupRoles(users[0].id, undefined); + await services[0].syncGroupRoles(identity!.id, undefined); expect(await permissions.hasPermission(users[0].id, 'executions', 'read')).toBe(false); - const { token, refreshToken } = await services[0].authService.generateTokenPair(users[0]); + const { token, refreshToken } = await services[0].authService.generateTokenPair(users[0], { provider: 'entra-id', identityId: identity!.id }); const binding = 'a'.repeat(64); await adapters[0].execute(`INSERT INTO oauth_auth_codes (code, access_token, refresh_token, user_id, created_at, expires_at, browser_binding) diff --git a/backend/test/fixtures/ldap/Dockerfile b/backend/test/fixtures/ldap/Dockerfile new file mode 100644 index 00000000..4b031726 --- /dev/null +++ b/backend/test/fixtures/ldap/Dockerfile @@ -0,0 +1,7 @@ +FROM debian@sha256:7fa362f5e7c036d7f45621a6c721c03493cdcb5889adfcd65587759e34fe4c6f +RUN mkdir /downloads && apt-get update \ + && apt-get --download-only --no-install-recommends install -y slapd ldap-utils openssl \ + && cp /var/cache/apt/archives/*.deb /downloads/ \ + && DEBIAN_FRONTEND=noninteractive apt-get --no-install-recommends install -y slapd ldap-utils openssl +COPY entrypoint.sh seed.ldif /fixture/ +ENTRYPOINT ["bash", "/fixture/entrypoint.sh"] diff --git a/backend/test/fixtures/ldap/README.md b/backend/test/fixtures/ldap/README.md new file mode 100644 index 00000000..681f0bd1 --- /dev/null +++ b/backend/test/fixtures/ldap/README.md @@ -0,0 +1,212 @@ +# OpenLDAP test fixture + +This fixture contains synthetic accounts only. It uses OpenLDAP from a pinned +Debian base, generates a short-lived CA and certificate on startup, and provides +a read-only lookup account. Its configured ACL hides password values. + +From the repository root: + +~~~bash +docker build -t pabawi-ldap-fixture:package3 backend/test/fixtures/ldap +docker run --detach --name pabawi-ldap-p3-openldap --pull never \ + -p 127.0.0.1::1389 -p 127.0.0.1::1636 pabawi-ldap-fixture:package3 +docker port pabawi-ldap-p3-openldap +mkdir -p /tmp/pabawi-ldap-fixture-tls /tmp/pabawi-ldap-fixture-downloads +docker cp pabawi-ldap-p3-openldap:/fixture/tls/ca.pem /tmp/pabawi-ldap-fixture-tls/ca.pem +docker cp pabawi-ldap-p3-openldap:/downloads/. /tmp/pabawi-ldap-fixture-downloads +clamscan -r /tmp/pabawi-ldap-fixture-downloads +~~~ + +Use the published 1636 and 1389 ports, respectively: + +~~~bash +TEST_LDAP_LDAPS_PORT=PORT_1636 \ +TEST_LDAP_STARTTLS_PORT=PORT_1389 \ +TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-fixture-tls/ca.pem \ +npm run test --workspace=backend -- test/integration/ldap-directory.test.ts +docker stop pabawi-ldap-p3-openldap +~~~ + +The fixture uses FQDN localhost.localdomain, which must resolve to loopback. +The test skips when the three TEST_LDAP variables are absent. An ordinary full +backend test run therefore does not constitute directory interoperability evidence. +Containers, image and temporary artifacts are retained for inspection. + +The service is read-only. Fixture setup uses slapadd before starting slapd. +The test credentials are fixture-reader, fixture-user and fixture-admin. They have +no meaning outside this disposable directory. No real AD interoperability is +claimed by this fixture. + +## Browser contract fixture + +Run from the repository root with the supported Node 24 runtime: + +~~~bash +npx playwright test --config playwright.ldap.config.ts +~~~ + +This separate suite starts an in-memory database and loopback-only HTTP server with +synthetic directory responses, builds the frontend, and exercises real auth, mapping, +user/role routes and sessions through Chromium. It uses no developer database or real +directory. It covers short LDAP credentials, provider isolation, local login, page +permissions, mappings, failed diagnostics and read-only nullable directory profiles. +It does not establish LDAP protocol or AD interoperability. The regular Playwright +configuration excludes this directory so it cannot run against infrastructure fixtures. +Browser artifacts and screenshots are retained under /tmp/pabawi-ldap-p6-*. + +## Live rollout and worker acceptance + +Use a fresh container from the verified fixture image for each acceptance session. The current +entrypoint seeds an empty database and cannot safely restart a previously seeded container. + +With the same three `TEST_LDAP_*` variables above and an optional disposable +`TEST_DATABASE_URL`, run from the repository root: + +~~~bash +npm run test --workspace=backend -- test/integration/ldap-rollout.test.ts test/database/ldap-authentication.test.ts test/database/provider-bound-sessions.test.ts +~~~ + +The rollout file uses the fixture's synthetic administrator only to create and mutate uniquely named +test entries. Production directory operations remain read-only. It checks zero-role/manual enrollment, +profile and DN moves, group rename/recreation, user recreation and terminal policy revocation through +real authentication HTTP routes. All four adapter/TLS combinations run when PostgreSQL is configured; +PostgreSQL cases are explicitly skipped otherwise. Cleanup removes only case-owned entries. + +Database authentication tests additionally launch `validation-worker.ts` as a separate Node process +using the installed tsx loader. Controlled directory results allow deterministic lease coalescing, +fencing and mapping-revision races on both adapters. These are actual process-boundary tests with +synthetic directory responses, independent of the real-directory and browser evidence. + +## Reproducible acceptance runner + +From the repository root, with supported Node 24, Docker, ClamAV and installed project dependencies: + +~~~bash +npm run test:ldap -- --ldap-image pabawi-ldap-fixture:package3-verified --output-root /tmp +~~~ + +Use any locally available image built from this fixture with --ldap-image. On a fresh machine, +--build-fixture builds the default pabawi-ldap-fixture:acceptance tag from the repository Dockerfile. +A local postgres:17 image is also required; --postgres-image accepts another local reference. +Runtime containers use --pull never. --focused runs the LDAP/backend matrix without the full +frontend/browser/build gates. The full run additionally requires detect-secrets on PATH and the +repository's Chromium test installation. + +The runner creates fresh, uniquely named OpenLDAP and PostgreSQL containers with dynamic loopback +ports, retains/scans the public CA and fixture package downloads, records image IDs and versions, +and supplies the live test environment automatically. It stops its own fixtures in finally after +success or failure, retaining containers, database volumes and evidence. It never removes containers +or overwrites an earlier evidence directory. Commands append to ~/.agents/logs/pabawi.jsonl. + +Each run prints an evidence directory containing result.json, environment.json, command outputs, +browser screenshots and upgrade-recovery-* subdirectories. The recovery cases retain SQLite backups +and PostgreSQL custom-format archives plus a machine-readable list of passed checks. No real +directory, developer database or infrastructure provider is used. + +The transport suite runs nine scenarios in each of five configurations: synthetic SQLite plus actual +OpenLDAP LDAPS/StartTLS on SQLite/PostgreSQL. Its loopback relay interrupts real TLS connections for +outage checks. Its fixture administrator changes only uniquely named test accounts for policy checks. +Provider adapters and infrastructure result payloads remain local fixtures; this does not establish +real Proxmox or AD interoperability. + +## CI acceptance + +The `ldap-acceptance` job in `.github/workflows/ci.yml` runs PostgreSQL 15 and 17 independently. +Each invocation retains SQLite, both real OpenLDAP TLS modes, transport checks, process coordination +and database recovery. `--focused --browser` also runs the dedicated LDAP Chromium suite, which the +normal Playwright configuration excludes. This suite still uses synthetic directory responses. +The runner rejects missing, skipped or failed live-directory/recovery cases and browser cases even +if the underlying test command exits zero. `--postgres-major` checks the actual server version. + +Each job builds the repository's OpenLDAP fixture, explicitly pulls its PostgreSQL image, installs +Chromium and ClamAV, and uses the existing approved dependency-install steps. Runtime containers +still use `--pull never`. Only synthetic acceptance evidence is uploaded, on success and failure, +with 14-day retention: JSON/JUnit results, recovery backups/manifests, browser HTML reports and +failure screenshots/traces. Private keys, fixture downloads and CA files are excluded from upload; +only the public CA is copied from the fixture. No directory credentials or real AD evidence enter +this artifact tree. Local successful invocations validate runner behavior, not GitHub-hosted execution. + +## Opt-in actual AD lab harness + +`ad-lab.example.json` is a configuration shape with local file references, not a usable lab. +Keep the actual configuration outside the repository. All three password references must point to +private regular files outside the repository (mode 0600); symlinks are checked by their resolved +location. The CA reference must be a readable PEM certificate/bundle. No inline passwords or +additional configuration keys are accepted. Fixture and lookup bind identities are distinct roles: +a delegated writer creates fixtures below the explicitly configured parent OU, while the production +service uses the lookup identity to prove read visibility. Domain policy and existing objects are +never modified. + +Run from the repository root to validate configuration, production settings, certificate and secret +references entirely offline: + +~~~bash +npm run test:ldap:ad -- --config /absolute/local/ad-lab.json --output-root /tmp +~~~ + +Without `--execute`, the result is `not-run`, `adVerified=false`, exit 1. Without configuration it is +`unavailable`, with every required case explicitly `not-run` and exit 1. Invalid configuration fails +without recording its contents or raw errors. No connection is opened in either offline mode. + +For a separately authorized disposable Microsoft AD DS lab, the explicit network/mutation opt-in is: + +~~~bash +npm run test:ldap:ad -- --config /absolute/local/ad-lab.json --execute --output-root /tmp +~~~ + +That command has not been executed in this implementation session. It requires two independently +configured equivalent controller FQDNs with trusted LDAPS and StartTLS and an operator attestation +that the lab is actual Microsoft AD DS. RootDSE capabilities are checked and an advertised Samba +vendor is rejected. Capabilities alone do not prove a Microsoft implementation; mocks, OpenLDAP +and Samba never establish actual AD compatibility. + +Each TLS mode creates a random child OU and synthetic objects. The ownership ledger permits only +its generated direct children, checks the marker and binary GUID before every mutation/deletion, +and refuses cleanup if ownership changes. Cleanup never enumerates or recursively deletes arbitrary +OU contents. The retained result journals synthetic run IDs, relative object names and GUIDs as +operations occur, so incomplete cleanup can be investigated with the local lab configuration. +A failed cleanup makes acceptance fail. Only these disposable AD objects are cleaned up; the local +OpenLDAP/PostgreSQL runner continues to retain its containers, volumes, databases and evidence. + +Cases cover binary objectGUID retrieval/equality queries and production immutable-ID resolution; +user/group rename and recreation; disabled, expired, password-expired and computed locked state; +explicit AD matching-rule-in-chain plus bounded traversal; and membership beyond the configured +1501-3000 range. The large group uses synthetic contacts and requires an actual nonterminal ranged +`member` response. No change to MaxValRange or domain lockout/password policy is attempted. The lab +must expose a lockout within its configured 1-20 wrong binds against the harness-created user. +Missing policy visibility, unsuitable lab policy, missing ranged results or replication timeout fail +acceptance. Failover refuses primary transport establishment through an injected connector and then +uses the real alternate controller/TLS/user bind after bounded replication convergence. This provides +controlled outage evidence, not an observed controller shutdown. + +The configured mutation limits and replication timeout are validated offline. Local ownership tests +simulate collisions, rename, replacement, foreign objects and lost creation replies; they provide +harness safety evidence only. Actual AD account-policy/replication/schema behavior remains unverified. +Protocol references: [Microsoft computed account state](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/b80798ae-1f8c-4d30-9d80-a1f3281e96e2), +[range retrieval](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/e27b48db-6f82-44cd-9038-2e54f790cc1f), +[capabilities](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/3ed61e6c-cfdc-487d-9f02-5a3397be3772), +and [ldapts binary attributes](https://github.com/ldapts/ldapts#searchbasedn-options-controls). + +## Runner failure and interruption regressions + +~~~bash +npm run test:ldap:runner +LDAP_RUNNER_REAL_FAILURES=1 node --test scripts/acceptance/ldap.test.mjs +~~~ + +The default tests run the real CLI with controlled executable shims and retained synthetic state. +The second command additionally creates real local Docker fixtures using the verified local +`pabawi-ldap-fixture:package3-verified` and `postgres:17` images. It injects scanner rejection, +readiness timeout, test subprocess failure, command timeout and both SIGINT/SIGTERM. The tests prove +nonzero exit, persisted command/environment/result manifests, verified shutdown, no subsequent +acceptance stages and termination of detached descendants that ignore SIGTERM. A separate synthetic +creation-interruption case proves the shutdown ledger includes Docker creation before it returns. +Every fixture is retained, never removed automatically. Rejected scanner artifacts are retained for +inspection; scan them with real ClamAV after an intentionally injected scanner rejection. + +The runner has separate readiness deadlines (default 30 seconds each) and a command deadline +(default 15 minutes), configurable with `--readiness-timeout-ms` and `--command-timeout-ms`. +Cancellation exits 130/143, prevents further work, terminates command groups and detached descendants, +and then stops/verifies every attempted fixture. Shutdown has its own bounded budget. Evidence marks +unavailable shutdown inspection or a failed stop as failure rather than claiming cleanup succeeded. +SIGKILL and host loss cannot execute in-process cleanup; retained container names are in the logs. diff --git a/backend/test/fixtures/ldap/ad-lab.example.json b/backend/test/fixtures/ldap/ad-lab.example.json new file mode 100644 index 00000000..491aaed9 --- /dev/null +++ b/backend/test/fixtures/ldap/ad-lab.example.json @@ -0,0 +1,19 @@ +{ + "implementation": "microsoft-ad-ds", + "disposableLab": true, + "baseDn": "dc=lab,dc=example,dc=test", + "parentOu": "ou=PabawiAcceptance,dc=lab,dc=example,dc=test", + "controllers": [ + { "hostname": "dc1.lab.example.test", "ldapsPort": 636, "starttlsPort": 389 }, + { "hostname": "dc2.lab.example.test", "ldapsPort": 636, "starttlsPort": 389 } + ], + "caFile": "/absolute/local/ad-ca.pem", + "fixtureBindDn": "cn=fixture-writer,ou=LabServices,dc=lab,dc=example,dc=test", + "fixturePasswordFile": "/absolute/local/private/fixture-password", + "lookupBindDn": "cn=lookup-reader,ou=LabServices,dc=lab,dc=example,dc=test", + "lookupPasswordFile": "/absolute/local/private/lookup-password", + "userPasswordFile": "/absolute/local/private/disposable-user-password", + "largeMemberCount": 1601, + "maxLockoutAttempts": 10, + "replicationTimeoutSeconds": 120 +} diff --git a/backend/test/fixtures/ldap/ad-lab.ts b/backend/test/fixtures/ldap/ad-lab.ts new file mode 100644 index 00000000..56964668 --- /dev/null +++ b/backend/test/fixtures/ldap/ad-lab.ts @@ -0,0 +1,334 @@ +import assert from 'node:assert/strict'; +import { randomUUID } from 'node:crypto'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { Attribute, Change, Client, EqualityFilter, ExtensibleFilter } from 'ldapts'; +import type { Entry } from 'ldapts'; +import { ldapDnEquals, ldapDnWithinScope, parseLdapDn } from '../../../src/config/ldapDn'; +import { parseLdapConfig } from '../../../src/config/ldap'; +import { LdapDirectoryService } from '../../../src/services/LdapDirectoryService'; +import { LoggerService } from '../../../src/services/LoggerService'; +import { guidToSubject } from '../../../src/services/ldap/identity'; +import { attributeValues, textAttribute } from '../../../src/services/ldap/policy'; + +export interface AdLabConfig { + implementation: string; disposableLab: boolean; baseDn: string; parentOu: string; + controllers: { hostname: string; ldapsPort: number; starttlsPort: number }[]; + caFile: string; fixtureBindDn: string; fixturePasswordFile: string; + lookupBindDn: string; lookupPasswordFile: string; userPasswordFile: string; + largeMemberCount: number; maxLockoutAttempts: number; replicationTimeoutSeconds: number; +} +interface Report { + status: string; adVerified: boolean; reason: string; + cases: { name: string; status: string }[]; + cleanup?: { status: string; remaining: number }; platform?: string; + fixtureOwnership?: { runId: string; objects: { relativeDn: string; guid?: string }[] }[]; +} +type Writer = Pick; + +export function validateAdBoundary(config: AdLabConfig): void { + const base = parseLdapDn(config.baseDn); + const parent = parseLdapDn(config.parentOu); + assert(base.length >= 2 && base.every(rdn => rdn.length === 1 && (JSON.parse(rdn[0]) as string[])[0] === 'dc')); + assert(parent[0].length === 1 && (JSON.parse(parent[0][0]) as string[])[0] === 'ou'); + assert(!ldapDnEquals(config.parentOu, config.baseDn) && ldapDnWithinScope(config.parentOu, config.baseDn)); + parseLdapDn(config.fixtureBindDn); + parseLdapDn(config.lookupBindDn); +} + +export function validateAdSettings(config: AdLabConfig, lookupPassword: string): void { + validateAdBoundary(config); + for (const endpoint of config.controllers) { + for (const mode of ['ldaps', 'starttls'] as const) { + parseLdapConfig({ LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'actual-ad-lab', LDAP_DIRECTORY_TYPE: 'ad', + LDAP_HOSTNAME: endpoint.hostname, LDAP_PORT: String(mode === 'ldaps' ? endpoint.ldapsPort : endpoint.starttlsPort), + LDAP_TLS_MODE: mode, LDAP_CA_FILE: config.caFile, LDAP_BASE_DN: config.parentOu, + LDAP_LOOKUP_USER: config.lookupBindDn, LDAP_LOOKUP_PASSWORD: lookupPassword }); + } + } +} + +export class OwnedAdFixtures { + public readonly marker = 'pabawi-acceptance-' + randomUUID(); + public readonly ou: string; + private readonly owned = new Map(); + private cleaning = false; + constructor(private readonly client: Writer, parentOu: string, private readonly checkpoint: () => void = () => undefined, private readonly check: () => void = () => undefined) { + this.ou = 'ou=' + this.marker + ',' + parentOu; + } + public snapshot(): { runId: string; objects: { relativeDn: string; guid?: string }[] } { + return { runId: this.marker, objects: [...this.owned].map(([dn, guid]) => ({ + relativeDn: dn === this.ou ? '' : dn.slice(0, -(this.ou.length + 1)), guid: guid?.toString('hex'), + })) }; + } + public dn(name: string): string { + assert(/^[a-z][a-z0-9-]{0,60}$/.test(name)); + return 'cn=' + name + ',' + this.ou; + } + private boundary(dn: string): void { + assert(ldapDnEquals(dn, this.ou) || ldapDnWithinScope(dn, this.ou)); + assert(this.owned.has(dn), 'Mutation requires a run-owned object'); + } + public async read(dn: string): Promise { + this.boundary(dn); + try { + const result = await this.client.search(dn, { scope: 'base', filter: '(objectClass=*)', + attributes: ['objectGUID', 'description'], explicitBufferAttributes: ['objectGUID'], sizeLimit: 1 }); + assert(result.searchReferences.length === 0 && result.searchEntries.length <= 1); + return result.searchEntries[0]; + } catch (error) { + if ((error as { code?: number }).code === 32) return undefined; + throw error; + } + } + private async prove(dn: string): Promise { + const entry = await this.read(dn); + assert(entry && textAttribute(entry, 'description', true) === this.marker, 'Ownership marker changed'); + const [guid] = attributeValues(entry, 'objectGUID'); + assert(Buffer.isBuffer(guid) && guid.length === 16, 'Binary ownership identity required'); + const previous = this.owned.get(dn); + assert(!previous || previous.equals(guid), 'Ownership identity changed'); + this.owned.set(dn, guid); + this.checkpoint(); + return guid; + } + private child(dn: string): boolean { + const name = dn.slice(3, dn.indexOf(',')); + return /^[a-z][a-z0-9-]{0,60}$/.test(name) && dn === this.dn(name); + } + public async add(dn: string, attributes: Record): Promise { + assert((dn === this.ou || this.child(dn)) && !this.owned.has(dn)); + this.owned.set(dn, undefined); + this.checkpoint(); + this.check(); + await this.client.add(dn, { ...attributes, description: this.marker }); + return this.prove(dn); + } + public async replace(dn: string, type: string, values: string[] | Buffer[]): Promise { + await this.prove(dn); + assert(['unicodePwd', 'userAccountControl', 'accountExpires', 'pwdLastSet', 'lockoutTime', 'member'].includes(type)); + this.check(); + await this.client.modify(dn, new Change({ operation: 'replace', modification: new Attribute({ type, values }) })); + } + public async rename(dn: string, next: string): Promise { + assert(this.child(next) && !this.owned.has(next)); + const guid = await this.prove(dn); + this.owned.set(next, guid); + this.checkpoint(); + this.check(); + await this.client.modifyDN(dn, next); + await this.prove(next); + this.owned.delete(dn); + this.checkpoint(); + } + public async remove(dn: string): Promise { + await this.prove(dn); + if (!this.cleaning) this.check(); + await this.client.del(dn); + this.owned.delete(dn); + this.checkpoint(); + } + public async cleanup(): Promise<{ status: string; remaining: number }> { + this.cleaning = true; + for (const dn of [...this.owned.keys()].reverse()) { + try { + if (await this.read(dn)) await this.remove(dn); + else { this.owned.delete(dn); this.checkpoint(); } + } catch { /* Keep ownership evidence when an object changed or cleanup failed. */ } + } + return { status: this.owned.size ? 'failed' : 'passed', remaining: this.owned.size }; + } +} + +export async function runAdLab(config: AdLabConfig, report: Report, evidence: string, secrets: { fixturePassword: string; lookupPassword: string; userPassword: string }): Promise { + validateAdBoundary(config); + const { fixturePassword, lookupPassword, userPassword } = secrets; + const clients = new Set(); + const fixtures: OwnedAdFixtures[] = []; + let interrupted = false; + const cancel = (): void => { + interrupted = true; + // Let the bounded current operation settle; keep the writer bound for owned-object cleanup. + }; + process.on('SIGINT', cancel); + process.on('SIGTERM', cancel); + const check = (): void => { assert(!interrupted, 'AD harness interrupted'); }; + const connect = async (mode: 'ldaps' | 'starttls', controller = 0): Promise => { + check(); + const endpoint = config.controllers[controller]; + const tlsOptions = { ca: [readFileSync(config.caFile)], rejectUnauthorized: true, minVersion: 'TLSv1.2' as const, + servername: endpoint.hostname }; + const client = new Client({ url: (mode === 'ldaps' ? 'ldaps' : 'ldap') + '://' + endpoint.hostname + ':' + + (mode === 'ldaps' ? endpoint.ldapsPort : endpoint.starttlsPort), + timeout: 10000, connectTimeout: 10000, autoRebind: false, ...(mode === 'ldaps' ? { tlsOptions } : {}) }); + clients.add(client); + if (mode === 'starttls') await client.startTLS(tlsOptions); + return client; + }; + report.status = 'running'; + report.platform = 'operator-attested Microsoft AD DS; capabilities checked; no substitute establishes actual AD'; + try { + for (const mode of ['ldaps', 'starttls'] as const) { + check(); + const admin = await connect(mode); + await admin.bind(config.fixtureBindDn, fixturePassword); + const root = await admin.search('', { scope: 'base', attributes: ['supportedCapabilities', 'vendorName'], filter: '(objectClass=*)' }); + assert(root.searchEntries.length === 1 && root.searchReferences.length === 0); + assert(attributeValues(root.searchEntries[0], 'supportedCapabilities').includes('1.2.840.113556.1.4.800')); + assert(!JSON.stringify(root.searchEntries).toLowerCase().includes('samba')); + const owned = new OwnedAdFixtures(admin, config.parentOu, () => { + report.fixtureOwnership = fixtures.map(fixture => fixture.snapshot()); + writeFileSync(join(evidence, 'result.json'), JSON.stringify(report, null, 2), { mode: 0o600 }); + }, check); + fixtures.push(owned); + await owned.add(owned.ou, { objectClass: 'organizationalUnit', ou: owned.marker }); + const sam = 'pa' + randomUUID().replaceAll('-', '').slice(0, 14); + let userDn = owned.dn('user'); + const addUser = async (): Promise => { + const guid = await owned.add(userDn, { objectClass: 'user', cn: userDn.slice(3, userDn.indexOf(',')), + sAMAccountName: sam, sn: 'Synthetic', userAccountControl: '514' }); + await owned.replace(userDn, 'unicodePwd', [Buffer.from('"' + userPassword + '"', 'utf16le')]); + await owned.replace(userDn, 'userAccountControl', ['512']); + return guid; + }; + const guid = await addUser(); + const subject = guidToSubject(guid); + const baseConfig = parseLdapConfig({ LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'actual-ad-lab', LDAP_DIRECTORY_TYPE: 'ad', + LDAP_HOSTNAME: config.controllers[0].hostname, LDAP_PORT: String(mode === 'ldaps' ? config.controllers[0].ldapsPort : config.controllers[0].starttlsPort), + LDAP_TLS_MODE: mode, LDAP_CA_FILE: config.caFile, LDAP_BASE_DN: owned.ou, + LDAP_LOOKUP_USER: config.lookupBindDn, LDAP_LOOKUP_PASSWORD: lookupPassword, + LDAP_SEARCH_NESTED_GROUPS: 'true', LDAP_REQUEST_TIMEOUT_SECONDS: '60' })!; + const directory = new LdapDirectoryService(baseConfig, new LoggerService('error')); + const record = async (name: string, action: () => Promise): Promise => { + check(); + const item = { name: mode + '/' + name, status: 'running' }; + report.cases.push(item); + try { await action(); check(); item.status = 'passed'; } + catch { item.status = 'failed'; throw new Error('AD acceptance case failed'); } + finally { writeFileSync(join(evidence, 'result.json'), JSON.stringify(report, null, 2), { mode: 0o600 }); } + }; + await record('binary-guid-retrieval-filter', async () => { + const result = await admin.search(owned.ou, { scope: 'sub', filter: new EqualityFilter({ attribute: 'objectGUID', value: guid }), + attributes: ['objectGUID'], explicitBufferAttributes: ['objectGUID'] }); + assert(result.searchEntries.length === 1 && result.searchReferences.length === 0); + assert((await directory.authenticate(sam, userPassword)).user.subject === subject); + assert((await directory.revalidate(subject)).user.subject === subject); + }); + await record('rename-recreation', async () => { + const next = owned.dn('renamed-user'); + await owned.rename(userDn, next); userDn = next; + assert(ldapDnEquals((await directory.revalidate(subject)).user.dn, next)); + await owned.remove(userDn); + const replacement = await addUser(); + assert(!replacement.equals(guid)); + await assert.rejects(directory.revalidate(subject)); + assert((await directory.authenticate(sam, userPassword)).user.subject === guidToSubject(replacement)); + }); + const current = (await directory.authenticate(sam, userPassword)).user.subject; + await record('account-states', async () => { + await owned.replace(userDn, 'userAccountControl', ['514']); + await assert.rejects(directory.revalidate(current), { code: 'INELIGIBLE' }); + await owned.replace(userDn, 'userAccountControl', ['512']); + await owned.replace(userDn, 'accountExpires', ['1']); + await assert.rejects(directory.revalidate(current), { code: 'INELIGIBLE' }); + await owned.replace(userDn, 'accountExpires', ['0']); + await owned.replace(userDn, 'pwdLastSet', ['0']); + await assert.rejects(directory.revalidate(current), { code: 'INELIGIBLE' }); + await owned.replace(userDn, 'pwdLastSet', ['-1']); + await directory.revalidate(current); + let locked = false; + for (let attempt = 0; attempt < config.maxLockoutAttempts; attempt++) { + check(); + const badBind = await connect(mode); + try { await assert.rejects(badBind.bind(userDn, randomUUID())); } + finally { await badBind.unbind(); clients.delete(badBind); } + try { await directory.revalidate(current); } + catch (error) { if ((error as { code?: string }).code === 'INELIGIBLE') { + const policy = await admin.search(userDn, { scope: 'base', attributes: ['msDS-User-Account-Control-Computed'], filter: '(objectClass=*)' }); + const value = textAttribute(policy.searchEntries[0], 'msDS-User-Account-Control-Computed', true); + assert(value && (BigInt(value) & 16n) !== 0n, 'Lockout must be observed, not inferred from denial'); + locked = true; break; + } throw error; } + } + assert(locked, 'Lab must have observable bounded lockout policy'); + await owned.replace(userDn, 'lockoutTime', ['0']); + assert((await directory.authenticate(sam, userPassword)).user.subject === current); + }); + const directDn = owned.dn('direct-group'); + const parentDn = owned.dn('parent-group'); + let directSubject = ''; + let parentSubject = ''; + await record('nested-groups', async () => { + directSubject = guidToSubject(await owned.add(directDn, { objectClass: 'group', cn: 'direct-group', sAMAccountName: sam + 'd', groupType: '-2147483646', member: [userDn] })); + parentSubject = guidToSubject(await owned.add(parentDn, { objectClass: 'group', cn: 'parent-group', sAMAccountName: sam + 'p', groupType: '-2147483646', member: [directDn] })); + const subjects = [directSubject, parentSubject]; + const chain = await admin.search(owned.ou, { scope: 'sub', + filter: new ExtensibleFilter({ matchType: 'member', rule: '1.2.840.113556.1.4.1941', value: userDn }), + attributes: ['objectGUID'], explicitBufferAttributes: ['objectGUID'], sizeLimit: 3 }); + assert(chain.searchReferences.length === 0); + assert.deepEqual(new Set(chain.searchEntries.map(entry => { + const [value] = attributeValues(entry, 'objectGUID'); assert(Buffer.isBuffer(value)); return guidToSubject(value); + })), new Set(subjects)); + assert.deepEqual(new Set((await directory.authenticate(sam, userPassword, subjects)).groupSubjects), new Set(subjects)); + const traversal = new LdapDirectoryService({ ...baseConfig, disableMatchingRuleInChain: true }, new LoggerService('error')); + assert.deepEqual(new Set((await traversal.revalidate(current, subjects)).groupSubjects), new Set(subjects)); + const bounded = new LdapDirectoryService({ ...baseConfig, nestedGroupMaxDepth: 1 }, new LoggerService('error')); + await assert.rejects(bounded.revalidate(current, subjects), { code: 'LIMIT_EXCEEDED' }); + await owned.rename(parentDn, owned.dn('renamed-group')); + assert(ldapDnEquals((await directory.resolveGroup(parentSubject)).dn, owned.dn('renamed-group'))); + await owned.remove(owned.dn('renamed-group')); + const replacement = guidToSubject(await owned.add(parentDn, { objectClass: 'group', cn: 'parent-group', sAMAccountName: sam + 'p', groupType: '-2147483646', member: [directDn] })); + assert(replacement !== parentSubject); + assert(!(await directory.revalidate(current, subjects)).groupSubjects.includes(parentSubject)); + }); + await record('large-membership', async () => { + const largeDn = owned.dn('large-group'); + const largeSubject = guidToSubject(await owned.add(largeDn, { objectClass: 'group', cn: 'large-group', sAMAccountName: sam + 'l', groupType: '8' })); + const members = [userDn]; + for (let i = 1; i < config.largeMemberCount; i++) { + check(); + const dn = owned.dn('member-' + i); + await owned.add(dn, { objectClass: 'contact', cn: 'member-' + i, sn: 'Synthetic' }); + members.push(dn); + } + await owned.replace(largeDn, 'member', members); + const ranged = await admin.search(largeDn, { scope: 'base', attributes: ['member'], filter: '(objectClass=*)' }); + assert(Object.keys(ranged.searchEntries[0]).some(key => /^member;range=0-\d+$/i.test(key)), 'Lab did not produce ranged membership'); + assert((await directory.revalidate(current, [largeSubject])).groupSubjects.includes(largeSubject)); + const bounded = new LdapDirectoryService({ ...baseConfig, groupTraversalLimit: 1 }, new LoggerService('error')); + await assert.rejects(bounded.revalidate(current, [directSubject]), { code: 'LIMIT_EXCEEDED' }); + }); + await record('equivalent-controller-failover', async () => { + const second = config.controllers[1]; + const alternate = { hostname: second.hostname, port: mode === 'ldaps' ? second.ldapsPort : second.starttlsPort }; + const secondDirectory = new LdapDirectoryService({ ...baseConfig, ...alternate }, new LoggerService('error')); + const deadline = Date.now() + config.replicationTimeoutSeconds * 1000; + while (true) { + check(); + try { assert((await secondDirectory.revalidate(current, [directSubject])).groupSubjects.includes(directSubject)); break; } + catch { if (Date.now() >= deadline) throw new Error('Equivalent controller replication unavailable'); await delay(500); } + } + // Refuse only primary connection establishment, keeping the real configured controller/TLS identity. + const { openLdapConnection } = await import('../../../src/services/ldap/transport'); + const failover = new LdapDirectoryService({ ...baseConfig, failoverEndpoints: [alternate] }, new LoggerService('error'), + async (settings, endpoint, signal) => { + if (endpoint.hostname === baseConfig.hostname) throw Object.assign(new Error('Controlled primary transport outage'), { code: 'ECONNREFUSED' }); + return openLdapConnection(settings, endpoint, signal); + }); + assert((await failover.authenticate(sam, userPassword, [directSubject])).user.subject === current); + }); + } + report.cases = report.cases.filter(item => item.status !== 'not-run'); + report.status = 'passed'; report.adVerified = true; + report.reason = 'Operator-attested actual AD lab cases passed in LDAPS and StartTLS'; + } finally { + let remaining = 0; + for (const fixture of fixtures.reverse()) remaining += (await fixture.cleanup()).remaining; + report.cleanup = { status: remaining ? 'failed' : 'passed', remaining }; + if (remaining || interrupted) { report.status = 'failed'; report.adVerified = false; } + for (const client of clients) await client.unbind().catch(() => undefined); + process.removeListener('SIGINT', cancel); process.removeListener('SIGTERM', cancel); + assert(remaining === 0 && !interrupted, 'AD cleanup incomplete or interrupted'); + } +} diff --git a/backend/test/fixtures/ldap/entrypoint.sh b/backend/test/fixtures/ldap/entrypoint.sh new file mode 100644 index 00000000..6a8c04b0 --- /dev/null +++ b/backend/test/fixtures/ldap/entrypoint.sh @@ -0,0 +1,38 @@ +#!/bin/bash +set -eu +mkdir -p /fixture/tls /fixture/db +openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 2 \ + -subj /CN=Pabawi-LDAP-fixture-CA -keyout /fixture/tls/ca.key -out /fixture/tls/ca.pem +openssl req -newkey rsa:2048 -nodes -subj /CN=localhost.localdomain \ + -keyout /fixture/tls/server.key -out /fixture/tls/server.csr +printf 'subjectAltName=DNS:localhost.localdomain,DNS:*.fixture.test\nextendedKeyUsage=serverAuth\n' > /fixture/tls/extensions +openssl x509 -req -in /fixture/tls/server.csr -CA /fixture/tls/ca.pem \ + -CAkey /fixture/tls/ca.key -CAcreateserial -days 2 -sha256 \ + -extfile /fixture/tls/extensions -out /fixture/tls/server.pem +cat > /fixture/slapd.conf <<'CONF' +include /etc/ldap/schema/core.schema +include /etc/ldap/schema/cosine.schema +include /etc/ldap/schema/inetorgperson.schema +pidfile /fixture/slapd.pid +argsfile /fixture/slapd.args +modulepath /usr/lib/ldap +moduleload back_mdb +TLSCACertificateFile /fixture/tls/ca.pem +TLSCertificateFile /fixture/tls/server.pem +TLSCertificateKeyFile /fixture/tls/server.key +TLSProtocolMin 3.3 +database mdb +maxsize 10485760 +suffix "dc=example,dc=test" +rootdn "cn=admin,dc=example,dc=test" +rootpw fixture-admin +directory /fixture/db +access to attrs=userPassword + by anonymous auth + by * none +access to * + by dn.exact="cn=reader,dc=example,dc=test" read + by * none +CONF +slapadd -f /fixture/slapd.conf -l /fixture/seed.ldif +exec slapd -f /fixture/slapd.conf -h "ldap://0.0.0.0:1389 ldaps://0.0.0.0:1636" -d 0 diff --git a/backend/test/fixtures/ldap/seed.ldif b/backend/test/fixtures/ldap/seed.ldif new file mode 100644 index 00000000..f54bb9ac --- /dev/null +++ b/backend/test/fixtures/ldap/seed.ldif @@ -0,0 +1,95 @@ +dn: dc=example,dc=test +objectClass: domain +dc: example + +dn: cn=reader,dc=example,dc=test +objectClass: simpleSecurityObject +objectClass: organizationalRole +cn: reader +userPassword: fixture-reader + +dn: ou=people,dc=example,dc=test +objectClass: organizationalUnit +ou: people + +dn: ou=groups,dc=example,dc=test +objectClass: organizationalUnit +ou: groups + +dn: uid=alice,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: alice +cn: Alice +sn: Example +displayName: Alice Fixture +mail: alice@example.test +employeeType: active +userPassword: fixture-user + +dn: uid=inactive,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: inactive +cn: Inactive +sn: Example +employeeType: inactive +userPassword: fixture-user + +dn: uid=missing-policy,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: missing-policy +cn: Missing +sn: Example +userPassword: fixture-user + +dn: cn=operators,ou=groups,dc=example,dc=test +objectClass: groupOfUniqueNames +cn: operators +uniqueMember: uid=alice,ou=people,dc=example,dc=test +uniqueMember: cn=admins,ou=groups,dc=example,dc=test + +dn: cn=admins,ou=groups,dc=example,dc=test +objectClass: groupOfUniqueNames +cn: admins +uniqueMember: cn=operators,ou=groups,dc=example,dc=test + +dn: cn=ordinary,ou=groups,dc=example,dc=test +objectClass: groupOfNames +cn: ordinary +member: uid=alice,ou=people,dc=example,dc=test + +dn: uid=josé,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: josé +cn: José +sn: Example +employeeType: active +userPassword: fixture-user + +dn: uid=duplicate,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: duplicate +cn: Duplicate One +sn: Example +employeeType: active +userPassword: fixture-user + +dn: cn=duplicate-two,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: duplicate +cn: duplicate-two +sn: Example +employeeType: active +userPassword: fixture-user + +dn: uid=suffix,ou=people,dc=example,dc=test +objectClass: inetOrgPerson +uid: suffix +cn: Suffix +sn: Example +employeeType: active +userPassword: fixture-user + +dn: cn=optionaluid,ou=groups,dc=example,dc=test +objectClass: groupOfUniqueNames +cn: optionaluid +uniqueMember: uid=suffix,ou=people,dc=example,dc=test#'0101'B diff --git a/backend/test/fixtures/ldap/tsconfig.ad.json b/backend/test/fixtures/ldap/tsconfig.ad.json new file mode 100644 index 00000000..6ace4772 --- /dev/null +++ b/backend/test/fixtures/ldap/tsconfig.ad.json @@ -0,0 +1,6 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { "noEmit": true, "rootDir": "../../.." }, + "include": ["ad-lab.ts", "../../../src/types/node-tls.d.ts"], + "exclude": [] +} diff --git a/backend/test/fixtures/ldap/ui-server.ts b/backend/test/fixtures/ldap/ui-server.ts new file mode 100644 index 00000000..acd9c304 --- /dev/null +++ b/backend/test/fixtures/ldap/ui-server.ts @@ -0,0 +1,93 @@ +import express from 'express'; +import { resolve } from 'node:path'; +import { DatabaseService } from '../../../src/database/DatabaseService'; +import { createDefaultContainer, resolveAuthenticationService } from '../../../src/container/DIContainer'; +import { LdapDirectoryService, LdapDirectoryError, type LdapDiagnostics } from '../../../src/services/LdapDirectoryService'; +import { LdapMappingService } from '../../../src/services/LdapMappingService'; +import { LdapAuthenticationService } from '../../../src/services/LdapAuthenticationService'; +import { UserService } from '../../../src/services/UserService'; +import { createAuthRouter } from '../../../src/routes/auth'; +import { createLdapAdministrationRouter } from '../../../src/routes/ldapAdministration'; +import { createUsersRouter } from '../../../src/routes/users'; +import { createRolesRouter } from '../../../src/routes/roles'; +import { createGroupsRouter } from '../../../src/routes/groups'; +import { inputSanitizationMiddleware } from '../../../src/middleware/securityMiddleware'; + +const group = { subject: '10112233-4455-6677-8899-aabbccddeeff', + dn: 'cn=operators,dc=example,dc=test', name: 'Operators' }; +const result = { user: { subject: '00112233-4455-6677-8899-aabbccddeeff', + dn: 'uid=a,dc=example,dc=test', loginName: 'a', displayName: 'Directory A', + email: null, firstName: '', lastName: '' }, groupSubjects: [group.subject] }; +const directoryPassword = 'x'; // pragma: allowlist secret +const localPassword = 'LocalTest123!'; // pragma: allowlist secret + +// Synthetic directory responses isolate browser contracts from LDAP protocol acceptance. +class BrowserDirectory extends LdapDirectoryService { + override async authenticate(username: string, password: string) { + if (username !== 'a' || password !== directoryPassword) throw new LdapDirectoryError('INVALID_CREDENTIALS'); + return result; + } + override async revalidate() { return result; } + override async searchGroups(query: string) { return query === 'empty' ? [] : [group]; } + override async resolveGroup(subject: string) { + if (subject !== group.subject) throw new LdapDirectoryError('INVALID_IDENTITY'); + return group; + } + override async diagnose(input: { username?: string; groupSubjects?: string[] }): Promise { + if (input.username === 'outage') return { authenticated: false, stages: [ + { stage: 'tls', status: 'failed', durationMs: 2, code: 'UNAVAILABLE' }, + ] }; + return { authenticated: false, stages: [ + { stage: 'tls', status: 'passed', durationMs: 1 }, { stage: 'lookup', status: 'passed', durationMs: 1 }, + ...(input.username ? [{ stage: 'identity' as const, status: 'passed' as const, durationMs: 1 }, + { stage: 'eligibility' as const, status: 'passed' as const, durationMs: 1 }] : []), + ], ...(input.groupSubjects ? { groupSubjects: input.groupSubjects } : {}) }; + } +} + +async function start(): Promise { + const database = new DatabaseService(':memory:'); + await database.initialize(); + const container = createDefaultContainer(); + const config = container.resolve('config').getLdapConfig(); + if (!config) throw new Error('Browser fixture requires LDAP configuration'); + const db = database.getAdapter(); + const auth = resolveAuthenticationService(db, container); + const users = new UserService(db, auth); + const admin = await users.createUser({ username: 'browseradmin', email: 'admin@example.test', + password: localPassword, firstName: 'Browser', lastName: 'Admin', isAdmin: true }); + await users.createUser({ username: 'browserviewer', email: 'viewer@example.test', + password: localPassword, firstName: 'Browser', lastName: 'Viewer' }); + const directory = new BrowserDirectory(config, container.resolve('logger')); + const mappings = new LdapMappingService(db, config.directoryId, directory); + await mappings.create(group.subject, 'role-viewer-001', { userId: admin.id }); + await users.createFederatedUser({ provider: 'ldap', issuer: config.directoryId, + ...result.user, defaultRole: 'none' }); + const ldap = new LdapAuthenticationService(db, config, directory, mappings, users); + await ldap.initialize(); + container.register('ldapDirectory', directory); + container.register('ldapMappings', mappings); + container.register('ldapAuthentication', ldap); + + const app = express(); + app.use(express.json({ limit: '100kb' })); + app.use(inputSanitizationMiddleware); + app.get('/api/setup/status', (_req, res) => res.json({ isComplete: true, config: { allowSelfRegistration: false } })); + app.use('/api/auth/ldap', createLdapAdministrationRouter(database, container)); + app.use('/api/auth', createAuthRouter(database, container)); + app.use('/api/users', createUsersRouter(database, container)); + app.use('/api/roles', createRolesRouter(database, container)); + app.use('/api/groups', createGroupsRouter(database, container)); + app.use('/api', (_req, res) => res.status(404).json({ error: { message: 'Outside browser fixture scope' } })); + app.use(express.static(resolve('frontend/dist'))); + app.get('*', (_req, res) => res.sendFile(resolve('frontend/dist/index.html'))); + const server = app.listen(3186, '127.0.0.1'); + async function close(): Promise { + await new Promise((yes, no) => server.close(error => error ? no(error) : yes())); + await database.close(); + } + process.once('SIGTERM', () => { void close(); }); + process.once('SIGINT', () => { void close(); }); +} + +void start(); diff --git a/backend/test/fixtures/ldap/validation-worker.ts b/backend/test/fixtures/ldap/validation-worker.ts new file mode 100644 index 00000000..9acc229c --- /dev/null +++ b/backend/test/fixtures/ldap/validation-worker.ts @@ -0,0 +1,47 @@ +import { DatabaseService } from '../../../src/database/DatabaseService'; +import { AuthenticationService } from '../../../src/services/AuthenticationService'; +import { UserService } from '../../../src/services/UserService'; +import { LdapMappingService } from '../../../src/services/LdapMappingService'; +import { LdapAuthenticationService } from '../../../src/services/LdapAuthenticationService'; +import type { LdapAuthenticationProof } from '../../../src/services/LdapAuthenticationService'; +import type { LdapConfig } from '../../../src/config/ldap'; +import type { LdapDirectoryResult } from '../../../src/services/LdapDirectoryService'; + +interface Input { + databasePath: string; dialect: 'sqlite' | 'postgres'; databaseUrl: string; + config: LdapConfig; proof: LdapAuthenticationProof; result: LdapDirectoryResult; +} + +process.once('message', (input: Input) => { + void (async () => { + const database = new DatabaseService(input.databasePath, input.dialect, input.databaseUrl); + try { + await database.initialize(); + const db = database.getAdapter(); + const users = new UserService(db, new AuthenticationService(db, 'ldap-authentication-fixture-jwt-secret')); // pragma: allowlist secret + const directory = { + authenticate: async () => input.result, + revalidate: async () => { + const released = new Promise(resolve => process.once('message', () => { resolve(); })); + process.send!({ type: 'reading', pid: process.pid }); + await released; + return input.result; + }, + }; + const mappings = new LdapMappingService(db, input.config.directoryId, { + resolveGroup: async subject => ({ subject, dn: 'cn=operators,dc=example,dc=test', name: 'Operators' }), + }); + const service = new LdapAuthenticationService(db, input.config, directory, mappings, users); + await service.initialize(); + const proof = input.proof; + await service.assertEligible(proof.user.id, proof.identityId, proof.directoryId, proof.sessionVersion, true); + process.send!({ type: 'done', code: 'ok' }); + } catch (error) { + const code = error instanceof Error && 'code' in error ? String(error.code) : 'UNEXPECTED_ERROR'; + process.send!({ type: 'done', code }); + } finally { + await database.close(); + process.disconnect(); + } + })(); +}); diff --git a/backend/test/helpers/consoleUser.ts b/backend/test/helpers/consoleUser.ts index c874a80f..6fb6f7c1 100644 --- a/backend/test/helpers/consoleUser.ts +++ b/backend/test/helpers/consoleUser.ts @@ -7,3 +7,9 @@ export async function ensureConsoleUser(db: DatabaseAdapter, userId: string): Pr [userId, userId, `${userId}@example.test`], ); } + +export async function consoleAuthentication(db: DatabaseAdapter, userId: string) { + const row = await db.queryOne<{ sessionVersion: string }>('SELECT session_version AS "sessionVersion" FROM users WHERE id = ?', [userId]); + if (!row) throw new Error('Missing console fixture account'); + return { authContext: { provider: 'local' as const, identityId: null }, sessionVersion: row.sessionVersion }; +} diff --git a/backend/test/helpers/ldapAuthentication.ts b/backend/test/helpers/ldapAuthentication.ts new file mode 100644 index 00000000..d5e052a8 --- /dev/null +++ b/backend/test/helpers/ldapAuthentication.ts @@ -0,0 +1,57 @@ +import { vi } from 'vitest'; +import express from 'express'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { createDefaultContainer, resolveAuthenticationService } from '../../src/container/DIContainer'; +import { parseLdapConfig } from '../../src/config/ldap'; +import { LdapAuthenticationService } from '../../src/services/LdapAuthenticationService'; +import { LdapMappingService } from '../../src/services/LdapMappingService'; +import { UserService } from '../../src/services/UserService'; +import { createAuthRouter } from '../../src/routes/auth'; +import { createAuthMiddleware } from '../../src/middleware/authMiddleware'; +import { inputSanitizationMiddleware } from '../../src/middleware/securityMiddleware'; +import type { LdapDirectoryResult } from '../../src/services/LdapDirectoryService'; + +export const ldapPassword = 'synthetic-directory-password'; // pragma: allowlist secret +export const ldapGroup = '10112233-4455-6677-8899-aabbccddeeff'; +export const ldapResult: LdapDirectoryResult = { user: { subject: '00112233-4455-6677-8899-aabbccddeeff', + dn: 'uid=a,dc=example,dc=test', loginName: 'a', displayName: 'Directory A', email: null, firstName: '', lastName: '' }, +groupSubjects: [ldapGroup] }; + +export async function createLdapTestContext(database = new DatabaseService(':memory:')) { + vi.stubEnv('JWT_SECRET', 'ldap-http-fixture-signing-secret-key'); + vi.stubEnv('LDAP_ENABLED', 'false'); + vi.stubEnv('ENTRA_ID_ENABLED', 'false'); + await database.initialize(); + const db = database.getAdapter(); + const container = createDefaultContainer(); + const config = parseLdapConfig({ LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'ldap.example.test', LDAP_ANONYMOUS_LOOKUP: 'true', LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)' })!; + vi.spyOn(container.resolve('config'), 'getLdapConfig').mockReturnValue(config); + const auth = resolveAuthenticationService(db, container); + const users = new UserService(db, auth); + const administrator = await users.createUser({ username: 'administrator', email: 'admin@example.test', password: 'LocalTest123!', // pragma: allowlist secret + firstName: '', lastName: '', isAdmin: true }); // pragma: allowlist secret + const directory = { authenticate: vi.fn().mockResolvedValue(ldapResult), revalidate: vi.fn().mockResolvedValue(ldapResult) }; + const mappings = new LdapMappingService(db, config.directoryId, { resolveGroup: async subject => ({ + subject, dn: 'cn=operators,dc=example,dc=test', name: 'Operators', + }) }); + await mappings.create(ldapGroup, 'role-viewer-001', { userId: administrator.id }); + const ldap = new LdapAuthenticationService(db, config, directory, mappings, users); + await ldap.initialize(); + container.register('ldapAuthentication', ldap); + const app = express(); + app.use(express.json({ limit: '100kb' })); + app.use(inputSanitizationMiddleware); + app.use('/api/auth', createAuthRouter(database, container)); + const authenticate = createAuthMiddleware(auth); + app.get('/protected', authenticate, (req, res) => { res.json({ context: req.authContext }); }); + return { database, db, container, config, auth, users, administrator, directory, mappings, ldap, app, authenticate }; +} + +export function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} diff --git a/backend/test/helpers/ldapTransport.ts b/backend/test/helpers/ldapTransport.ts new file mode 100644 index 00000000..3d7f9bb7 --- /dev/null +++ b/backend/test/helpers/ldapTransport.ts @@ -0,0 +1,121 @@ +import { vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { createServer, connect, type Socket } from 'node:net'; +import { Attribute, Change, Client } from 'ldapts'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import { parseLdapConfig } from '../../src/config/ldap'; +import { LdapDirectoryService } from '../../src/services/LdapDirectoryService'; +import { LdapMappingService } from '../../src/services/LdapMappingService'; +import { LdapAuthenticationService } from '../../src/services/LdapAuthenticationService'; +import { createLdapTestContext, ldapPassword } from './ldapAuthentication'; + +export const liveDirectoryReady = !!(process.env.TEST_LDAP_LDAPS_PORT && process.env.TEST_LDAP_STARTTLS_PORT && process.env.TEST_LDAP_CA_FILE); +export type DirectoryMode = 'synthetic' | 'ldaps' | 'starttls'; + +export async function createLdapTransportContext(mode: DirectoryMode, dialect: 'sqlite' | 'postgres' = 'sqlite') { + let database: DatabaseService | undefined; + let control: PostgresAdapter | undefined; + const schema = 'ldaptransport_' + randomUUID().replaceAll('-', ''); + if (dialect === 'postgres') { + control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute('CREATE SCHEMA ' + schema); + const url = new URL(process.env.TEST_DATABASE_URL!); + url.searchParams.set('options', '-csearch_path=' + schema); + database = new DatabaseService(':memory:', 'postgres', url.toString()); + } + const releaseDatabase = async () => { + if (control) { + await control.execute('DROP SCHEMA ' + schema + ' CASCADE'); + await control.close(); + } + }; + const ctx = await createLdapTestContext(database); + if (mode === 'synthetic') return { ...ctx, releaseDatabase, live: undefined, loginName: 'a', loginPassword: ldapPassword }; + const loginName = 'transport-' + randomUUID(); + const userDn = 'uid=' + loginName + ',ou=people,dc=example,dc=test'; + const groupDn = 'cn=' + loginName + ',ou=groups,dc=example,dc=test'; + const targetPort = Number(mode === 'ldaps' ? process.env.TEST_LDAP_LDAPS_PORT : process.env.TEST_LDAP_STARTTLS_PORT); + const sockets = new Set(); + let unavailable = false; + let paused = false; + const relay = createServer(client => { + sockets.add(client); + client.once('close', () => sockets.delete(client)); + client.on('error', () => client.destroy()); + if (unavailable) { client.destroy(); return; } + const upstream = connect({ host: 'localhost.localdomain', port: targetPort }); + sockets.add(upstream); + upstream.once('close', () => { sockets.delete(upstream); client.destroy(); }); + upstream.on('error', () => { upstream.destroy(); client.destroy(); }); + client.once('close', () => upstream.destroy()); + client.pipe(upstream); + upstream.pipe(client); + if (paused) { client.pause(); upstream.pause(); } + }); + await new Promise((resolve, reject) => { + relay.once('error', reject); + relay.listen(0, '127.0.0.1', () => { relay.removeListener('error', reject); resolve(); }); + }); + const address = relay.address(); + if (!address || typeof address === 'string') throw new Error('Missing LDAP relay address'); + const config = parseLdapConfig({ + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'localhost.localdomain', LDAP_PORT: String(address.port), LDAP_TLS_MODE: mode, + LDAP_CA_FILE: process.env.TEST_LDAP_CA_FILE, LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_RDN: 'ou=people', LDAP_GROUP_RDN: 'ou=groups', + LDAP_LOOKUP_USER: 'cn=reader,dc=example,dc=test', LDAP_LOOKUP_PASSWORD: 'fixture-reader', // pragma: allowlist secret + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', + })!; + const tlsOptions = { ca: [readFileSync(config.caFile)], rejectUnauthorized: true, + minVersion: 'TLSv1.2' as const, servername: config.hostname }; + const admin = new Client({ + url: (mode === 'ldaps' ? 'ldaps://' : 'ldap://') + config.hostname + ':' + targetPort, + timeout: 5000, connectTimeout: 5000, autoRebind: false, ...(mode === 'ldaps' ? { tlsOptions } : {}), + }); + const owned: string[] = []; + const live = { + pause: () => { paused = true; }, + outage: (value: boolean) => { + unavailable = value; + paused = false; + for (const socket of sockets) socket.destroy(); + }, + setEligible: async (value: boolean) => { + await admin.modify(userDn, new Change({ operation: 'replace', + modification: new Attribute({ type: 'employeeType', values: [value ? 'active' : 'inactive'] }) })); + }, + close: async () => { + for (const socket of sockets) socket.destroy(); + await new Promise((resolve, reject) => relay.close(error => error ? reject(error) : resolve())); + try { for (const dn of owned.reverse()) await admin.del(dn); } + finally { await admin.unbind(); } + }, + }; + try { + if (mode === 'starttls') await admin.startTLS(tlsOptions); + await admin.bind('cn=admin,dc=example,dc=test', 'fixture-admin'); // pragma: allowlist secret + await admin.add(userDn, { objectClass: 'inetOrgPerson', uid: loginName, cn: 'Transport Fixture', + sn: 'Fixture', employeeType: 'active', userPassword: ldapPassword }); // pragma: allowlist secret + owned.push(userDn); + await admin.add(groupDn, { objectClass: 'groupOfUniqueNames', cn: loginName, uniqueMember: userDn }); + owned.push(groupDn); + for (const mapping of await ctx.mappings.list()) await ctx.mappings.remove(mapping.id, { userId: ctx.administrator.id }); + const directory = new LdapDirectoryService(config, ctx.container.resolve('logger')); + const calls = { authenticate: vi.spyOn(directory, 'authenticate'), revalidate: vi.spyOn(directory, 'revalidate') }; + const mappings = new LdapMappingService(ctx.db, config.directoryId, directory); + await mappings.create((await directory.searchGroups(loginName))[0].subject, 'role-viewer-001', { userId: ctx.administrator.id }); + const ldap = new LdapAuthenticationService(ctx.db, config, directory, mappings, ctx.users); + await ldap.initialize(); + ctx.container.register('ldapAuthentication', ldap); + vi.mocked(ctx.container.resolve('config').getLdapConfig).mockReturnValue(config); + return { ...ctx, config, ldap, mappings, directory: calls, live, releaseDatabase, loginName, loginPassword: ldapPassword }; + } catch (error) { + await live.close(); + await ctx.database.close(); + await releaseDatabase(); + throw error; + } +} diff --git a/backend/test/integration/EntraIdAuthFlow.test.ts b/backend/test/integration/EntraIdAuthFlow.test.ts index ef10b5c0..92ea80ea 100644 --- a/backend/test/integration/EntraIdAuthFlow.test.ts +++ b/backend/test/integration/EntraIdAuthFlow.test.ts @@ -154,6 +154,7 @@ describe('Entra ID Auth Flow Integration Tests', () => { container = new DIContainer(); container.register('logger', logger); + container.register('authentication', authService); const configService = new ConfigService(); container.register('config', configService); @@ -265,7 +266,7 @@ describe('Entra ID Auth Flow Integration Tests', () => { await db.execute(`INSERT INTO users (id, username, email, first_name, last_name, is_active, is_admin, created_at, updated_at) VALUES (?, ?, ?, '', '', 1, 0, 'now', 'now')`, [id, id, `${id}@example.test`]); } - const token = await entraIdService.authService.generateToken({ id: 'actor', username: 'actor' }); + const token = await entraIdService.authService.generateToken({ id: 'actor', username: 'actor' }, { provider: 'local', identityId: null }); const input = { userId: 'target', subject: 'enrolled-subject' }; await browser.post('/api/auth/entra-id/enroll').send(input).expect(401); await browser.post('/api/auth/entra-id/enroll').set('Authorization', `Bearer ${token}`).send(input).expect(403); @@ -358,6 +359,15 @@ describe('Entra ID Auth Flow Integration Tests', () => { expect(tokenResponse.body).toHaveProperty('user'); expect(tokenResponse.body.user.username).toBe('testuser'); expect(tokenResponse.body.user.email).toBe('testuser@example.com'); + const identity = await databaseService.getAdapter().queryOne<{ id: string }>( + 'SELECT id FROM federated_identities WHERE user_id = ? AND provider = ?', [tokenResponse.body.user.id, 'entra-id'], + ); + const context = { provider: 'entra-id', identityId: identity!.id }; + expect(await entraIdService.authService.verifyToken(tokenResponse.body.token)).toMatchObject({ authContext: context }); + expect(jwt.decode(tokenResponse.body.refreshToken)).toMatchObject({ authContext: context }); + const refreshed = await browser.post('/api/auth/refresh').send({ refreshToken: tokenResponse.body.refreshToken }).expect(200); + expect(await entraIdService.authService.verifyToken(refreshed.body.token)).toMatchObject({ authContext: context }); + expect(jwt.decode(refreshed.body.refreshToken)).toMatchObject({ authContext: context }); // Step 4: Verify the auth code cannot be reused (single-use) const replayResponse = await browser diff --git a/backend/test/integration/ldap-account-ownership.test.ts b/backend/test/integration/ldap-account-ownership.test.ts new file mode 100644 index 00000000..d373eecf --- /dev/null +++ b/backend/test/integration/ldap-account-ownership.test.ts @@ -0,0 +1,112 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { UserService, type User } from '../../src/services/UserService'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { createAuthRouter } from '../../src/routes/auth'; +import { createUsersRouter } from '../../src/routes/users'; +import { DIContainer } from '../../src/container/DIContainer'; +import { ConfigService } from '../../src/config/ConfigService'; +import { LoggerService } from '../../src/services/LoggerService'; +import { createHttpHarness, type HttpHarness } from '../helpers/httpHarness'; + +const fixtureSecret = 'ldap-ownership-test-jwt-secret-for-fixtures'; // pragma: allowlist secret +const fixturePassword = 'ValidPass123!'; // pragma: allowlist secret +let harness: HttpHarness; +beforeAll(async () => { harness = await createHttpHarness(); }); +afterAll(async () => { await harness.close(); }); + +describe('LDAP account ownership at HTTP boundaries', () => { + let database: DatabaseService; + let users: UserService; + let auth: AuthenticationService; + let app: express.Express; + let ldapUser: User; + let adminToken: string; + + beforeEach(async () => { + vi.stubEnv('JWT_SECRET', fixtureSecret); + database = new DatabaseService(':memory:'); + await database.initialize(); + auth = new AuthenticationService(database.getAdapter(), fixtureSecret, undefined, 4); + users = new UserService(database.getAdapter(), auth); + const container = new DIContainer(); + container.register('logger', new LoggerService()); + container.register('config', new ConfigService()); + app = express(); + app.use(express.json()); + app.use('/api/auth', createAuthRouter(database, container)); + app.use('/api/users', createUsersRouter(database, container)); + const admin = await users.createUser({ username: 'admin', email: 'admin@example.test', + password: fixturePassword, firstName: 'Admin', lastName: 'User', isAdmin: true }); + adminToken = await auth.generateToken(admin, { provider: 'local', identityId: null }); + ldapUser = await users.createFederatedUser({ provider: 'ldap', issuer: 'directory', subject: 'subject', + loginName: 'alice', dn: 'uid=alice,dc=example', email: 'alice@example.test', displayName: 'Alice', + firstName: 'Alice', lastName: 'User', defaultRole: 'none' }); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + await database.close(); + }); + + it('rejects administrator profile and password writes atomically', async () => { + for (const body of [{ email: 'other@example.test' }, { firstName: 'Changed' }, + { lastName: 'Changed' }, { password: fixturePassword, isActive: false }]) { + const result = await request(harness.use(app)).put(`/api/users/${ldapUser.id}`) + .set('Authorization', `Bearer ${adminToken}`).send(body).expect(403); + expect(result.body.error.code).toBe('DIRECTORY_ACCOUNT_READ_ONLY'); + } + expect(await users.getUserById(ldapUser.id)).toMatchObject({ email: ldapUser.email, isActive: 1, passwordHash: null }); + }); + + it('allows administrative suspension, manual role assignment and admin status changes', async () => { + await request(harness.use(app)).post(`/api/users/${ldapUser.id}/roles/role-viewer-001`) + .set('Authorization', `Bearer ${adminToken}`).expect(204); + await request(harness.use(app)).put(`/api/users/${ldapUser.id}/admin-status`) + .set('Authorization', `Bearer ${adminToken}`).send({ isAdmin: true }).expect(200); + await request(harness.use(app)).put(`/api/users/${ldapUser.id}`) + .set('Authorization', `Bearer ${adminToken}`).send({ isActive: false }).expect(200); + expect(await users.getUserById(ldapUser.id)).toMatchObject({ isActive: 0, isAdmin: 1 }); + expect(await users.getUserRoles(ldapUser.id)).toHaveLength(1); + }); + + it('rejects authenticated password changes before password verification or lockout accounting', async () => { + const verify = vi.spyOn(AuthenticationService.prototype, 'verifyPassword'); + // Exercise the server-side ownership guard for a legacy mixed account. + await database.getAdapter().execute('UPDATE users SET local_auth_enabled = 1, password_hash = ? WHERE id = ?', + [await auth.hashPassword(fixturePassword), ldapUser.id]); + const token = await auth.generateToken(ldapUser, { provider: 'local', identityId: null }); + const response = await request(harness.use(app)).post('/api/auth/change-password') + .set('Authorization', `Bearer ${token}`).send({ currentPassword: fixturePassword, newPassword: fixturePassword }).expect(403); + expect(response.body.error.code).toBe('DIRECTORY_ACCOUNT_READ_ONLY'); + expect(verify).not.toHaveBeenCalled(); + expect(await database.getAdapter().query('SELECT * FROM login_attempt_counters')).toEqual([]); + }); + + it('exposes source and profile ownership only through protected administration DTOs', async () => { + const detail = await request(harness.use(app)).get('/api/users/' + ldapUser.id) + .set('Authorization', 'Bearer ' + adminToken).expect(200); + expect(detail.body.authentication).toEqual({ profileReadOnly: true, sources: [ + { provider: 'ldap', name: 'LDAP', directoryId: 'directory', loginName: 'alice' }, + ] }); + expect(detail.body.roleSources).toEqual([]); + expect(detail.body).not.toHaveProperty('passwordHash'); + expect(detail.body.authentication.sources[0]).not.toHaveProperty('dn'); + const list = await request(harness.use(app)).get('/api/users') + .set('Authorization', 'Bearer ' + adminToken).expect(200); + expect(list.body.users.find((user: { id: string }) => user.id === ldapUser.id).authentication) + .toEqual(detail.body.authentication); + await request(harness.use(app)).get('/api/users/' + ldapUser.id).expect(401); + const local = list.body.users.find((user: { id: string }) => user.id !== ldapUser.id); + expect(local.authentication).toEqual({ profileReadOnly: false, sources: [{ provider: 'local', name: 'Local' }] }); + }); + + it('does not advertise LDAP or expose an authentication endpoint', async () => { + const response = await request(harness.use(app)).get('/api/auth/providers').expect(200); + expect(response.body).toEqual({ local: true }); + await request(harness.use(app)).post('/api/auth/ldap/login').send({ username: 'alice', password: fixturePassword }).expect(404); + }); +}); diff --git a/backend/test/integration/ldap-administration.test.ts b/backend/test/integration/ldap-administration.test.ts new file mode 100644 index 00000000..55b78004 --- /dev/null +++ b/backend/test/integration/ldap-administration.test.ts @@ -0,0 +1,241 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import { randomUUID } from 'node:crypto'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { UserService } from '../../src/services/UserService'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { createAuthRouter } from '../../src/routes/auth'; +import { createLdapAdministrationRouter } from '../../src/routes/ldapAdministration'; +import { DIContainer } from '../../src/container/DIContainer'; +import { ConfigService } from '../../src/config/ConfigService'; +import { parseLdapConfig } from '../../src/config/ldap'; +import { LoggerService } from '../../src/services/LoggerService'; +import { LdapDirectoryService, LdapDirectoryError } from '../../src/services/LdapDirectoryService'; +import { LdapMappingService } from '../../src/services/LdapMappingService'; +import { createHttpHarness, type HttpHarness } from '../helpers/httpHarness'; + +const fixtureSecret = 'ldap-administration-fixture-jwt-secret-for-tests'; // pragma: allowlist secret +const fixturePassword = 'ValidPass123!'; // pragma: allowlist secret +const groupSubject = '10112233-4455-6677-8899-aabbccddeeff'; +const group = { subject: groupSubject, dn: 'cn=operators,ou=groups,dc=example,dc=test', name: 'Operators' }; +const roleId = 'role-viewer-001'; +const prefix = '/api/auth/ldap'; +let harness: HttpHarness; +beforeAll(async () => { harness = await createHttpHarness(); }); +afterAll(async () => { await harness.close(); }); + +describe('restricted LDAP administration HTTP contract', () => { + let database: DatabaseService; + let container: DIContainer; + let directory: LdapDirectoryService; + let mappings: LdapMappingService; + let app: express.Express; + let adminToken: string; + let viewerToken: string; + let managerToken: string; + + beforeEach(async () => { + vi.stubEnv('JWT_SECRET', fixtureSecret); + vi.stubEnv('LDAP_ENABLED', 'false'); + database = new DatabaseService(':memory:'); + await database.initialize(); + const db = database.getAdapter(); + const auth = new AuthenticationService(db, fixtureSecret, undefined, 4); + const users = new UserService(db, auth); + container = new DIContainer(); + const logger = new LoggerService('error'); + container.register('logger', logger); + container.register('config', new ConfigService()); + directory = new LdapDirectoryService(parseLdapConfig({ + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'ldap.example.test', LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_ANONYMOUS_LOOKUP: 'true', LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', + })!, logger); + vi.spyOn(directory, 'resolveGroup').mockResolvedValue(group); + vi.spyOn(directory, 'searchGroups').mockResolvedValue([group]); + vi.spyOn(directory, 'diagnose').mockResolvedValue({ authenticated: false, stages: [ + { stage: 'tls', status: 'passed', durationMs: 1 }, { stage: 'lookup', status: 'passed', durationMs: 1 }, + ] }); + mappings = new LdapMappingService(db, 'directory', directory); + container.register('ldapDirectory', directory); + container.register('ldapMappings', mappings); + app = express(); + app.use(express.json({ limit: '16kb' })); + app.use(prefix, createLdapAdministrationRouter(database, container)); + app.use('/api/auth', createAuthRouter(database, container)); + for (const name of ['administrator', 'viewer', 'manager']) { + const user = await users.createUser({ username: name, email: `${name}@example.test`, + password: fixturePassword, firstName: '', lastName: '', isAdmin: name === 'administrator' }); + if (name === 'manager') { + await db.execute("INSERT INTO roles VALUES ('manager', 'Manager', '', 0, 'now', 'now')"); + await db.execute(`INSERT INTO role_permissions (role_id, permission_id, assigned_at) + SELECT 'manager', id, 'now' FROM permissions WHERE resource = 'rbac' AND "action" = 'admin'`); + await users.assignRoleToUser(user.id, 'manager'); + } + const token = await auth.generateToken(user, { provider: 'local', identityId: null }); + if (name === 'administrator') adminToken = token; + if (name === 'viewer') viewerToken = token; + if (name === 'manager') managerToken = token; + } + }); + afterEach(async () => { vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllEnvs(); await database.close(); }); + + it.each([ + ['get', '/groups?query=op'], ['get', '/mappings'], ['post', '/mappings'], + ['put', '/mappings/absent'], ['delete', '/mappings/absent'], ['post', '/test'], + ] as const)('%s %s independently enforces authentication and rbac:admin before directory work', async (method, path) => { + await request(harness.use(app))[method](prefix + path).send({}).expect(401); + await request(harness.use(app))[method](prefix + path).set('Authorization', `Bearer ${viewerToken}`).send({}).expect(403); + expect(directory.searchGroups).not.toHaveBeenCalled(); + expect(directory.resolveGroup).not.toHaveBeenCalled(); + expect(directory.diagnose).not.toHaveBeenCalled(); + expect(await mappings.list()).toEqual([]); + }); + + it('accepts delegated rbac administration and records authoritative labels and role provenance', async () => { + const result = await request(harness.use(app)).post(prefix + '/mappings').set('Authorization', `Bearer ${managerToken}`) + .send({ groupSubject, roleId }).expect(201); + expect(result.body).toMatchObject({ source: 'ldap', directoryId: 'directory', groupSubject, + groupName: group.name, groupDn: group.dn, roleName: 'Viewer', enabled: true }); + const listed = await request(harness.use(app)).get(prefix + '/mappings').set('Authorization', `Bearer ${managerToken}`).expect(200); + expect(listed.body.items).toEqual([result.body]); + expect(listed.headers['cache-control']).toBe('no-store'); + await request(harness.use(app)).put(prefix + '/mappings/' + result.body.id).set('Authorization', `Bearer ${managerToken}`) + .send({ roleId: 'role-operator-001' }).expect(200); + await request(harness.use(app)).delete(prefix + '/mappings/' + result.body.id).set('Authorization', `Bearer ${managerToken}`).expect(204); + const audits = await database.getAdapter().query<{ action: string }>('SELECT "action" FROM audit_logs ORDER BY timestamp, id'); + expect(audits.map(row => row.action)).toEqual(['createLdapMapping', 'updateLdapMapping', 'deleteLdapMapping']); + expect(await database.getAdapter().query('SELECT * FROM federated_user_roles')).toEqual([]); + }); + + it('returns conflicts, missing roles, scoped IDs and fabricated directory subjects safely', async () => { + const headers = { Authorization: `Bearer ${adminToken}` }; + await request(harness.use(app)).post(prefix + '/mappings').set(headers).send({ groupSubject, roleId }).expect(201); + await request(harness.use(app)).post(prefix + '/mappings').set(headers).send({ groupSubject, roleId }).expect(409); + await request(harness.use(app)).post(prefix + '/mappings').set(headers).send({ groupSubject, roleId: 'absent' }).expect(404); + await request(harness.use(app)).put(prefix + '/mappings/absent').set(headers).send({ enabled: true }).expect(404); + vi.mocked(directory.resolveGroup).mockRejectedValue(new LdapDirectoryError('INVALID_IDENTITY')); + const fabricated = await request(harness.use(app)).post(prefix + '/mappings').set(headers) + .send({ groupSubject: randomUUID(), roleId }).expect(422); + expect(fabricated.body.error.code).toBe('INVALID_IDENTITY'); + }); + + it('rejects raw filters, browser labels, credentials and connection overrides before directory calls', async () => { + const headers = { Authorization: `Bearer ${adminToken}` }; + for (const body of [ { groupSubject, roleId, groupDn: 'cn=forged' }, { groupSubject: 'cn=operators', roleId }, { groupSubject, roleId, directoryId: 'other' } ]) { + await request(harness.use(app)).post(prefix + '/mappings').set(headers).send(body).expect(400); + } + for (const body of [{ username: 'alice', password: fixturePassword }, { hostname: 'evil.example' }, + { filter: '(uid=*)' }, { groupSubjects: [groupSubject] }, { username: 'alice', groupSubjects: [groupSubject] }]) { + const result = await request(harness.use(app)).post(prefix + '/test').set(headers).send(body).expect(400); + expect(JSON.stringify(result.body)).not.toContain(fixturePassword); + } + await request(harness.use(app)).get(prefix + '/groups?query=op&filter=raw').set(headers).expect(400); + await request(harness.use(app)).get(prefix + '/groups?query=' + 'a'.repeat(1025)).set(headers).expect(400); + expect(directory.resolveGroup).not.toHaveBeenCalled(); + expect(directory.diagnose).not.toHaveBeenCalled(); + expect(directory.searchGroups).not.toHaveBeenCalled(); + }); + + it('keeps listing and withdrawal available during outages while directory errors return safe status codes', async () => { + const mapping = await mappings.create(groupSubject, roleId, { userId: (await database.getAdapter().queryOne<{ id: string }>("SELECT id FROM users WHERE username = 'administrator'"))!.id }); + vi.mocked(directory.resolveGroup).mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + const headers = { Authorization: `Bearer ${adminToken}` }; + await request(harness.use(app)).get(prefix + '/mappings').set(headers).expect(200); + await request(harness.use(app)).post(prefix + '/mappings').set(headers).send({ groupSubject, roleId }).expect(503); + await request(harness.use(app)).put(prefix + '/mappings/' + mapping.id).set(headers).send({ enabled: false }).expect(200); + await request(harness.use(app)).delete(prefix + '/mappings/' + mapping.id).set(headers).expect(204); + for (const [code, status] of [['BUSY', 429], ['TIMEOUT', 503], ['INCOMPLETE_RESULT', 503], ['LIMIT_EXCEEDED', 503]] as const) { + vi.mocked(directory.searchGroups).mockRejectedValue(new LdapDirectoryError(code)); + const result = await request(harness.use(app)).get(prefix + '/groups?query=op').set(headers).expect(status); + expect(result.body.error.code).toBe(code); + } + vi.mocked(directory.searchGroups).mockRejectedValue(new Error('unsafe password host DN diagnostic')); + const result = await request(harness.use(app)).get(prefix + '/groups?query=op').set(headers).expect(500); + expect(JSON.stringify(result.body)).not.toMatch(/unsafe|password|host|stack|diagnostic/); + }); + + it('pages a bounded snapshot with opaque cursors bound to actor, query, lifetime and configured router', async () => { + vi.mocked(directory.searchGroups).mockResolvedValue(Array.from({ length: 53 }, (_, i) => ({ ...group, subject: randomUUID(), name: `Group ${i}` }))); + const headers = { Authorization: `Bearer ${adminToken}` }; + const first = await request(harness.use(app)).get(prefix + '/groups?query=op').set(headers).expect(200); + expect(first.body.items).toHaveLength(50); + expect(first.body.nextCursor).toMatch(/^[a-f0-9]{64}$/); + const url = prefix + '/groups?query=op&cursor=' + first.body.nextCursor; + const second = await request(harness.use(app)).get(url).set(headers).expect(200); + expect(second.body.items).toHaveLength(3); + expect(second.body.nextCursor).toBeNull(); + expect(directory.searchGroups).toHaveBeenCalledTimes(1); + await request(harness.use(app)).get(url.replace('query=op', 'query=admin')).set(headers).expect(400); + await request(harness.use(app)).get(url).set('Authorization', `Bearer ${managerToken}`).expect(400); + const changed = express(); + changed.use(prefix, createLdapAdministrationRouter(database, container)); + await request(harness.use(changed)).get(url).set(headers).expect(400); + const now = Date.now(); + vi.spyOn(Date, 'now').mockReturnValue(now + 60_001); + await request(harness.use(app)).get(url).set(headers).expect(400); + }); + + it('returns staged diagnostics, selects only enabled mappings and rate limits before more directory work', async () => { + const admin = (await database.getAdapter().queryOne<{ id: string }>("SELECT id FROM users WHERE username = 'administrator'"))!.id; + const mapping = await mappings.create(groupSubject, roleId, { userId: admin }); + const headers = { Authorization: `Bearer ${adminToken}` }; + await request(harness.use(app)).post(prefix + '/test').set(headers).send({ username: 'alice', groupSubjects: [groupSubject] }).expect(200); + expect(directory.diagnose).toHaveBeenLastCalledWith({ username: 'alice', groupSubjects: [groupSubject] }); + await mappings.update(mapping.id, { enabled: false }, { userId: admin }); + await request(harness.use(app)).post(prefix + '/test').set(headers).send({ username: 'alice', groupSubjects: [groupSubject] }).expect(400); + for (const [code, status] of [['INELIGIBLE', 422], ['POLICY_UNREADABLE', 503], ['UNAVAILABLE', 503], ['BUSY', 429]] as const) { + vi.mocked(directory.diagnose).mockResolvedValue({ authenticated: false, stages: [{ stage: 'eligibility', status: 'failed', durationMs: 2, code }] }); + const result = await request(harness.use(app)).post(prefix + '/test').set(headers).send({ username: 'alice' }).expect(status); + expect(result.body).toMatchObject({ authenticated: false, stages: [{ code }] }); + } + for (let i = 0; i < 4; i++) await request(harness.use(app)).post(prefix + '/test').set(headers).send({}).expect(429); + expect(directory.diagnose).toHaveBeenCalledTimes(9); + await request(harness.use(app)).post(prefix + '/test').set(headers).send({}).expect(429); + expect(directory.diagnose).toHaveBeenCalledTimes(9); + }); + + it('keeps public LDAP discovery and login unavailable and returns 404 when directory support is disabled', async () => { + const result = await request(harness.use(app)).get('/api/auth/providers').expect(200); + expect(result.body).toEqual({ local: true }); + await request(harness.use(app)).post(prefix + '/login').send({ username: 'alice', password: fixturePassword }).expect(404); + const disabled = new DIContainer(); + disabled.register('config', container.resolve('config')); + disabled.register('logger', container.resolve('logger')); + const other = express(); + other.use(prefix, createLdapAdministrationRouter(database, disabled)); + await request(harness.use(other)).get(prefix + '/mappings').set('Authorization', `Bearer ${adminToken}`).expect(404); + }); + + it.skipIf(!process.env.TEST_LDAP_LDAPS_PORT || !process.env.TEST_LDAP_CA_FILE)('searches, maps and diagnoses through real verified LDAP without authenticating or importing a user', async () => { + const config = parseLdapConfig({ + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'localhost.localdomain', LDAP_PORT: process.env.TEST_LDAP_LDAPS_PORT, + LDAP_CA_FILE: process.env.TEST_LDAP_CA_FILE, LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_RDN: 'ou=people', LDAP_GROUP_RDN: 'ou=groups', + LDAP_LOOKUP_USER: 'cn=reader,dc=example,dc=test', + LDAP_LOOKUP_PASSWORD: 'fixture-reader', // pragma: allowlist secret + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', + })!; + const live = new LdapDirectoryService(config, container.resolve('logger')); + container.register('ldapDirectory', live); + container.register('ldapMappings', new LdapMappingService(database.getAdapter(), config.directoryId, live)); + const headers = { Authorization: `Bearer ${adminToken}` }; + const before = await database.getAdapter().query('SELECT id FROM users ORDER BY id'); + const groups = await request(harness.use(app)).get(prefix + '/groups?query=operators').set(headers).expect(200); + const subject = groups.body.items[0].subject; + await request(harness.use(app)).post(prefix + '/mappings').set(headers).send({ groupSubject: subject, roleId }).expect(201); + const diagnostic = await request(harness.use(app)).post(prefix + '/test').set(headers).send({ username: 'alice', groupSubjects: [subject] }).expect(200); + expect(diagnostic.body.authenticated).toBe(false); + expect(diagnostic.body.groupSubjects).toEqual([subject]); + expect(diagnostic.body.stages.map((stage: { status: string }) => stage.status)).toEqual(Array(5).fill('passed')); + const inactive = await request(harness.use(app)).post(prefix + '/test').set(headers).send({ username: 'inactive' }).expect(422); + expect(inactive.body.stages.at(-1)).toMatchObject({ stage: 'eligibility', code: 'INELIGIBLE' }); + expect(await database.getAdapter().query('SELECT id FROM users ORDER BY id')).toEqual(before); + expect(await database.getAdapter().query('SELECT * FROM federated_user_roles')).toEqual([]); + expect(await database.getAdapter().query('SELECT * FROM federated_identities')).toEqual([]); + expect(await database.getAdapter().query('SELECT * FROM oauth_auth_codes')).toEqual([]); + expect(JSON.stringify(diagnostic.body)).not.toMatch(/alice|fixture-reader|ldap:\/\/|ldaps:\/\//); + }); +}); diff --git a/backend/test/integration/ldap-authentication.test.ts b/backend/test/integration/ldap-authentication.test.ts new file mode 100644 index 00000000..4f768a9e --- /dev/null +++ b/backend/test/integration/ldap-authentication.test.ts @@ -0,0 +1,158 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import request from 'supertest'; +import jwt from 'jsonwebtoken'; +import { createLdapTestContext, ldapPassword, ldapResult } from '../helpers/ldapAuthentication'; +import { createHttpHarness, type HttpHarness } from '../helpers/httpHarness'; +import { LdapDirectoryError, LdapDirectoryService } from '../../src/services/LdapDirectoryService'; +import { LdapMappingService } from '../../src/services/LdapMappingService'; +import { LdapAuthenticationService } from '../../src/services/LdapAuthenticationService'; +import { parseLdapConfig } from '../../src/config/ldap'; +import { createAuthRateLimitMiddleware } from '../../src/middleware/securityMiddleware'; + +describe('LDAP HTTP authentication and provider-bound tokens', () => { + let harness: HttpHarness; + let ctx: Awaited>; + beforeAll(async () => { harness = await createHttpHarness(); }); + afterAll(async () => { await harness.close(); }); + beforeEach(async () => { ctx = await createLdapTestContext(); harness.use(ctx.app); }); + afterEach(async () => { await ctx.database.close(); vi.restoreAllMocks(); vi.unstubAllEnvs(); }); + async function login(username = 'a', password = ldapPassword) { + return request(harness.use(ctx.app)).post('/api/auth/ldap/login').send({ username, password }); + } + + it('advertises only safe provider metadata even during an outage', async () => { + ctx.directory.authenticate.mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + const response = await request(harness.use(ctx.app)).get('/api/auth/providers').expect(200); + expect(response.body).toEqual({ local: true, ldap: { enabled: true, name: 'LDAP', loginHelpUrl: '' } }); + expect(response.text).not.toMatch(/ldap.example|baseDn|directoryId|password/); + expect((await login()).status).toBe(503); + expect((await request(harness.use(ctx.app)).get('/api/auth/providers')).body).toEqual(response.body); + }); + + it('accepts short directory credentials unchanged and rotates exact provider context', async () => { + const response = await login(' A ', ' p '); + expect(response.status).toBe(200); + expect(ctx.directory.authenticate).toHaveBeenCalledWith(' A ', ' p ', expect.any(Array)); + expect(response.body.user).toMatchObject({ email: null, displayName: 'Directory A' }); + const context = { provider: 'ldap', identityId: expect.any(String), directoryId: 'directory' }; + expect(jwt.decode(response.body.token)).toMatchObject({ authContext: context }); + expect(jwt.decode(response.body.refreshToken)).toMatchObject({ authContext: context }); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${response.body.token}`).expect(200); + const rotated = await request(harness.use(ctx.app)).post('/api/auth/refresh').send({ refreshToken: response.body.refreshToken }).expect(200); + expect(jwt.decode(rotated.body.token)).toMatchObject({ authContext: context }); + expect(ctx.directory.revalidate).toHaveBeenCalledOnce(); + expect(rotated.body.refreshToken).not.toBe(response.body.refreshToken); + }); + + it('rejects empty, oversized, nonstring or extra input before directory work', async () => { + for (const body of [{ username: '', password: 'x' }, { username: 'a', password: '' }, { username: 'a', password: 1 }, + { username: 'a', password: 'x', hostname: 'evil.test' }, { username: 'ü'.repeat(1024), password: 'x' }, + { username: 'a', password: 'x'.repeat(4097) }]) { + await request(harness.use(ctx.app)).post('/api/auth/ldap/login').send(body).expect(400); + } + expect(ctx.directory.authenticate).not.toHaveBeenCalled(); + }); + + it('returns generic credentials, explicit denied access and safe temporary/capacity errors without provider fallthrough', async () => { + const local = vi.spyOn(ctx.auth, 'authenticate'); + for (const [code, status] of [['INVALID_CREDENTIALS', 401], ['INELIGIBLE', 401], ['UNAVAILABLE', 503], + ['INCOMPLETE_RESULT', 503], ['TIMEOUT', 503], ['BUSY', 429]] as const) { + ctx.directory.authenticate.mockRejectedValueOnce(new LdapDirectoryError(code)); + const response = await login(); + expect(response.status).toBe(status); + expect(response.text).not.toContain('ldap.example'); + } + ctx.directory.authenticate.mockResolvedValueOnce({ ...ldapResult, groupSubjects: [] }); + expect((await login()).status).toBe(403); + expect(local).not.toHaveBeenCalled(); + const failed = await request(harness.use(ctx.app)).post('/api/auth/login').send({ username: 'a', password: ldapPassword }); + expect(failed.status).toBe(401); + expect(ctx.directory.authenticate).toHaveBeenCalledTimes(7); + }); + + it('scopes lockouts by provider, directory and submitted login while IP throttling covers LDAP', async () => { + ctx.directory.authenticate.mockRejectedValue(new LdapDirectoryError('INVALID_CREDENTIALS')); + for (let i = 0; i < 5; i++) expect((await login()).status).toBe(401); + expect((await login()).status).toBe(429); + expect(ctx.directory.authenticate).toHaveBeenCalledTimes(5); + expect(await ctx.auth.isLdapLoginLocked('other-directory', 'a')).toBe(false); + expect(await ctx.auth.isLdapLoginLocked('directory', 'other')).toBe(false); + const local = await request(harness.use(ctx.app)).post('/api/auth/login').send({ username: 'administrator', password: 'LocalTest123!' }); // pragma: allowlist secret + expect(local.status).toBe(200); + const limiter = createAuthRateLimitMiddleware(); + ctx.app.post('/ip-budget', limiter, (_req, res) => { res.json({ ok: true }); }); + for (let i = 0; i < 10; i++) await request(harness.use(ctx.app)).post('/ip-budget').expect(200); + await request(harness.use(ctx.app)).post('/ip-budget').expect(429); + }); + + it('forces refresh during fresh state, preserves inbound refresh on outage, and never extends failed freshness', async () => { + const pair = (await login()).body; + const before = await ctx.db.queryOne('SELECT * FROM ldap_validation_state'); + ctx.directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('UNAVAILABLE')); + await request(harness.use(ctx.app)).post('/api/auth/refresh').send({ refreshToken: pair.refreshToken }).expect(503); + expect(await ctx.db.queryOne('SELECT * FROM ldap_validation_state')).toEqual(before); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${pair.token}`).expect(200); + await request(harness.use(ctx.app)).post('/api/auth/refresh').send({ refreshToken: pair.refreshToken }).expect(200); + }); + + it('blocks stale REST sessions during an outage and recovers without revoking otherwise valid tokens', async () => { + const pair = (await login()).body; + await ctx.db.execute('UPDATE ldap_validation_state SET last_validated_at = 1'); + ctx.directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('UNAVAILABLE')); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${pair.token}`).expect(503); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${pair.token}`).expect(200); + }); + + it('positive revocation remains terminal for access and refresh after a fresh login', async () => { + const old = (await login()).body; + await ctx.db.execute('UPDATE ldap_validation_state SET last_validated_at = 1'); + ctx.directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('INELIGIBLE')); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${old.token}`).expect(403); + const fresh = (await login()).body; + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${old.token}`).expect(401); + await request(harness.use(ctx.app)).post('/api/auth/refresh').send({ refreshToken: old.refreshToken }).expect(401); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${fresh.token}`).expect(200); + }); + + it('keeps local and Entra token checks independent of an unavailable directory', async () => { + const user = ctx.administrator; + await ctx.users.linkFederatedIdentity(user.id, 'entra-id', 'subject', 'tenant', user.email); + const identity = await ctx.db.queryOne<{ id: string }>('SELECT id FROM federated_identities WHERE user_id = ?', [user.id]); + ctx.directory.revalidate.mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + for (const context of [{ provider: 'local', identityId: null }, { provider: 'entra-id', identityId: identity!.id }] as const) { + const pair = await ctx.auth.generateTokenPair(user, context); + await ctx.auth.verifyToken(pair.token); + expect((await ctx.auth.refreshToken(pair.refreshToken)).success).toBe(true); + } + expect(ctx.directory.revalidate).not.toHaveBeenCalled(); + }); + + it.skipIf(!process.env.TEST_LDAP_LDAPS_PORT || !process.env.TEST_LDAP_STARTTLS_PORT || !process.env.TEST_LDAP_CA_FILE) + .each(['ldaps', 'starttls'] as const)('authenticates and refreshes real OpenLDAP credentials over %s through HTTP', async mode => { + const config = parseLdapConfig({ LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'directory', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'localhost.localdomain', LDAP_TLS_MODE: mode, + LDAP_PORT: mode === 'ldaps' ? process.env.TEST_LDAP_LDAPS_PORT : process.env.TEST_LDAP_STARTTLS_PORT, + LDAP_CA_FILE: process.env.TEST_LDAP_CA_FILE, LDAP_BASE_DN: 'dc=example,dc=test', LDAP_USER_RDN: 'ou=people', LDAP_GROUP_RDN: 'ou=groups', + LDAP_LOOKUP_USER: 'cn=reader,dc=example,dc=test', LDAP_LOOKUP_PASSWORD: 'fixture-reader', // pragma: allowlist secret + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', + })!; + const directory = new LdapDirectoryService(config, ctx.container.resolve('logger')); + for (const mapping of await ctx.mappings.list()) await ctx.mappings.remove(mapping.id, { userId: ctx.administrator.id }); + const mappings = new LdapMappingService(ctx.db, config.directoryId, directory); + const group = (await directory.searchGroups('operators'))[0]; + await mappings.create(group.subject, 'role-viewer-001', { userId: ctx.administrator.id }); + const ldap = new LdapAuthenticationService(ctx.db, config, directory, mappings, ctx.users); + await ldap.initialize(); + ctx.container.register('ldapAuthentication', ldap); + vi.mocked(ctx.container.resolve('config').getLdapConfig).mockReturnValue(config); + expect((await login('alice', 'incorrect')).status).toBe(401); + expect(await ctx.db.query('SELECT * FROM federated_identities')).toEqual([]); + const pair = await login('alice', 'fixture-user'); // pragma: allowlist secret + expect(pair.status).toBe(200); + expect(pair.body.user).toMatchObject({ displayName: 'Alice Fixture', email: 'alice@example.test' }); + await request(harness.use(ctx.app)).post('/api/auth/refresh').send({ refreshToken: pair.body.refreshToken }).expect(200); + await ctx.db.execute('UPDATE ldap_validation_state SET last_validated_at = 1'); + await request(harness.use(ctx.app)).get('/protected').set('Authorization', `Bearer ${pair.body.token}`).expect(200); + expect(ctx.directory.authenticate).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/test/integration/ldap-directory.test.ts b/backend/test/integration/ldap-directory.test.ts new file mode 100644 index 00000000..6f8defce --- /dev/null +++ b/backend/test/integration/ldap-directory.test.ts @@ -0,0 +1,147 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createServer } from 'node:net'; +import { setTimeout as delay } from 'node:timers/promises'; +import { parseLdapConfig } from '../../src/config/ldap'; +import type { LdapConfig } from '../../src/config/ldap'; +import { LdapDirectoryService } from '../../src/services/LdapDirectoryService'; +import { LoggerService } from '../../src/services/LoggerService'; +import { openLdapConnection } from '../../src/services/ldap/transport'; + +const fixturePassword = 'fixture-user'; // pragma: allowlist secret +const ready = !!(process.env.TEST_LDAP_LDAPS_PORT && process.env.TEST_LDAP_STARTTLS_PORT && process.env.TEST_LDAP_CA_FILE); +const logger = new LoggerService('error'); +function fixtureConfig(mode: 'ldaps' | 'starttls' = 'ldaps'): LdapConfig { + return parseLdapConfig({ + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'fixture', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'localhost.localdomain', LDAP_TLS_MODE: mode, + LDAP_PORT: mode === 'ldaps' ? process.env.TEST_LDAP_LDAPS_PORT : process.env.TEST_LDAP_STARTTLS_PORT, + LDAP_CA_FILE: process.env.TEST_LDAP_CA_FILE, LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_RDN: 'ou=people', LDAP_GROUP_RDN: 'ou=groups', + LDAP_LOOKUP_USER: 'cn=reader,dc=example,dc=test', + LDAP_LOOKUP_PASSWORD: 'fixture-reader', // pragma: allowlist secret + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', + })!; +} +afterEach(() => vi.restoreAllMocks()); + +describe.skipIf(!ready)('real OpenLDAP directory interoperability', () => { + for (const mode of ['ldaps', 'starttls'] as const) { + it(mode + ' verifies TLS, isolates binds, checks status and resolves nested cyclic membership', async () => { + const config = fixtureConfig(mode); + const directory = new LdapDirectoryService(config, logger); + const groups = await directory.searchGroups('operators'); + expect(groups).toHaveLength(1); + const [operators] = groups; + const [admins] = await directory.searchGroups('admins'); + const direct = await directory.authenticate('alice', fixturePassword, [operators.subject, admins.subject]); + expect(direct.user).toMatchObject({ loginName: 'alice', displayName: 'Alice Fixture', email: 'alice@example.test' }); + expect(direct.groupSubjects).toEqual([operators.subject]); + expect((await directory.resolveGroup(operators.subject)).dn).toBe(operators.dn); + const diagnostic = await directory.diagnose({ username: 'alice', groupSubjects: [operators.subject] }); + expect(diagnostic.authenticated).toBe(false); + expect(diagnostic.stages.map(stage => stage.status)).toEqual(Array(5).fill('passed')); + expect(diagnostic.groupSubjects).toEqual([operators.subject]); + expect(JSON.stringify(diagnostic)).not.toMatch(/Alice|alice@|uid=|fixture-reader/); + expect((await directory.diagnose({ username: 'inactive' })).stages.at(-1)) + .toMatchObject({ stage: 'eligibility', status: 'failed', code: 'INELIGIBLE' }); + expect((await directory.diagnose({ username: 'absent' })).stages.at(-1)) + .toMatchObject({ stage: 'identity', status: 'failed', code: 'INVALID_IDENTITY' }); + const nested = new LdapDirectoryService({ ...config, searchNestedGroups: true }, logger); + expect(new Set((await nested.authenticate('alice', fixturePassword, [operators.subject, admins.subject])).groupSubjects)) + .toEqual(new Set([operators.subject, admins.subject])); + expect((await directory.revalidate(direct.user.subject, [operators.subject])).user.subject).toBe(direct.user.subject); + for (const login of ['inactive', 'missing-policy', '*)(uid=*)', 'absent']) { + await expect(directory.authenticate(login, fixturePassword)).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + } + await expect(directory.authenticate('alice', 'wrong')).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + await expect(directory.authenticate('alice', '')).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + }); + } + + it('preserves Unicode login and absent contacts, rejects ambiguous login and missing IDs', async () => { + const config = fixtureConfig(); + const directory = new LdapDirectoryService(config, logger); + expect((await directory.authenticate('josé', fixturePassword)).user) + .toMatchObject({ loginName: 'josé', displayName: 'josé', email: null, firstName: '', lastName: 'Example' }); + await expect(directory.authenticate('duplicate', fixturePassword)).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + await expect(new LdapDirectoryService({ ...config, userIdAttr: 'description' }, logger) + .authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'INVALID_IDENTITY' }); + await expect(directory.searchGroups('optionaluid')).rejects.toMatchObject({ code: 'INCOMPLETE_RESULT' }); + }); + + it('supports groupOfNames/member as an explicit OpenLDAP schema override', async () => { + const directory = new LdapDirectoryService({ ...fixtureConfig(), groupObjectClass: 'groupOfNames', groupMemberAttr: 'member' }, logger); + const [ordinary] = await directory.searchGroups('ordinary'); + expect((await directory.authenticate('alice', fixturePassword, [ordinary.subject])).groupSubjects).toEqual([ordinary.subject]); + }); + + it('denies administrative search, traversal and depth truncation without partial grants', async () => { + const config = fixtureConfig(); + const directory = new LdapDirectoryService(config, logger); + const [operators] = await directory.searchGroups('operators'); + await expect(new LdapDirectoryService({ ...config, groupSearchLimit: 1 }, logger).searchGroups('s')) + .rejects.toMatchObject({ code: 'LIMIT_EXCEEDED' }); + await expect(new LdapDirectoryService({ ...config, searchNestedGroups: true, nestedGroupMaxDepth: 1 }, logger) + .authenticate('alice', fixturePassword, [operators.subject])).rejects.toMatchObject({ code: 'LIMIT_EXCEEDED' }); + await expect(new LdapDirectoryService({ ...config, searchNestedGroups: true, groupTraversalLimit: 1 }, logger) + .authenticate('alice', fixturePassword, [operators.subject])).rejects.toMatchObject({ code: 'LIMIT_EXCEEDED' }); + }); + + for (const mode of ['ldaps', 'starttls'] as const) { + it(mode + ' rejects an untrusted CA and hostname mismatch', async () => { + const config = fixtureConfig(mode); + await expect(new LdapDirectoryService({ ...config, caFile: '' }, logger).searchGroups('op')) + .rejects.toMatchObject({ code: 'UNAVAILABLE' }); + await expect(new LdapDirectoryService({ ...config, hostname: 'localhost' }, logger).searchGroups('op')) + .rejects.toMatchObject({ code: 'UNAVAILABLE' }); + }); + } + + it('fails over only transport setup and authenticates on the selected endpoint', async () => { + const config = fixtureConfig(); + const directory = new LdapDirectoryService({ + ...config, port: 1, failoverEndpoints: [{ hostname: config.hostname, port: config.port }], + }, logger); + expect((await directory.authenticate('alice', fixturePassword)).user.loginName).toBe('alice'); + }); + + it('requires a successful StartTLS upgrade before sending any bind credentials', async () => { + const chunks: Buffer[] = []; + const server = createServer(socket => socket.on('data', data => { chunks.push(data); socket.destroy(); })); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Missing fixture address'); + try { + const directory = new LdapDirectoryService({ ...fixtureConfig('starttls'), port: address.port }, logger); + await expect(directory.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + const captured = Buffer.concat(chunks); + expect(captured.toString()).toContain('1.3.6.1.4.1.1466.20037'); + expect(captured.toString()).not.toContain('fixture-reader'); + expect(captured.toString()).not.toContain(fixturePassword); + } finally { + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } + }); + + it('closes sockets on the transaction deadline and rejects reconnect after explicit close', async () => { + const sockets = new Set(); + const server = createServer(socket => { sockets.add(socket); socket.resume(); socket.once('close', () => sockets.delete(socket)); }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (!address || typeof address === 'string') throw new Error('Missing fixture address'); + try { + const directory = new LdapDirectoryService({ ...fixtureConfig('starttls'), port: address.port, requestTimeoutSeconds: 1 }, logger); + await expect(directory.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'TIMEOUT' }); + for (let attempt = 0; attempt < 20 && sockets.size; attempt++) await delay(10); + expect(sockets.size).toBe(0); + } finally { + for (const socket of sockets) socket.destroy(); + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } + const config = fixtureConfig(); + const connection = await openLdapConnection(config, { hostname: config.hostname, port: config.port }, new AbortController().signal); + await connection.bind(config.lookupUser, config.lookupPassword); + connection.close(); + await expect(connection.bind(config.lookupUser, config.lookupPassword)).rejects.toBeInstanceOf(Error); + }); +}); diff --git a/backend/test/integration/ldap-rollout.test.ts b/backend/test/integration/ldap-rollout.test.ts new file mode 100644 index 00000000..c45fbe0e --- /dev/null +++ b/backend/test/integration/ldap-rollout.test.ts @@ -0,0 +1,221 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import express from 'express'; +import request from 'supertest'; +import { Attribute, Change, Client } from 'ldapts'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { PostgresAdapter } from '../../src/database/PostgresAdapter'; +import { createDefaultContainer, resolveAuthenticationService } from '../../src/container/DIContainer'; +import { parseLdapConfig } from '../../src/config/ldap'; +import { LdapDirectoryService } from '../../src/services/LdapDirectoryService'; +import { LdapMappingService } from '../../src/services/LdapMappingService'; +import { LdapAuthenticationService } from '../../src/services/LdapAuthenticationService'; +import { UserService } from '../../src/services/UserService'; +import { createAuthRouter } from '../../src/routes/auth'; +import { createAuthMiddleware } from '../../src/middleware/authMiddleware'; +import { inputSanitizationMiddleware } from '../../src/middleware/securityMiddleware'; +import { createHttpHarness, type HttpHarness } from '../helpers/httpHarness'; + +const ready = !!(process.env.TEST_LDAP_LDAPS_PORT && process.env.TEST_LDAP_STARTTLS_PORT && process.env.TEST_LDAP_CA_FILE); +const password = 'fixture-user'; // pragma: allowlist secret +const viewer = 'role-viewer-001'; +const people = 'ou=people,dc=example,dc=test'; +const groups = 'ou=groups,dc=example,dc=test'; +interface Pair { token: string; refreshToken: string; user: { id: string; displayName: string; email: string | null } } + +for (const dialect of ['sqlite', 'postgres'] as const) { + for (const mode of ['ldaps', 'starttls'] as const) { + describe.skipIf(!ready || (dialect === 'postgres' && !process.env.TEST_DATABASE_URL))( + `real OpenLDAP rollout: ${dialect} / ${mode}`, () => { + let database: DatabaseService; + let control: PostgresAdapter | undefined; + let schema: string; + let harness: HttpHarness; + let admin: Client; + const owned = new Set(); + + beforeAll(async () => { harness = await createHttpHarness(); }); + afterAll(async () => { await harness.close(); }); + beforeEach(() => { + vi.stubEnv('JWT_SECRET', 'ldap-rollout-fixture-signing-secret-key'); // pragma: allowlist secret + vi.stubEnv('LDAP_ENABLED', 'false'); + vi.stubEnv('ENTRA_ID_ENABLED', 'false'); + }); + afterEach(async () => { + try { + // Only entries created by this case are removed; shared seed accounts stay intact. + for (const dn of [...owned].reverse()) { + await admin.del(dn); + owned.delete(dn); + } + } finally { + await admin?.unbind(); + await database?.close(); + if (control) { + await control.execute(`DROP SCHEMA ${schema} CASCADE`); + await control.close(); + control = undefined; + } + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + } + }); + + it('preserves immutable identities through moves, withdraws recreated-group grants and makes observed policy revocation terminal', async () => { + const key = 'rollout-' + randomUUID(); + const originalLogin = key; + const movedLogin = key + '-moved'; + const branch = `ou=${key},${people}`; + let userDn = `uid=${originalLogin},${people}`; + let groupDn = `cn=${key},${groups}`; + const config = parseLdapConfig({ + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'rollout-fixture', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'localhost.localdomain', LDAP_TLS_MODE: mode, + LDAP_PORT: mode === 'ldaps' ? process.env.TEST_LDAP_LDAPS_PORT : process.env.TEST_LDAP_STARTTLS_PORT, + LDAP_CA_FILE: process.env.TEST_LDAP_CA_FILE, LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_RDN: 'ou=people', LDAP_GROUP_RDN: 'ou=groups', + LDAP_LOOKUP_USER: 'cn=reader,dc=example,dc=test', + LDAP_LOOKUP_PASSWORD: 'fixture-reader', // pragma: allowlist secret + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', + })!; + const tlsOptions = { ca: [readFileSync(config.caFile)], minVersion: 'TLSv1.2' as const, + rejectUnauthorized: true, servername: config.hostname }; + admin = new Client({ + url: `${mode === 'ldaps' ? 'ldaps' : 'ldap'}://${config.hostname}:${config.port}`, + timeout: 5000, connectTimeout: 5000, autoRebind: false, + ...(mode === 'ldaps' ? { tlsOptions } : {}), + }); + if (mode === 'starttls') await admin.startTLS(tlsOptions); + await admin.bind('cn=admin,dc=example,dc=test', 'fixture-admin'); // pragma: allowlist secret + await admin.add(branch, { objectClass: 'organizationalUnit', ou: key }); + owned.add(branch); + async function addUser(login: string) { + await admin.add(userDn, { objectClass: 'inetOrgPerson', uid: login, cn: 'Rollout Fixture', + sn: 'Fixture', employeeType: 'active', userPassword: password }); // pragma: allowlist secret + owned.add(userDn); + } + async function addGroup() { + await admin.add(groupDn, { objectClass: 'groupOfUniqueNames', + cn: groupDn.slice(3, groupDn.indexOf(',')), uniqueMember: userDn }); + owned.add(groupDn); + } + async function replace(dn: string, type: string, values: string[]) { + await admin.modify(dn, new Change({ operation: 'replace', modification: new Attribute({ type, values }) })); + } + await addUser(originalLogin); + await addGroup(); + + let url: string | undefined; + if (dialect === 'postgres') { + schema = 'ldaprollout_' + randomUUID().replaceAll('-', ''); + control = new PostgresAdapter(process.env.TEST_DATABASE_URL!); + await control.initialize(); + await control.execute(`CREATE SCHEMA ${schema}`); + const scoped = new URL(process.env.TEST_DATABASE_URL!); + scoped.searchParams.set('options', `-csearch_path=${schema}`); + url = scoped.toString(); + } + database = new DatabaseService(':memory:', dialect, url); + await database.initialize(); + const db = database.getAdapter(); + const container = createDefaultContainer(); + vi.spyOn(container.resolve('config'), 'getLdapConfig').mockReturnValue(config); + const auth = resolveAuthenticationService(db, container); + const users = new UserService(db, auth); + const administrator = await users.createUser({ username: 'rolloutadmin', email: 'rollout@example.test', + password: 'LocalFixture123!', firstName: '', lastName: '', isAdmin: true }); // pragma: allowlist secret + const directory = new LdapDirectoryService(config, container.resolve('logger')); + const mappings = new LdapMappingService(db, config.directoryId, directory); + const ldap = new LdapAuthenticationService(db, config, directory, mappings, users); + await ldap.initialize(); + container.register('ldapAuthentication', ldap); + const app = express(); + app.use(express.json(), inputSanitizationMiddleware); + app.use('/api/auth', createAuthRouter(database, container)); + app.get('/protected', createAuthMiddleware(auth), (_req, res) => { res.json({ ok: true }); }); + const server = harness.use(app); + const login = (username: string) => request(server).post('/api/auth/ldap/login').send({ username, password }); + const refresh = (pair: Pair) => request(server).post('/api/auth/refresh').send({ refreshToken: pair.refreshToken }); + const protectedRequest = (pair: Pair) => request(server).get('/protected').set('Authorization', `Bearer ${pair.token}`); + const actor = { userId: administrator.id }; + + const denied = await login(originalLogin).expect(403); + expect(denied.body.token).toBeUndefined(); + expect(denied.body.refreshToken).toBeUndefined(); + const identity = await db.queryOne<{ id: string; user_id: string; subject: string }>( + "SELECT id, user_id, subject FROM federated_identities WHERE provider = 'ldap'"); + expect(identity).not.toBeNull(); + expect(await users.getUserRoles(identity!.user_id)).toEqual([]); + await users.assignRoleToUser(identity!.user_id, viewer); + const manual: Pair = (await login(originalLogin).expect(200)).body; + expect(manual.user).toMatchObject({ id: identity!.user_id, email: null }); + await request(server).post('/api/auth/login').send({ username: originalLogin, password }).expect(401); + + const group = (await directory.searchGroups(key))[0]; + await mappings.create(group.subject, viewer, actor); + const mapped: Pair = (await refresh(manual).expect(200)).body; + await users.removeRoleFromUser(manual.user.id, viewer); + await protectedRequest(manual).expect(200); + expect(await db.query('SELECT * FROM federated_user_roles WHERE user_id = ?', [manual.user.id])).toHaveLength(1); + + const movedDn = `uid=${movedLogin},${branch}`; + await admin.modifyDN(userDn, movedDn); + owned.delete(userDn); + userDn = movedDn; + owned.add(userDn); + await replace(groupDn, 'uniqueMember', [userDn]); + await replace(userDn, 'displayName', ['Moved Fixture']); + const moved: Pair = (await refresh(mapped).expect(200)).body; + expect(moved.user).toMatchObject({ id: manual.user.id, displayName: 'Moved Fixture', email: null }); + expect(await db.queryOne('SELECT subject FROM federated_identities WHERE id = ?', [identity!.id])) + .toEqual({ subject: identity!.subject }); + expect(await db.queryOne('SELECT login_name, dn FROM ldap_identity_metadata WHERE identity_id = ?', [identity!.id])) + .toEqual({ login_name: movedLogin, dn: userDn }); + await protectedRequest(manual).expect(200); + await login(originalLogin).expect(401); + + await replace(userDn, 'employeeType', ['inactive']); + await refresh(moved).expect(403); + await replace(userDn, 'employeeType', ['active']); + const recovered: Pair = (await login(movedLogin).expect(200)).body; + await protectedRequest(moved).expect(401); + await refresh(moved).expect(401); + await protectedRequest(recovered).expect(200); + + const renamedGroup = `cn=${key}-renamed,${groups}`; + await admin.modifyDN(groupDn, renamedGroup); + owned.delete(groupDn); + groupDn = renamedGroup; + owned.add(groupDn); + const renamed: Pair = (await refresh(recovered).expect(200)).body; + expect((await directory.resolveGroup(group.subject)).dn).toBe(groupDn); + await admin.del(groupDn); + owned.delete(groupDn); + await addGroup(); + const replacement = (await directory.searchGroups(key))[0]; + expect(replacement.subject).not.toBe(group.subject); + await refresh(renamed).expect(403); + expect(await db.query('SELECT * FROM federated_user_roles WHERE user_id = ?', [manual.user.id])).toEqual([]); + await login(movedLogin).expect(403); + await mappings.create(replacement.subject, viewer, actor); + const remapped: Pair = (await login(movedLogin).expect(200)).body; + expect(remapped.user.id).toBe(manual.user.id); + await protectedRequest(renamed).expect(401); + + await admin.del(userDn); + owned.delete(userDn); + await refresh(remapped).expect(403); + await addUser(movedLogin); + const recreated: Pair = (await login(movedLogin).expect(200)).body; + expect(recreated.user.id).not.toBe(manual.user.id); + expect(await db.queryOne('SELECT subject FROM federated_identities WHERE user_id = ?', [recreated.user.id])) + .not.toEqual({ subject: identity!.subject }); + expect(await db.query('SELECT * FROM user_roles WHERE user_id = ?', [recreated.user.id])).toEqual([]); + await protectedRequest(remapped).expect(401); + await protectedRequest(recreated).expect(200); + await request(server).post('/api/auth/login').send({ username: 'rolloutadmin', password: 'LocalFixture123!' }).expect(200); // pragma: allowlist secret + }, 30000); + }); + } +} diff --git a/backend/test/integration/mcp-authorization.test.ts b/backend/test/integration/mcp-authorization.test.ts index 5575f537..1ae18370 100644 --- a/backend/test/integration/mcp-authorization.test.ts +++ b/backend/test/integration/mcp-authorization.test.ts @@ -68,14 +68,14 @@ describe('Production MCP authentication and session boundary', () => { alice = await users.createUser({ username: 'alice', email: 'alice@example.test', password: 'Test!password123', firstName: 'Test', lastName: 'User', isActive: true, isAdmin: false }); // pragma: allowlist secret bob = await users.createUser({ username: 'bob', email: 'bob@example.test', password: 'Test!password123', firstName: 'Test', lastName: 'User', isActive: true, isAdmin: false }); // pragma: allowlist secret await db.execute('DELETE FROM user_roles WHERE user_id IN (?, ?)', [alice.id, bob.id]); - aliceToken = await auth.generateToken(alice); - bobToken = await auth.generateToken(bob); + aliceToken = await auth.generateToken(alice, { provider: 'local', identityId: null }); + bobToken = await auth.generateToken(bob, { provider: 'local', identityId: null }); mcp = createMcpRouter({ integrationManager: manager, executionRepository: new ExecutionRepository(db), journalService: new JournalService(db), permissionService: permissions, hieraPlugin: undefined, puppetDBService: undefined, puppetRunHistoryService: undefined, logger, version: 'test', - }, createMcpAuthMiddleware(machineToken, machine.userId, createAuthMiddleware(db, jwtSecret), db), + }, createMcpAuthMiddleware(machineToken, machine.userId, createAuthMiddleware(new AuthenticationService(db, jwtSecret)), db), { total: 4, perPrincipal: 2, ttlMs: 86400000 }); const app = express(); app.use(express.json()); @@ -119,7 +119,7 @@ describe('Production MCP authentication and session boundary', () => { it('rejects missing credentials, refresh JWTs and invalid initialization', async () => { await request(`http://127.0.0.1:${String(harness.port)}`).post('/mcp').send(initialize).expect(401); - const pair = await auth.generateTokenPair(alice); + const pair = await auth.generateTokenPair(alice, { provider: 'local', identityId: null }); await send(pair.refreshToken).send(initialize).expect(401); await send(aliceToken).send({ jsonrpc: '2.0', id: 1, method: 'tools/list' }).expect(400); }); @@ -151,7 +151,7 @@ describe('Production MCP authentication and session boundary', () => { }); it('separates JWT and static authentication even for the same user ID', async () => { - const jwt = await auth.generateToken({ id: machine.userId, username: 'mcp-service' }); + const jwt = await auth.generateToken({ id: machine.userId, username: 'mcp-service' }, { provider: 'local', identityId: null }); const staticSession = await open(machineToken); const jwtSession = await open(jwt); for (const method of ['get', 'post', 'delete'] as const) { @@ -188,7 +188,7 @@ describe('Production MCP authentication and session boundary', () => { it('revokes opening JWT credentials even if a new JWT is supplied for continuation', async () => { const session = await open(aliceToken); await database.getAdapter().execute('UPDATE users SET session_version = ? WHERE id = ?', ['a'.repeat(32), alice.id]); - const fresh = await auth.generateToken(alice); + const fresh = await auth.generateToken(alice, { provider: 'local', identityId: null }); await send(fresh, 'post', session).send({ jsonrpc: '2.0', id: 2, method: 'tools/list' }).expect(401); await send(fresh, 'post', session).send(initialize).expect(404); }); diff --git a/backend/test/integration/shared-authentication.test.ts b/backend/test/integration/shared-authentication.test.ts new file mode 100644 index 00000000..bd55145d --- /dev/null +++ b/backend/test/integration/shared-authentication.test.ts @@ -0,0 +1,104 @@ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; +import express from 'express'; +import request from 'supertest'; +import { DatabaseService } from '../../src/database/DatabaseService'; +import { DIContainer, createDefaultContainer, resolveAuthenticationService } from '../../src/container/DIContainer'; +import { AuthenticationService } from '../../src/services/AuthenticationService'; +import { UserService } from '../../src/services/UserService'; +import { AuditLoggingService } from '../../src/services/AuditLoggingService'; +import { LoggerService } from '../../src/services/LoggerService'; +import { IntegrationManager } from '../../src/integrations/IntegrationManager'; +import { ConsoleConfigSchema } from '../../src/config/schema'; +import { ConsoleSessionManager } from '../../src/services/ConsoleSessionManager'; +import { createAuthMiddleware } from '../../src/middleware/authMiddleware'; +import { createMcpAuthMiddleware } from '../../src/middleware/mcpAuthMiddleware'; +import { createAuthRouter } from '../../src/routes/auth'; +import { createUsersRouter } from '../../src/routes/users'; +import { createGroupsRouter } from '../../src/routes/groups'; +import { createRolesRouter } from '../../src/routes/roles'; +import { createPermissionsRouter } from '../../src/routes/permissions'; +import { createJournalRouter } from '../../src/routes/journal'; +import { createConsoleRouter } from '../../src/routes/console'; +import { createLdapAdministrationRouter } from '../../src/routes/ldapAdministration'; +import { createEntraIdAuthRouter } from '../../src/routes/entraIdAuth'; +import { createHttpHarness, type HttpHarness } from '../helpers/httpHarness'; + +let harness: HttpHarness; +beforeAll(async () => { harness = await createHttpHarness(); }); +afterAll(async () => { await harness.close(); }); + +describe('configured authentication dependency boundary', () => { + let database: DatabaseService; + let container: DIContainer; + let auth: AuthenticationService; + let token: string; + let app: express.Express; + + beforeEach(async () => { + vi.stubEnv('JWT_SECRET', 'shared-authentication-fixture-secret-key'); + vi.stubEnv('LDAP_ENABLED', 'false'); + vi.stubEnv('ENTRA_ID_ENABLED', 'false'); + database = new DatabaseService(':memory:'); + await database.initialize(); + const db = database.getAdapter(); + container = createDefaultContainer(); + auth = resolveAuthenticationService(db, container); + expect(resolveAuthenticationService(db, container)).toBe(auth); + const user = await new UserService(db, auth).createUser({ username: 'admin', email: 'admin@example.test', + password: 'SharedAuthTest123!', firstName: '', lastName: '', isAdmin: true }); // pragma: allowlist secret + token = await auth.generateToken(user, { provider: 'local', identityId: null }); + app = express(); + app.use(express.json()); + app.use('/api/auth', createAuthRouter(database, container)); + app.use('/api/users', createUsersRouter(database, container)); + app.use('/api/groups', createGroupsRouter(database, container)); + app.use('/api/roles', createRolesRouter(database, container)); + app.use('/api/permissions', createPermissionsRouter(database, container)); + app.use('/api/journal', createJournalRouter(database, {}, container)); + app.use('/api/auth/ldap', createLdapAdministrationRouter(database, container)); + app.use('/api/auth/entra-id', createEntraIdAuthRouter(database, container)); + const logger = new LoggerService(); + const manager = new ConsoleSessionManager(db, ConsoleConfigSchema.parse({}), logger, new AuditLoggingService(db), auth); + app.use('/api/console', createConsoleRouter(container, new IntegrationManager({ logger }), manager, db)); + const middleware = createAuthMiddleware(auth); + app.get('/mcp-auth', createMcpAuthMiddleware(undefined, 'machine', middleware, db), (_req, res) => { res.json({ ok: true }); }); + }); + + afterEach(async () => { vi.restoreAllMocks(); vi.unstubAllEnvs(); await database.close(); }); + + it('all JWT route guards and MCP use the configured eligibility service', async () => { + await request(harness.use(app)).get('/api/auth/permissions').set('Authorization', `Bearer ${token}`).expect(200); + const eligible = vi.spyOn(auth, 'assertSessionEligible').mockRejectedValue(new Error('Invalid token')); + const paths = ['/api/auth/permissions', '/api/users', '/api/groups', '/api/roles', '/api/permissions', + '/api/journal/search', '/api/console/sessions/anything', '/api/auth/ldap/mappings', '/mcp-auth']; + for (const path of paths) { + await request(harness.use(app)).get(path).set('Authorization', `Bearer ${token}`).expect(401); + } + await request(harness.use(app)).post('/api/auth/entra-id/enroll').set('Authorization', `Bearer ${token}`).send({}).expect(401); + expect(eligible).toHaveBeenCalledTimes(paths.length + 1); + }); + + it('passes verified context and captures the same service for stream revalidation', async () => { + let revalidate: (() => Promise) | undefined; + app.get('/stream-boundary', createAuthMiddleware(auth), (req, res) => { + revalidate = req.revalidateAuth; + res.json({ context: req.authContext }); + }); + const response = await request(harness.use(app)).get('/stream-boundary').set('Authorization', `Bearer ${token}`).expect(200); + expect(response.body.context).toEqual({ provider: 'local', identityId: null }); + const eligible = vi.spyOn(auth, 'assertSessionEligible').mockRejectedValue(new Error('Invalid token')); + expect(revalidate).toBeDefined(); + await expect(revalidate!()).rejects.toThrow('Invalid token'); + expect(eligible).toHaveBeenCalledOnce(); + }); + + it('login and refresh reach the same configured issuance and eligibility boundary', async () => { + const issued = vi.spyOn(auth, 'generateTokenPair'); + const login = await request(harness.use(app)).post('/api/auth/login').send({ username: 'admin', password: 'SharedAuthTest123!' }).expect(200); // pragma: allowlist secret + expect(issued).toHaveBeenCalledWith(expect.objectContaining({ username: 'admin' }), { provider: 'local', identityId: null }, expect.any(String)); + const eligible = vi.spyOn(auth, 'assertSessionEligible').mockRejectedValue(new Error('Invalid token')); + await request(harness.use(app)).post('/api/auth/refresh').send({ refreshToken: login.body.refreshToken }).expect(401); + expect(eligible).toHaveBeenCalledOnce(); + expect(issued).toHaveBeenCalledOnce(); + }); +}); diff --git a/backend/test/middleware/authMiddleware.test.ts b/backend/test/middleware/authMiddleware.test.ts index d7febf04..186a8197 100644 --- a/backend/test/middleware/authMiddleware.test.ts +++ b/backend/test/middleware/authMiddleware.test.ts @@ -41,7 +41,7 @@ describe("Authentication Middleware", () => { ); // Create middleware instance - middleware = createAuthMiddleware(db, jwtSecret); + middleware = createAuthMiddleware(new AuthenticationService(db, jwtSecret)); }); afterEach(async () => { @@ -93,7 +93,7 @@ describe("Authentication Middleware", () => { lastLoginAt: null }; - const token = await authService.generateToken(user); + const token = await authService.generateToken(user, { provider: 'local', identityId: null }); const { req, res, next } = createMocks(); req.headers.authorization = `Bearer ${token}`; @@ -226,7 +226,7 @@ describe("Authentication Middleware", () => { lastLoginAt: null }; - const token = await authService.generateToken(user); + const token = await authService.generateToken(user, { provider: 'local', identityId: null }); // Revoke the token await authService.revokeToken(token); @@ -263,7 +263,7 @@ describe("Authentication Middleware", () => { lastLoginAt: null }; - const token = await authService.generateToken(user); + const token = await authService.generateToken(user, { provider: 'local', identityId: null }); const { req, res, next } = createMocks(); req.headers.authorization = `Bearer ${token}`; @@ -284,7 +284,7 @@ describe("Authentication Middleware", () => { it("should return generic error for unexpected errors", async () => { // Create middleware with invalid database to trigger error const badDb = {} as Database; - const badMiddleware = createAuthMiddleware(badDb, jwtSecret); + const badMiddleware = createAuthMiddleware(new AuthenticationService(badDb, jwtSecret)); const user = { id: "test-user-id", @@ -300,7 +300,7 @@ describe("Authentication Middleware", () => { lastLoginAt: null }; - const token = await authService.generateToken(user); + const token = await authService.generateToken(user, { provider: 'local', identityId: null }); const { req, res, next } = createMocks(); req.headers.authorization = `Bearer ${token}`; diff --git a/backend/test/properties/EntraIdAuthCode.property.test.ts b/backend/test/properties/EntraIdAuthCode.property.test.ts index 3774558b..c4a6d034 100644 --- a/backend/test/properties/EntraIdAuthCode.property.test.ts +++ b/backend/test/properties/EntraIdAuthCode.property.test.ts @@ -110,7 +110,7 @@ describe('EntraIdService — Property 16: Authorization code single-use and TTL' const mockUserService = { findByFederatedIdentity: vi.fn().mockResolvedValue(null), - findByEmail: vi.fn().mockResolvedValue(null), + findAllByEmail: vi.fn().mockResolvedValue([]), createFederatedUser: vi.fn().mockResolvedValue(mockUser), getUserById: vi.fn().mockResolvedValue(mockUser), toUserDTO: vi.fn().mockReturnValue({ id: mockUser.id, username: mockUser.username }), diff --git a/backend/test/properties/EntraIdCallback.property.test.ts b/backend/test/properties/EntraIdCallback.property.test.ts index afe7fe8f..08b1a76b 100644 --- a/backend/test/properties/EntraIdCallback.property.test.ts +++ b/backend/test/properties/EntraIdCallback.property.test.ts @@ -221,7 +221,7 @@ describe('EntraIdService — Callback Validation Properties', () => { const mockUserService = { findByFederatedIdentity: vi.fn().mockResolvedValue(null), - findByEmail: vi.fn().mockResolvedValue(null), + findAllByEmail: vi.fn().mockResolvedValue([]), createFederatedUser: vi.fn().mockResolvedValue(mockUser), getUserById: vi.fn().mockResolvedValue(mockUser), toUserDTO: vi.fn().mockReturnValue({ id: mockUser.id, username: mockUser.username }), @@ -295,6 +295,8 @@ describe('EntraIdService — Callback Validation Properties', () => { const expiredAt = new Date(now.getTime() - minutesAgo * 60 * 1000); (db.queryOne as ReturnType).mockResolvedValue({ + id: 'identity', + userId: mockUser.id, state, nonce: 'test-nonce', code_verifier: 'test-verifier-value-that-is-long-enough', @@ -337,6 +339,8 @@ describe('EntraIdService — Callback Validation Properties', () => { function setupValidStateEntry(): void { const future = new Date(Date.now() + 5 * 60 * 1000).toISOString(); (db.queryOne as ReturnType).mockResolvedValue({ + id: 'identity', + userId: mockUser.id, state: 'valid-state', nonce: storedNonce, code_verifier: 'valid-code-verifier-value-here-long', @@ -420,6 +424,8 @@ describe('EntraIdService — Callback Validation Properties', () => { async ([storedNonce, tokenNonce], code) => { const future = new Date(Date.now() + 5 * 60 * 1000).toISOString(); (db.queryOne as ReturnType).mockResolvedValue({ + id: 'identity', + userId: mockUser.id, state: 'valid-state', nonce: storedNonce, code_verifier: 'valid-code-verifier-value-here-long', @@ -460,6 +466,8 @@ describe('EntraIdService — Callback Validation Properties', () => { function setupValidState(): void { const future = new Date(Date.now() + 5 * 60 * 1000).toISOString(); (db.queryOne as ReturnType).mockResolvedValue({ + id: 'identity', + userId: mockUser.id, state: 'valid-state', nonce: storedNonce, code_verifier: 'valid-code-verifier-value-here-long', @@ -556,6 +564,8 @@ describe('EntraIdService — Callback Validation Properties', () => { async (state, code) => { const future = new Date(Date.now() + 5 * 60 * 1000).toISOString(); (db.queryOne as ReturnType).mockResolvedValue({ + id: 'identity', + userId: mockUser.id, state, nonce: storedNonce, code_verifier: 'valid-code-verifier-value-here-long', @@ -604,6 +614,8 @@ describe('EntraIdService — Callback Validation Properties', () => { async (state, code) => { const future = new Date(Date.now() + 5 * 60 * 1000).toISOString(); (db.queryOne as ReturnType).mockResolvedValue({ + id: 'identity', + userId: mockUser.id, state, nonce: storedNonce, code_verifier: 'valid-code-verifier-value-here-long', diff --git a/backend/test/properties/EntraIdGroupSync.property.test.ts b/backend/test/properties/EntraIdGroupSync.property.test.ts index 21e25f10..3bf6c59c 100644 --- a/backend/test/properties/EntraIdGroupSync.property.test.ts +++ b/backend/test/properties/EntraIdGroupSync.property.test.ts @@ -21,6 +21,7 @@ describe('Entra group reconciliation against storage', () => { await initializeTestSchema(db); await db.execute(`INSERT INTO users (id, username, email, first_name, last_name, is_active, is_admin, created_at, updated_at) VALUES ('user', 'user', 'user@example.test', '', '', 1, 0, 'now', 'now')`); + await db.execute("INSERT INTO federated_identities (id, user_id, provider, subject, issuer, created_at, updated_at) VALUES ('identity', 'user', 'entra-id', 'subject', 'https://login.microsoftonline.com/tenant/v2.0', 'now', 'now')"); config = { enabled: true, tenantId: 'tenant', clientId: 'client', clientSecret: 'fixture', redirectUri: 'http://localhost/callback', scopes: ['openid'], jwksCacheTtlMs: 1000, groupMapping: { A: 'Viewer', B: 'Operator' } }; @@ -29,12 +30,12 @@ describe('Entra group reconciliation against storage', () => { }); afterEach(async () => { await db.close(); }); const grants = async (db: SQLiteAdapter, table: string) => - (await db.query<{ role_id: string }>(`SELECT role_id FROM ${table} WHERE user_id = 'user' ORDER BY role_id`)).map(row => row.role_id); + (await db.query<{ role_id: string }>(`SELECT DISTINCT role_id FROM ${table} WHERE user_id = 'user' ORDER BY role_id`)).map(row => row.role_id); it('reconciles arbitrary claim changes while preserving manual grants to the same role', async () => { await db.execute("INSERT INTO user_roles VALUES ('user', 'role-viewer-001', 'now')"); await fc.assert(fc.asyncProperty(fc.array(fc.boolean(), { minLength: 2, maxLength: 2 }), async ([viewer, operator]) => { - await service.syncGroupRoles('user', [...(viewer ? ['a'] : []), ...(operator ? ['b'] : [])]); + await service.syncGroupRoles('identity', [...(viewer ? ['a'] : []), ...(operator ? ['b'] : [])]); expect(await grants(db, 'federated_user_roles')).toEqual([ ...(operator ? ['role-operator-001'] : []), ...(viewer ? ['role-viewer-001'] : []), ]); @@ -44,36 +45,39 @@ describe('Entra group reconciliation against storage', () => { it('removes provider grants when groups or the mapping disappear and invalidates cached permissions', async () => { const permissions = new PermissionService(db); - await service.syncGroupRoles('user', ['A']); + await service.syncGroupRoles('identity', ['A']); expect(await permissions.hasPermission('user', 'executions', 'read')).toBe(true); - await service.syncGroupRoles('user', undefined); + await service.syncGroupRoles('identity', undefined); expect(await permissions.hasPermission('user', 'executions', 'read')).toBe(false); - await service.syncGroupRoles('user', ['A']); + await service.syncGroupRoles('identity', ['A']); config.groupMapping = null; - await service.syncGroupRoles('user', ['A']); + await service.syncGroupRoles('identity', ['A']); expect(await grants(db, 'federated_user_roles')).toEqual([]); }); it('reconciles legacy grants once, without erasing subsequent manual assignments', async () => { await db.execute("INSERT INTO user_roles VALUES ('user', 'role-viewer-001', 'now')"); await db.execute("INSERT INTO legacy_federated_user_roles VALUES ('user', 'role-viewer-001')"); - await service.syncGroupRoles('user', []); + await service.syncGroupRoles('identity', []); expect(await grants(db, 'user_roles')).toEqual([]); await db.execute("INSERT INTO user_roles VALUES ('user', 'role-viewer-001', 'now')"); - await service.syncGroupRoles('user', []); + await service.syncGroupRoles('identity', []); expect(await grants(db, 'user_roles')).toEqual(['role-viewer-001']); }); it('rolls back partial reconciliation and fails login work when a mapped role is invalid', async () => { - await service.syncGroupRoles('user', ['B']); + await service.syncGroupRoles('identity', ['B']); config.groupMapping = { A: 'Viewer', B: 'Missing role' }; - await expect(service.syncGroupRoles('user', ['A', 'B'])).rejects.toThrow('unknown role'); + await expect(service.syncGroupRoles('identity', ['A', 'B'])).rejects.toThrow('unknown role'); expect(await grants(db, 'federated_user_roles')).toEqual(['role-operator-001']); }); - it('supports duplicate targets and simultaneous reconciliation without duplicate grants', async () => { + it('retains both group sources under simultaneous reconciliation to the same role', async () => { config.groupMapping = { A: 'Viewer', B: 'viewer' }; - await Promise.all(Array.from({ length: 8 }, () => service.syncGroupRoles('user', ['A', 'B']))); + await Promise.all(Array.from({ length: 8 }, () => service.syncGroupRoles('identity', ['A', 'B']))); expect(await grants(db, 'federated_user_roles')).toEqual(['role-viewer-001']); + expect(await db.query('SELECT source_key FROM federated_user_roles ORDER BY source_key')).toEqual([ + { source_key: 'group:a' }, { source_key: 'group:b' }, + ]); }); }); diff --git a/backend/test/properties/EntraIdProvisioning.property.test.ts b/backend/test/properties/EntraIdProvisioning.property.test.ts index 496b3a1f..54e8da82 100644 --- a/backend/test/properties/EntraIdProvisioning.property.test.ts +++ b/backend/test/properties/EntraIdProvisioning.property.test.ts @@ -19,7 +19,7 @@ import { import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; import type { EntraIdConfig } from '../../src/config/schema'; import type { AuthenticationService } from '../../src/services/AuthenticationService'; -import type { UserService, User } from '../../src/services/UserService'; +import type { UserService, User, FederatedProvisioningInput } from '../../src/services/UserService'; import type { RoleService } from '../../src/services/RoleService'; import type { AuditLoggingService } from '../../src/services/AuditLoggingService'; import type { LoggerService } from '../../src/services/LoggerService'; @@ -74,6 +74,8 @@ function createMockUser(overrides: Partial = {}): User { username: 'testuser', email: 'user@example.com', passwordHash: '', + localAuthEnabled: 0, + displayName: null, firstName: 'Test', lastName: 'User', isActive: 1, @@ -144,15 +146,15 @@ describe('EntraIdService — User Provisioning Properties', () => { mockUserService = { findByFederatedIdentity: vi.fn().mockResolvedValue(null), - findByEmail: vi.fn().mockResolvedValue(null), - createFederatedUser: vi.fn().mockImplementation(async (claims: IdTokenClaims) => { + findAllByEmail: vi.fn().mockResolvedValue([]), + createFederatedUser: vi.fn().mockImplementation(async (input: FederatedProvisioningInput) => { return createMockUser({ - id: `new-user-${claims.sub}`, - username: claims.preferred_username || claims.email.split('@')[0], - email: claims.email, + id: `new-user-${input.subject}`, + username: input.provider === 'entra-id' ? input.username : '', + email: input.email, passwordHash: '', - firstName: claims.given_name, - lastName: claims.family_name, + firstName: input.firstName, + lastName: input.lastName, isActive: 1, }); }), @@ -207,7 +209,7 @@ describe('EntraIdService — User Provisioning Properties', () => { async (claims) => { // Reset mocks for each iteration vi.mocked(mockUserService.findByFederatedIdentity).mockResolvedValue(null); - vi.mocked(mockUserService.findByEmail).mockResolvedValue(null); + vi.mocked(mockUserService.findAllByEmail).mockResolvedValue([]); vi.mocked(mockUserService.createFederatedUser).mockResolvedValue( createMockUser({ id: `new-user-${claims.sub}`, @@ -229,8 +231,12 @@ describe('EntraIdService — User Provisioning Properties', () => { claims.iss, ); - // No existing identity → called createFederatedUser with the claims - expect(mockUserService.createFederatedUser).toHaveBeenCalledWith(claims); + // No existing identity: supply an explicit identity, profile and role policy + expect(mockUserService.createFederatedUser).toHaveBeenCalledWith({ + provider: 'entra-id', issuer: claims.iss, subject: claims.sub, + username: claims.preferred_username, email: claims.email || null, displayName: null, + firstName: claims.given_name, lastName: claims.family_name, defaultRole: 'configured', + }); // Returned user has is_active=1 and empty passwordHash expect(result.isActive).toBe(1); @@ -250,7 +256,7 @@ describe('EntraIdService — User Provisioning Properties', () => { validClaimsArb, async (claims) => { vi.mocked(mockUserService.findByFederatedIdentity).mockResolvedValue(null); - vi.mocked(mockUserService.findByEmail).mockResolvedValue(null); + vi.mocked(mockUserService.findAllByEmail).mockResolvedValue([]); const createdUser = createMockUser({ id: `new-user-${claims.sub}`, @@ -384,18 +390,18 @@ describe('EntraIdService — User Provisioning Properties', () => { }; vi.mocked(mockUserService.findByFederatedIdentity).mockResolvedValue(null); - vi.mocked(mockUserService.findByEmail).mockResolvedValue(null); + vi.mocked(mockUserService.findAllByEmail).mockResolvedValue([]); // Capture what createFederatedUser receives to verify username derivation - let receivedClaims: IdTokenClaims | null = null; + let receivedInput: FederatedProvisioningInput | null = null; vi.mocked(mockUserService.createFederatedUser).mockImplementation( - async (c: IdTokenClaims) => { - receivedClaims = c; + async (c: FederatedProvisioningInput) => { + receivedInput = c; return createMockUser({ - id: `new-user-${c.sub}`, + id: `new-user-${c.subject}`, email: c.email, - // UserService.createFederatedUser internally derives the username - username: c.email.split('@')[0].replace(/[^a-zA-Z0-9_]/g, '_').slice(0, 50), + // EntraIdService supplies the provider-neutral username + username: c.provider === 'entra-id' ? c.username : '', passwordHash: '', isActive: 1, }); @@ -404,11 +410,8 @@ describe('EntraIdService — User Provisioning Properties', () => { const result = await service.provisionUser(claims); - // createFederatedUser was called with original claims - // (UserService.deriveUsername handles the derivation internally) - expect(receivedClaims).not.toBeNull(); - expect(receivedClaims!.preferred_username).toBe(invalidUsername); - expect(receivedClaims!.email).toBe(email); + expect(receivedInput).not.toBeNull(); + expect(receivedInput!.email).toBe(email); // The returned username must be derived from email local-part: // replace non-[a-zA-Z0-9_] with underscores, truncate to 50 @@ -447,14 +450,12 @@ describe('EntraIdService — User Provisioning Properties', () => { }; vi.mocked(mockUserService.findByFederatedIdentity).mockResolvedValue(null); - vi.mocked(mockUserService.findByEmail).mockResolvedValue(null); + vi.mocked(mockUserService.findAllByEmail).mockResolvedValue([]); vi.mocked(mockUserService.createFederatedUser).mockImplementation( - async (c: IdTokenClaims) => { - const username = c.email.split('@')[0] - .replace(/[^a-zA-Z0-9_]/g, '_') - .slice(0, 50); + async (c: FederatedProvisioningInput) => { + const username = c.provider === 'entra-id' ? c.username : ''; return createMockUser({ - id: `new-user-${c.sub}`, + id: `new-user-${c.subject}`, email: c.email, username, passwordHash: '', @@ -491,14 +492,12 @@ describe('EntraIdService — User Provisioning Properties', () => { }; vi.mocked(mockUserService.findByFederatedIdentity).mockResolvedValue(null); - vi.mocked(mockUserService.findByEmail).mockResolvedValue(null); + vi.mocked(mockUserService.findAllByEmail).mockResolvedValue([]); vi.mocked(mockUserService.createFederatedUser).mockImplementation( - async (c: IdTokenClaims) => { - const username = c.email.split('@')[0] - .replace(/[^a-zA-Z0-9_]/g, '_') - .slice(0, 50); + async (c: FederatedProvisioningInput) => { + const username = c.provider === 'entra-id' ? c.username : ''; return createMockUser({ - id: `new-user-${c.sub}`, + id: `new-user-${c.subject}`, email: c.email, username, passwordHash: '', diff --git a/backend/test/properties/auth/token-validity.property.test.ts b/backend/test/properties/auth/token-validity.property.test.ts index 313f07ce..3912b3f0 100644 --- a/backend/test/properties/auth/token-validity.property.test.ts +++ b/backend/test/properties/auth/token-validity.property.test.ts @@ -70,6 +70,7 @@ describe('Token Validity Properties', () => { // Create a token with custom expiry const now = Math.floor(Date.now() / 1000); const payload = { + authContext: { provider: 'local', identityId: null }, userId: user.userId, username: user.username, roles: user.roles, @@ -126,6 +127,7 @@ describe('Token Validity Properties', () => { const now = Math.floor(Date.now() / 1000); const payload = { + authContext: { provider: 'local', identityId: null }, userId: user.userId, username: user.username, roles: user.roles, @@ -172,6 +174,7 @@ describe('Token Validity Properties', () => { // Create a valid token const now = Math.floor(Date.now() / 1000); const payload = { + authContext: { provider: 'local', identityId: null }, userId: user.userId, username: user.username, roles: user.roles, @@ -223,6 +226,7 @@ describe('Token Validity Properties', () => { // Create a token that expires in the past const now = Math.floor(Date.now() / 1000); const payload = { + authContext: { provider: 'local', identityId: null }, userId: user.userId, username: user.username, roles: user.roles, @@ -267,6 +271,7 @@ describe('Token Validity Properties', () => { async (user) => { const now = Math.floor(Date.now() / 1000); const payload = { + authContext: { provider: 'local', identityId: null }, userId: user.userId, username: user.username, roles: user.roles, diff --git a/backend/test/properties/consoleAuditLog.property.test.ts b/backend/test/properties/consoleAuditLog.property.test.ts index 49d2a449..beda2caf 100644 --- a/backend/test/properties/consoleAuditLog.property.test.ts +++ b/backend/test/properties/consoleAuditLog.property.test.ts @@ -1,3 +1,5 @@ +import { AuthenticationService } from "../../src/services/AuthenticationService"; +import { consoleAuthentication } from "../helpers/consoleUser"; import { ensureConsoleUser } from "../helpers/consoleUser"; /** * Property-Based Tests for Console Audit Log Completeness @@ -132,6 +134,7 @@ describe("Feature: console-integration, Property 9: Audit log completeness for s DEFAULT_CONSOLE_CONFIG, logger, auditLogger, + new AuthenticationService(db, "console-property-fixture-jwt-secret"), ); }); @@ -149,7 +152,7 @@ describe("Feature: console-integration, Property 9: Audit log completeness for s await db.execute("DELETE FROM console_sessions"); await ensureConsoleUser(db, data.userId); - const reservation = await sessionManager.reserveSession(data); + const reservation = await sessionManager.reserveSession({ ...data, ...await consoleAuthentication(db, data.userId) }); expect(auditLogger.calls.length).toBe(1); const call = auditLogger.calls[0]; @@ -184,7 +187,7 @@ describe("Feature: console-integration, Property 9: Audit log completeness for s // First reserve the session so terminateSession can find it await ensureConsoleUser(db, data.userId); - const reservation = await sessionManager.reserveSession(data); + const reservation = await sessionManager.reserveSession({ ...data, ...await consoleAuthentication(db, data.userId) }); await sessionManager.activateSession(reservation.sessionId); // Clear audit calls from the reservation diff --git a/backend/test/properties/consoleConcurrentLimit.property.test.ts b/backend/test/properties/consoleConcurrentLimit.property.test.ts index 68c65ec3..8b762b2c 100644 --- a/backend/test/properties/consoleConcurrentLimit.property.test.ts +++ b/backend/test/properties/consoleConcurrentLimit.property.test.ts @@ -1,3 +1,5 @@ +import { AuthenticationService } from "../../src/services/AuthenticationService"; +import { consoleAuthentication } from "../helpers/consoleUser"; import { initializeTestSchema } from "../helpers/schema"; import { ensureConsoleUser } from "../helpers/consoleUser"; /** @@ -65,7 +67,7 @@ describe("Feature: console-integration, Property 7: Concurrent session limit enf }); function makeManager(maxConcurrent: number): ConsoleSessionManager { - return new ConsoleSessionManager(db, makeConfig(maxConcurrent), makeLogger(), makeAuditLogger()); + return new ConsoleSessionManager(db, makeConfig(maxConcurrent), makeLogger(), makeAuditLogger(), new AuthenticationService(db, "console-property-fixture-jwt-secret")); } /** Reserve and activate one session, the shape the create route produces. */ @@ -76,7 +78,7 @@ describe("Feature: console-integration, Property 7: Concurrent session limit enf ): Promise { await ensureConsoleUser(db, userId); const reservation = await manager.reserveSession({ - userId, nodeId: `node-${String(index)}`, provider: "proxmox", transport: "websocket-vnc", + ...await consoleAuthentication(db, userId), userId, nodeId: `node-${String(index)}`, provider: "proxmox", transport: "websocket-vnc", }); await manager.activateSession(reservation.sessionId); return reservation.sessionId; @@ -117,7 +119,7 @@ describe("Feature: console-integration, Property 7: Concurrent session limit enf } await expect(manager.reserveSession({ - userId, nodeId: "node-over", provider: "proxmox", transport: "websocket-vnc", + ...await consoleAuthentication(db, userId), userId, nodeId: "node-over", provider: "proxmox", transport: "websocket-vnc", })).rejects.toThrow(ConsoleCapacityError); // The refusal admits nothing: no extra row, so no provider resource @@ -139,14 +141,14 @@ describe("Feature: console-integration, Property 7: Concurrent session limit enf const manager = makeManager(1); await manager.reserveSession({ - userId, nodeId: "node-1", provider: "proxmox", transport: "websocket-vnc", + ...await consoleAuthentication(db, userId), userId, nodeId: "node-1", provider: "proxmox", transport: "websocket-vnc", }); // Still 'creating': the slot is held while the provider works, which // is what stops a second request from racing into the same slot. expect(await manager.getActiveSessionCount(userId)).toBe(0); await expect(manager.reserveSession({ - userId, nodeId: "node-2", provider: "proxmox", transport: "websocket-vnc", + ...await consoleAuthentication(db, userId), userId, nodeId: "node-2", provider: "proxmox", transport: "websocket-vnc", })).rejects.toThrow(ConsoleCapacityError); }, ), @@ -166,8 +168,8 @@ describe("Feature: console-integration, Property 7: Concurrent session limit enf const manager = makeManager(maxConcurrent); const attempts = maxConcurrent + 3; const outcomes = await Promise.allSettled( - Array.from({ length: attempts }, (_, index) => manager.reserveSession({ - userId, nodeId: `node-${String(index)}`, provider: "proxmox", transport: "websocket-vnc", + Array.from({ length: attempts }, async (_, index) => manager.reserveSession({ + ...await consoleAuthentication(db, userId), userId, nodeId: `node-${String(index)}`, provider: "proxmox", transport: "websocket-vnc", })), ); @@ -211,7 +213,7 @@ describe("Feature: console-integration, Property 7: Concurrent session limit enf // Terminated sessions released their slots, so the cap admits again. await expect(manager.reserveSession({ - userId, nodeId: "node-next", provider: "proxmox", transport: "websocket-vnc", + ...await consoleAuthentication(db, userId), userId, nodeId: "node-next", provider: "proxmox", transport: "websocket-vnc", })).resolves.toBeDefined(); }, ), diff --git a/backend/test/properties/consoleRbacCreation.property.test.ts b/backend/test/properties/consoleRbacCreation.property.test.ts index 3c1f7d21..b1227bf3 100644 --- a/backend/test/properties/consoleRbacCreation.property.test.ts +++ b/backend/test/properties/consoleRbacCreation.property.test.ts @@ -164,7 +164,7 @@ describe("Feature: console-integration, Property 5: RBAC enforcement for session await userService.assignRoleToUser(user.id, role.id); } - const token = await authService.generateToken(user); + const token = await authService.generateToken(user, { provider: 'local', identityId: null }); return { token, userId: user.id }; } diff --git a/backend/test/properties/consoleRbacTermination.property.test.ts b/backend/test/properties/consoleRbacTermination.property.test.ts index 352cb982..d17211d4 100644 --- a/backend/test/properties/consoleRbacTermination.property.test.ts +++ b/backend/test/properties/consoleRbacTermination.property.test.ts @@ -1,3 +1,4 @@ +import { consoleAuthentication } from "../helpers/consoleUser"; /** * Property-Based Tests for RBAC Enforcement for Cross-User Termination * @@ -109,6 +110,7 @@ describe("Feature: console-integration, Property 6: RBAC enforcement for cross-u makeConsoleConfig(), new LoggerService(), makeAuditLogger(), + authService, ); // Find or create console:access and console:admin permissions @@ -204,7 +206,7 @@ describe("Feature: console-integration, Property 6: RBAC enforcement for cross-u } // If neither, user has no console permissions - const token = await authService.generateToken(user); + const token = await authService.generateToken(user, { provider: 'local', identityId: null }); return { userId: user.id, token }; } @@ -213,6 +215,7 @@ describe("Feature: console-integration, Property 6: RBAC enforcement for cross-u */ async function createOwnedSession(ownerId: string): Promise { const reservation = await sessionManager.reserveSession({ + ...await consoleAuthentication(db, ownerId), userId: ownerId, nodeId: `node-${randomUUID().substring(0, 8)}`, provider: "proxmox", diff --git a/backend/test/properties/consoleSessionRecord.property.test.ts b/backend/test/properties/consoleSessionRecord.property.test.ts index 33c293e5..1e0a9364 100644 --- a/backend/test/properties/consoleSessionRecord.property.test.ts +++ b/backend/test/properties/consoleSessionRecord.property.test.ts @@ -1,3 +1,5 @@ +import { AuthenticationService } from "../../src/services/AuthenticationService"; +import { consoleAuthentication } from "../helpers/consoleUser"; import { initializeTestSchema } from "../helpers/schema"; import { ensureConsoleUser } from "../helpers/consoleUser"; /** @@ -108,6 +110,7 @@ describe("Feature: console-integration, Property 8: Session record completeness" defaultConfig, createMockLogger(), createMockAuditLogger(), + new AuthenticationService(db, "console-property-fixture-jwt-secret"), ); }); @@ -120,7 +123,7 @@ describe("Feature: console-integration, Property 8: Session record completeness" fc.asyncProperty(reservationRequestArb, async (request) => { await db.execute("DELETE FROM console_sessions"); await ensureConsoleUser(db, request.userId); - const reservation = await sessionManager.reserveSession(request); + const reservation = await sessionManager.reserveSession({ ...request, ...await consoleAuthentication(db, request.userId) }); const row = await db.queryOne<{ id: string | null; @@ -152,7 +155,7 @@ describe("Feature: console-integration, Property 8: Session record completeness" fc.asyncProperty(reservationRequestArb, async (request) => { await db.execute("DELETE FROM console_sessions"); await ensureConsoleUser(db, request.userId); - const reservation = await sessionManager.reserveSession(request); + const reservation = await sessionManager.reserveSession({ ...request, ...await consoleAuthentication(db, request.userId) }); const row = await db.queryOne<{ id: string; diff --git a/backend/test/properties/consoleTokenValidation.property.test.ts b/backend/test/properties/consoleTokenValidation.property.test.ts index 1d409417..c79a37bc 100644 --- a/backend/test/properties/consoleTokenValidation.property.test.ts +++ b/backend/test/properties/consoleTokenValidation.property.test.ts @@ -1,3 +1,5 @@ +import { AuthenticationService } from "../../src/services/AuthenticationService"; +import { consoleAuthentication } from "../helpers/consoleUser"; import { initializeTestSchema } from "../helpers/schema"; import { ensureConsoleUser } from "../helpers/consoleUser"; /** @@ -133,8 +135,8 @@ async function insertSession( `INSERT INTO console_sessions ( id, user_id, node_id, provider, transport, state, token, token_created_at, token_consumed, upstream_url, - started_at, last_heartbeat_at, session_version - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0)`, + started_at, last_heartbeat_at, session_version, auth_context + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, 0, ?)`, [ params.sessionId, params.ownerUserId, @@ -147,6 +149,7 @@ async function insertSession( params.consumed ? 1 : 0, now, now, + JSON.stringify((await consoleAuthentication(db, params.ownerUserId)).authContext), ], ); } @@ -164,6 +167,7 @@ describe("Feature: console-integration, Property 2: Session token validation cor CONSOLE_CONFIG, createMockLogger(), createMockAuditLogger(), + new AuthenticationService(db, "console-property-fixture-jwt-secret"), ); }); diff --git a/backend/test/properties/user/email-uniqueness.property.test.ts b/backend/test/properties/user/email-uniqueness.property.test.ts index bff61d6a..4b8e787a 100644 --- a/backend/test/properties/user/email-uniqueness.property.test.ts +++ b/backend/test/properties/user/email-uniqueness.property.test.ts @@ -201,7 +201,7 @@ describe('Email Uniqueness Properties', () => { // Verify all users can still be retrieved by email for (const user of createdUsers) { - const retrieved = await userService.getUserByEmail(user.email); + const retrieved = await userService.findLocalByEmail(user.email!); expect(retrieved).not.toBeNull(); expect(retrieved?.id).toBe(user.id); expect(retrieved?.email).toBe(user.email); diff --git a/backend/test/routes/auth.test.ts b/backend/test/routes/auth.test.ts index b8bf011c..512ac149 100644 --- a/backend/test/routes/auth.test.ts +++ b/backend/test/routes/auth.test.ts @@ -2039,6 +2039,7 @@ describe('Auth Routes - POST /api/auth/refresh', () => { const jwt = require('jsonwebtoken'); const fakeRefreshToken = jwt.sign( { + authContext: { provider: 'local', identityId: null }, userId: 'non-existent-user-id', username: 'nonexistent', type: 'refresh', diff --git a/backend/test/routes/aws.test.ts b/backend/test/routes/aws.test.ts index af027398..a3fff610 100644 --- a/backend/test/routes/aws.test.ts +++ b/backend/test/routes/aws.test.ts @@ -125,7 +125,7 @@ describe("AWS Router", () => { } await userService.assignRoleToUser(adminUserId, awsRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Build app with the mock plugin app = express(); diff --git a/backend/test/routes/groups.test.ts b/backend/test/routes/groups.test.ts index 4b5438e2..344a4d28 100644 --- a/backend/test/routes/groups.test.ts +++ b/backend/test/routes/groups.test.ts @@ -102,7 +102,7 @@ describe('Groups Router - POST /api/groups', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -116,7 +116,7 @@ describe('Groups Router - POST /api/groups', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); }); afterEach(async () => { @@ -296,7 +296,7 @@ describe('Groups Router - GET /api/groups', () => { await roleService.assignPermissionToRole(adminRole.id, groupsReadPermission.id); await userService.assignRoleToUser(adminUser.id, adminRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); const regularUser = await userService.createUser({ username: 'regular_user', @@ -306,7 +306,7 @@ describe('Groups Router - GET /api/groups', () => { lastName: 'User', isAdmin: false, }); - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); }); afterEach(async () => { @@ -464,7 +464,7 @@ describe('Groups Router - GET /api/groups/:id', () => { await roleService.assignPermissionToRole(adminRole.id, groupsReadPermission.id); await userService.assignRoleToUser(adminUser.id, adminRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create test group const group = await groupService.createGroup({ @@ -580,7 +580,7 @@ describe('Groups Router - PUT /api/groups/:id', () => { await roleService.assignPermissionToRole(adminRole.id, groupsWritePermission.id); await userService.assignRoleToUser(adminUser.id, adminRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create test group const group = await groupService.createGroup({ @@ -719,7 +719,7 @@ describe('Groups Router - DELETE /api/groups/:id', () => { await roleService.assignPermissionToRole(adminRole.id, groupsAdminPermission.id); await userService.assignRoleToUser(adminUser.id, adminRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); const regularUser = await userService.createUser({ username: 'regular_user', @@ -729,7 +729,7 @@ describe('Groups Router - DELETE /api/groups/:id', () => { lastName: 'User', isAdmin: false, }); - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test group const group = await groupService.createGroup({ @@ -854,7 +854,7 @@ describe('Groups Router - POST /api/groups/:id/roles/:roleId', () => { await roleService.assignPermissionToRole(adminRole.id, groupsWritePermission.id); await userService.assignRoleToUser(adminUser.id, adminRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); const regularUser = await userService.createUser({ username: 'regular_user', @@ -864,7 +864,7 @@ describe('Groups Router - POST /api/groups/:id/roles/:roleId', () => { lastName: 'User', isAdmin: false, }); - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test group const group = await groupService.createGroup({ @@ -1071,7 +1071,7 @@ describe('Groups Router - DELETE /api/groups/:id/roles/:roleId', () => { await roleService.assignPermissionToRole(adminRole.id, groupsWritePermission.id); await userService.assignRoleToUser(adminUser.id, adminRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); const regularUser = await userService.createUser({ username: 'regular_user', @@ -1081,7 +1081,7 @@ describe('Groups Router - DELETE /api/groups/:id/roles/:roleId', () => { lastName: 'User', isAdmin: false, }); - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test group const group = await groupService.createGroup({ diff --git a/backend/test/routes/journal.test.ts b/backend/test/routes/journal.test.ts index 95cb89ed..afe94d05 100644 --- a/backend/test/routes/journal.test.ts +++ b/backend/test/routes/journal.test.ts @@ -111,7 +111,7 @@ describe("Journal Router", () => { } await userService.assignRoleToUser(adminUserId, journalRole.id); - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without journal permissions const regularUser = await userService.createUser({ @@ -123,7 +123,7 @@ describe("Journal Router", () => { isAdmin: false, }); - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Seed some journal entries for testing await journalService.recordEvent({ diff --git a/backend/test/routes/permissions.test.ts b/backend/test/routes/permissions.test.ts index 17d341be..9fe50d2f 100644 --- a/backend/test/routes/permissions.test.ts +++ b/backend/test/routes/permissions.test.ts @@ -87,7 +87,7 @@ describe('Permissions Router', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -101,7 +101,7 @@ describe('Permissions Router', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); }); afterEach(async () => { diff --git a/backend/test/routes/roles-permissions.test.ts b/backend/test/routes/roles-permissions.test.ts index 4227cf46..9facb9c2 100644 --- a/backend/test/routes/roles-permissions.test.ts +++ b/backend/test/routes/roles-permissions.test.ts @@ -101,7 +101,7 @@ describe('Roles Router - Role-Permission Association Routes', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -115,7 +115,7 @@ describe('Roles Router - Role-Permission Association Routes', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test role const testRole = await roleService.createRole({ diff --git a/backend/test/routes/users.test.ts b/backend/test/routes/users.test.ts index 1519896d..3587b15a 100644 --- a/backend/test/routes/users.test.ts +++ b/backend/test/routes/users.test.ts @@ -117,7 +117,7 @@ describe('Users Router - GET /api/users', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -131,7 +131,7 @@ describe('Users Router - GET /api/users', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); }); afterEach(async () => { @@ -363,7 +363,7 @@ describe('Users Router - GET /api/users', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); const response = await request(harness.use(app)) .get('/api/users') @@ -456,7 +456,7 @@ describe('Users Router - GET /api/users/:id', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -470,7 +470,7 @@ describe('Users Router - GET /api/users/:id', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user with groups and roles const testUser = await userService.createUser({ @@ -709,7 +709,7 @@ describe('Users Router - GET /api/users/:id', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); const response = await request(harness.use(app)) .get(`/api/users/${testUserId}`) @@ -820,7 +820,7 @@ describe('Users Router - PUT /api/users/:id', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -834,7 +834,7 @@ describe('Users Router - PUT /api/users/:id', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user to be updated const testUser = await userService.createUser({ @@ -1225,7 +1225,7 @@ describe('Users Router - PUT /api/users/:id', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); const response = await request(harness.use(app)) .put(`/api/users/${testUserId}`) @@ -1387,7 +1387,7 @@ describe('Users Router - DELETE /api/users/:id', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create user with users:write permission (but not users:admin) const writerUser = await userService.createUser({ @@ -1429,7 +1429,7 @@ describe('Users Router - DELETE /api/users/:id', () => { await userService.assignRoleToUser(writerUserId, writerRole.id); // Generate token for writer user - writerUserToken = await authService.generateToken(writerUser); + writerUserToken = await authService.generateToken(writerUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -1443,7 +1443,7 @@ describe('Users Router - DELETE /api/users/:id', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user to be deleted const testUser = await userService.createUser({ @@ -1617,7 +1617,7 @@ describe('Users Router - DELETE /api/users/:id', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); await request(harness.use(app)) .delete(`/api/users/${testUserId}`) @@ -1813,7 +1813,7 @@ describe('Users Router - POST /api/users/:id/groups/:groupId', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -1827,7 +1827,7 @@ describe('Users Router - POST /api/users/:id/groups/:groupId', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user to be added to group const testUser = await userService.createUser({ @@ -2087,7 +2087,7 @@ describe('Users Router - POST /api/users/:id/groups/:groupId', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); await request(harness.use(app)) .post(`/api/users/${testUserId}/groups/${testGroupId}`) @@ -2225,7 +2225,7 @@ describe('Users Router - DELETE /api/users/:id/groups/:groupId', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -2239,7 +2239,7 @@ describe('Users Router - DELETE /api/users/:id/groups/:groupId', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user to be removed from group const testUser = await userService.createUser({ @@ -2555,7 +2555,7 @@ describe('Users Router - DELETE /api/users/:id/groups/:groupId', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); await request(harness.use(app)) .delete(`/api/users/${testUserId}/groups/${testGroupId}`) @@ -2680,7 +2680,7 @@ describe('Users Router - POST /api/users/:id/roles/:roleId', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -2694,7 +2694,7 @@ describe('Users Router - POST /api/users/:id/roles/:roleId', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user to be assigned role const testUser = await userService.createUser({ @@ -2980,7 +2980,7 @@ describe('Users Router - POST /api/users/:id/roles/:roleId', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); await request(harness.use(app)) .post(`/api/users/${testUserId}/roles/${testRoleId}`) @@ -3144,7 +3144,7 @@ describe('Users Router - DELETE /api/users/:id/roles/:roleId', () => { await userService.assignRoleToUser(adminUserId, adminRole.id); // Generate token for admin user - adminToken = await authService.generateToken(adminUser); + adminToken = await authService.generateToken(adminUser, { provider: 'local', identityId: null }); // Create regular user without permissions const regularUser = await userService.createUser({ @@ -3158,7 +3158,7 @@ describe('Users Router - DELETE /api/users/:id/roles/:roleId', () => { regularUserId = regularUser.id; // Generate token for regular user - regularUserToken = await authService.generateToken(regularUser); + regularUserToken = await authService.generateToken(regularUser, { provider: 'local', identityId: null }); // Create test user to be assigned role const testUser = await userService.createUser({ @@ -3480,7 +3480,7 @@ describe('Users Router - DELETE /api/users/:id/roles/:roleId', () => { isAdmin: true, }); - const superAdminToken = await authService.generateToken(superAdmin); + const superAdminToken = await authService.generateToken(superAdmin, { provider: 'local', identityId: null }); await request(harness.use(app)) .delete(`/api/users/${testUserId}/roles/${testRoleId}`) diff --git a/backend/test/security/console-lifecycle.test.ts b/backend/test/security/console-lifecycle.test.ts index f4eef822..ba9f5426 100644 --- a/backend/test/security/console-lifecycle.test.ts +++ b/backend/test/security/console-lifecycle.test.ts @@ -1,3 +1,4 @@ +import { consoleAuthentication } from "../helpers/consoleUser"; /** * Console session lifecycle against a live fake upstream (A15 / I06, S08, S09). * @@ -121,7 +122,7 @@ describe('A15: console session lifecycle', () => { firstName: 'Console', lastName: 'Owner', }); await grantConsole(owner, 'access'); - ownerToken = await auth.generateToken(owner); + ownerToken = await auth.generateToken(owner, { provider: 'local', identityId: null }); // A local WebSocket server stands in for the provider's upstream. upstreamServer = new WebSocketServer({ host: '127.0.0.1', port: 0 }); @@ -133,7 +134,7 @@ describe('A15: console session lifecycle', () => { broker = new ConsoleConnectionBroker(new LoggerService()); attachments = vi.spyOn(broker, 'attach'); manager = new ConsoleSessionManager( - db, consoleConfig, new LoggerService(), new AuditLoggingService(db), broker, + db, consoleConfig, new LoggerService(), new AuditLoggingService(db), auth, broker, // The same bridge server.ts wires: the manager owns the transitions and // has no plugin registry, so provider cleanup arrives from outside. (providerName: string, sessionId: string): Promise => { @@ -313,7 +314,7 @@ describe('A15: console session lifecycle', () => { it('refuses a session whose provider produced no upstream', async () => { const reservation = await manager.reserveSession({ - userId: owner.id, nodeId: 'proxmox:pve:101', provider: 'proxmox', transport: 'websocket-vnc', + ...await consoleAuthentication(database.getAdapter(), owner.id), userId: owner.id, nodeId: 'proxmox:pve:101', provider: 'proxmox', transport: 'websocket-vnc', }); await manager.activateSession(reservation.sessionId); @@ -401,7 +402,7 @@ describe('A15: console session lifecycle', () => { firstName: 'Console', lastName: 'Operator', }); await grantConsole(operator, 'admin'); - const operatorToken = await auth.generateToken(operator); + const operatorToken = await auth.generateToken(operator, { provider: 'local', identityId: null }); const { sessionId, wsToken } = await createSession(); const { client, peer } = await connect(wsToken); @@ -518,7 +519,7 @@ describe('A15: console session lifecycle', () => { try { const reservation = await manager.reserveSession({ - userId: owner.id, nodeId: 'proxmox:pve:102', provider: 'proxmox', transport: 'websocket-vnc', + ...await consoleAuthentication(database.getAdapter(), owner.id), userId: owner.id, nodeId: 'proxmox:pve:102', provider: 'proxmox', transport: 'websocket-vnc', }); broker.offer(reservation.sessionId, `ws://127.0.0.1:${String(slowPort)}`); await manager.activateSession(reservation.sessionId); @@ -571,7 +572,7 @@ describe('A15: console session lifecycle', () => { firstName: 'Other', lastName: 'User', }); await grantConsole(other, 'access'); - otherToken = await auth.generateToken(other); + otherToken = await auth.generateToken(other, { provider: 'local', identityId: null }); }); it('denies another user\'s heartbeat', async () => { diff --git a/backend/test/security/entitlement-administration.test.ts b/backend/test/security/entitlement-administration.test.ts index fa803ca6..2aad1042 100644 --- a/backend/test/security/entitlement-administration.test.ts +++ b/backend/test/security/entitlement-administration.test.ts @@ -66,8 +66,8 @@ describe('A07: deliberate entitlement administration', () => { await new GroupService(db).assignRoleToGroup(groupId, 'role-admin-001'); roleId = (await roles.createRole({ name: 'Custom role', description: '' })).id; await users.assignRoleToUser(editor.id, roleId); - editorToken = await auth.generateToken(editor); - delegateToken = await auth.generateToken(delegate); + editorToken = await auth.generateToken(editor, { provider: 'local', identityId: null }); + delegateToken = await auth.generateToken(delegate, { provider: 'local', identityId: null }); app = express(); app.use(express.json()); app.use('/api/users', createUsersRouter(database)); @@ -100,7 +100,7 @@ describe('A07: deliberate entitlement administration', () => { const tables = ['users', 'roles', 'groups', 'permissions', 'user_roles', 'user_groups', 'group_roles', 'role_permissions']; const snapshot = () => Promise.all(tables.map(table => database.getAdapter().query(`SELECT * FROM ${table} ORDER BY 1`))); const before = await snapshot(); - for (const token of [undefined, await auth.generateToken(target), editorToken]) { + for (const token of [undefined, await auth.generateToken(target, { provider: 'local', identityId: null }), editorToken]) { for (const [method, path, body] of mutations()) { const call = request(harness.use(app))[method](path).send(body); if (token) call.set('Authorization', `Bearer ${token}`); diff --git a/backend/test/security/ldap-transports.test.ts b/backend/test/security/ldap-transports.test.ts new file mode 100644 index 00000000..1796650d --- /dev/null +++ b/backend/test/security/ldap-transports.test.ts @@ -0,0 +1,239 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import request from 'supertest'; +import { once } from 'node:events'; +import { WebSocket, WebSocketServer } from 'ws'; +import { deferred, ldapResult } from '../helpers/ldapAuthentication'; +import { createLdapTransportContext, liveDirectoryReady } from '../helpers/ldapTransport'; +import { createHttpHarness, type HttpHarness } from '../helpers/httpHarness'; +import { LdapDirectoryError } from '../../src/services/LdapDirectoryService'; +import type { LdapDirectoryResult } from '../../src/services/LdapDirectoryService'; +import { StreamingExecutionManager } from '../../src/services/StreamingExecutionManager'; +import { createJournalRouter } from '../../src/routes/journal'; +import { JournalService } from '../../src/services/journal/JournalService'; +import type { JournalEntry } from '../../src/services/journal/types'; +import { createMcpRouter } from '../../src/mcp/McpRouter'; +import { createMcpAuthMiddleware } from '../../src/middleware/mcpAuthMiddleware'; +import { PermissionService } from '../../src/services/PermissionService'; +import { ExecutionRepository } from '../../src/database/ExecutionRepository'; +import { IntegrationManager } from '../../src/integrations/IntegrationManager'; +import { ConsoleSessionManager } from '../../src/services/ConsoleSessionManager'; +import { ConsoleConnectionBroker } from '../../src/services/ConsoleConnectionBroker'; +import { ConsoleWebSocketProxy } from '../../src/services/ConsoleWebSocketProxy'; +import { ConsoleConfigSchema } from '../../src/config/schema'; +import { createConsoleRouter } from '../../src/routes/console'; +import { LoggerService } from '../../src/services/LoggerService'; +import { AuditLoggingService } from '../../src/services/AuditLoggingService'; + +const headers = { Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json' }; +const initialize = { jsonrpc: '2.0', id: 1, method: 'initialize', params: { + protocolVersion: '2025-03-26', capabilities: {}, clientInfo: { name: 'ldap-test', version: '1' }, +} }; + +for (const [mode, dialect] of [['synthetic', 'sqlite'], ['ldaps', 'sqlite'], ['starttls', 'sqlite'], ['ldaps', 'postgres'], ['starttls', 'postgres']] as const) { +describe.skipIf((mode !== 'synthetic' && !liveDirectoryReady) || (dialect === 'postgres' && !process.env.TEST_DATABASE_URL))('LDAP protected delivery across transports: ' + dialect + '/' + mode, () => { + let ctx: Awaited>; + let harness: HttpHarness; + let pair: { token: string; refreshToken: string; user: { id: string } }; + let cleanup: (() => void | Promise)[]; + + beforeEach(async () => { + ctx = await createLdapTransportContext(mode, dialect); + harness = await createHttpHarness(); + harness.use(ctx.app); + // Administrative authority still requires an explicit LDAP/manual role. + const proof = await ctx.ldap.authenticate(ctx.loginName, ctx.loginPassword); + await ctx.users.updateUser(proof.user.id, { isAdmin: true }); + pair = (await request(harness.use(ctx.app)).post('/api/auth/ldap/login').send({ username: ctx.loginName, password: ctx.loginPassword }).expect(200)).body; + cleanup = []; + }); + afterEach(async () => { + vi.useRealTimers(); + for (const close of cleanup.reverse()) await close(); + await harness.close(); + await ctx.live?.close(); + await ctx.database.close(); + await ctx.releaseDatabase(); + vi.restoreAllMocks(); + vi.unstubAllEnvs(); + }); + async function expire() { await ctx.db.execute('UPDATE ldap_validation_state SET last_validated_at = 1'); } + async function openEvents(path: string) { + const abort = new AbortController(); + cleanup.push(() => { abort.abort(); }); + const response = await fetch(`http://127.0.0.1:${harness.port}${path}`, { + headers: { Authorization: `Bearer ${pair.token}` }, signal: abort.signal, + }); + expect(response.status).toBe(200); + const reader = response.body!.getReader(); + return { reader, read: async () => { + const next = await reader.read(); + return next.done ? null : new TextDecoder().decode(next.value); + } }; + } + + it('REST and refresh fail without extending freshness during an outage, retain retryable credentials and recover independently of local login', async () => { + const before = await ctx.db.queryOne('SELECT * FROM ldap_validation_state'); + if (ctx.live) ctx.live.outage(true); + else ctx.directory.revalidate.mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + const server = harness.use(ctx.app); + await request(server).post('/api/auth/refresh').send({ refreshToken: pair.refreshToken }).expect(503); + expect(await ctx.db.queryOne('SELECT * FROM ldap_validation_state')).toEqual(before); + await request(server).get('/protected').set('Authorization', 'Bearer ' + pair.token).expect(200); + await expire(); + const expired = await ctx.db.queryOne('SELECT * FROM ldap_validation_state'); + await request(server).get('/protected').set('Authorization', 'Bearer ' + pair.token).expect(503); + expect(await ctx.db.queryOne('SELECT * FROM ldap_validation_state')).toEqual(expired); + await request(server).post('/api/auth/login').send({ username: 'administrator', password: 'LocalTest123!' }).expect(200); // pragma: allowlist secret + if (ctx.live) ctx.live.outage(false); + else ctx.directory.revalidate.mockResolvedValue(ldapResult); + await request(server).get('/protected').set('Authorization', 'Bearer ' + pair.token).expect(200); + await request(server).post('/api/auth/refresh').send({ refreshToken: pair.refreshToken }).expect(200); + }); + + it('execution SSE stops output while revalidation is pending and closes without protected delivery on failure', async () => { + const streaming = new StreamingExecutionManager(); + cleanup.push(() => { streaming.cleanup(); }); + ctx.app.get('/events', ctx.authenticate, (_req, res) => { streaming.subscribe('execution', res); }); + const stream = await openEvents('/events'); + await stream.read(); + const pending = deferred(); + if (ctx.live) ctx.live.pause(); + else ctx.directory.revalidate.mockReturnValueOnce(pending.promise); + await expire(); + streaming.emit('execution', { type: 'stdout', data: 'protected-output' }); + await vi.waitFor(() => expect(ctx.directory.revalidate).toHaveBeenCalledOnce()); + if (ctx.live) ctx.live.outage(true); + else pending.reject(new LdapDirectoryError('UNAVAILABLE')); + expect(await stream.read()).toBeNull(); + }); + + it('idle SSE revalidates on the shared timer and closes at expired freshness', async () => { + vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }); + const streaming = new StreamingExecutionManager(); + cleanup.push(() => { streaming.cleanup(); }); + ctx.app.get('/idle', ctx.authenticate, (_req, res) => { streaming.subscribe('execution', res); }); + const stream = await openEvents('/idle'); + await stream.read(); + await expire(); + if (ctx.live) await ctx.live.setEligible(false); + else ctx.directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('INELIGIBLE')); + await vi.advanceTimersByTimeAsync(1000); + expect(await stream.read()).toBeNull(); + await expect(ctx.auth.verifyToken(pair.token)).rejects.toThrow(); + }); + + it.each(['/api/journal/node/stream', '/api/journal/global/stream'])('journal SSE checks delayed batches at delivery: %s', async path => { + const pending = deferred(); + vi.spyOn(JournalService.prototype, 'getNodeTimeline').mockReturnValue(pending.promise); + vi.spyOn(JournalService.prototype, 'getGlobalTimeline').mockReturnValue(pending.promise); + ctx.app.use('/api/journal', createJournalRouter(ctx.database, {}, ctx.container)); + const stream = await openEvents(path + '?source=system'); + expect(await stream.read()).toContain('event: init'); + await expire(); + if (ctx.live) ctx.live.outage(true); + else ctx.directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('UNAVAILABLE')); + pending.resolve([{ summary: 'protected-journal-data' } as JournalEntry]); + expect(await stream.read()).toBeNull(); + }); + + it('MCP rechecks an in-flight tool result and does not deliver data after freshness expires', async () => { + const logger = new LoggerService('error'); + const manager = new IntegrationManager({ logger }); + const pending = deferred>>(); + const query = vi.spyOn(manager, 'getAggregatedInventory').mockReturnValueOnce(pending.promise); + const mcp = createMcpRouter({ integrationManager: manager, executionRepository: new ExecutionRepository(ctx.db), + journalService: new JournalService(ctx.db), permissionService: new PermissionService(ctx.db), + hieraPlugin: undefined, puppetDBService: undefined, puppetRunHistoryService: undefined, logger, version: 'test', + }, createMcpAuthMiddleware(undefined, 'machine', ctx.authenticate, ctx.db)); + cleanup.push(async () => { await mcp.close(); }); + ctx.app.use('/mcp', mcp.router); + const opening = await request(harness.use(ctx.app)).post('/mcp').set(headers).set('Authorization', `Bearer ${pair.token}`).send(initialize).expect(200); + const session = opening.headers['mcp-session-id'] as string; + const output = request(harness.use(ctx.app)).post('/mcp').set(headers).set('Authorization', `Bearer ${pair.token}`) + .set('mcp-session-id', session).send({ jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'inventory_list', arguments: {} } }).then(response => response); + await vi.waitFor(() => expect(query).toHaveBeenCalledOnce()); + await expire(); + if (ctx.live) ctx.live.outage(true); + else ctx.directory.revalidate.mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + pending.resolve({ nodes: [{ id: 'protected-node', name: 'protected-node', source: 'ssh' }], groups: [], sources: {} } as Awaited>); + const response = await output; + expect(response.text).not.toContain('protected-node'); + expect(response.text).toMatch(/authorization unavailable|session revoked/i); + }); + + it.each(['websocket-vnc', 'websocket-terminal'] as const)('console %s retains provider context and stops both delivery directions on stale authorization', async transport => { + const upstream = new WebSocketServer({ host: '127.0.0.1', port: 0 }); + await once(upstream, 'listening'); + const address = upstream.address(); + if (typeof address === 'string') throw new Error('Unexpected address'); + cleanup.push(async () => { for (const ws of upstream.clients) ws.terminate(); await new Promise(resolve => { upstream.close(() => { resolve(); }); }); }); + const logger = new LoggerService('error'); + const broker = new ConsoleConnectionBroker(logger); + const config = ConsoleConfigSchema.parse({}); + const manager = new ConsoleSessionManager(ctx.db, config, logger, new AuditLoggingService(ctx.db), ctx.auth, broker); + const integrations = { getConsoleProvider: () => ({ getSupportedTransports: () => [transport], + createSession: async () => ({ upstream: { url: `ws://127.0.0.1:${address.port}` } }), terminateSession: async () => true, + }), getAggregatedInventory: async () => ({ nodes: [], groups: [], sources: {} }) } as unknown as IntegrationManager; + ctx.app.use('/api/console', createConsoleRouter(ctx.container, integrations, manager, ctx.db, broker)); + const proxy = new ConsoleWebSocketProxy(harness.use(ctx.app), manager, { allowedOrigins: ['http://localhost'], console: config }, logger, broker); + cleanup.push(async () => { broker.revokeAll('test_teardown'); await new Promise(resolve => setImmediate(resolve)); await proxy.drain(); }); + const admission = await request(harness.use(ctx.app)).post('/api/console/sessions').set('Authorization', `Bearer ${pair.token}`) + .send({ nodeId: 'node', provider: 'proxmox' }).expect(201); + const row = await ctx.db.queryOne<{ auth_context: string }>('SELECT auth_context FROM console_sessions'); + expect(JSON.parse(row!.auth_context)).toMatchObject({ provider: 'ldap', directoryId: 'directory' }); + const connected = once(upstream, 'connection'); + const pathname = transport === 'websocket-vnc' ? 'vnc' : 'terminal'; + const ws = new WebSocket(`ws://127.0.0.1:${harness.port}/ws/console/${pathname}?token=${admission.body.session.token}`, { origin: 'http://localhost' }); + cleanup.push(() => { ws.close(); }); + await once(ws, 'open'); + const [peer] = await connected; + // Wait for relay registration after the upstream opens. + await new Promise(resolve => setTimeout(resolve, 30)); + const sent = vi.fn(); const received = vi.fn(); + peer.on('message', received); ws.on('message', sent); + await expire(); + if (ctx.live) ctx.live.outage(true); + else ctx.directory.revalidate.mockRejectedValue(new LdapDirectoryError('UNAVAILABLE')); + const closed = once(ws, 'close'); + peer.send('protected-upstream'); ws.send('protected-client'); + await closed; + expect(sent).not.toHaveBeenCalled(); + expect(received).not.toHaveBeenCalled(); + // A transient failure closes this relay but does not rotate account tokens. + if (ctx.live) ctx.live.outage(false); + else ctx.directory.revalidate.mockResolvedValue(ldapResult); + await expect(ctx.auth.verifyToken(pair.token)).resolves.toMatchObject({ authContext: { provider: 'ldap' } }); + + const second = await request(harness.use(ctx.app)).post('/api/console/sessions').set('Authorization', `Bearer ${pair.token}`) + .send({ nodeId: 'node', provider: 'proxmox' }).expect(201); + const idle = new WebSocket(`ws://127.0.0.1:${harness.port}/ws/console/${pathname}?token=${second.body.session.token}`, { origin: 'http://localhost' }); + cleanup.push(() => { idle.close(); }); + const idleUpstream = once(upstream, 'connection'); + await once(idle, 'open'); + await idleUpstream; + await new Promise(resolve => setTimeout(resolve, 30)); + const idleClosed = once(idle, 'close'); + await expire(); + if (ctx.live) await ctx.live.setEligible(false); + else ctx.directory.revalidate.mockRejectedValue(new LdapDirectoryError('INELIGIBLE')); + await idleClosed; + await expect(ctx.auth.verifyToken(pair.token)).rejects.toThrow(); + }); + + it('rejects console upgrade on stale eligibility before an upstream is claimed', async () => { + const config = ConsoleConfigSchema.parse({}); + const logger = new LoggerService('error'); + const manager = new ConsoleSessionManager(ctx.db, config, logger, new AuditLoggingService(ctx.db), ctx.auth); + const payload = await ctx.auth.verifyToken(pair.token); + const reservation = await manager.reserveSession({ userId: pair.user.id, nodeId: 'node', provider: 'proxmox', transport: 'websocket-vnc', + authContext: payload.authContext, sessionVersion: payload.sessionVersion }); + await expire(); + if (ctx.live) await ctx.live.setEligible(false); + else ctx.directory.revalidate.mockRejectedValueOnce(new LdapDirectoryError('INELIGIBLE')); + await expect(manager.claimTokenForUpgrade(reservation.token)).rejects.toMatchObject({ code: 'DENIED' }); + expect(await manager.claimTokenForUpgrade(reservation.token)).toBeNull(); + expect(await ctx.db.queryOne('SELECT token_consumed FROM console_sessions')).toEqual({ token_consumed: 1 }); + }); +}); + +} diff --git a/backend/test/security/route-authorization.test.ts b/backend/test/security/route-authorization.test.ts index 8a311f78..c0399813 100644 --- a/backend/test/security/route-authorization.test.ts +++ b/backend/test/security/route-authorization.test.ts @@ -146,7 +146,7 @@ beforeAll(async () => { if (principal !== "noRole" && principal !== "boltOnly" && principal !== "awsOnly") { await userService.assignRoleToUser(user.id, ROLE_IDS[principal]); } - tokens.set(principal, await authService.generateToken(user)); + tokens.set(principal, await authService.generateToken(user, { provider: 'local', identityId: null })); } const scoped = await userService.createUser({ username: "bolt_only", email: "bolt_only@test.local", password: "RouteAuthzPass123!", firstName: "Bolt", lastName: "Only", isAdmin: false }); @@ -154,18 +154,18 @@ beforeAll(async () => { await db.execute("INSERT INTO roles (id, name, description, is_built_in, created_at, updated_at) VALUES ('bolt-only', 'Bolt only', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"); await db.execute("INSERT INTO role_permissions (role_id, permission_id, assigned_at) SELECT 'bolt-only', id, CURRENT_TIMESTAMP FROM permissions WHERE (resource = 'bolt' AND \"action\" IN ('read', 'execute')) OR (resource = 'executions' AND \"action\" = 'read')"); await userService.assignRoleToUser(scoped.id, "bolt-only"); - tokens.set("boltOnly", await authService.generateToken(scoped)); + tokens.set("boltOnly", await authService.generateToken(scoped, { provider: 'local', identityId: null })); const awsScoped = await userService.createUser({ username: "aws_only", email: "aws_only@test.local", password: "RouteAuthzPass123!", firstName: "AWS", lastName: "Only", isAdmin: false }); await db.execute("DELETE FROM user_roles WHERE user_id = ?", [awsScoped.id]); await db.execute("INSERT INTO roles (id, name, description, is_built_in, created_at, updated_at) VALUES ('aws-only', 'AWS lifecycle only', '', 0, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)"); await db.execute("INSERT INTO role_permissions (role_id, permission_id, assigned_at) SELECT 'aws-only', id, CURRENT_TIMESTAMP FROM permissions WHERE resource = 'aws' AND \"action\" IN ('read', 'lifecycle')"); await userService.assignRoleToUser(awsScoped.id, "aws-only"); - tokens.set("awsOnly", await authService.generateToken(awsScoped)); + tokens.set("awsOnly", await authService.generateToken(awsScoped, { provider: 'local', identityId: null })); spies = makeSpies(); - const authMiddleware = asyncHandler(createAuthMiddleware(db, JWT_SECRET)); + const authMiddleware = asyncHandler(createAuthMiddleware(new AuthenticationService(db, JWT_SECRET))); const rawRbac = createRbacMiddleware(db); const rbacMiddleware: PermissionMiddlewareFactory = (resource, action) => asyncHandler(rawRbac(resource, action)); diff --git a/backend/test/security/session-revocation.test.ts b/backend/test/security/session-revocation.test.ts index 9d4eaed2..e1b399f9 100644 --- a/backend/test/security/session-revocation.test.ts +++ b/backend/test/security/session-revocation.test.ts @@ -1,3 +1,4 @@ +import { consoleAuthentication } from "../helpers/consoleUser"; import { beforeAll, afterAll, beforeEach, afterEach, describe, it, expect, vi } from 'vitest'; import express from 'express'; import request from 'supertest'; @@ -51,14 +52,14 @@ describe('A05: token purpose and durable revocation', () => { user = await users.createUser({ username: 'alice', email: 'alice@example.test', password: 'Password123!', firstName: 'Alice', lastName: 'Test' }); await users.assignRoleToUser(user.id, 'role-viewer-001'); const admin = await users.createUser({ username: 'admin', email: 'admin@example.test', password: 'Password123!', firstName: 'Admin', lastName: 'Test', isAdmin: true }); - access = await auth.generateToken(user); - refresh = await auth.generateRefreshToken(user); - adminAccess = await auth.generateToken(admin); + access = await auth.generateToken(user, { provider: 'local', identityId: null }); + refresh = await auth.generateRefreshToken(user, { provider: 'local', identityId: null }); + adminAccess = await auth.generateToken(admin, { provider: 'local', identityId: null }); app = express(); app.use(express.json()); app.use('/api/users', createUsersRouter(database)); app.use('/api/auth', createAuthRouter(database)); - const authenticate = createAuthMiddleware(db, secret); + const authenticate = createAuthMiddleware(new AuthenticationService(db, secret)); const authorize = createRbacMiddleware(db); app.get('/read', authenticate, authorize('executions', 'read'), (_req, res) => { res.json({ ok: true }); }); app.get('/mcp-auth', createMcpAuthMiddleware(undefined, 'machine', authenticate, db), (_req, res) => { res.json({ ok: true }); }); @@ -91,7 +92,7 @@ describe('A05: token purpose and durable revocation', () => { await auth.revokeAllUserTokens(user.id); return token; }); - await expect(auth.generateTokenPair(user)).rejects.toThrow('revoked'); + await expect(auth.generateTokenPair(user, { provider: 'local', identityId: null })).rejects.toThrow('revoked'); }); it.each([ @@ -180,7 +181,7 @@ describe('A05: token purpose and durable revocation', () => { await users.updateUser(user.id, { isAdmin: true }); const config = ConsoleConfigSchema.parse({}); const broker = new ConsoleConnectionBroker(new LoggerService()); - const manager = new ConsoleSessionManager(database.getAdapter(), config, new LoggerService(), new AuditLoggingService(database.getAdapter()), broker); + const manager = new ConsoleSessionManager(database.getAdapter(), config, new LoggerService(), new AuditLoggingService(database.getAdapter()), auth, broker); const termination = vi.spyOn(manager, "terminateSession"); const upstream = new WebSocketServer({ host: '127.0.0.1', port: 0 }); await once(upstream, 'listening'); @@ -189,7 +190,7 @@ describe('A05: token purpose and durable revocation', () => { const local = await createHttpHarness(); const server = local.use(express()); new ConsoleWebSocketProxy(server, manager, { allowedOrigins: ['http://localhost'], console: config }, new LoggerService(), broker); - const reservation = await manager.reserveSession({ userId: user.id, nodeId: 'node', provider: 'proxmox', transport: 'websocket-vnc' }); + const reservation = await manager.reserveSession({ ...await consoleAuthentication(database.getAdapter(), user.id), userId: user.id, nodeId: 'node', provider: 'proxmox', transport: 'websocket-vnc' }); // Connection material reaches the proxy through the broker, never the database. broker.offer(reservation.sessionId, `ws://127.0.0.1:${upstreamAddress.port}`); await manager.activateSession(reservation.sessionId); @@ -205,7 +206,7 @@ describe('A05: token purpose and durable revocation', () => { await Promise.all([clientClosed, peerClosed]); // The token was consumed by this upgrade, so a fresh one for the same // revoked account is what proves no second console can be opened. - await expect(manager.reserveSession({ userId: user.id, nodeId: 'node', provider: 'proxmox', transport: 'websocket-vnc' })) + await expect(manager.reserveSession({ ...await consoleAuthentication(database.getAdapter(), user.id), userId: user.id, nodeId: 'node', provider: 'proxmox', transport: 'websocket-vnc' })) .rejects.toThrow('User not found or inactive'); } finally { client.terminate(); diff --git a/backend/test/services/AuthenticationService.bruteforce.test.ts b/backend/test/services/AuthenticationService.bruteforce.test.ts index 8a7bf553..a850c669 100644 --- a/backend/test/services/AuthenticationService.bruteforce.test.ts +++ b/backend/test/services/AuthenticationService.bruteforce.test.ts @@ -3,6 +3,7 @@ import { SQLiteAdapter } from '../../src/database/SQLiteAdapter'; import type { DatabaseAdapter } from '../../src/database/DatabaseAdapter'; import { AuthenticationService } from '../../src/services/AuthenticationService'; import { randomUUID } from 'crypto'; +import { initializeTestSchema } from '../helpers/schema'; describe('AuthenticationService - Brute Force Protection', () => { let db: DatabaseAdapter; @@ -16,117 +17,7 @@ describe('AuthenticationService - Brute Force Protection', () => { db = new SQLiteAdapter(':memory:'); await db.initialize(); - // Initialize schema - await runQuery(db, ` - CREATE TABLE users ( - id TEXT PRIMARY KEY, - username TEXT NOT NULL UNIQUE, - email TEXT NOT NULL UNIQUE, - password_hash TEXT NOT NULL, - session_version TEXT NOT NULL DEFAULT '0', - first_name TEXT NOT NULL, - last_name TEXT NOT NULL, - is_active INTEGER NOT NULL DEFAULT 1, - is_admin INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL, - last_login_at TEXT - ) - `); - - await runQuery(db, ` - CREATE TABLE roles ( - id TEXT PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - description TEXT NOT NULL, - is_built_in INTEGER NOT NULL DEFAULT 0, - created_at TEXT NOT NULL, - updated_at TEXT NOT NULL - ) - `); - - await runQuery(db, ` - CREATE TABLE user_roles ( - user_id TEXT NOT NULL, - role_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (user_id, role_id) - ) - `); - - await runQuery(db, ` - CREATE TABLE group_roles ( - group_id TEXT NOT NULL, - role_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (group_id, role_id) - ) - `); - - await runQuery(db, ` - CREATE TABLE user_groups ( - user_id TEXT NOT NULL, - group_id TEXT NOT NULL, - assigned_at TEXT NOT NULL, - PRIMARY KEY (user_id, group_id) - ) - `); - - await runQuery(db, ` - CREATE TABLE revoked_tokens ( - token TEXT PRIMARY KEY, - user_id TEXT NOT NULL, - revoked_at TEXT NOT NULL, - expires_at TEXT NOT NULL - ) - `); - - // Create brute force protection tables - await runQuery(db, ` - CREATE TABLE failed_login_attempts ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - username TEXT NOT NULL, - attempted_at TEXT NOT NULL, - ip_address TEXT, - reason TEXT - ) - `); - - await runQuery(db, ` - CREATE TABLE account_lockouts ( - username TEXT PRIMARY KEY, - lockout_type TEXT NOT NULL, - locked_at TEXT NOT NULL, - locked_until TEXT, - failed_attempts INTEGER NOT NULL DEFAULT 0, - last_attempt_at TEXT - ) - `); - - await runQuery(db, ` - CREATE TABLE login_attempt_counters ( - username TEXT PRIMARY KEY, - cumulative_failed_attempts INTEGER NOT NULL DEFAULT 0, - last_failed_at TEXT - ) - `); - - await runQuery(db, ` - CREATE TABLE config ( - key TEXT PRIMARY KEY, - value TEXT NOT NULL, - updated_at TEXT NOT NULL - ) - `); - - await runQuery(db, ` - INSERT INTO config (key, value, updated_at) VALUES - ('allow_self_registration', 'false', datetime('now')), - ('default_new_user_role', 'role-viewer-001', datetime('now')) - `); - - // Create test user - await db.execute('CREATE VIEW effective_user_roles AS SELECT user_id, role_id FROM user_roles'); + await initializeTestSchema(db); authService = new AuthenticationService(db, 'test-secret-key-for-route-tests-32chars'); const passwordHash = await authService.hashPassword(testPassword); diff --git a/backend/test/unit/ad-lab.test.ts b/backend/test/unit/ad-lab.test.ts new file mode 100644 index 00000000..47dab396 --- /dev/null +++ b/backend/test/unit/ad-lab.test.ts @@ -0,0 +1,90 @@ +import { describe, expect, it, vi } from 'vitest'; +import { randomBytes } from 'node:crypto'; +import type { Client, Entry } from 'ldapts'; +import { OwnedAdFixtures, validateAdBoundary } from '../fixtures/ldap/ad-lab'; +import type { AdLabConfig } from '../fixtures/ldap/ad-lab'; + +const parent = 'ou=Acceptance,dc=example,dc=test'; +function fixture() { + const entries = new Map(); + const client = { + add: vi.fn(async (dn: string, attributes: Record) => { + if (entries.has(dn)) throw new Error('Already exists'); + entries.set(dn, { dn, ...attributes, objectGUID: randomBytes(16) }); + }), + search: vi.fn(async (dn: string) => ({ searchEntries: entries.has(dn) ? [entries.get(dn)!] : [], searchReferences: [] })), + modify: vi.fn(async () => undefined), + modifyDN: vi.fn(async (dn: string, next: string) => { entries.set(next, { ...entries.get(dn)!, dn: next }); entries.delete(dn); }), + del: vi.fn(async (dn: string) => { entries.delete(dn); }), + }; + return { entries, client, owned: new OwnedAdFixtures(client as unknown as Client, parent) }; +} + +describe('AD lab mutation boundaries, synthetic local verification only', () => { + it('requires a child OU under a domain DN and parses escaped locators', () => { + const config = { baseDn: 'dc=example,dc=test', parentOu: parent, fixtureBindDn: 'cn=writer,' + parent, lookupBindDn: 'cn=reader,' + parent } as AdLabConfig; + expect(() => validateAdBoundary(config)).not.toThrow(); + for (const parentOu of [config.baseDn, 'ou=Acceptance,dc=elsewhere,dc=test', 'cn=Acceptance,dc=example,dc=test', 'ou=bad,']) { + expect(() => validateAdBoundary({ ...config, parentOu })).toThrow(); + } + }); + it('refuses mutation outside its exact generated children and refuses arbitrary attributes', async () => { + const { client, owned } = fixture(); + for (const dn of [parent, 'cn=external,' + parent, 'cn=bad\\,cn=other,' + owned.ou]) { + await expect(owned.add(dn, { objectClass: 'user' })).rejects.toThrow(); + await expect(owned.replace(dn, 'member', [])).rejects.toThrow(); + await expect(owned.remove(dn)).rejects.toThrow(); + } + expect(client.add).not.toHaveBeenCalled(); + expect(client.modify).not.toHaveBeenCalled(); + expect(client.del).not.toHaveBeenCalled(); + const dn = owned.dn('user'); + await owned.add(dn, { objectClass: 'user' }); + await expect(owned.replace(dn, 'description', ['stolen'])).rejects.toThrow(); + expect(client.modify).not.toHaveBeenCalled(); + }); + it('preserves unowned, renamed and replaced objects while cleaning only its own ledger', async () => { + const { client, entries, owned } = fixture(); + await owned.add(owned.ou, { objectClass: 'organizationalUnit' }); + const dn = owned.dn('user'); + const guid = await owned.add(dn, { objectClass: 'user' }); + await owned.rename(dn, owned.dn('renamed')); + expect(entries.get(owned.dn('renamed'))!.objectGUID).toEqual(guid); + entries.get(owned.dn('renamed'))!.objectGUID = randomBytes(16); + entries.set('cn=external,' + parent, { dn: 'cn=external,' + parent, description: owned.marker }); + expect(await owned.cleanup()).toEqual({ status: 'failed', remaining: 1 }); + expect(client.del).toHaveBeenCalledTimes(1); + expect(entries.has(owned.dn('renamed'))).toBe(true); + expect(entries.has('cn=external,' + parent)).toBe(true); + }); + it('retains ambiguous failed creations and refuses cleanup after marker changes', async () => { + const { client, entries, owned } = fixture(); + const dn = owned.dn('user'); + await owned.add(dn, { objectClass: 'user' }); + entries.get(dn)!.description = 'foreign'; + expect(await owned.cleanup()).toEqual({ status: 'failed', remaining: 1 }); + expect(client.del).not.toHaveBeenCalled(); + }); + it('blocks further writes after cancellation while allowing bounded owned cleanup', async () => { + const { client, entries } = fixture(); + let cancelled = false; + const owned = new OwnedAdFixtures(client as unknown as Client, parent, () => undefined, + () => { if (cancelled) throw new Error('Cancelled'); }); + await owned.add(owned.dn('user'), { objectClass: 'user' }); + cancelled = true; + await expect(owned.replace(owned.dn('user'), 'member', [])).rejects.toThrow('Cancelled'); + await expect(owned.add(owned.dn('later'), { objectClass: 'user' })).rejects.toThrow('Cancelled'); + expect(client.modify).not.toHaveBeenCalled(); + expect(await owned.cleanup()).toEqual({ status: 'passed', remaining: 0 }); + expect(entries.size).toBe(0); + expect(owned.snapshot().objects).toEqual([]); + }); + it('cleans a creation even when the successful server write loses its response', async () => { + const { client, owned } = fixture(); + const add = client.add.getMockImplementation()!; + client.add.mockImplementationOnce(async (dn, attributes) => { await add(dn, attributes); throw new Error('Lost reply'); }); + await expect(owned.add(owned.dn('user'), { objectClass: 'user' })).rejects.toThrow(); + expect(await owned.cleanup()).toEqual({ status: 'passed', remaining: 0 }); + expect(client.del).toHaveBeenCalledTimes(1); + }); +}); diff --git a/backend/test/unit/cli/resetUserPassword.test.ts b/backend/test/unit/cli/resetUserPassword.test.ts new file mode 100644 index 00000000..bdafc6d7 --- /dev/null +++ b/backend/test/unit/cli/resetUserPassword.test.ts @@ -0,0 +1,142 @@ +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { SQLiteAdapter } from '../../../src/database/SQLiteAdapter'; +import { AuthenticationService } from '../../../src/services/AuthenticationService'; +import { AuditLoggingService } from '../../../src/services/AuditLoggingService'; +import { UserService } from '../../../src/services/UserService'; +import { validatePassword } from '../../../src/utils/passwordValidation'; +import { generatePassword, resetUserPassword } from '../../../src/cli/resetUserPassword'; +import { parseArgs } from '../../../src/cli/reset-password'; +import { initializeTestSchema } from '../../helpers/schema'; + +const OLD_PASSWORD = 'OldPass123!'; // pragma: allowlist secret +const NEW_PASSWORD = 'NewPass456@'; // pragma: allowlist secret + +describe('resetUserPassword', () => { + let db: SQLiteAdapter; + let authService: AuthenticationService; + let userService: UserService; + let auditLogger: AuditLoggingService; + let userId: string; + + const deps = () => ({ db, userService, authService, auditLogger }); + + beforeEach(async () => { + db = new SQLiteAdapter(':memory:'); + await db.initialize(); + await initializeTestSchema(db); + auditLogger = new AuditLoggingService(db); + authService = new AuthenticationService(db, 'test-secret-test-secret-test-secret', auditLogger); + userService = new UserService(db, authService); + const user = await userService.createUser({ + username: 'admin', + email: 'admin@example.com', + password: OLD_PASSWORD, + firstName: 'Ad', + lastName: 'Min', + isActive: true, + isAdmin: true, + }); + userId = user.id; + }); + + afterEach(async () => { + await db.close(); + }); + + it('sets the new password, which verifies, and invalidates the old one', async () => { + await resetUserPassword(deps(), { username: 'admin', password: NEW_PASSWORD }); + const user = await userService.getUserById(userId); + expect(await authService.verifyPassword(NEW_PASSWORD, user!.passwordHash)).toBe(true); + expect(await authService.verifyPassword(OLD_PASSWORD, user!.passwordHash)).toBe(false); + }); + + it('rotates the session version so issued tokens are revoked', async () => { + const before = await db.queryOne<{ v: string }>('SELECT session_version AS v FROM users WHERE id = ?', [userId]); + await resetUserPassword(deps(), { username: 'admin', password: NEW_PASSWORD }); + const after = await db.queryOne<{ v: string }>('SELECT session_version AS v FROM users WHERE id = ?', [userId]); + expect(after!.v).not.toBe(before!.v); + }); + + it('clears lockouts and failed-login counters', async () => { + const now = new Date().toISOString(); + await db.execute( + `INSERT INTO account_lockouts (username, lockout_type, locked_at, locked_until, failed_attempts, last_attempt_at) + VALUES (?, 'permanent', ?, NULL, 5, ?)`, + ['admin', now, now], + ); + await db.execute( + 'INSERT INTO login_attempt_counters (username, cumulative_failed_attempts, last_failed_at) VALUES (?, 7, ?)', + ['admin', now], + ); + await resetUserPassword(deps(), { username: 'admin', password: NEW_PASSWORD }); + expect(await db.query('SELECT 1 FROM account_lockouts WHERE username = ?', ['admin'])).toHaveLength(0); + expect(await db.query('SELECT 1 FROM login_attempt_counters WHERE username = ?', ['admin'])).toHaveLength(0); + }); + + it('writes an audit entry that does not contain the password', async () => { + await resetUserPassword(deps(), { username: 'admin', password: NEW_PASSWORD, invokedBy: 'root' }); + const rows = await db.query<{ action: string; details: string }>( + 'SELECT "action", details FROM audit_logs WHERE "action" = ?', + ['cli_password_reset'], + ); + expect(rows).toHaveLength(1); + expect(rows[0].details).toContain('root'); + expect(rows[0].details).not.toContain(NEW_PASSWORD); + }); + + it('rejects a weak password and leaves the account untouched', async () => { + const before = await userService.getUserById(userId); + await expect(resetUserPassword(deps(), { username: 'admin', password: 'weak' })) + .rejects.toThrow('Password validation failed'); + const after = await userService.getUserById(userId); + expect(after!.passwordHash).toBe(before!.passwordHash); + }); + + it('fails for an unknown user', async () => { + await expect(resetUserPassword(deps(), { username: 'nobody', password: NEW_PASSWORD })) + .rejects.toThrow('User not found: nobody'); + }); + + it('does not reactivate a disabled account unless asked', async () => { + await db.execute('UPDATE users SET is_active = 0 WHERE id = ?', [userId]); + const plain = await resetUserPassword(deps(), { username: 'admin', password: NEW_PASSWORD }); + expect(plain.reactivated).toBe(false); + expect((await userService.getUserById(userId))!.isActive).toBe(0); + + const activated = await resetUserPassword(deps(), { username: 'admin', password: NEW_PASSWORD, activate: true }); + expect(activated.reactivated).toBe(true); + expect((await userService.getUserById(userId))!.isActive).toBe(1); + }); +}); + +describe('generatePassword', () => { + it('always satisfies the password policy and is not constant', () => { + const seen = new Set(); + for (let i = 0; i < 200; i++) { + const p = generatePassword(); + expect(validatePassword(p).valid).toBe(true); + seen.add(p); + } + expect(seen.size).toBe(200); + }); +}); + +describe('parseArgs', () => { + it('defaults to admin with prompt mode', () => { + expect(parseArgs([])).toMatchObject({ username: 'admin', generate: false, passwordStdin: false, activate: false }); + }); + + it('parses flags', () => { + expect(parseArgs(['--username', 'bob', '--generate', '--activate'])) + .toMatchObject({ username: 'bob', generate: true, activate: true }); + }); + + it('rejects unknown args, including a password on the command line', () => { + expect(() => parseArgs(['--password', 'x'])).toThrow('Unknown argument'); + }); + + it('rejects conflicting modes and missing values', () => { + expect(() => parseArgs(['--generate', '--password-stdin'])).toThrow('mutually exclusive'); + expect(() => parseArgs(['--username'])).toThrow('requires a value'); + }); +}); diff --git a/backend/test/unit/integrations/CircuitBreaker.test.ts b/backend/test/unit/integrations/CircuitBreaker.test.ts new file mode 100644 index 00000000..d4467162 --- /dev/null +++ b/backend/test/unit/integrations/CircuitBreaker.test.ts @@ -0,0 +1,79 @@ +/** + * Unit tests for CircuitBreaker + * + * Covers consecutive-failure semantics while closed (issue #59). + */ + +import { describe, it, expect, beforeEach } from "vitest"; +import { + CircuitBreaker, + CircuitBreakerOpenError, +} from "../../../src/integrations/puppetdb/CircuitBreaker"; + +describe("CircuitBreaker", () => { + let breaker: CircuitBreaker; + + beforeEach(() => { + breaker = new CircuitBreaker({ + failureThreshold: 3, + resetTimeout: 1000, + }); + }); + + describe("failure counting while closed", () => { + it("opens after consecutive failures reach the threshold", async () => { + const fail = async (): Promise => { + throw new Error("boom"); + }; + + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + expect(breaker.getState()).toBe("closed"); + + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + expect(breaker.getState()).toBe("open"); + expect(breaker.getStats().failureCount).toBe(3); + }); + + it("resets failureCount on success while closed so sparse failures do not trip", async () => { + const fail = async (): Promise => { + throw new Error("boom"); + }; + const succeed = async (): Promise => "ok"; + + // Two failures, then a success (still under threshold) + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + expect(breaker.getStats().failureCount).toBe(2); + + await expect(breaker.execute(succeed)).resolves.toBe("ok"); + expect(breaker.getState()).toBe("closed"); + expect(breaker.getStats().failureCount).toBe(0); + + // Two more failures after the success must not open the circuit + // (would have been 4 cumulative without the reset) + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + expect(breaker.getState()).toBe("closed"); + expect(breaker.getStats().failureCount).toBe(2); + + // A third consecutive failure does open it + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + expect(breaker.getState()).toBe("open"); + }); + + it("rejects requests while open", async () => { + const fail = async (): Promise => { + throw new Error("boom"); + }; + + for (let i = 0; i < 3; i++) { + await expect(breaker.execute(fail)).rejects.toThrow("boom"); + } + + await expect(breaker.execute(async () => "ok")).rejects.toThrow( + CircuitBreakerOpenError, + ); + }); + }); +}); diff --git a/backend/test/unit/mcp/McpServiceUser.test.ts b/backend/test/unit/mcp/McpServiceUser.test.ts index 96a443ca..fc30055f 100644 --- a/backend/test/unit/mcp/McpServiceUser.test.ts +++ b/backend/test/unit/mcp/McpServiceUser.test.ts @@ -1,9 +1,12 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { provisionMcpServiceUser } from '../../../src/mcp/McpServiceUser'; -import type { UserService } from '../../../src/services/UserService'; -import type { RoleService } from '../../../src/services/RoleService'; -import type { PermissionService } from '../../../src/services/PermissionService'; +import { UserService } from '../../../src/services/UserService'; +import { RoleService } from '../../../src/services/RoleService'; +import { PermissionService } from '../../../src/services/PermissionService'; import type { LoggerService } from '../../../src/services/LoggerService'; +import { AuthenticationService } from '../../../src/services/AuthenticationService'; +import { SQLiteAdapter } from '../../../src/database/SQLiteAdapter'; +import { initializeTestSchema } from '../../helpers/schema'; function createMockLogger(): LoggerService { return { @@ -27,6 +30,7 @@ function createMockUserService(overrides: Partial = {}): UserServic function createMockRoleService(overrides: Partial = {}): RoleService { return { createRole: vi.fn().mockResolvedValue({ id: 'role-1', name: 'MCP Service' }), + getRoleByName: vi.fn().mockResolvedValue(null), assignPermissionToRole: vi.fn().mockResolvedValue(undefined), ...overrides, } as unknown as RoleService; @@ -54,7 +58,7 @@ describe('provisionMcpServiceUser', () => { logger = createMockLogger(); }); - describe('first run — user does not exist', () => { + describe('first run: user does not exist', () => { it('should create user, role, assign permissions, and assign role', async () => { const userService = createMockUserService(); const roleService = createMockRoleService(); @@ -98,7 +102,7 @@ describe('provisionMcpServiceUser', () => { }); }); - describe('idempotency — user already exists', () => { + describe('idempotency: user already exists', () => { it('should reuse existing user and role without modification', async () => { const userService = createMockUserService({ getUserByUsername: vi.fn().mockResolvedValue({ id: 'existing-user', username: 'mcp-service' }), @@ -123,7 +127,7 @@ describe('provisionMcpServiceUser', () => { expect(userService.assignRoleToUser).not.toHaveBeenCalled(); }); - it('should throw if user exists but MCP Service role is missing', async () => { + it('should repair an existing user when MCP Service role is missing', async () => { const userService = createMockUserService({ getUserByUsername: vi.fn().mockResolvedValue({ id: 'existing-user', username: 'mcp-service' }), getUserRoles: vi.fn().mockResolvedValue([ @@ -135,7 +139,132 @@ describe('provisionMcpServiceUser', () => { await expect( provisionMcpServiceUser(userService, roleService, permissionService, logger), - ).rejects.toThrow('MCP service user exists but MCP Service role not found'); + ).resolves.toEqual({ userId: 'existing-user', roleId: 'role-1' }); + expect(userService.createUser).not.toHaveBeenCalled(); + expect(roleService.createRole).toHaveBeenCalledOnce(); + expect(roleService.assignPermissionToRole).toHaveBeenCalledTimes(2); + expect(userService.assignRoleToUser).toHaveBeenCalledWith('existing-user', 'role-1'); + }); + + it('should restore a missing assignment without changing existing role permissions', async () => { + const userService = createMockUserService({ + getUserByUsername: vi.fn().mockResolvedValue({ id: 'existing-user', username: 'mcp-service' }), + }); + const roleService = createMockRoleService({ + getRoleByName: vi.fn().mockResolvedValue({ id: 'existing-role', name: 'MCP Service' }), + }); + const permissionService = createMockPermissionService(); + + await expect( + provisionMcpServiceUser(userService, roleService, permissionService, logger), + ).resolves.toEqual({ userId: 'existing-user', roleId: 'existing-role' }); + expect(userService.createUser).not.toHaveBeenCalled(); + expect(roleService.createRole).not.toHaveBeenCalled(); + expect(permissionService.listPermissions).not.toHaveBeenCalled(); + expect(roleService.assignPermissionToRole).not.toHaveBeenCalled(); + expect(userService.assignRoleToUser).toHaveBeenCalledWith('existing-user', 'existing-role'); + }); + + it('should reuse an existing role when creating a missing user', async () => { + const userService = createMockUserService(); + const roleService = createMockRoleService({ + getRoleByName: vi.fn().mockResolvedValue({ id: 'existing-role', name: 'MCP Service' }), + }); + const permissionService = createMockPermissionService(); + + await expect( + provisionMcpServiceUser(userService, roleService, permissionService, logger), + ).resolves.toEqual({ userId: 'user-1', roleId: 'existing-role' }); + expect(userService.createUser).toHaveBeenCalledOnce(); + expect(roleService.createRole).not.toHaveBeenCalled(); + expect(permissionService.listPermissions).not.toHaveBeenCalled(); + expect(userService.assignRoleToUser).toHaveBeenCalledWith('user-1', 'existing-role'); }); }); }); + +describe('provisionMcpServiceUser with persisted RBAC state', () => { + let db: SQLiteAdapter; + let userService: UserService; + let roleService: RoleService; + let permissionService: PermissionService; + let logger: LoggerService; + + beforeEach(async () => { + db = new SQLiteAdapter(':memory:'); + await db.initialize(); + await initializeTestSchema(db); + const authService = new AuthenticationService(db, 'test-mcp-secret'); // pragma: allowlist secret + userService = new UserService(db, authService); + roleService = new RoleService(db); + permissionService = new PermissionService(db); + logger = createMockLogger(); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await db.close(); + }); + + it('should recover on restart after role creation fails with the user already persisted', async () => { + vi.spyOn(roleService, 'createRole').mockRejectedValueOnce(new Error('Interrupted role creation')); + + await expect( + provisionMcpServiceUser(userService, roleService, permissionService, logger), + ).rejects.toThrow('Interrupted role creation'); + const user = await userService.getUserByUsername('mcp-service'); + expect(user).not.toBeNull(); + + const result = await provisionMcpServiceUser(userService, roleService, permissionService, logger); + + expect(result.userId).toBe(user?.id); + expect(await userService.getUserRoles(result.userId)).toEqual( + expect.arrayContaining([expect.objectContaining({ id: result.roleId, name: 'MCP Service' })]), + ); + const permissions = await roleService.getRolePermissions(result.roleId); + const readPermissions = await permissionService.listPermissions({ action: 'read', limit: 1000 }); + expect(permissions.map((permission) => permission.id).sort()).toEqual( + readPermissions.items.map((permission) => permission.id).sort(), + ); + await expect( + provisionMcpServiceUser(userService, roleService, permissionService, logger), + ).resolves.toEqual(result); + }); + + it('should recover on restart after role assignment fails', async () => { + vi.spyOn(userService, 'assignRoleToUser').mockRejectedValueOnce(new Error('Interrupted role assignment')); + + await expect( + provisionMcpServiceUser(userService, roleService, permissionService, logger), + ).rejects.toThrow('Interrupted role assignment'); + const role = await roleService.getRoleByName('MCP Service'); + expect(role).not.toBeNull(); + + const result = await provisionMcpServiceUser(userService, roleService, permissionService, logger); + + expect(result.roleId).toBe(role?.id); + expect(await userService.getUserRoles(result.userId)).toEqual( + expect.arrayContaining([expect.objectContaining({ id: result.roleId })]), + ); + await expect( + provisionMcpServiceUser(userService, roleService, permissionService, logger), + ).resolves.toEqual(result); + }); + + it('should preserve customized permissions when reusing an unassigned role', async () => { + const role = await roleService.createRole({ + name: 'MCP Service', description: 'Restricted machine access', isBuiltIn: true, + }); + const readPermissions = await permissionService.listPermissions({ action: 'read', limit: 1000 }); + await roleService.assignPermissionToRole(role.id, readPermissions.items[0].id); + const permissions = await roleService.getRolePermissions(role.id); + + const result = await provisionMcpServiceUser(userService, roleService, permissionService, logger); + + expect(result.roleId).toBe(role.id); + expect(await roleService.getRolePermissions(role.id)).toEqual(permissions); + expect(await userService.getUserRoles(result.userId)).toEqual( + expect.arrayContaining([expect.objectContaining({ id: role.id })]), + ); + }); +}); diff --git a/backend/test/unit/services/EntraIdService.test.ts b/backend/test/unit/services/EntraIdService.test.ts index 5c061090..45957076 100644 --- a/backend/test/unit/services/EntraIdService.test.ts +++ b/backend/test/unit/services/EntraIdService.test.ts @@ -220,7 +220,7 @@ describe('EntraIdService', () => { describe('provisionUser()', () => { let mockUserService: { findByFederatedIdentity: ReturnType; - findByEmail: ReturnType; + findAllByEmail: ReturnType; createFederatedUser: ReturnType; linkFederatedIdentity: ReturnType; }; @@ -231,6 +231,8 @@ describe('EntraIdService', () => { username: 'testuser', email: 'test@example.com', passwordHash: 'hashed', + localAuthEnabled: 1, + displayName: null, firstName: 'Test', lastName: 'User', isActive: 1, @@ -255,7 +257,7 @@ describe('EntraIdService', () => { beforeEach(() => { mockUserService = { findByFederatedIdentity: vi.fn().mockResolvedValue(null), - findByEmail: vi.fn().mockResolvedValue(null), + findAllByEmail: vi.fn().mockResolvedValue([]), createFederatedUser: vi.fn().mockResolvedValue(baseUser), linkFederatedIdentity: vi.fn().mockResolvedValue({ id: 'fed-id-1', @@ -308,11 +310,11 @@ describe('EntraIdService', () => { // Must not call create or link expect(mockUserService.createFederatedUser).not.toHaveBeenCalled(); expect(mockUserService.linkFederatedIdentity).not.toHaveBeenCalled(); - expect(mockUserService.findByEmail).not.toHaveBeenCalled(); + expect(mockUserService.findAllByEmail).not.toHaveBeenCalled(); }); it('rejects an email collision without linking or creating an account', async () => { - mockUserService.findByEmail.mockResolvedValue(baseUser); + mockUserService.findAllByEmail.mockResolvedValue([baseUser]); await expect(provisionService.provisionUser(baseClaims)).rejects.toMatchObject({ code: 'IDENTITY_COLLISION' }); expect(mockUserService.linkFederatedIdentity).not.toHaveBeenCalled(); expect(mockUserService.createFederatedUser).not.toHaveBeenCalled(); @@ -320,7 +322,7 @@ describe('EntraIdService', () => { it('creates new federated user when no match found', async () => { mockUserService.findByFederatedIdentity.mockResolvedValue(null); - mockUserService.findByEmail.mockResolvedValue(null); + mockUserService.findAllByEmail.mockResolvedValue([]); const newUser = { ...baseUser, id: 'new-user-456' }; mockUserService.createFederatedUser.mockResolvedValue(newUser); @@ -328,12 +330,17 @@ describe('EntraIdService', () => { const result = await provisionService.provisionUser(baseClaims); expect(result).toBe(newUser); - expect(mockUserService.createFederatedUser).toHaveBeenCalledWith(baseClaims); + expect(mockUserService.createFederatedUser).toHaveBeenCalledWith({ + provider: 'entra-id', issuer: baseClaims.iss, subject: baseClaims.sub, + username: baseClaims.preferred_username, email: baseClaims.email || null, + displayName: null, firstName: baseClaims.given_name, lastName: baseClaims.family_name, + defaultRole: 'configured', + }); }); it('wraps createFederatedUser errors as PROVISIONING_FAILED', async () => { mockUserService.findByFederatedIdentity.mockResolvedValue(null); - mockUserService.findByEmail.mockResolvedValue(null); + mockUserService.findAllByEmail.mockResolvedValue([]); mockUserService.createFederatedUser.mockRejectedValue( new Error('UNIQUE constraint failed: users.username'), ); @@ -346,12 +353,17 @@ describe('EntraIdService', () => { it('proceeds to createFederatedUser when email is present but no email match', async () => { mockUserService.findByFederatedIdentity.mockResolvedValue(null); - mockUserService.findByEmail.mockResolvedValue(null); + mockUserService.findAllByEmail.mockResolvedValue([]); await provisionService.provisionUser(baseClaims); - expect(mockUserService.findByEmail).toHaveBeenCalledWith(baseClaims.email); - expect(mockUserService.createFederatedUser).toHaveBeenCalledWith(baseClaims); + expect(mockUserService.findAllByEmail).toHaveBeenCalledWith(baseClaims.email); + expect(mockUserService.createFederatedUser).toHaveBeenCalledWith({ + provider: 'entra-id', issuer: baseClaims.iss, subject: baseClaims.sub, + username: baseClaims.preferred_username, email: baseClaims.email || null, + displayName: null, firstName: baseClaims.given_name, lastName: baseClaims.family_name, + defaultRole: 'configured', + }); }); it('skips email lookup and creates user when email is empty but preferred_username is present', async () => { @@ -365,14 +377,19 @@ describe('EntraIdService', () => { await provisionService.provisionUser(claims); - // findByEmail should not be called with empty string - expect(mockUserService.findByEmail).not.toHaveBeenCalled(); - expect(mockUserService.createFederatedUser).toHaveBeenCalledWith(claims); + // findAllByEmail should not be called with empty string + expect(mockUserService.findAllByEmail).not.toHaveBeenCalled(); + expect(mockUserService.createFederatedUser).toHaveBeenCalledWith({ + provider: 'entra-id', issuer: claims.iss, subject: claims.sub, + username: claims.preferred_username, email: claims.email || null, + displayName: null, firstName: claims.given_name, lastName: claims.family_name, + defaultRole: 'configured', + }); }); it('logs provisioning actions without exposing tokens or secrets', async () => { mockUserService.findByFederatedIdentity.mockResolvedValue(null); - mockUserService.findByEmail.mockResolvedValue(null); + mockUserService.findAllByEmail.mockResolvedValue([]); await provisionService.provisionUser(baseClaims); diff --git a/backend/test/unit/services/LdapDirectoryService.test.ts b/backend/test/unit/services/LdapDirectoryService.test.ts new file mode 100644 index 00000000..62886c66 --- /dev/null +++ b/backend/test/unit/services/LdapDirectoryService.test.ts @@ -0,0 +1,332 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { Entry } from 'ldapts'; +import { BerWriter, InappropriateMatchingError, InvalidCredentialsError, SizeLimitExceededError } from 'ldapts'; +import { parseLdapConfig } from '../../../src/config/ldap'; +import { LdapDirectoryService } from '../../../src/services/LdapDirectoryService'; +import { LoggerService } from '../../../src/services/LoggerService'; +import type { LdapConnection, LdapConnector } from '../../../src/services/ldap/transport'; +import { canonicalUuid, guidToSubject, subjectToGuid } from '../../../src/services/ldap/identity'; +import { adPolicyAttributes, checkAdEligibility } from '../../../src/services/ldap/policy'; +import { verifyLdapHostname } from '../../../src/services/ldap/transport'; +import type { PeerCertificate } from 'node:tls'; + +const subject = '00112233-4455-6677-8899-aabbccddeeff'; +const guidHex = '33221100554477668899aabbccddeeff'; // pragma: allowlist secret (GUID codec vector) +const groupId = '10112233-4455-6677-8899-aabbccddeeff'; +const parentId = '20112233-4455-6677-8899-aabbccddeeff'; +const replacement = '30112233-4455-6677-8899-aabbccddeeff'; +const fixturePassword = 'fixture-user'; // pragma: allowlist secret +const config = parseLdapConfig({ + LDAP_ENABLED: 'true', LDAP_DIRECTORY_ID: 'test', LDAP_DIRECTORY_TYPE: 'openldap', + LDAP_HOSTNAME: 'ldap.example.test', LDAP_BASE_DN: 'dc=example,dc=test', + LDAP_USER_RDN: 'ou=people', LDAP_GROUP_RDN: 'ou=groups', + LDAP_USER_ELIGIBILITY_FILTER: '(employeeType=active)', LDAP_ANONYMOUS_LOOKUP: 'true', +})!; +const user: Entry = { dn: 'uid=alice,ou=people,dc=example,dc=test', uid: 'alice', entryUUID: subject }; +const group: Entry = { dn: 'cn=operators,ou=groups,dc=example,dc=test', cn: 'operators', entryUUID: groupId }; +const parent: Entry = { dn: 'cn=admins,ou=groups,dc=example,dc=test', cn: 'admins', entryUUID: parentId }; +const adUser: Entry = { + ...user, objectGUID: subjectToGuid(subject), sAMAccountName: 'alice', + userAccountControl: '512', 'msDS-User-Account-Control-Computed': '0', + accountExpires: '0', pwdLastSet: '133000000000000000', 'msDS-UserPasswordExpiryTimeComputed': '9223372036854775807', +}; + +function fixture(entries: (Entry[] | Error)[] = [[user], [user]]) { + const lookup: LdapConnection = { + bind: vi.fn().mockResolvedValue(undefined), + search: vi.fn().mockImplementation(async () => { + const next = entries.shift(); + if (next instanceof Error) throw next; + return { searchEntries: next ?? [], searchReferences: [] }; + }), close: vi.fn(), + }; + const userConnection: LdapConnection = { ...lookup, bind: vi.fn().mockResolvedValue(undefined), close: vi.fn() }; + const connect = vi.fn().mockResolvedValueOnce(lookup).mockResolvedValue(userConnection); + const logger = new LoggerService('error'); + const warn = vi.spyOn(logger, 'warn'); + return { lookup, userConnection, connect, logger, warn, + service: new LdapDirectoryService(config, logger, connect) }; +} +afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks(); }); + +describe('immutable LDAP identities and AD policy', () => { + it('canonicalizes UUIDs and round-trips little-endian binary AD GUIDs', () => { + expect(subjectToGuid(subject).toString('hex')).toBe(guidHex); + expect(guidToSubject(Buffer.from(guidHex, 'hex'))).toBe(subject); + expect(canonicalUuid(subject.toUpperCase())).toBe(subject); + for (const input of ['', 'uid=alice', '00000000-0000-0000-0000-000000000000']) { + expect(() => canonicalUuid(input)).toThrow(); + } + expect(() => guidToSubject(Buffer.alloc(15))).toThrow(); + }); + + it('uses FILETIME sentinel values and computed lockout/password-expiry bits', () => { + expect(() => checkAdEligibility(adUser)).not.toThrow(); + expect(() => checkAdEligibility({ ...adUser, accountExpires: '9223372036854775807' })).not.toThrow(); + for (const change of [ + { userAccountControl: '514' }, { 'msDS-User-Account-Control-Computed': '16' }, + { 'msDS-User-Account-Control-Computed': '8388608' }, { accountExpires: '1' }, + { pwdLastSet: '0' }, { 'msDS-UserPasswordExpiryTimeComputed': '1' }, + { 'msDS-UserPasswordExpiryTimeComputed': '0' }, + ]) expect(() => checkAdEligibility({ ...adUser, ...change })).toThrow('INELIGIBLE'); + for (const name of adPolicyAttributes) { + const incomplete = { ...adUser }; + delete incomplete[name]; + expect(() => checkAdEligibility(incomplete)).toThrow('POLICY_UNREADABLE'); + } + expect(() => checkAdEligibility({ ...adUser, accountExpires: 'not-an-integer' })).toThrow('POLICY_UNREADABLE'); + }); + + it('applies normal hostname validation and the additional wildcard restriction', () => { + const cert = { subject: { CN: '*.example.test' }, subjectaltname: 'DNS:*.example.test' } as PeerCertificate; + expect(verifyLdapHostname('ldap.example.test', cert, false)).toBeInstanceOf(Error); + expect(verifyLdapHostname('ldap.example.test', cert, true)).toBeUndefined(); + expect(verifyLdapHostname('other.test', cert, true)).toBeInstanceOf(Error); + expect(verifyLdapHostname('ldap.example.test', { + subjectaltname: 'DNS:ldap.example.test, DNS:*.unrelated.test', + } as PeerCertificate, false)).toBeUndefined(); + }); +}); + +describe('read-only LDAP directory transactions', () => { + it('diagnoses lookup, immutable identity, eligibility and selected membership without a user bind or personal fields', async () => { + const f = fixture([[user], [user], [group], [group]]); + const result = await f.service.diagnose({ username: 'alice', groupSubjects: [groupId] }); + expect(result.authenticated).toBe(false); + expect(result.groupSubjects).toEqual([groupId]); + expect(result.stages.map(stage => [stage.stage, stage.status])).toEqual([ + ['tls', 'passed'], ['lookup', 'passed'], ['identity', 'passed'], ['eligibility', 'passed'], ['groups', 'passed'], + ]); + expect(f.connect).toHaveBeenCalledTimes(1); + expect(f.userConnection.bind).not.toHaveBeenCalled(); + expect(JSON.stringify(result)).not.toMatch(/alice|uid=|email|fixture-user/); + const filters = vi.mocked(f.lookup.search).mock.calls.map(call => String(call[1].filter)); + expect(filters[0]).not.toContain('employeeType'); + expect(filters[1]).toContain('employeeType'); + expect(f.lookup.close).toHaveBeenCalled(); + }); + + it('distinguishes absent identity, ineligible policy and unreadable AD policy in restricted diagnostics', async () => { + const absent = await fixture([[]]).service.diagnose({ username: 'absent' }); + expect(absent.stages.at(-1)).toMatchObject({ stage: 'identity', status: 'failed', code: 'INVALID_IDENTITY' }); + const inactive = await fixture([[user], []]).service.diagnose({ username: 'alice' }); + expect(inactive.stages.at(-1)).toMatchObject({ stage: 'eligibility', status: 'failed', code: 'INELIGIBLE' }); + const f = fixture([[adUser], [{ ...adUser, pwdLastSet: [] }]]); + const ad = new LdapDirectoryService({ ...config, directoryType: 'ad', userIdAttr: 'objectGUID' }, f.logger, f.connect); + const unreadable = await ad.diagnose({ username: 'alice' }); + expect(unreadable.stages.at(-1)).toMatchObject({ stage: 'eligibility', status: 'failed', code: 'POLICY_UNREADABLE' }); + }); + + it('redacts raw TLS and lookup failures and returns no partial membership diagnostics', async () => { + const f = fixture(); + f.connect.mockReset().mockRejectedValue(new Error('private endpoint and secret')); + const tls = await f.service.diagnose({}); + expect(tls.stages).toEqual([{ stage: 'tls', status: 'failed', code: 'UNAVAILABLE', durationMs: expect.any(Number) }]); + const bound = fixture(); + vi.mocked(bound.lookup.bind).mockRejectedValue(new InvalidCredentialsError('private lookup password')); + const lookup = await bound.service.diagnose({}); + expect(lookup.stages.at(-1)).toMatchObject({ stage: 'lookup', status: 'failed', code: 'UNAVAILABLE' }); + const limited = fixture([[user], [user], [group], new SizeLimitExceededError('private server message')]); + const result = await limited.service.diagnose({ username: 'alice', groupSubjects: [groupId] }); + expect(result.groupSubjects).toBeUndefined(); + expect(result.stages.at(-1)).toMatchObject({ stage: 'groups', status: 'failed' }); + expect(JSON.stringify([tls, lookup, result])).not.toContain('private'); + }); + + it('bounds diagnostic deadlines and closes lookup sockets without granting authentication', async () => { + vi.useFakeTimers(); + const f = fixture(); + vi.mocked(f.lookup.search).mockImplementation(() => new Promise(() => {})); + const pending = f.service.diagnose({ username: 'alice' }); + await vi.advanceTimersByTimeAsync(config.requestTimeoutSeconds * 1000 + 1); + const result = await pending; + expect(result.stages.at(-1)).toMatchObject({ status: 'failed', code: 'TIMEOUT' }); + expect(result.authenticated).toBe(false); + expect(f.lookup.close).toHaveBeenCalled(); + }); + + it('isolates the user bind, rereads identity and returns explicit mapped direct membership', async () => { + const f = fixture([[user], [user], [group]]); + expect(await f.service.authenticate('alice', fixturePassword, [groupId, parentId])).toEqual({ + user: { subject, dn: user.dn, loginName: 'alice', displayName: 'alice', email: null, firstName: '', lastName: '' }, + groupSubjects: [groupId], + }); + expect(f.lookup.bind).toHaveBeenCalledExactlyOnceWith('', ''); + expect(f.userConnection.bind).toHaveBeenCalledExactlyOnceWith(user.dn, fixturePassword); + expect(f.connect).toHaveBeenCalledTimes(2); + expect(f.userConnection.close).toHaveBeenCalled(); + expect(f.lookup.close).toHaveBeenCalled(); + const filters = vi.mocked(f.lookup.search).mock.calls.map(call => String(call[1].filter)); + expect(filters[0]).toContain('(employeeType=\\61\\63\\74\\69\\76\\65)'); + expect(filters[0]).toContain('(uid=alice)'); + expect(filters[2]).toContain('(uniqueMember='); + }); + + it('preserves UTF-8 runtime values in typed filters', async () => { + const f = fixture(); + await f.service.authenticate('é-user', fixturePassword); + const filter = vi.mocked(f.lookup.search).mock.calls[0][1].filter; + if (!filter || typeof filter === 'string') throw new Error('Typed filter required'); + const writer = new BerWriter(); + filter.write(writer); + expect(writer.buffer.includes(Buffer.from('é-user', 'utf8'))).toBe(true); + }); + + it('never opens connections for empty passwords or oversized credential payloads', async () => { + const f = fixture(); + for (const [login, password] of [['alice', ''], ['', fixturePassword], ['a'.repeat(1025), fixturePassword], ['alice', 'p'.repeat(4097)]]) { + await expect(f.service.authenticate(login, password)).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + } + expect(f.connect).not.toHaveBeenCalled(); + }); + + it('preserves whitespace and escapes filter injection without broadening searches', async () => { + const f = fixture(); + await f.service.authenticate('*)(uid=*)', ' padded '); + expect(f.userConnection.bind).toHaveBeenCalledWith(user.dn, ' padded '); + expect(String(vi.mocked(f.lookup.search).mock.calls[0][1].filter)).toContain('\\2a\\29\\28uid=\\2a\\29'); + }); + + it.each([[], [user, user], [{ ...user, entryUUID: [] }]])('rejects missing, ambiguous or malformed immutable identities', async entries => { + const f = fixture([entries]); + await expect(f.service.authenticate('alice', fixturePassword)).rejects.toBeInstanceOf(Error); + expect(f.userConnection.bind).not.toHaveBeenCalled(); + }); + + it('rejects replacement objects after a correct bind', async () => { + const f = fixture([[user], [{ ...user, entryUUID: replacement }]]); + await expect(f.service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'IDENTITY_CHANGED' }); + }); + + it('treats disappearance or a moved locator during bind as a retryable identity change', async () => { + for (const after of [[], [{ ...user, dn: 'uid=moved,ou=people,dc=example,dc=test' }]]) { + const f = fixture([[user], after]); + await expect(f.service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'IDENTITY_CHANGED' }); + } + }); + + it('does not retry wrong user credentials on another endpoint or expose raw errors', async () => { + const f = fixture(); + vi.mocked(f.userConnection.bind).mockRejectedValue(new InvalidCredentialsError('unsafe server message')); + const service = new LdapDirectoryService({ ...config, failoverEndpoints: [{ hostname: 'other.test', port: 636 }] }, f.logger, f.connect); + await expect(service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'INVALID_CREDENTIALS' }); + expect(f.connect).toHaveBeenCalledTimes(2); + expect(JSON.stringify(f.warn.mock.calls)).not.toContain('unsafe server message'); + }); + + it('fails over connection establishment, but never retries lookup credentials', async () => { + const f = fixture(); + const connect = vi.fn().mockRejectedValueOnce(Object.assign(new Error('TCP unavailable'), { code: 'ECONNREFUSED' })) + .mockResolvedValueOnce(f.lookup).mockResolvedValue(f.userConnection); + const service = new LdapDirectoryService({ ...config, failoverEndpoints: [{ hostname: 'other.test', port: 636 }] }, f.logger, connect); + await service.authenticate('alice', fixturePassword); + expect(connect.mock.calls[1][1].hostname).toBe('other.test'); + expect(connect.mock.calls[2][1].hostname).toBe('other.test'); + vi.mocked(f.lookup.bind).mockRejectedValue(new InvalidCredentialsError()); + connect.mockClear().mockResolvedValue(f.lookup); + await expect(service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + expect(connect).toHaveBeenCalledTimes(1); + }); + + it('does not fail over TLS or protocol validation failures', async () => { + const f = fixture(); + const connect = vi.fn().mockRejectedValueOnce(Object.assign(new Error('private diagnostic'), { code: 'ERR_TLS_CERT_ALTNAME_INVALID' })) + .mockResolvedValue(f.lookup); + const service = new LdapDirectoryService({ ...config, failoverEndpoints: [{ hostname: 'other.test', port: 636 }] }, f.logger, connect); + await expect(service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'UNAVAILABLE' }); + expect(connect).toHaveBeenCalledOnce(); + }); + + it('treats ambiguous immutable revalidation as incomplete evidence, not positive revocation', async () => { + const f = fixture([[user, user]]); + await expect(f.service.revalidate(subject)).rejects.toMatchObject({ code: 'INCOMPLETE_RESULT' }); + }); + + it('revalidates by immutable subject without a user password or user bind', async () => { + const f = fixture([[{ ...user, uid: 'renamed', dn: 'uid=renamed,ou=people,dc=example,dc=test' }]]); + expect((await f.service.revalidate(subject)).user.loginName).toBe('renamed'); + expect(f.connect).toHaveBeenCalledTimes(1); + expect(String(vi.mocked(f.lookup.search).mock.calls[0][1].filter)).toContain('(entryUUID='); + }); + + it('traverses nested group cycles once and enforces depth and visit limits', async () => { + const f = fixture([[user], [user], [group], [parent], [group]]); + const service = new LdapDirectoryService({ ...config, searchNestedGroups: true }, f.logger, f.connect); + expect((await service.authenticate('alice', fixturePassword, [groupId, parentId])).groupSubjects).toEqual([groupId, parentId]); + const limited = fixture([[user], [user], [group], [parent]]); + await expect(new LdapDirectoryService({ ...config, searchNestedGroups: true, nestedGroupMaxDepth: 1 }, limited.logger, limited.connect) + .authenticate('alice', fixturePassword, [parentId])).rejects.toMatchObject({ code: 'LIMIT_EXCEEDED' }); + const visited = fixture([[user], [user], [group, parent]]); + await expect(new LdapDirectoryService({ ...config, groupTraversalLimit: 1 }, visited.logger, visited.connect) + .authenticate('alice', fixturePassword, [groupId])).rejects.toMatchObject({ code: 'LIMIT_EXCEEDED' }); + }); + + it('denies partial/referral and server-limited searches', async () => { + const f = fixture(); + vi.mocked(f.lookup.search).mockResolvedValue({ searchEntries: [user], searchReferences: ['ldap://elsewhere.test'] }); + await expect(f.service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'INCOMPLETE_RESULT' }); + const limited = fixture([new SizeLimitExceededError()]); + await expect(limited.service.authenticate('alice', fixturePassword)).rejects.toMatchObject({ code: 'LIMIT_EXCEEDED' }); + }); + + it('bounds group search and resolves immutable identities in the configured scope', async () => { + const f = fixture([[group], [group]]); + expect(await f.service.searchGroups('op*')).toEqual([{ subject: groupId, dn: group.dn, name: 'operators' }]); + expect(vi.mocked(f.lookup.search).mock.calls[0][1]).toMatchObject({ sizeLimit: 100, paged: false, derefAliases: 'never' }); + expect(String(vi.mocked(f.lookup.search).mock.calls[0][1].filter)).toContain('*op\\2a*'); + // A second independent transaction requires a fresh lookup connection. + const g = fixture([[group]]); + expect(await g.service.resolveGroup(groupId)).toEqual({ subject: groupId, dn: group.dn, name: 'operators' }); + const outside = fixture([[{ ...group, dn: 'cn=operators,ou=outside,dc=example,dc=test' }]]); + await expect(outside.service.searchGroups('op')).rejects.toMatchObject({ code: 'INCOMPLETE_RESULT' }); + }); + + it('rejects unsupported optional UID suffixes in group membership', async () => { + const f = fixture([[{ ...group, uniqueMember: user.dn + "#'0101'B" }]]); + await expect(f.service.resolveGroup(groupId)).rejects.toMatchObject({ code: 'INCOMPLETE_RESULT' }); + }); + + it('uses binary AD GUID filters and required account-policy attributes', async () => { + const f = fixture([[adUser], [adUser]]); + const ad = { ...config, directoryType: 'ad' as const, userIdAttr: 'objectGUID', groupIdAttr: 'objectGUID', + userLookupAttr: 'sAMAccountName', userEligibilityFilter: '' }; + const service = new LdapDirectoryService(ad, f.logger, f.connect); + expect((await service.revalidate(subject)).user.subject).toBe(subject); + expect(vi.mocked(f.lookup.search).mock.calls[0][1]).toMatchObject({ explicitBufferAttributes: ['objectGUID', 'objectGUID'] }); + const filter = vi.mocked(f.lookup.search).mock.calls[0][1].filter; + if (!filter || typeof filter === 'string') throw new Error('Typed filter required'); + const writer = new BerWriter(); + filter.write(writer); + expect(writer.buffer.includes(subjectToGuid(subject))).toBe(true); + const bad = fixture([[{ ...adUser, objectGUID: subject }]]); + await expect(new LdapDirectoryService(ad, bad.logger, bad.connect).revalidate(subject)).rejects.toMatchObject({ code: 'INVALID_IDENTITY' }); + }); + + it('falls back from the AD chain check only on a definitive unsupported-rule response', async () => { + const adGroup = { ...group, objectGUID: subjectToGuid(groupId) }; + const f = fixture([[adUser], [adGroup], [], new InappropriateMatchingError()]); + const service = new LdapDirectoryService({ + ...config, directoryType: 'ad', userIdAttr: 'objectGUID', groupIdAttr: 'objectGUID', + userLookupAttr: 'sAMAccountName', groupMemberAttr: 'member', searchNestedGroups: true, + }, f.logger, f.connect); + expect((await service.revalidate(subject, [groupId])).groupSubjects).toEqual([groupId]); + expect(String(vi.mocked(f.lookup.search).mock.calls[3][1].filter)).toContain('1.2.840.113556.1.4.1941'); + }); + + it('rejects excess admission and aborts the entire transaction deadline', async () => { + vi.useFakeTimers(); + const f = fixture(); + let release!: (value: LdapConnection) => void; + const connect = vi.fn().mockImplementation(() => new Promise(resolve => { release = resolve; })); + const service = new LdapDirectoryService({ ...config, maxConcurrentOperations: 1, requestTimeoutSeconds: 1 }, f.logger, connect); + const first = service.revalidate(subject); + const rejected = expect(first).rejects.toMatchObject({ code: 'TIMEOUT' }); + await expect(service.revalidate(subject)).rejects.toMatchObject({ code: 'BUSY' }); + await vi.advanceTimersByTimeAsync(1000); + await rejected; + expect(connect.mock.calls[0][2].aborted).toBe(true); + release(f.lookup); + await Promise.resolve(); + expect(f.lookup.close).toHaveBeenCalled(); + }); +}); diff --git a/charts/pabawi/Chart.yaml b/charts/pabawi/Chart.yaml index 28a1cb26..bab84b03 100644 --- a/charts/pabawi/Chart.yaml +++ b/charts/pabawi/Chart.yaml @@ -2,8 +2,8 @@ apiVersion: v2 name: pabawi description: Pabawi infrastructure management web UI type: application -version: 0.2.0 -appVersion: "1.5.0" +version: 0.2.1 +appVersion: "1.6.0" home: https://github.com/example42/pabawi sources: - https://github.com/example42/pabawi diff --git a/charts/pabawi/values.yaml b/charts/pabawi/values.yaml index daae6211..40af9341 100644 --- a/charts/pabawi/values.yaml +++ b/charts/pabawi/values.yaml @@ -6,6 +6,8 @@ revisionHistoryLimit: 10 image: repository: example42/pabawi pullPolicy: IfNotPresent + # Use batteries- when Bolt, Ansible, Puppet/OpenVox, or OpenSSH + # commands must run inside the pod. tag: "" imagePullSecrets: [] diff --git a/docker-compose.yml b/docker-compose.yml index 24ea002c..a047a9db 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,7 @@ services: app: - image: example42/pabawi:latest + # This example mounts Bolt and Ansible projects, so it uses the toolchain image. + image: example42/pabawi:batteries container_name: pabawi env_file: - .env diff --git a/docs/api.md b/docs/api.md index 2736f0e9..b95f7e48 100644 --- a/docs/api.md +++ b/docs/api.md @@ -23,6 +23,21 @@ JWT plus `rbac:admin` and `users:admin`. Refresh tokens work only at the refresh exchange. Generic inventory lifecycle requests also accept the scoped machine credential described below. `/mcp` has its own [authentication policy](mcp.md). +Access and refresh JWTs carry signed `authContext`: `{ "provider": "local", "identityId": null }` +or `{ "provider": "entra-id", "identityId": "" }`, or +`{ "provider": "ldap", "identityId": "", "directoryId": "" }`. The server checks local +authentication scope or exact identity ownership on issuance, verification and rotation. +Refresh preserves the authenticating identity even for an account enrolled in multiple providers. +Migration 032 intentionally invalidates existing account sessions, console credentials and pending +OAuth state/code exchanges once. Users must sign in again; legacy tokens without context are rejected. +LDAP sessions require current directory eligibility and at least one explicit role. Successful directory reads +remain usable for at most `LDAP_REVALIDATION_INTERVAL_SECONDS` from their start; every refresh forces a new +check, coalescing only overlapping work. REST, execution/journal SSE, MCP and console websockets use the same +eligibility boundary. Transient failures preserve grants and tokens but block stale access; recovery permits +valid tokens to resume. Confirmed ineligibility or loss of every role revokes existing LDAP sessions permanently. +Migration 034 preserves console rows and adds their exact authentication context. Legacy console rows lacking +that context cannot upgrade. Local and Entra sessions do not depend on directory availability. + The [OpenAPI contract](openapi.yaml) describes the REST subset tracked by [contract coverage](api-contract-coverage.md), including intentional omissions. @@ -768,6 +783,20 @@ All endpoints require access JWT authentication and appropriate RBAC permissions ### Users +User DTOs from authentication and user administration include nullable `email` +and `displayName` fields. Group member DTOs also allow a null `email`. External +contact email can be absent or shared across accounts; it never identifies an +account for linking. Local account creation still requires a unique local email +and username. The `ldap:` username prefix is reserved for directory accounts. +Password hashes are excluded from responses. Entra enrollment continues to +require explicit administrative authority and rejects implicit email linking. +LDAP-owned profile fields (email, given name, surname) and local password writes +are rejected with HTTP 403 and code `DIRECTORY_ACCOUNT_READ_ONLY` through +`PUT /api/users/:id` and `POST /api/auth/change-password`, including for +administrators. Directory password changes must be performed at the directory. +Local suspension, administrative status and manual role assignments remain +managed in Pabawi. LDAP login is available when configured. + | Method | Endpoint | Description | |---|---|---| | `POST` | `/api/users` | Create user | @@ -778,6 +807,34 @@ All endpoints require access JWT authentication and appropriate RBAC permissions | `POST` | `/api/users/:id/roles/:roleId` | Assign role to user | | `DELETE` | `/api/users/:id/roles/:roleId` | Remove role from user | +User list and detail responses include `authentication` administration metadata: + +```json +{ + "authentication": { + "profileReadOnly": true, + "sources": [{ + "provider": "ldap", + "name": "Corporate directory", + "directoryId": "corporate", + "loginName": "alice" + }] + } +} +``` + +Local and Entra sources use `provider: "local"` and `"entra-id"`. +LDAP names use the current directory display label, otherwise `LDAP`. +These fields appear only on existing `users:read` routes, not public discovery +or authentication user DTOs. No passwords, tokens, user DNs or immutable subjects appear. + +User details also include `roleSources`: an array of `{ roleId, source }` where +source is `manual`, `ldap` or `entra-id`. LDAP entries may include +`directoryId` and authoritative `groupName`. Multiple sources can refer to +one role; `roles` remains the effective union. Removing an assignment through +the user-role endpoint removes only its manual source. +See the [LDAP operator guide](integrations/ldap.md). + ### Roles | Method | Endpoint | Description | @@ -816,11 +873,29 @@ All endpoints require access JWT authentication and appropriate RBAC permissions | Method | Endpoint | Description | |---|---|---| | `POST` | `/api/auth/login` | Login, returns token, refreshToken and user | +| `POST` | `/api/auth/ldap/login` | Explicit LDAP password login; same successful DTO as local login | | `POST` | `/api/auth/refresh` | Rotate token pair using refreshToken in the body | | `POST` | `/api/auth/register` | Register when self-registration is enabled | | `POST` | `/api/auth/logout` | Logout (includes `entraIdLogoutUrl` for SSO sessions) | | `GET` | `/api/auth/providers` | Available auth methods (public, no auth required) | +LDAP login is available when `LDAP_ENABLED=true`; otherwise it returns 404. Submit +`{ "username": "", "password": "" }`. +Both fields must be nonempty, with UTF-8 limits of 1024 and 4096 bytes respectively. +The submitted case, login whitespace and password are preserved. Requests never fall through +to another provider. A failed or ambiguous credential check returns generic 401; a proven account +without access returns 403. Capacity or throttling returns 429, and unavailable/incomplete directory +validation returns 503 with safe error codes. Refresh and protected REST checks use the same temporary +unavailability semantics. Failed refresh validation leaves the inbound refresh token available for retry. + +The existing IP authentication limit includes LDAP. Failed credential counters use a separate +`ldap:` namespace with SHA-256 over the structured tuple `["ldap", directoryId, submittedLogin]`. +Five failed credentials in fifteen minutes temporarily lock that key for fifteen minutes. +Local usernames and other directories use independent account counters. Credential failures never +replay a user bind against another endpoint. Proven accounts receive no automatic role; an account +with no grants remains visible for manual role assignment and receives no tokens. +Rejected lookup-account credentials return temporary unavailability and do not increment user credential counters. + ### Azure Entra ID SSO Available when `ENTRA_ID_ENABLED=true`. Returns 404 otherwise. Callback and token @@ -839,10 +914,14 @@ State and final codes are single-use. Enrollment requires both `rbac:admin` and ```json { "local": true, - "entraId": { "enabled": true, "name": "Microsoft Entra ID" } + "entraId": { "enabled": true, "name": "Microsoft Entra ID" }, + "ldap": { "enabled": true, "name": "Corporate directory", "loginHelpUrl": "" } } ``` +Optional provider entries appear only when configured. LDAP remains advertised during directory outages; +discovery contains no directory ID, endpoints, search settings or credentials. + **`POST /api/auth/entra-id/token` request:** ```json @@ -861,6 +940,81 @@ State and final codes are single-use. Enrollment requires both `rbac:admin` and --- +## LDAP administration + +Available when `LDAP_ENABLED=true`. Every endpoint requires a Pabawi access JWT +and `rbac:admin`, independently of page-level controls. An authorized request gets +404 when LDAP is disabled. Public discovery and password authentication use the +separate exchanges described under [Auth](#auth). + +| Method | Endpoint | Description | +|---|---|---| +| `GET` | `/api/auth/ldap/groups` | Search configured group scope with required `query`, optional opaque `cursor` | +| `GET` | `/api/auth/ldap/mappings` | List stored mappings for the configured directory, including during outages | +| `POST` | `/api/auth/ldap/mappings` | Create a mapping from `{ "groupSubject": "", "roleId": "" }` | +| `PUT` | `/api/auth/ldap/mappings/:id` | Change `roleId` and/or boolean `enabled` | +| `DELETE` | `/api/auth/ldap/mappings/:id` | Delete mapping and withdraw only its attributable grants | +| `POST` | `/api/auth/ldap/test` | Diagnose configured TLS/lookup; optionally exact `username` and mapped `groupSubjects` | + +Search matches escaped substrings of the configured group lookup or display-name +attribute. `query` is nonempty and at most 1024 UTF-8 bytes. Only `{ subject, dn, +name }` is returned per group. The whole directory search must complete within +`LDAP_GROUP_SEARCH_LIMIT`; truncation returns 503 with `LIMIT_EXCEEDED`, without +partial results. A successful response is `{ items, nextCursor }`, with pages of +up to 50 groups. The cursor is a random opaque reference to the same bounded +snapshot, tied to the administrator, exact query and configured router instance. +It expires after 60 seconds; paging never extends that deadline. Each process +retains at most 64 continuation references. Expiry, eviction, restart or routing +to another process returns 400 `INVALID_CURSOR`; restart the search. All routes +return `Cache-Control: no-store` to authorized callers. + +Mapping lists return `{ items }`. Each item contains `id`, `source: "ldap"`, +`directoryId`, `groupSubject`, `groupDn`, `groupName`, `roleId`, `roleName`, boolean +`enabled`, `createdAt` and `updatedAt`. Group locators and names come from the +directory when created or reverified; listing uses stored labels. Submitted +DNs, labels, directory IDs and other undeclared input properties are rejected. +Creation returns 201, update 200 and deletion 204. Multiple roles for a group +use separate mappings. Duplicate group/role mappings return 409 `CONFLICT`. +Absent roles and mappings, including mappings belonging to another directory, +return 404. An unresolvable group subject returns 422 `INVALID_IDENTITY`. + +Creation, role changes and enabling require fresh immutable group resolution. +Disabling with only `{ "enabled": false }` and deletion remain available during +outages. Every successful mutation transaction increments the directory mapping +revision, invalidates persisted validation timestamps and withdraws the edited +mapping's grants. Manual roles, local RBAC groups, Entra grants and other mappings +are preserved. New/enabled mappings do not materialize grants until future +successful membership validation. Audit actions are `createLdapMapping`, +`updateLdapMapping` and `deleteLdapMapping`, with actor and directory/mapping/group/ +role IDs and enabled state. Audit failure rolls back the entire mutation. +Concurrent mapping changes during directory resolution return 409 +`STALE_REVISION`; reload the list and retry. + +Diagnostics accept `{}` or `{ "username": "alice" }`. Adding `groupSubjects` +requires `username`, at most 20 immutable UUIDs and only currently enabled mapped +groups. Unknown/disabled selections return 400 `INVALID_GROUP_SELECTION`. +The directory checks selected group existence and direct/nested membership under +the configured policy and bounds. Responses contain `authenticated: false`, +`stages` and, when membership completes, the matching `groupSubjects`. Each stage +has `stage` (`tls`, `lookup`, `identity`, `eligibility`, `groups`), `status` +(`passed` or `failed`), `durationMs`, and a safe failure `code` when failed. +Later stages are omitted after failure. No user bind, user import, grants or token +issuance occurs. Identity lookup is separate from eligibility: a visible inactive +user fails eligibility; absent/ambiguous identity fails identity. AD attributes +that are not readable yield `POLICY_UNREADABLE`. OpenLDAP's configured filter +cannot always distinguish inactive policy from missing policy attributes. + +No password, arbitrary filter or endpoint override is accepted. Reports omit +profile fields, raw LDAP messages and connection configuration. Success returns +200; `INVALID_IDENTITY`, `INELIGIBLE` and `IDENTITY_CHANGED` return 422 in this +restricted administration context. `BUSY` returns 429. Other directory failures +(`UNAVAILABLE`, `TIMEOUT`, `POLICY_UNREADABLE`, `INCOMPLETE_RESULT`, +`LIMIT_EXCEEDED`, and lookup credential rejection) return 503. Validation errors +return 400, unauthenticated/unauthorized requests 401/403, and unexpected server +errors a redacted 500. Diagnostics allow 10 requests per minute per administrator; +the router also applies the existing 100 requests/minute authenticated-user +budget. These requests do not consume the local-login attempt budget. + ## Debug Used internally by the frontend for expert mode log collection. diff --git a/docs/configuration.md b/docs/configuration.md index bc076620..4f862597 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -141,6 +141,132 @@ Optional federated authentication via OpenID Connect. When enabled, the login pa When `ENTRA_ID_ENABLED=true`, all four required variables must be set or the server refuses to start with a validation error listing the missing ones. +## LDAP directory service + +LDAP configuration, read-only directory operations and restricted group-mapping +administration and frontend controls are implemented. See the [operator guide](integrations/ldap.md). +The [LDAP administration API](api.md#ldap-administration) +requires `rbac:admin` for group search, stored mappings and diagnostics. +Enabling complete configuration advertises LDAP and enables explicit LDAP login +with shared session eligibility enforcement. It does not grant any role automatically. + +LDAP is disabled by default. When disabled, only LDAP_ENABLED is parsed. Enabled +invalid configuration fails startup. Construction performs no directory connection; +a valid but unreachable directory therefore leaves process startup and local access +intact. Changes require restart. Directory ID is case-sensitive and must remain +stable across endpoint changes; every endpoint must describe the same logical +directory. Additional endpoints share schema, TLS and policy settings. + +| Variable | Default | Contract | Secret | +| --- | --- | --- | --- | +| `LDAP_ENABLED` | `false` | strict boolean | no | +| `LDAP_DIRECTORY_ID` | Required when enabled | stable operator-chosen identifier, restricted to letters, digits, `_`, and `-` | no | +| `LDAP_DIRECTORY_TYPE` | See contract | Required: `ad` or `openldap` | no | +| `LDAP_DISPLAY_NAME` | `LDAP` | provider label in login and user administration | no | +| `LDAP_LOGIN_HELP_URL` | Empty | optional HTTP(S) help link, safely rendered | no | +| `LDAP_HOSTNAME` | Required FQDN | no embedded credentials, protocol, path, or search parameters | no | +| `LDAP_PORT` | `636` for LDAPS, `389` for StartTLS | integer 1 through 65535 | no | +| `LDAP_FAILOVER_ENDPOINTS` | `[]` | JSON array of additional `{ "hostname": "...", "port": 636 }` objects; maximum four | no | +| `LDAP_TLS_MODE` | `ldaps` | either `ldaps` or `starttls`; applies to every endpoint | no | +| `LDAP_CA_FILE` | Empty uses system trust | otherwise readable PEM CA bundle path, added to system trust | no | +| `LDAP_ALLOW_WILDCARD_CERTIFICATES` | `false` | additional restriction beyond normal hostname validation | no | +| `LDAP_LOOKUP_USER` | See contract | Required DN unless anonymous lookup is explicitly enabled | no | +| `LDAP_LOOKUP_PASSWORD` | Required nonempty value with lookup user | never expose in discovery, logs, or diagnostics | yes | +| `LDAP_ANONYMOUS_LOOKUP` | `false` | when true, lookup user/password must both be absent | no | +| `LDAP_CONNECT_TIMEOUT_SECONDS` | `10` | positive integer, at most 30 | no | +| `LDAP_OPERATION_TIMEOUT_SECONDS` | `10` | positive integer, at most 30 | no | +| `LDAP_REQUEST_TIMEOUT_SECONDS` | `30` | total LDAP transaction deadline across endpoints, binds, searches, and traversal; at most 60 | no | +| `LDAP_BASE_DN` | See contract | Required nonempty valid DN | no | +| `LDAP_USER_RDN` | Empty | optional relative DN beneath base DN | no | +| `LDAP_USER_OBJECT_CLASS` | See contract | `user` for AD, `inetOrgPerson` for OpenLDAP | no | +| `LDAP_USER_LOOKUP_ATTR` | See contract | `sAMAccountName` for AD, `uid` for OpenLDAP | no | +| `LDAP_USER_ID_ATTR` | `objectGUID` for AD, `entryUUID` for OpenLDAP | must be immutable and readable | no | +| `LDAP_USER_EMAIL_ATTR` | `mail` | missing value becomes null, never a fabricated address | no | +| `LDAP_USER_DISPLAY_NAME_ATTR` | `displayName` | fallback to current directory login name | no | +| `LDAP_USER_GIVEN_NAME_ATTR` | `givenName` | missing value becomes an empty profile field | no | +| `LDAP_USER_SURNAME_ATTR` | `sn` | missing value becomes an empty profile field | no | +| `LDAP_USER_ELIGIBILITY_FILTER` | Empty for AD means built-in AD policy | required valid filter for OpenLDAP | no | +| `LDAP_GROUP_RDN` | Empty | optional relative DN beneath base DN | no | +| `LDAP_GROUP_OBJECT_CLASS` | See contract | `group` for AD, `groupOfUniqueNames` for OpenLDAP | no | +| `LDAP_GROUP_MEMBER_ATTR` | `member` for AD, `uniqueMember` for OpenLDAP | DN-valued memberships only | no | +| `LDAP_GROUP_ID_ATTR` | See contract | `objectGUID` for AD, `entryUUID` for OpenLDAP | no | +| `LDAP_GROUP_NAME_ATTR` | `name` for AD, `displayName` for OpenLDAP | display falls back to lookup attribute | no | +| `LDAP_GROUP_LOOKUP_ATTR` | `cn` | used for administrative search, not persistent identity | no | +| `LDAP_SEARCH_NESTED_GROUPS` | `false` | direct membership only unless enabled | no | +| `LDAP_DISABLE_MATCHING_RULE_IN_CHAIN` | `false` | AD optimization switch, irrelevant for OpenLDAP | no | +| `LDAP_NESTED_GROUP_MAX_DEPTH` | `10` | positive integer, at most 32 | no | +| `LDAP_GROUP_SEARCH_LIMIT` | `100` | total returned administrative search entries, at most 500 | no | +| `LDAP_GROUP_TRAVERSAL_LIMIT` | `1000` | maximum visited groups per eligibility transaction, at most 10000 | no | +| `LDAP_REVALIDATION_INTERVAL_SECONDS` | `300` | positive integer at most 300, so operators can tighten the agreed freshness bound | no | +| `LDAP_MAX_CONCURRENT_OPERATIONS` | `10` | positive integer at most 100; bounded admission, with excess requests rejected temporarily | no | + +All booleans accept only literal true or false. Attribute names/OIDs, DNs, filters, +JSON and bounds are validated. OpenLDAP requires a deployment-specific positive +eligibility filter, for example (employeeType=active). The lookup account must see +all attributes used by that policy. Missing policy attributes do not match the +example filter. The application cannot infer an operator's account-status schema. + +TLS 1.2 or later, CA verification, hostname validation and endpoint SNI are required +for LDAPS and StartTLS. A configured PEM bundle adds certificates to Node's default +trust roots (including configured system/extra roots). A failed StartTLS negotiation never falls back to plaintext. Default +wildcard restrictions supplement normal hostname verification. User binds use a +separate connection to the selected endpoint. No reconnect or password replay is +permitted. Failover applies only to transient transport establishment failures before lookup binding; +certificate, hostname and protocol validation failures stop the operation. + +Searches use server limits, no paging, no alias dereferencing and no referral +following. Server truncation, referrals and traversal/depth bounds fail the whole +operation. Admission rejects excess transactions immediately; a single total +deadline covers all endpoints, connections, searches and group traversal. Errors +and logs expose safe reason codes, never raw directory responses or credentials. + +OpenLDAP subjects must be UUID attributes (entryUUID by default). AD subjects must +be 16-byte binary GUID attributes (objectGUID by default), encoded as lowercase +canonical UUIDs with the Windows field byte order. Neither DN, login nor email is +an identity key. OpenLDAP groupOfUniqueNames/uniqueMember and groupOfNames/member +are supported using DN membership. Optional uniqueMember UID suffixes are rejected +when encountered. RFC2307 memberUid membership is unsupported. + +AD policy requires readable userAccountControl, +msDS-User-Account-Control-Computed, accountExpires, pwdLastSet and +msDS-UserPasswordExpiryTimeComputed. It denies disabled, currently locked, +expired-account and observable password-expiration/change-required states. FILETIME +is evaluated with integer arithmetic; accountExpires 0 and 9223372036854775807 +mean no expiration. See Microsoft's [computed account flags](https://learn.microsoft.com/en-us/windows/win32/adschema/a-msds-user-account-control-computed) +and [account expiration](https://learn.microsoft.com/en-us/windows/win32/adschema/a-accountexpires). +Missing required policy visibility fails closed. Bind-only conditions cannot be +rechecked without another password-based login. + +Nested membership uses bounded reverse membership searches in the configured group +scope. This avoids reading AD member ranges. AD matching-rule-in-chain results are +checked against that bounded traversal to prevent out-of-scope paths or unbounded +recursion from adding grants. Only definitive unsupported-rule errors permit the +traversal result alone. Primary groups and cross-domain/out-of-scope memberships +are excluded. Actual AD interoperability remains unverified. + +Reproducible OpenLDAP TLS tests and commands are in +[the fixture guide](../backend/test/fixtures/ldap/README.md). + +When enabled, LDAP is advertised by `/api/auth/providers` and accepts explicit password +authentication at `/api/auth/ldap/login`. Directory unavailability does not prevent startup or local/Entra access. +The login UI and operator walkthrough are tracked separately in the LDAP implementation plan. +No default role is assigned: configure group mappings or manually grant an account a role after its first +proven login. An account without any explicit role receives no tokens. + +Successful eligibility state is persisted with mapping/configuration revisions and measured from the +start of the directory read using database time. Its maximum age is `LDAP_REVALIDATION_INTERVAL_SECONDS`. +Refresh forces validation; ordinary REST and active stream/websocket checks share persisted freshness, +single-flight work and bounded database leases. Changed mappings or configuration invalidate freshness. +All processes serving one directory must use the same configuration; replace older workers during a +configuration rollout. A stale worker cannot reinstate its old configuration on an authentication request. +Configuration hashing includes the configured CA bundle contents and lookup credential configuration. + +Transient directory failures preserve materialized grants and existing token versions. Expired sessions +stop protected access until validation succeeds. Confirmed ineligibility or no remaining explicit role +revokes LDAP sessions; directory recovery then requires a new login. Profile refresh preserves local +suspension, administrative state and manual assignments. Migration 032 requires reauthentication once; +migration 034 rejects legacy console credentials lacking a verified provider context. + ## Bolt | Variable | Default | Description | Secret value | diff --git a/docs/deployment/docker.md b/docs/deployment/docker.md index 131ecd98..f78b05d8 100644 --- a/docs/deployment/docker.md +++ b/docs/deployment/docker.md @@ -7,7 +7,7 @@ Before starting a fresh container, configure `JWT_SECRET` and an independent [Initial setup](../initial-setup.md) to claim the administrator account. ```bash -# Using published image +# Using the batteries image because this example mounts a Bolt project docker run -d \ --name pabawi \ --user "$(id -u):1001" \ @@ -15,9 +15,20 @@ docker run -d \ -v "$(pwd)/bolt-project:/opt/pabawi/bolt-project:ro" \ -v "$(pwd)/data:/opt/pabawi/data" \ --env-file .env \ - example42/pabawi:latest + example42/pabawi:batteries ``` +Two image profiles are published from the same source and version: + +| Tag | Contents | Use when | +|---|---|---| +| `example42/pabawi:latest` | Pabawi application and Node dependencies | Integrations use HTTP APIs, cloud SDKs, or the embedded SSH client | +| `example42/pabawi:batteries` | Core plus Bolt, Ansible, Puppet/OpenVox, OpenSSH, Git, rsync, and sshpass | Integrations need local infrastructure commands | + +Versioned core tags use ``, `.`, and ``. The full +image uses `batteries-`, `batteries-.`, and +`batteries-`. Pre-releases receive only their exact version tags. + `--user "$(id -u):1001"`: your user must be able to read all mounted files. Run build and repository Compose examples from the repository root. Standalone @@ -34,13 +45,15 @@ See [Docker port binding](https://docs.docker.com/reference/compose-file/service ```bash docker build -t pabawi:latest . -docker build -f Dockerfile.alpine -t pabawi:alpine . # smaller +docker build --target core -t pabawi:core . +docker build --target batteries -t pabawi:batteries . ``` **Multi-arch:** ```bash -docker buildx build --platform linux/amd64,linux/arm64 -t pabawi:latest . +docker buildx build --platform linux/amd64,linux/arm64 --target core -t pabawi:core . +docker buildx build --platform linux/amd64,linux/arm64 --target batteries -t pabawi:batteries . ``` ## Volume Mounts @@ -69,7 +82,7 @@ chmod 600 ./certs/*.pem ./certs/*.key ```yaml services: pabawi: - image: example42/pabawi:latest + image: example42/pabawi:batteries restart: unless-stopped ports: - "127.0.0.1:3000:3000" diff --git a/docs/deployment/supply-chain.md b/docs/deployment/supply-chain.md index 420c14a6..54879987 100644 --- a/docs/deployment/supply-chain.md +++ b/docs/deployment/supply-chain.md @@ -38,30 +38,44 @@ From the repository root: ```bash node --test scripts/supply-chain/install-approved.test.mjs -docker build -t pabawi:verify . -bash scripts/supply-chain/image-smoke.sh pabawi:verify -docker run --rm -i --entrypoint node pabawi:verify < scripts/supply-chain/dependency-graph.cjs > dependencies.json -bash scripts/supply-chain/scan-image.sh pabawi:verify /tmp/pabawi-image-evidence +docker build --target core -t pabawi:core-verify . +bash scripts/supply-chain/image-smoke.sh pabawi:core-verify core +docker build --target batteries -t pabawi:batteries-verify . +bash scripts/supply-chain/image-smoke.sh pabawi:batteries-verify batteries +docker run --rm -i --entrypoint node pabawi:core-verify < scripts/supply-chain/dependency-graph.cjs > dependencies.json +bash scripts/supply-chain/scan-image.sh pabawi:core-verify /tmp/pabawi-core-image-evidence +bash scripts/supply-chain/scan-image.sh pabawi:batteries-verify /tmp/pabawi-batteries-image-evidence scripts/supply-chain/trivy-batteries-ignore.yaml ``` -Repeat with `-f Dockerfile.alpine` and `-f Dockerfile.ubuntu` and distinct tags. +Build the alternative Dockerfiles with distinct tags and run the smoke script +with the `bolt` profile. The smoke test checks the non-root Node runtime, bcrypt, an actual SQLite query, -SSH module loading, Bolt task discovery, migrations, HTTP health, frontend delivery -and denial of anonymous inventory requests. It uses disposable container storage -and does not dispatch infrastructure commands. +SSH module loading, migrations, HTTP health, frontend delivery and denial of +anonymous inventory requests. The core profile also proves that integration CLIs +are absent. The batteries profile checks Bolt task discovery and the Bolt, +Ansible, Puppet/OpenVox and OpenSSH commands. It uses disposable container +storage and does not dispatch infrastructure commands. -CI builds all three variants, then performs a second uncached production -installation and compares its dependency graph with the shipped image. The graph -check validates installed versions against the lockfile and root security overrides. -Release CI smoke-tests each architecture, scans the locally exported image, and -pushes that same image without rebuilding. The multi-architecture manifest is -published only after both architecture jobs succeed. +CI builds core and batteries targets plus the Alpine and Ubuntu alternatives, +then performs a second uncached production installation and compares its +dependency graph with each image. The graph check validates installed versions +against the lockfile and root security overrides. Release CI smoke-tests both +profiles on each architecture, scans the locally exported images, and pushes +those same images to Docker Hub and GHCR without rebuilding. Both +multi-architecture manifests are published only after all four architecture +and profile jobs succeed. GitHub Actions requires `DOCKERHUB_USERNAME` and +`DOCKERHUB_TOKEN` repository secrets. The pinned Trivy scanner produces `sbom.cdx.json` and `vulnerabilities.json` from the exported image archive. It scans OS, Ruby, Python, Java and JavaScript packages, including the embedded frontend SBOM. The image digest and dependency inventory -are retained with the reports. High or critical advisories fail the release gate, -including findings without an available fix. Scanner errors also fail the gate. +are retained with the reports. Fixable high or critical advisories fail the +release gate. Scanner errors also fail the gate. The batteries image has one +scoped, expiring exception for `CVE-2026-85396` in its bundled `rubyzip` 2.4.1. +OpenBolt 5.6.0 depends on `winrm-fs` 1.3.5, which constrains rubyzip to the +vulnerable 2.x line. The exception matches that exact package URL and gemspec +path, applies only to the batteries profile, and expires on 2026-12-31. The +unfiltered JSON report still records the finding. See [Trivy's SBOM documentation](https://github.com/aquasecurity/trivy/blob/main/docs/guide/supply-chain/sbom.md). ## Triage and reproducibility limits @@ -69,9 +83,9 @@ See [Trivy's SBOM documentation](https://github.com/aquasecurity/trivy/blob/main The release maintainer owns scan triage with the security maintainer. For each finding, record the artifact digest, advisory, installed and fixed versions, reachability assessment, remediation owner and disposition. Do not equate an -unreachable-looking dependency with an approved exception. No advisory suppressions -are configured. A blocked gate requires remediation or a separately reviewed, -scoped and expiring exception before release. +unreachable-looking dependency with an approved exception. A blocked gate +requires remediation or a separately reviewed, scoped and expiring exception +before release. The npm graph and base-image inputs are pinned. Distribution packages still come from live signed repositories, and the Alpine OpenBolt gem dependency tree is resolved by RubyGems. diff --git a/docs/integrations/ldap.md b/docs/integrations/ldap.md new file mode 100644 index 00000000..9f4a5bbc --- /dev/null +++ b/docs/integrations/ldap.md @@ -0,0 +1,286 @@ +# LDAP authentication + +Pabawi authenticates against one configured directory, with optional equivalent failover +endpoints. Local password login and Entra ID can remain enabled. Select **Local** or +the configured directory under **Sign in using**. Entra retains its redirect button. +A rejected LDAP attempt stays on LDAP and never tries another provider. + +Real OpenLDAP fixtures cover LDAPS and StartTLS. AD policy and GUID handling have +service-level coverage, but real AD interoperability remains unverified. The AD example +is not support certification. DN parsing is project-owned, with bounded syntax and scope +regressions described below. The decommissioned parser dependency has been removed. + +## Configuration + +Use environment variables, including protected runtime configuration for the lookup +password. Source development loads `backend/.env`. See the +[complete reference](../configuration.md#ldap-directory-service) and +[environment example](../../backend/.env.example). + +LDAP is disabled by default. Enabled invalid configuration fails startup. An unreachable +directory with valid configuration permits startup and local/Entra login. Configuration +changes require a coordinated restart of all backend workers. Keep `LDAP_DIRECTORY_ID` +stable across endpoint moves. Failover endpoints must represent the same directory, +identity attributes, scope and policy. A different directory dataset requires an +intentional identity migration. + +OpenLDAP with StartTLS: + +```dotenv +LDAP_ENABLED=true +LDAP_DIRECTORY_ID=corporate-openldap +LDAP_DIRECTORY_TYPE=openldap +LDAP_DISPLAY_NAME=Corporate directory +LDAP_LOGIN_HELP_URL=https://help.example.com/directory +LDAP_HOSTNAME=ldap1.example.com +LDAP_PORT=389 +LDAP_TLS_MODE=starttls +LDAP_CA_FILE=/etc/pabawi/corporate-ca.pem +LDAP_LOOKUP_USER=cn=pabawi-reader,ou=services,dc=example,dc=com +# Supply LDAP_LOOKUP_PASSWORD through protected runtime configuration. +LDAP_BASE_DN=dc=example,dc=com +LDAP_USER_RDN=ou=people +LDAP_USER_ELIGIBILITY_FILTER=(employeeType=active) +LDAP_GROUP_RDN=ou=groups +LDAP_GROUP_OBJECT_CLASS=groupOfUniqueNames +LDAP_GROUP_MEMBER_ATTR=uniqueMember +LDAP_GROUP_ID_ATTR=entryUUID +LDAP_SEARCH_NESTED_GROUPS=false +``` + +This example requires a deployment schema containing `employeeType` and a policy +where `active` positively establishes eligibility. OpenLDAP has no universal account +status attribute. Supply a positive filter excluding your disabled, locked and expired +states. Test missing status attributes explicitly. Both examples intentionally omit the +required lookup password and cannot start until a real secret is supplied. + +AD with LDAPS, pending real AD verification: + +```dotenv +LDAP_ENABLED=true +LDAP_DIRECTORY_ID=corporate-ad +LDAP_DIRECTORY_TYPE=ad +LDAP_DISPLAY_NAME=Corporate AD +LDAP_HOSTNAME=dc1.example.com +LDAP_PORT=636 +LDAP_FAILOVER_ENDPOINTS='[{"hostname":"dc2.example.com","port":636}]' +LDAP_TLS_MODE=ldaps +LDAP_CA_FILE=/etc/pabawi/corporate-ca.pem +LDAP_LOOKUP_USER=CN=pabawi-reader,OU=Service Accounts,DC=example,DC=com +# Supply LDAP_LOOKUP_PASSWORD through protected runtime configuration. +LDAP_BASE_DN=DC=example,DC=com +LDAP_USER_RDN=OU=People +LDAP_GROUP_RDN=OU=Groups +LDAP_SEARCH_NESTED_GROUPS=false +``` + +AD presets use `sAMAccountName`, `objectGUID`, `group` and `member`. +The user scope must resolve each login uniquely. The lookup account must read +`userAccountControl`, `msDS-User-Account-Control-Computed`, `accountExpires`, +`pwdLastSet` and `msDS-UserPasswordExpiryTimeComputed`. Missing or malformed +attributes deny validation. Policy checks observable disablement, lockout, forced +password change, password expiry and account expiry. States observable only during +user bind cannot be detected by lookup-only session checks. + +Use a read-only lookup account scoped to required entries and attributes. Anonymous +lookup requires `LDAP_ANONYMOUS_LOOKUP=true` and absent lookup user/password; it +still requires complete identity, policy and membership visibility. + +## TLS, scope and actual defaults + +Both modes require TLS 1.2 or newer, chain validation, endpoint SNI and hostname +verification. There is no insecure bypass. A public PEM CA bundle augments system +trust. Wildcard certificates are rejected by default; permitting them still requires +standard hostname validation. Failed StartTLS never falls back to plaintext. + +Failover retries known transient connection-establishment failures within one deadline. +Certificate failures and rejected lookup credentials stop the transaction. A rejected +user bind never replays the password to another endpoint. Referrals, aliases and partial +searches cannot establish authorization. + + +DNs use a bounded project-owned RFC 4514 parser. Attribute descriptors compare without case; +values remain exact for client-side scope/locator checks. Use the directory's rendered value +casing for configured bases. Multi-valued RDN order and equivalent escaped UTF-8 octets are +handled structurally. BER hex values remain opaque; only complete definite-length values with +single-octet tags are accepted. Unknown schema matching rules, OID aliases and value case folding +are never guessed. Unsupported or malformed encodings fail closed. + +Direct membership is the default. OpenLDAP supports DN-valued +`groupOfUniqueNames/uniqueMember` and `groupOfNames/member`. Override both +variables together for the latter. Optional UID suffixes and RFC2307 `memberUid` +are unsupported. Nested traversal stays in scope, detects cycles and enforces depth, +count and time bounds. AD matching-rule-in-chain is enabled for nested membership unless +`LDAP_DISABLE_MATCHING_RULE_IN_CHAIN=true`. Only a definitive unsupported-rule +response permits bounded traversal alone. AD primary groups, out-of-scope membership, +forest discovery, cross-domain referrals, directory writes and bulk sync are excluded. + +| Setting | Actual default | +| --- | --- | +| TLS / port | `ldaps` / 636; StartTLS defaults to 389 | +| Connect / operation / transaction timeout | 10 / 10 / 30 seconds | +| Nested membership / maximum depth | false / 10 | +| Administrative search / traversal entries | 100 / 1000 | +| Concurrent directory transactions | 10, immediate bounded admission | +| Eligibility freshness | 300 seconds, configurable downward | +| Diagnostics | 10 per minute per authenticated user | +| Search UI page size / cursor lifetime | 50 / 60 seconds | + +Exceeded bounds reject incomplete decisions. Search again if a cursor expires. Cursors +are opaque and bound to the original query, administrator and backend configuration. +Snapshots live in the serving process; use sticky routing for pagination. + +## Map groups and diagnose access + +1. Verify an emergency local administrator before enabling LDAP. +2. Sign in as a Pabawi administrator holding `rbac:admin`. Open **Role Management**. + The existing management-page administrator guard remains in force. +3. Search directory groups, select the returned group and Pabawi role, then choose + **Create mapping**. A role detail dialog maps directly to its current role. + Multiple roles use separate mappings. Search never imports users or grants access. + The server resolves immutable group IDs and supplies authoritative names and DNs. +4. Run **Restricted directory diagnostics** without a username for TLS and lookup bind. + Supply an exact username for identity and policy visibility. Select up to 20 enabled + mapped groups for membership checks. A passing lookup is not password authentication. +5. In a separate login, select the directory and use a synthetic eligible account. + Verify access, denial after eligibility/grant removal, and outage/recovery behavior. + +Stored mappings remain visible during outages. Disablement and removal withdraw only +attributable grants without directory lookup. Creation, enabling and role replacement +require fresh group identity proof. Reload after a failed or concurrent edit. Removal +requires UI confirmation. Every administration API independently enforces `rbac:admin`; +delegated API authority does not bypass the administrator-only UI pages. + +There is no default LDAP role. Valid credentials and eligibility with no explicit role +create a visible account but return 403 without tokens. In **User Management**, locate +it by current directory login or display name, assign a manual role, then log in again. + +## Identity and profile ownership + +Directory ID and immutable subject define identity. Renaming or moving an entry preserves +the account; recreation with a new immutable ID does not inherit it. Administration shows +the reserved internal username, source, current login and display name. Matching local +or Entra names/emails never link accounts. External contact email may be absent or shared. + +Directory names/email refresh at login and successful revalidation. These fields are +read-only; LDAP accounts cannot receive local passwords even through administrator APIs. +Change passwords in the directory. Pabawi owns suspension, administrative status and +manual roles. User details show manual/external role provenance. Removing a manual +assignment preserves other sources for that role. Manage LDAP grants through mappings. + +## Sessions, failures and operations + +Login establishes fresh eligibility. Refresh always forces lookup-only validation. +Other activity can reuse success only until its configured deadline, measured from +the start of the directory read. Passwords are never retained for revalidation. +Shared database revisions, leases and fencing protect concurrent workers. REST, +execution/journal SSE, MCP and console websocket delivery share this boundary. +Already dispatched infrastructure work continues independently. + +| Outcome | Behavior | +| --- | --- | +| Bad or ambiguous credentials | Generic 401; no account-existence disclosure | +| Ineligible, suspended or no remaining explicit role | 403; positive revocation invalidates existing sessions | +| Too many attempts or concurrent operations | 429; wait before retrying | +| Directory/TLS error, incomplete search or exceeded limit | 503; no fresh eligibility or token issuance | +| Outage after login | Existing freshness lasts only to its original deadline; refresh needs directory availability | +| Transient recovery | Otherwise valid tokens may resume after a successful check | +| Recovery after positive revocation | New login required; old tokens stay invalid | + +IP throttling accompanies separate provider/directory/submitted-login counters. +Five credential failures within fifteen minutes lock that key for fifteen minutes. +Rejected lookup credentials are availability errors and do not consume user failure +budgets. Avoid repeated bind attempts against locked directory accounts. + +Use restricted stage results and structured logs for latency, limits, failover and safe +reason codes. Do not share passwords, tokens, full entries or raw directory diagnostics. +Public discovery exposes only configured name/help metadata and stays visible during +outages. The browser retains tokens after a temporary refresh failure (429/503 or a +network error), displays a warning and permits a later retry; it does not treat the failed +check as fresh authorization. Definitive refresh rejection clears the session. +Keep local emergency access available. + +## Upgrade and rollout + +Back up the database/configuration using normal operational procedures. Apply the release +consistently across backend workers and never edit historic migrations. Migration 031 +preserves identity/grant ownership and local email constraints. Migration 032 intentionally +invalidates legacy sessions once; all providers must sign in again with provider-bound +tokens. Later migrations add validation decisions and console context. Legacy console +reservations without provable authentication context cannot upgrade. + +Stage the deployment and verify both database adapters, local/Entra login, configured TLS, +mapping withdrawal, outage/recovery and long-lived transports. Real AD acceptance remains +a release gate: GUIDs, account state, nested matching rules, large membership and failover. +Real Proxmox console compatibility is separately unverified; authorization fixture tests +do not establish provider interoperability. + +The [OpenLDAP fixture](../../backend/test/fixtures/ldap/README.md) documents live directory +checks. The [implementation plan](../internal/plans/ldap-authentication.md) tracks full +acceptance and release blockers. + +### Staged upgrade procedure + +The current acceptance evidence covers disposable SQLite/PostgreSQL upgrades, live OpenLDAP in both +TLS modes, and local browser/transport fixtures. The [release acceptance report](../internal/plans/ldap-acceptance.md) +lists the remaining real AD gates. Complete those gates before releasing LDAP support. + +1. Verify an emergency local administrator and record the current artifact/configuration versions. + Take a consistent database backup and retain the matching configuration through the existing secret + boundary. With SQLite, include committed WAL contents using a database-aware backup or stop all + writers before copying. Rehearse restoration into a separate staging database. +2. Stop every old backend worker before starting the candidate. Database migrations run automatically + during `DatabaseService.initialize()`, before LDAP authentication routes are mounted. Start one + candidate worker against the staging database and check migration success through 034. Never mix old + and new schema consumers or edit recorded migration checksums. +3. Confirm preserved local/Entra users, explicit enrollments, manual roles and external grant sources. + Confirm pre-upgrade access and refresh tokens require reauthentication, then verify new local login. + A failed migration must keep the candidate out of service; restore the backup and matching old + artifact together if abandoning the upgrade. +4. Supply the directory configuration and public CA bundle, retaining its stable directory ID. + Start candidate workers with identical configuration. Restricted diagnostics must prove lookup, + identity, policy and selected membership visibility. A passing diagnostic does not prove a user bind. +5. Perform a synthetic password login with no role and verify 403 without tokens. Grant a manual or + mapped role, log in again, refresh, and exercise each deployed transport. Observe mapping withdrawal, + positive policy denial and terminal rejection of old sessions after recovery. Test connection + failover only between equivalent configured endpoints. +6. In the isolated staging directory, interrupt availability through the original freshness deadline. + Check temporary 503/429 behavior, unchanged freshness, local emergency access and recovery of + otherwise valid sessions. Keep real infrastructure operations out of this rehearsal. +7. After the remaining release gates pass, follow the normal deployment change process with the + retained backup and rollback pair. Keep configuration changes coordinated across workers and + repeat local/directory login and restricted diagnostics after restart. + +The automated fixture covers account/mapping/policy transitions, actual LDAP transport outages, +and populated backup/restore/re-upgrade on both adapters in this procedure. Environment-specific backup restoration and actual deployment still require a staging +rehearsal; no production rollout is implied by passing the fixture. + +### Rehearsed database backup and restore + +The local recovery suite now exercises populated migration-030 databases through migration 034, +restarts the candidate without repeated invalidation, rolls back a failed candidate migration, +restores the original backup and repeats the upgrade on both adapters. It checks local login, +Entra-bound token issuance/rotation, roles, explicit enrollments, group membership and audit links. +This is a local rehearsal; validate storage, secrets and service management in your deployment environment. + +For SQLite, the rehearsal keeps committed changes in a nonempty WAL and uses a consistent live backup: + +~~~sql +VACUUM INTO '/secure-backups/pabawi-before-ldap.db'; +~~~ + +Run this against the source database with an unused backup filename. A completed backup includes +committed WAL contents. Do not copy only the main file while writers are active. Retain the backup +unchanged and restore a copy to a separate database path before testing startup. + +For PostgreSQL, use matching-version tools and restore into a newly created empty database: + +~~~bash +pg_dump --format=custom --no-owner --file=pabawi-before-ldap.dump "$DATABASE_URL" +pg_restore --exit-on-error --single-transaction --no-owner --dbname="$RESTORE_DATABASE_URL" pabawi-before-ldap.dump +~~~ + +The automated rehearsal runs those tools inside its isolated PostgreSQL container. Rollback restores +the matching database/configuration/artifact set; it does not run down migrations or edit checksums. +See the [fixture runner](../../backend/test/fixtures/ldap/README.md#reproducible-acceptance-runner) +for the observed local procedure and retained evidence. diff --git a/docs/internal/dockerhub.md b/docs/internal/dockerhub.md index ffa36d57..0179766f 100644 --- a/docs/internal/dockerhub.md +++ b/docs/internal/dockerhub.md @@ -44,6 +44,14 @@ docker run -d \ example42/pabawi:latest ``` +This is the core image. It intentionally excludes Bolt, Ansible, Puppet/OpenVox, +OpenSSH, Git, rsync, and sshpass. For local integration commands, use the +batteries-included image instead: + +```bash +docker run --rm example42/pabawi:batteries +``` + Access the UI at ## Documentation diff --git a/docs/internal/plans/ldap-acceptance.md b/docs/internal/plans/ldap-acceptance.md new file mode 100644 index 00000000..462d870d --- /dev/null +++ b/docs/internal/plans/ldap-acceptance.md @@ -0,0 +1,196 @@ +# LDAP package 7 acceptance evidence + +**Candidate:** branch `151`, current base `7389784`, plus the uncommitted CI/harness/runner changes. +The initial base in this session was `55c8107`; the existing package-7 work was committed concurrently and preserved. +**Date:** 2026-10-21. +**Release decision:** blocked on actual AD evidence. Parser dependency cleanup is complete; local OpenLDAP transport and database recovery rehearsals pass. + +This report maps the [implementation plan](ldap-authentication.md#acceptance-tests) to executable evidence. +A passing synthetic protocol or browser fixture does not establish AD or Proxmox interoperability. +Evidence paths below are local artifacts retained outside the repository; exact commands and outcomes are in +`~/.agents/logs/pabawi.jsonl`. + +## Acceptance matrix + +| Area | Current evidence | Remaining gate | +| --- | --- | --- | +| Configuration | `backend/test/config/LdapConfig.test.ts` and `LdapDn.test.ts`: owned bounded DN syntax, exact value/scope semantics, UTF-8/BER/multi-valued vectors; disabled/enabled settings, positive policy, invalid filters/DNs/attributes/TLS/CA and startup parsing. Server composition constructs LDAP without an initial network dependency. | None for configuration; actual AD attribute visibility remains below. | +| TLS and failover | `backend/test/integration/ldap-directory.test.ts`: real trusted LDAPS/StartTLS, bad CA/hostname, failed upgrade without credentials, transport-only failover and socket deadlines. Unit tests cover wildcard restrictions and rejected bind/certificate failover behavior. | Real AD endpoint/certificate and equivalent-controller failover. | +| Credentials | Real directory and HTTP tests cover valid/invalid/empty passwords, ambiguity, missing immutable ID, injection input, incomplete/limited results and timeouts. `provider-bound-sessions.test.ts` now proves local and LDAP temporary lockout on both adapters. | Real AD user/lookup bind behavior. | +| Identity | Both-adapter schema/provisioning tests plus all four live `ldap-rollout.test.ts` combinations prove move/rename continuity and new identity after DN/login reuse. Concurrent first-login tests preserve one identity/account. | Real AD binary GUID retrieval and equality filters. | +| Profiles | Live HTTP refresh after moving an entry updates login/DN/display name without replacing the user or revoking valid access. Null contacts, suspension and server-enforced profile/password ownership have HTTP and component regressions. | None for the shared ownership contract. | +| Authorization | Live zero-role enrollment returns 403 without tokens; manual role enables login, mapped grants survive manual withdrawal, recreated groups withdraw old grants and require a new immutable mapping. Database tests cover source unions and revisions. | None for the shared grant contract. | +| Groups | Real OpenLDAP covers both supported group classes, nested cycles, depth/count limits and group rename/recreation. AD matching-rule errors and bounded traversal have synthetic protocol tests. | Real AD nested matching-rule behavior, large/ranged membership and bounds. | +| Status | Real OpenLDAP positive-policy denial, missing-policy attributes and terminal observed revocation. Unit tests cover AD FILETIME sentinels, disablement, computed lockout/password expiry and unreadable state. | Actual AD policy visibility and disabled/expired/locked accounts. | +| Freshness | Both-adapter controlled database clocks cover the exact deadline. HTTP and database regressions cover forced refresh, unchanged failed timestamps, transient recovery and terminal positive denial. Live OpenLDAP policy restoration leaves old access/refresh tokens invalid. | None for the shared freshness algorithm. | +| Concurrency | Both-adapter independent-connection tests cover login/refresh/publication races. New child-process cases prove lease coalescing, stale-worker fencing and mapping-revision rejection across distinct OS processes. | None for the covered coordination contract. | +| Transports | `ldap-transports.test.ts` now runs nine REST/refresh/SSE/MCP/console scenarios in synthetic mode and against real OpenLDAP in both TLS modes on both adapters. Real connection interruption and policy mutation exercise delivery, idle checks, retry and recovery. Local/Entra provider independence is covered separately. | Real Proxmox interoperability is separately unverified. These fixtures test authorization enforcement. | +| Administration | HTTP permission/validation/audit tests and both-adapter mapping provenance/revision tests. Endpoint override/fabricated identity and outage controls are rejected without leaking configuration. | None for the administration contract. | +| Migrations | Fresh and populated upgrades on SQLite/PostgreSQL cover identity/grant preservation, foreign keys, rollback, views/triggers and one-time legacy-session invalidation. | Local populated SQLite WAL backup and PostgreSQL pg_dump/pg_restore, rollback and repeat-upgrade rehearsal now pass. Deployment-specific storage/service procedures still need staging validation. | +| UI | Full frontend regression plus isolated Chromium cases for explicit provider choice, short credentials, denial without fallback, mapping/diagnostic controls, nullable read-only profiles and page guards. | Browser directory responses are synthetic; they provide UI/HTTP evidence. | + +## Added release-candidate checks + +`backend/test/integration/ldap-rollout.test.ts` runs with the existing synthetic OpenLDAP image and +three `TEST_LDAP_*` settings. With `TEST_DATABASE_URL`, it executes the complete SQLite/PostgreSQL +and LDAPS/StartTLS matrix. Every case creates uniquely named entries under the fixture people/groups +bases. Only those entries are removed at teardown. Shared seed data is preserved. + +The child-process tests live in `backend/test/database/ldap-authentication.test.ts`; +`backend/test/fixtures/ldap/validation-worker.ts` runs the unchanged authentication service and +database adapters in another Node process. Directory reads are controlled synthetic responses, so these +cases prove process isolation and database coordination, not directory protocol behavior. + +The live rollout exposed an existing PostgreSQL ambiguity in the failed-login counter upsert. +Qualifying the target counter restores the shared path for local and provider-scoped LDAP lockouts. +The new regression failed against the starting source on PostgreSQL and passes after the one-line fix. +No historic migration, token format or runtime configuration contract changed. Approved dependency +removal is recorded below. + +## Dependency maintenance gate + +Primary registry metadata was rechecked for the pinned versions: + +- [@ldapjs/dn 1.1.0](https://registry.npmjs.org/@ldapjs/dn/1.1.0) is explicitly decommissioned. +- [@ldapjs/asn1 2.0.0](https://registry.npmjs.org/@ldapjs/asn1/2.0.0), its transitive dependency, is also decommissioned. +- [ldapts 9.2.0](https://registry.npmjs.org/ldapts/9.2.0) declares Node >=22; the candidate was tested on supported Node 24.21.0. + +Runtime DN parsing now uses the project-owned `backend/src/config/ldapDn.ts`, not either deprecated +module. Current Context7/source review found no equivalent parser API in the pinned ldapts DN builder; +the reviewed community LDAP fork would add another complete LDAP stack for this narrow function. +Pabawi owns parser maintenance and regression coverage. No new package was installed. + +The bounded module parses escaped UTF-8, attribute names/OIDs, unordered multi-valued RDNs and opaque +BER hex values. Attribute descriptors normalize case; values remain exact and BER never guesses text +or schema matching. Only complete definite-length BER with single-octet tags is supported. Scope uses +parsed suffixes, never raw string endings or broad case folding. Malformed/unsupported encodings and +inputs above 8192 bytes fail closed. Standards: [RFC 4514](https://www.rfc-editor.org/rfc/rfc4514.html), +[RFC 4517 distinguishedNameMatch](https://www.rfc-editor.org/rfc/rfc4517.html#section-4.2.15). +The application deliberately uses conservative locator equality, not a complete schema matching engine. + +Focused regression and 200 randomized Unicode cases pass, as do the live OpenLDAP matrix and full +backend regression. After explicit user approval, the obsolete declaration and @ldapjs/dn dependency +were removed offline. Its unused @ldapjs/asn1 and process-warning transitives were pruned. The lockfile +comparison proves no added packages or changes to any remaining package entry. This maintenance gate +is closed; Pabawi owns the bounded parser and its regression suite. + +## Verification artifacts + +- `/tmp/pabawi-ldap-p7-prerequisites.log`: 85 prerequisite cases, both adapters and live TLS. +- `/tmp/pabawi-ldap-p7-lockout-red.log`: PostgreSQL regression before the fix. +- `/tmp/pabawi-ldap-p7-lockout-green.log`: both-adapter counter and live mutation regression. +- `/tmp/pabawi-ldap-p7-workers.log`: independent-connection and actual child-process tests. +- `/tmp/pabawi-ldap-p7-backend.log`, `frontend.log`, `browser.log`: final full regressions. + The last two names share the same `/tmp/pabawi-ldap-p7-` prefix. +- `/tmp/pabawi-ldap-p7-build-backend.log`, `lint.log`, `components.log`: final source gates, + with the same prefix. Chromium setup also builds the production frontend. +- `/tmp/pabawi-ldap-p7-dependencies.json` and `clamav.log`: registry review and clean artifact scan, + with the same prefix. + +Final counts, documentation/secret-scan evidence and retained fixture shutdown are recorded in the +package-7 handoff. No production deployment, remote push or PR was performed. + +## Remaining release work + +Obtain an authorized real AD fixture and verify every AD gate in the matrix against actual AD, +not a mock or Samba substitute. Approved parser dependency/type cleanup and lockfile verification +are complete. The automated local recovery rehearsal passes; validate environment-specific +backup/restore and the staged procedure in the +[operator guide](../../integrations/ldap.md#upgrade-and-rollout) in the intended deployment environment. +No production rollout has been observed or claimed. + +## Repeatable local acceptance + +`npm run test:ldap -- --ldap-image pabawi-ldap-fixture:package3-verified --output-root /tmp` +provisions fresh loopback-only fixtures, discovers ports, scans fixture artifacts, runs the complete +backend/frontend/browser/build/contract gates and stops fixtures while retaining all evidence. +`--focused` limits the run to backend LDAP checks; `--build-fixture` builds the default image. +See the [fixture guide](../../../backend/test/fixtures/ldap/README.md#reproducible-acceptance-runner). + +`ldap-upgrade-recovery.test.ts` retains a migration-030 snapshot, proves backup includes live WAL +commits or uses PostgreSQL custom format, upgrades through 034, checks legacy reauthentication, +local/Entra login and preserved relationships, restarts without a second session reset, rolls back a +failed candidate migration, restores the unchanged original snapshot and successfully upgrades it again. +Its synthetic migration 035 exists only in the retained fixture directory. No historic or new shipped +migration was edited or added. Artifact manifests distinguish this local rehearsal from production rollout. + +## Latest complete local run + +`/tmp/pabawi-ldap-acceptance-sGktn2/result.json` reports passed=true. The run passed 4176 backend +tests, 1079 frontend tests, three browser cases, both production builds, lint, components, all seven +documentation contracts and secret scanning. The environment and upgrade-recovery manifests retain +versions, ports, image IDs, original backups and every observed recovery stage. Both fixtures stopped. + +The explicit scanner-failure rehearsal in `/tmp/pabawi-ldap-acceptance-IjDzAQ/result.json` correctly +reports passed=false and proves both fixtures stop before acceptance can proceed. Copied artifacts +were subsequently scanned with real ClamAV. The latest handoff records completed approved dependency +cleanup and the remaining AD gate separately from these passing local checks. + +## Approved dependency cleanup verification + +User approval resolved the obsolete parser package/declaration gate. Offline uninstall removed only +@ldapjs/dn, @ldapjs/asn1 and process-warning; the obsolete declaration is deleted. The structural +lockfile proof in `/tmp/pabawi-ldap-p7c-lock-verified.json` confirms no additions or remaining package +changes. Post-removal `/tmp/pabawi-ldap-acceptance-3jP2T7/result.json` reports passed=true with 247 +focused parser, real TLS, both-adapter, transport, worker and recovery checks. Backend build and both +linters also pass. The prior complete local run remains the full frontend/browser regression evidence. +Actual AD remains the integration acceptance blocker. + + +## CI, AD harness and runner lifecycle continuation + +The LDAP CI job now calls the existing runner for PostgreSQL 15 and 17, retaining SQLite and +LDAPS/StartTLS in each job, plus the dedicated browser configuration. JSON/JUnit results, recovery +backups/manifests and browser reports/failure artifacts are uploaded with `if: always()`, limited to +the synthetic runner output. No private keys, fixture downloads, CA files or actual AD data are +uploaded. The runner checks that required live suites and browser cases actually passed, so an +exit-zero all-skipped run cannot establish acceptance. The server major version is also checked. + +The opt-in `scripts/acceptance/ad.mjs` validates local configuration, private secret references, +production LDAP settings and fixture scope without connecting. Its TypeScript fixture worker +prepares binary GUID, rename/recreation, account-state, nested-rule/traversal, ranged-membership and +equivalent-controller cases in both TLS modes. Mutations and cleanup require generated-child scope, +a run ownership marker and the unchanged binary GUID. Synthetic ownership journals support manual +investigation of incomplete cleanup. No remote provisioning or actual AD operation occurred. +Absent configuration reports `unavailable`, all cases `not-run`, `adVerified=false`, exit 1; +a valid offline configuration remains `not-run`. Local tests and those statuses are not AD evidence. + +Runner failure regressions exercise scanner rejection, readiness timeout, subprocess failure, +command deadline and SIGINT/SIGTERM. They assert nonzero status, accurate manifests, no work after +cancellation, shutdown of every attempted fixture and no surviving detached child. The detached-child +case failed against the intermediate group-only implementation and passes with descendant tracking. +Creation is recorded before Docker returns, failure paths retain environment evidence, each readiness +check has its own budget, and shutdown is inspected. Containers/data/evidence are retained. + +The fixture guide contains exact offline/opt-in commands and the distinction between controlled +transport failover and an observed controller shutdown. Actual AD remains unavailable and unverified; +package 7 remains blocked regardless of passing CI/local synthetic checks. + + +### Observed continuation evidence + +- PostgreSQL 15.17, OpenLDAP 2.6.10: `/tmp/pabawi-p7-candidate15/pabawi-ldap-acceptance-BP4dyF`. +- PostgreSQL 17.11, OpenLDAP 2.6.10: `/tmp/pabawi-p7-candidate17/pabawi-ldap-acceptance-mmfqO5`. +- Local `--build-fixture` branch plus PostgreSQL 17.11: + `/tmp/pabawi-p7-built17/pabawi-ldap-acceptance-FMdXtp`. +- Each run passes 252 focused cases, zero skipped, and all three dedicated browser cases. + Six later standalone AD ownership/cancellation tests pass. All recorded fixtures were independently + inspected as stopped. `/tmp/pabawi-p7-session-evidence.json` indexes versions, image IDs, + shutdown state and injected-failure evidence. +- `/tmp/pabawi-p7-runner-final.log`: 14 offline/configuration/workflow/runner contracts pass. + `/tmp/pabawi-p7-runner-real-final.log` retains the actual Docker failure/cancellation checks. + Their CLI/test/scanner failures are intentional; successful tests assert nonzero child results. + The final log also includes real Docker creation interrupted before its wrapper returns. +- `/tmp/pabawi-p7-ad-types.log`, `ad-unit.log`, `actionlint.log` and `actionlint-clamav.log`, + each with the `/tmp/pabawi-p7-` prefix, retain fixture typechecking, ownership tests, actionlint + 1.7.12 and the clean post-execution scanner result for its verified release archive/binary. +- `/tmp/pabawi-p7-next-build-backend.log`, `build-frontend.log`, `lint.log`, `components.log`, + `contracts.log`, `secrets.log` and `secrets-changed.log`, each with the + `/tmp/pabawi-p7-next-` prefix, retain production builds and repository gates. Scanner checks use + the unchanged reviewed baseline; synthetic invalid-configuration vectors have line-local pragmas. +- `/tmp/pabawi-p7-failure-clamav.log` retains an independent real scan of injected-failure artifacts, + including files retained after intentional scanner rejection. Containers, databases, backups, + public CAs, browser output and command evidence remain retained outside the repository. + +The workflow was parsed, checked with actionlint and its runner/build/browser behavior executed locally. +No GitHub Actions execution, remote workflow trigger, actual AD session or deployment is claimed. diff --git a/docs/internal/plans/ldap-authentication.md b/docs/internal/plans/ldap-authentication.md new file mode 100644 index 00000000..621d4a4c --- /dev/null +++ b/docs/internal/plans/ldap-authentication.md @@ -0,0 +1,1760 @@ +# LDAP authentication implementation plan + +**Status:** Packages 1 through 6 complete; package 7 CI integration, AD harness and runner failure checks implemented, blocked on actual AD +**Date:** 2026-10-21 +**Scope:** OpenLDAP and Active Directory authentication, directory group authorization, and provider-bound session revalidation + +## Agreed behavior + +Pabawi will authenticate users against one configured LDAP directory, with optional equivalent endpoints for failover. Local authentication, Entra ID, and LDAP can operate simultaneously. Users explicitly select a password authentication provider; a failed attempt never falls through to another provider. + +Connection credentials, TLS, search settings, and directory policy come from environment variables. Administrators search selected directory groups and map them directly to Pabawi roles through access administration. These mappings live in the database. There is no full-directory user import or synchronization job. + +An LDAP user gets a Pabawi account after successful credential and eligibility verification. Access requires at least one explicitly granted role, either through directory groups or a manual Pabawi assignment. New LDAP accounts receive no automatic default role. Accounts without grants can remain visible to administrators for subsequent manual assignment, but receive no session tokens. + +Directory identities remain separate from local and Entra identities, even when login names or email addresses match. LDAP passwords are used only for the current bind and are never persisted or retained for later revalidation. Directory writes, password changes, account linking, bulk synchronization, FreeIPA-specific behavior, RFC2307 `posixGroup` membership, and LDAP-specific MFA are outside this implementation. + +## Current architecture and required changes + +These observations describe the code inspected for this plan. Proposed interfaces and configuration below are implementation contracts, not existing functionality. + +| Existing surface | Current behavior | Required change | +| --- | --- | --- | +| `backend/src/routes/auth.ts` | Provider discovery advertises local and optional Entra; password login is local | Advertise LDAP public metadata and add an explicit LDAP login route | +| `backend/src/server.ts` | Entra is an authentication service outside the infrastructure plugin registry | Wire LDAP authentication and shared eligibility dependencies alongside authentication services | +| `backend/src/config/ConfigService.ts` | Parses and validates environment configuration | Add typed LDAP configuration and conditional validation; do not read `process.env` in LDAP services | +| `backend/src/services/UserService.ts` | Federated creation accepts Entra claims and hardcodes its provider | Extract provider-neutral transactional account provisioning while preserving Entra behavior | +| `backend/src/services/AuthenticationService.ts` | Shared token issuance and rotation; tokens lack provider context | Bind tokens to the authenticating identity and enforce LDAP eligibility on verification and refresh | +| `backend/src/middleware/authMiddleware.ts` | Creates its own authentication service and exposes `req.revalidateAuth` | Use shared configured authentication dependencies so request and stream checks see LDAP state | +| `backend/src/services/SessionAuthorization.ts` | Periodically checks authorization for long-lived connections | Keep its checks and place bounded LDAP freshness underneath them | +| `backend/src/services/PermissionService.ts` | Uses effective roles and database authorization revisions | Include LDAP grants and invalidate permissions on their mutation | +| `backend/src/database/migrations/016_entra_id_auth.sql`, `022_repair_entra_id_auth.sql` | Identity uniqueness is `(provider, subject)` although lookup also includes issuer | Include stable directory/provider scope in identity uniqueness and lookup | +| `backend/src/database/migrations/027_sso_boundaries.sqlite.sql` and PostgreSQL counterpart | Federated role grants lack identity provenance | Separate grants by source identity so one provider cannot erase another provider's grants | +| `frontend/src/pages/LoginPage.svelte` | Password form applies local minimum username/password lengths | For LDAP, require nonempty input and reasonable payload limits; do not impose local password creation rules | +| `frontend/src/lib/entraIdAuth.svelte.ts` | Provider discovery is Entra-specific | Extract common discovery while retaining Entra redirect handling | + +Authentication does not belong in `plugins/registry.ts`: that registry manages infrastructure integrations. Add focused authentication services rather than introducing an unrelated plugin framework. + +## Environment configuration + +### Parsing and defaults + +Use the existing configuration type definitions and `ConfigService` validation. `LDAP_ENABLED=false` is the default. When enabled, malformed configuration fails startup. Valid configuration with an unreachable directory permits startup with LDAP unavailable and local access intact. Configuration changes require restart. + +The primary host/port and additional endpoints must describe the same logical directory: identical identity attributes, search bases, schema, and policy. The stable directory ID must survive hostname changes. Pointing it at a different directory requires an intentional identity migration, not an ordinary endpoint edit. + +| Variable | Default and contract | Secret | +| --- | --- | --- | +| `LDAP_ENABLED` | `false`; strict boolean | no | +| `LDAP_DIRECTORY_ID` | Required when enabled; stable operator-chosen identifier, restricted to letters, digits, `_`, and `-` | no | +| `LDAP_DIRECTORY_TYPE` | Required: `ad` or `openldap` | no | +| `LDAP_DISPLAY_NAME` | `LDAP`; provider label in login and user administration | no | +| `LDAP_LOGIN_HELP_URL` | Empty; optional HTTP(S) help link, safely rendered | no | +| `LDAP_HOSTNAME` | Required FQDN; no embedded credentials, protocol, path, or search parameters | no | +| `LDAP_PORT` | `636` for LDAPS, `389` for StartTLS; integer 1 through 65535 | no | +| `LDAP_FAILOVER_ENDPOINTS` | `[]`; JSON array of additional `{ "hostname": "...", "port": 636 }` objects; maximum four | no | +| `LDAP_TLS_MODE` | `ldaps`; either `ldaps` or `starttls`; applies to every endpoint | no | +| `LDAP_CA_FILE` | Empty uses system trust; otherwise readable PEM CA bundle path, added to system trust | no | +| `LDAP_ALLOW_WILDCARD_CERTIFICATES` | `false`; additional restriction beyond normal hostname validation | no | +| `LDAP_LOOKUP_USER` | Required DN unless anonymous lookup is explicitly enabled | no | +| `LDAP_LOOKUP_PASSWORD` | Required nonempty value with lookup user; never expose in discovery, logs, or diagnostics | yes | +| `LDAP_ANONYMOUS_LOOKUP` | `false`; when true, lookup user/password must both be absent | no | +| `LDAP_CONNECT_TIMEOUT_SECONDS` | `10`; positive integer, at most 30 | no | +| `LDAP_OPERATION_TIMEOUT_SECONDS` | `10`; positive integer, at most 30 | no | +| `LDAP_REQUEST_TIMEOUT_SECONDS` | `30`; total LDAP transaction deadline across endpoints, binds, searches, and traversal; at most 60 | no | +| `LDAP_BASE_DN` | Required nonempty valid DN | no | +| `LDAP_USER_RDN` | Empty; optional relative DN beneath base DN | no | +| `LDAP_USER_OBJECT_CLASS` | `user` for AD, `inetOrgPerson` for OpenLDAP | no | +| `LDAP_USER_LOOKUP_ATTR` | `sAMAccountName` for AD, `uid` for OpenLDAP | no | +| `LDAP_USER_ID_ATTR` | `objectGUID` for AD, `entryUUID` for OpenLDAP; must be immutable and readable | no | +| `LDAP_USER_EMAIL_ATTR` | `mail`; missing value becomes null, never a fabricated address | no | +| `LDAP_USER_DISPLAY_NAME_ATTR` | `displayName`; fallback to current directory login name | no | +| `LDAP_USER_GIVEN_NAME_ATTR` | `givenName`; missing value becomes an empty profile field | no | +| `LDAP_USER_SURNAME_ATTR` | `sn`; missing value becomes an empty profile field | no | +| `LDAP_USER_ELIGIBILITY_FILTER` | Empty for AD means built-in AD policy; required valid filter for OpenLDAP | no | +| `LDAP_GROUP_RDN` | Empty; optional relative DN beneath base DN | no | +| `LDAP_GROUP_OBJECT_CLASS` | `group` for AD, `groupOfUniqueNames` for OpenLDAP | no | +| `LDAP_GROUP_MEMBER_ATTR` | `member` for AD, `uniqueMember` for OpenLDAP; DN-valued memberships only | no | +| `LDAP_GROUP_ID_ATTR` | `objectGUID` for AD, `entryUUID` for OpenLDAP | no | +| `LDAP_GROUP_NAME_ATTR` | `name` for AD, `displayName` for OpenLDAP; display falls back to lookup attribute | no | +| `LDAP_GROUP_LOOKUP_ATTR` | `cn`; used for administrative search, not persistent identity | no | +| `LDAP_SEARCH_NESTED_GROUPS` | `false`; direct membership only unless enabled | no | +| `LDAP_DISABLE_MATCHING_RULE_IN_CHAIN` | `false`; AD optimization switch, irrelevant for OpenLDAP | no | +| `LDAP_NESTED_GROUP_MAX_DEPTH` | `10`; positive integer, at most 32 | no | +| `LDAP_GROUP_SEARCH_LIMIT` | `100`; total returned administrative search entries, at most 500 | no | +| `LDAP_GROUP_TRAVERSAL_LIMIT` | `1000`; maximum visited groups per eligibility transaction, at most 10000 | no | +| `LDAP_REVALIDATION_INTERVAL_SECONDS` | `300`; positive integer at most 300, so operators can tighten the agreed freshness bound | no | +| `LDAP_MAX_CONCURRENT_OPERATIONS` | `10`; positive integer at most 100; bounded admission, with excess requests rejected temporarily | no | + +Validate attribute descriptions as LDAP attribute names/OIDs, DNs with a DN parser, and filters with a filter parser. Do not treat an arbitrary configured attribute name as safe filter syntax. Combine fixed administrative filters with escaped runtime values; do not support executable templates or raw client-supplied filters. + +TLS certificate verification and hostname checking are mandatory, with TLS 1.2 or newer. There is no environment option to disable them. Wildcard permission, when enabled, still uses standard hostname matching. With the default restriction, reject wildcard identities used to match the endpoint. Apply identical checks to LDAPS and StartTLS, including SNI for each selected FQDN. A failed StartTLS negotiation never falls back to plaintext. + +### Active Directory example + +Directory-service configuration, public authentication and frontend provider selection are implemented through package 6. See [the operator guide](../../integrations/ldap.md). Example: + +```dotenv +LDAP_ENABLED=true +LDAP_DIRECTORY_ID=corporate-ad +LDAP_DIRECTORY_TYPE=ad +LDAP_DISPLAY_NAME=Corporate directory +LDAP_HOSTNAME=dc1.example.com +LDAP_PORT=636 +LDAP_FAILOVER_ENDPOINTS='[{"hostname":"dc2.example.com","port":636}]' +LDAP_TLS_MODE=ldaps +LDAP_CA_FILE=/etc/pabawi/corporate-ca.pem +LDAP_LOOKUP_USER=CN=pabawi-reader,OU=Service Accounts,DC=example,DC=com +# Set LDAP_LOOKUP_PASSWORD in the protected runtime environment. +LDAP_BASE_DN=DC=example,DC=com +LDAP_USER_RDN=OU=People +LDAP_GROUP_RDN=OU=Groups +LDAP_SEARCH_NESTED_GROUPS=false +LDAP_REVALIDATION_INTERVAL_SECONDS=300 +``` + +The unset lookup password intentionally prevents this example from starting until a real secret is supplied. Use a read-only account with visibility of the relevant user status and membership attributes. The configured user search base must uniquely resolve a login name; `sAMAccountName` is not assumed unique across multiple domains. Forest-wide discovery and cross-domain referrals are excluded. + +### OpenLDAP example + +```dotenv +LDAP_ENABLED=true +LDAP_DIRECTORY_ID=corporate-openldap +LDAP_DIRECTORY_TYPE=openldap +LDAP_DISPLAY_NAME=Corporate directory +LDAP_HOSTNAME=ldap1.example.com +LDAP_PORT=389 +LDAP_TLS_MODE=starttls +LDAP_CA_FILE=/etc/pabawi/corporate-ca.pem +LDAP_LOOKUP_USER=cn=pabawi-reader,ou=services,dc=example,dc=com +# Set LDAP_LOOKUP_PASSWORD in the protected runtime environment. +LDAP_BASE_DN=dc=example,dc=com +LDAP_USER_RDN=ou=people +LDAP_USER_LOOKUP_ATTR=uid +LDAP_USER_ID_ATTR=entryUUID +# Example policy only: employeeType must exist in this deployment's schema. +LDAP_USER_ELIGIBILITY_FILTER=(employeeType=active) +LDAP_GROUP_RDN=ou=groups +LDAP_GROUP_OBJECT_CLASS=groupOfUniqueNames +LDAP_GROUP_MEMBER_ATTR=uniqueMember +LDAP_GROUP_ID_ATTR=entryUUID +LDAP_SEARCH_NESTED_GROUPS=false +``` + +OpenLDAP presets select schema attributes, not a universal account status policy. Operators must supply a positive eligibility filter and document which disabled, locked, and expired states it excludes. Test that missing status attributes do not inadvertently make a user eligible. A deployment using `groupOfNames` can override the class and membership attribute to `groupOfNames` and `member`. Memberships expressed as usernames, such as `memberUid`, require separate future support. Initially support the ordinary DN form of `uniqueMember`; reject unsupported optional UID suffixes rather than interpreting them incorrectly. + +### Relationship to Puppet Enterprise settings + +This is conceptual compatibility, not a promise to accept PE RBAC API payloads. The source of the terminology is [PE external directory settings](https://help.puppet.com/pe/current/topics/rbac_ldap_ext_directory_settings.htm). That retrieved page identifies itself as 2025.8; the requested [2025.12.0 URL](https://help.puppet.com/pe/2025.12.0/topics/rbac_ldap_ext_directory_settings.htm) was unavailable during design. + +| PE concept | Pabawi equivalent | +| --- | --- | +| Directory name and login help | `LDAP_DISPLAY_NAME`, `LDAP_LOGIN_HELP_URL` | +| Hostname, port, lookup user/password, timeout | Corresponding `LDAP_*` connection variables | +| SSL and StartTLS booleans | Single `LDAP_TLS_MODE` choice | +| Certificate chain | `LDAP_CA_FILE` | +| Hostname and wildcard validation | Mandatory hostname validation; optional wildcard permission | +| Base DN and user/group relative DNs | `LDAP_BASE_DN`, `LDAP_USER_RDN`, `LDAP_GROUP_RDN` | +| User login, email, full name attributes | Corresponding lookup/email/display name variables | +| Group object class, member, display, and lookup attributes | Corresponding `LDAP_GROUP_*` variables | +| Nested groups and matching rule switch | `LDAP_SEARCH_NESTED_GROUPS`, `LDAP_DISABLE_MATCHING_RULE_IN_CHAIN` | + +Pabawi additionally needs immutable user/group IDs, explicit eligibility policy, endpoint failover, query limits, and session freshness settings. Unlike the optional security choices in the reference, this design requires TLS and hostname validation. + +## Identity and database design + +### Accounts and profile ownership + +Keep the existing globally unique `users.username` as an internal identifier. New LDAP accounts receive a deterministic reserved identifier derived from provider, directory ID, and immutable subject, not their mutable login name. Encode components unambiguously and reserve this namespace from local account creation. Store directory login name and display name separately. Preserve existing local usernames and existing Entra accounts; do not mass-rename them. + +Make contact email nullable and nonunique for external accounts. Preserve local email requirements and uniqueness through an explicit local credential/account scope and a corresponding database constraint. Never use a global `findByEmail(): User | null` contract once duplicate emails are legal. Replace ambiguous callers with scoped local lookup or an explicit set of matches. Preserve the existing Entra collision rejection policy with an explicit query; changing the email index must not silently enable linking or change Entra enrollment behavior. + +Use nullable password hash types consistently in backend and frontend DTOs. A directory-only user has no local password. Authenticated password changes and administrative password updates must reject LDAP accounts. Existing explicitly enrolled Entra accounts that already have local credentials keep their established behavior. + +Add a dedicated display name field rather than splitting arbitrary full names into invented first and last names. Refresh LDAP login, display name, given name, surname, and contact email from directory data at login and successful revalidation. Profile refresh never alters Pabawi suspension, manual grants, or administrative status. LDAP profile fields are read-only through user management APIs as well as the UI. + +There is currently no email password recovery workflow. Preserve unambiguous local credential operations now; any future email recovery must select a local account explicitly and cannot resolve an account from an unscoped email match. + +### Required logical records + +Choose new migration numbers from the repository's current sequence during implementation. Implement equivalent SQLite and PostgreSQL migrations through `DatabaseService`. + +| Record | Required fields and invariants | +| --- | --- | +| Federated identity | Existing ID and user reference, provider, stable issuer/directory scope, immutable subject; unique `(provider, issuer, subject)` | +| LDAP identity metadata | Identity reference, current login name, DN and profile metadata; DN/login are mutable locators, never identity keys | +| External group mapping | ID, directory ID, immutable group subject, current DN/name, role ID, enabled flag, audit timestamps; unique `(directory_id, group_subject, role_id)` | +| External role grant | User ID, role ID, identity/source ownership, mapping ID when group-derived; retain multiple provenance rows when several mappings grant one role | +| LDAP validation state | Identity ID, last successful validation timestamp, monotonically increasing validation generation, and applicable mapping/config revision | +| LDAP validation lease | Identity ID, lease owner/expiry and fencing generation for cross-process refresh coordination | + +Reuse and extend `federated_identities` and `federated_user_roles` where this produces a coherent model. Do not create a second unsynchronized identity store. Entra reconciliation must delete only Entra-owned grants; LDAP reconciliation must delete only LDAP-owned grants. Manual `user_roles` and local group assignments remain separate. Backfill existing Entra grants with ownership, including accounts explicitly enrolled from local authentication, without dropping permissions. + +Update `effective_user_roles`, permission queries, authorization revision triggers, and indexes on both database adapters. Deduplicate effective roles while preserving grant provenance. Removing one mapping cannot remove an identical role still granted by another mapping or manually. + +Provision user, identity, initial grants, and validation state atomically. Resolve concurrent first logins using database identity uniqueness and a transaction retry/read strategy; never create two users for the same immutable identity. For a proven identity with no grants, commit the account without tokens so an administrator can later grant a role. Failed binds must not provision accounts. + +SQLite table rebuilds must preserve dependent foreign keys, indexes, views, triggers, and data. Test upgrades from real migrated databases, not only freshly created schemas. Existing identity references must remain stable. + +## Authentication services and login flow + +Add `LdapDirectoryService` for read-only connection/search/bind operations and `LdapAuthenticationService` for provisioning and authorization orchestration. Add a shared provider-aware session eligibility service usable by every authentication entry point. Follow existing typed errors and structured `LoggerService` metadata. Do not introduce a separate token implementation. + +Use `ldapts` as the proposed TypeScript client, with its exact release pinned in the lockfile after checking Node engine compatibility and package review. Its documented client supports LDAPS, `startTLS()`, connection/operation timeouts, binary attributes, paginated searches, filter escaping, and `unbind()`. Use dedicated user-bind connections and close clients in `finally`. The API references are the [ldapts repository](https://github.com/ldapts/ldapts); filter construction must conform to [RFC 4515](https://www.rfc-editor.org/rfc/rfc4515). + +The login transaction is: + +1. Require explicit LDAP selection and nonempty username/password. Apply body limits and rate limits before directory work. Do not trim or normalize passwords. Use case-preserving login input and the directory's matching semantics. +2. Select an endpoint, establish verified TLS, and bind the lookup account, or explicitly bind anonymously. No credential-bearing operation precedes StartTLS. +3. Search under `USER_RDN + BASE_DN` using the configured user class, escaped login equality, and eligibility policy. Request only needed identity, profile, and status attributes. Require exactly one result and a valid immutable ID. Zero results, ambiguity, or incomplete/limited results cannot authenticate. +4. Open a separate TLS connection to the same endpoint and bind with the returned user DN and supplied password. Never construct a user DN from submitted text. Never rebind a shared lookup client as the user. +5. With the lookup connection, read current status and resolve mapped direct/nested groups. Check the same immutable identity after the user bind so a changed locator cannot attach credentials to another object. Treat directory changes during authentication as a retryable transaction failure, not an identity substitution. +6. Transactionally provision or update the account and LDAP-owned grants, respecting local suspension. Evaluate effective explicit roles, including manual assignments. Issue no tokens if the user has no role or remains suspended. +7. Generate the existing Pabawi token pair with authenticated provider/identity context. Audit the result with safe reason codes and clear transient credential references on exit. + +Reject empty passwords before calling LDAP: a server accepting an unauthenticated bind must never authenticate an empty password. Automatic reconnect/rebind must not replay user credentials or resume a StartTLS session without reestablishing TLS. Use transaction-scoped clients; discard a connection when its TLS or bind state is uncertain. + +Canonicalize `entryUUID` as a validated UUID. Read AD `objectGUID` as binary, with a single tested canonical encoding for persistence and filter reconstruction. Do not use lossy text decoding, DN lowercasing, or a mutable login as the subject. Missing identity attributes are configuration/data failures, not permission to fall back to the DN. + +### Eligibility policy + +For AD, evaluate supported account disablement, account expiration, lockout, and password-expiration indicators using documented attributes and server-computed state where readable. Distinguish Windows FILETIME values from Unix timestamps and test sentinel values. Make the required readable attributes part of diagnostics. A configured extra eligibility filter further restricts the built-in policy and cannot bypass it. + +For OpenLDAP, use the operator's configured filter on every eligibility search. If policy relies on operational attributes, request them explicitly. Diagnostics must distinguish a readable inactive account from missing policy visibility where possible. A successful bind is necessary at login, but not a substitute for a revalidation policy. + +Password changes or conditions observable only during a user bind cannot reliably be detected later without the password. Do not claim otherwise. Revalidation enforces directory existence and the status/membership information available to the lookup identity; fresh authentication is required for bind-only conditions. + +## Group resolution and role administration + +Map external groups directly to roles, following the existing federated-role approach. Do not mirror every external group into local Pabawi RBAC groups. Add controls alongside `RoleManagementPage.svelte` and `RoleDetailDialog.svelte`, with provider/source information in user administration. `GroupDetailPage.svelte` manages infrastructure node groups and is not the appropriate surface. + +Administrator group search uses `GROUP_RDN + BASE_DN`, the configured object class, and an escaped name/lookup substring with server-enforced limits. Return current display/lookup name, DN, and immutable ID. Creating a mapping resolves the submitted immutable ID against the configured directory and confirms the target role. A DN or display label supplied by the browser is not authoritative. + +For direct membership, test whether each mapped group contains the user's current DN in the configured DN-valued membership attribute. Follow group references only when nested membership is enabled, remaining within the configured group search scope. Use parsed LDAP DN equality and a visited set; do not compare DNs using ad hoc string normalization. + +For AD nested membership, use `LDAP_MATCHING_RULE_IN_CHAIN` where supported and enabled; its recursive link rule is specified by [Microsoft](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/1e889adc-b503-4423-8985-c28d5c7d4887). The optimization must preserve the configured scope and resource limits. Use bounded traversal instead when disabled or when the server definitively reports the operation unsupported. Do not retry arbitrary directory errors as a different query strategy. + +For OpenLDAP nested membership, traverse supported DN-valued group memberships with depth, visited-group, time, and result limits. Detect cycles. For AD member retrieval, handle ranged attributes if a traversal reads large member lists. Primary-group SID resolution and membership outside the configured group scope are excluded from this first version and must be stated in the operator guide. + +Return no partial authorization decision when a query, referral, pagination boundary, depth bound, or result limit prevents establishing complete membership. Deny the attempted validation and preserve the distinction between an outage and a confirmed empty group set. Do not erase stored grants merely because a directory transaction failed. + +Mapping creation, replacement, disablement, and deletion require `rbac:admin`, as do directory search and diagnostics. Preserve the application's existing page-level management guard and enforce API permissions independently. Search and mapping are separate operations; viewing search results never imports users or assigns roles. + +On a mapping edit, increment a database mapping revision and invalidate affected validation state. Removal must withdraw that mapping's materialized grants transactionally, with authorization revision changes visible to all processes. New mappings force fresh membership validation before granting access. An in-flight validation must compare its starting revision with the current revision before committing, so it cannot resurrect a removed grant. + +## Session freshness and revocation + +Add signed authentication context to access and refresh tokens: provider, identity ID, and directory ID for LDAP. Resolve the identity from the database and verify it belongs to the token's user; token context cannot select arbitrary accounts or endpoints. Rotation retains the same context. Local and Entra behavior remains independent of directory availability. + +Every LDAP login establishes fresh directory state. Every refresh forces a fresh check, with only concurrent in-flight checks coalesced. Other authenticated activity may use the last successful check for at most `LDAP_REVALIDATION_INTERVAL_SECONDS`, measured from the start of the directory read to avoid extending freshness by a slow transaction. At the deadline, stop delivering protected data or authorizing new operations until a fresh check succeeds. + +Revalidation uses the lookup identity to find the immutable subject, evaluate status, refresh profile, and resolve mapped memberships. It never rebinds as the user. Persist successful validation state and mapping revision in the database. Coordinate concurrent checks through bounded leases/fencing and in-process single-flight. Expired or failed work cannot overwrite a newer result or extend a successful timestamp. Use database time for cross-process timestamps and lease checks. + +| Outcome | Required behavior | +| --- | --- | +| Eligible user with explicit roles | Reconcile LDAP grants and profile atomically; continue | +| Group removal with remaining manual/other mapped roles | Remove lost grants; continue with reduced permissions | +| No remaining explicit role | Reject protected access and revoke LDAP sessions | +| User deleted, observably disabled/expired, or locally suspended | Reject access and revoke LDAP sessions; never reactivate local suspension | +| Network/TLS/search error or exceeded resolution limit | Do not advance freshness or erase grants; block LDAP access once freshness expires | +| Directory recovery after transient failure | Existing otherwise valid sessions may resume after a successful fresh check | +| Positive revocation followed by directory recovery | Require a new login; previously revoked tokens remain invalid | + +Use existing account-wide `session_version` for LDAP-only accounts when positively revoked. Profile refreshes must not accidentally trigger session revocation. Permission changes must invalidate effective permission caches, even when sessions remain valid. + +Connect the common eligibility service to ordinary REST middleware, refresh, SSE revalidation, MCP authorization, and console websocket checks. The console path currently checks `ConsoleSessionManager.assertSessionAuthorized`, so JWT middleware alone is insufficient. Close or stop protected delivery on stale/invalid authorization for each transport. Already dispatched infrastructure jobs are not automatically cancelled; authorization is checked before new actions and output delivery. + +No background full-directory polling is needed. Active connections drive periodic checks; an idle HTTP session is checked when next used. Request coalescing and bounded concurrency prevent the existing frequent stream checks from becoming frequent LDAP queries. + +Deploy the token-context change with an intentional one-time session invalidation and required reauthentication. Do not guess a legacy token's provider from email or from whichever linked identity happens to be present. Issue provider-bound tokens for local and Entra login as part of the same release. + +## HTTP and frontend contracts + +The route contracts and frontend controls below are implemented through package 6. Use existing async route helpers, request validation, typed errors, audit infrastructure, and RBAC middleware. + +| Method and path | Access | Contract | +| --- | --- | --- | +| `GET /api/auth/providers` | Public | Add LDAP enabled/display/help metadata; expose no hostnames, search bases, credentials, or directory diagnostics | +| `POST /api/auth/ldap/login` | Public, rate limited | `{ username, password }`; same successful authentication DTO as local login | +| `POST /api/auth/refresh` | Existing refresh contract | Retain provider context and force LDAP verification for LDAP refresh tokens | +| `GET /api/auth/ldap/groups` | `rbac:admin` | Bounded `query` and opaque pagination cursor; selected group metadata only | +| `GET /api/auth/ldap/mappings` | `rbac:admin` | List mappings with roles and current/stored group labels | +| `POST /api/auth/ldap/mappings` | `rbac:admin` | Persist a verified group-subject/role mapping | +| `PUT /api/auth/ldap/mappings/:id` | `rbac:admin` | Change enabled state or role; verify directory/group ownership | +| `DELETE /api/auth/ldap/mappings/:id` | `rbac:admin` | Remove mapping and its attributable grants transactionally | +| `POST /api/auth/ldap/test` | `rbac:admin`, rate limited | Test configured TLS/lookup and optionally an exact user/group lookup; accept no user password or arbitrary connection overrides | + +Administrative cursors must be bound to the current directory/configuration and filter, bounded in lifetime and opaque to clients. Group creation can map several roles through separate unique mapping records. Mapping administration may show stored mappings during an outage, but cannot verify new directory identities until connectivity returns. + +Keep LDAP configured and visible in provider discovery during an outage; its login route can return temporary unavailability. Use `401` with a generic credential message for failed/ambiguous authentication, `403` for an authenticated but ineligible or unassigned user, `429` for rate/capacity limits, and `503` for directory unavailability or incomplete resolution. Return safe error codes; detailed directory reasons belong in restricted logs. All login failures must avoid disclosing whether a username exists. + +Reuse existing login throttling, but scope counters to provider, directory ID, and submitted login, with IP limits as well. A local username must not share a lockout counter with an LDAP username. Do not retry user bind failures across endpoints: a rejected credential must not multiply directory lockout attempts. + +The login page selects Local or the configured directory for password entry; Entra retains its redirect button. Keep token storage behavior in `auth.svelte.ts`. Show directory source and current directory login/display name in user administration. Render null contact emails safely in auth/user/group DTOs, filtering, search, dialogs, and tables. A missing email is not a broken profile. + +Diagnostics return per-stage status, timings, and safe error codes. Test both identity and eligibility visibility for an exact supplied user, without treating that lookup as proof of password authentication. Group diagnostics test direct/nested resolution for selected mapped groups. Redact passwords, token material, raw LDAP diagnostic strings, unnecessary personal fields, and raw connection configuration from responses. Diagnostics use only configured endpoints so they do not become an arbitrary network probe. + +## Failure handling and operations + +Retry only transient connection establishment failures against configured equivalent endpoints, within the total deadline. Stop on certificate/hostname failures, rejected lookup credentials, invalid user credentials, policy denial, malformed data, or ambiguity. Do not follow LDAP referrals to unconfigured endpoints. Search references or partial results that affect authentication cause validation failure. + +Preserve local startup/setup and emergency administrator access during directory outages. Directory availability is a degraded component signal, not process liveness failure. Add a restricted readiness/diagnostic view and metrics or existing structured monitoring hooks for connection latency, validation latency, revalidation failures, limits, and failover. Public health responses must not disclose directory topology. + +Use structured logs with `{ component, operation }` and safe provider/directory identifiers. Audit successful/failed login, mapping mutations, manual entitlement edits, suspension, positive revocation, and effective entitlement changes. Avoid one audit event per unchanged five-minute check. Record IDs and reason codes rather than passwords or complete directory entries. Environment lookup credentials remain in the deployment secret boundary; never store another copy in the database. + +## Implementation sequence + +1. **Schema and identity boundaries:** Add migrations for provider-scoped identity uniqueness, source-owned grants, optional external contact email, local credential scope, profile fields, and validation coordination. Backfill existing accounts and Entra grants. Update DTOs and scoped email callers. Verify SQLite and PostgreSQL upgrades before building LDAP on these assumptions. +2. **Provider-neutral provisioning:** Refactor Entra-specific creation into a shared transactional primitive with explicit default-role policy. Keep Entra defaults/enrollment behavior and manual assignments intact. LDAP explicitly requests no default role and forbids linking/local password creation. +3. **Directory configuration and client:** Add configuration types/parser, presets, conditional validation, TLS, bounded read-only operations, immutable ID codecs, status policies, failover, and direct/nested group resolution. Add the dependency through the approved package-install path. +4. **Authorization administration:** Add mapping persistence, restricted search/diagnostics/routes, source attribution, revision invalidation, and role-management UI controls. +5. **Provider-bound authentication:** Implement LDAP login and common session eligibility, token context, shared dependency wiring, refresh checks, and transport integration. Introduce the one-time session invalidation in the release migration. +6. **Frontend and operator documentation:** Add provider selection, directory-owned profile behavior, null-safe contact fields, examples, and documented policy/diagnostic behavior. Update `backend/.env.example`, `docs/configuration.md`, `docs/api.md`, `docs/openapi.yaml`, `docs/permissions-rbac.md`, and add `docs/integrations/ldap.md`. +7. **Acceptance and rollout:** Run migration, directory interoperability, revocation, RBAC, frontend, and regression coverage. Publish no support claim for real AD until tested against an actual AD environment. + +## Session execution plan + +These are ordered work packages, not estimates of context-window capacity. One session may complete several packages; a package may need several sessions. The design sections above remain authoritative. Record execution progress here so another agent can resume without conversation history. + +### Start and finish each session + +1. Read the current repository instructions, this package's prerequisites, its referenced design sections, and the latest handoff record. Check the actual branch, working tree, and prerequisite implementation before relying on recorded status. +2. Understand the affected architecture and callers before editing. Confirm current migration numbers, test locations, and package scripts from the repository. Preserve unrelated work. +3. Work within the selected package. Include the compatibility changes needed to keep local and Entra behavior working at every checkpoint. If a discovered dependency changes the package boundary, record it here before proceeding. +4. Run focused acceptance tests and relevant build/lint checks. Record exact commands and outcomes in the external command log. Update API/configuration contracts whenever an implemented route or variable changes, even when the full operator guide belongs to a later package. +5. Update the progress table and append a handoff entry before ending the session. Mark a package complete only when its acceptance criteria pass; missing AD/PostgreSQL evidence remains pending or blocked. Record pre-existing failures separately from regressions. + +Keep LDAP login unavailable until package 5B passes. Use the implementation's agreed configuration and wiring to enforce that boundary, without adding temporary bypasses or advertising unfinished authentication. A checkpoint must preserve existing functionality. + +### Package 1 Identity and schema + +**Prerequisites:** None. Read [Identity and database design](#identity-and-database-design) and the migrations, identity, profile, and authorization rows in [Acceptance tests](#acceptance-tests). + +**Scope and files:** Own forward SQLite/PostgreSQL migrations, identity uniqueness, external email nullability, local credential scope, source-owned grants, mapping/validation records, indexes, views, and revision triggers. Update affected queries and nullable DTO consumers together. Main surfaces: `backend/src/database/migrations/`, `UserService.ts`, `PermissionService.ts`, `AuthenticationService.ts` DTOs, Entra grant reconciliation, and frontend user/email consumers. + +**Exclusions:** LDAP network operations, login routes, and token-format changes. Validation tables may exist without enabling session checks. + +**Acceptance:** Fresh and upgraded databases preserve local and Entra identities, explicit enrollments, permissions, and referential integrity on both adapters. External missing/duplicate contact emails work; local uniqueness remains enforced. Existing Entra synchronization uses the new provenance model correctly. Null email renders safely. + +**Checks:** Focused migration, authorization-state, concurrency, user/Entra provisioning and frontend nullability tests; backend/frontend builds and applicable lint/component checks. + +**Handoff:** Record migration numbers, identity/grant keys, scoped email APIs, backfill assumptions, and exact upgrade fixtures/results. Existing writers and readers must agree on the schema before this package is complete. + +### Package 2 Shared provisioning + +**Prerequisites:** Package 1. Read [Authentication services and login flow](#authentication-services-and-login-flow) and the provisioning transaction rules in [Identity and database design](#identity-and-database-design). + +**Scope and files:** Extract provider-neutral transactional provisioning from `backend/src/services/UserService.ts`; adapt `EntraIdService.ts` callers. Define immutable identity inputs, profile ownership, explicit default-role policy, conflict handling, and first-login concurrency. Enforce LDAP account ownership in user/password update routes. + +**Exclusions:** Live LDAP access and public LDAP authentication. Preserve existing Entra default-role and explicit enrollment semantics. + +**Acceptance:** Existing local/Entra flows pass. Service-level LDAP provisioning creates one account under concurrency, assigns no default role, preserves suspension/manual grants, and prevents local password attachment or implicit linking. + +**Checks:** Provisioning, Entra auth-flow/group-sync, user update, and password-boundary regressions; backend build/lint. + +**Handoff:** Record the shared provisioning API, transaction ownership, role-policy inputs, and all migrated callers. + +### Package 3 Directory configuration and service + +**Prerequisites:** Packages 1 and 2. Read [Environment configuration](#environment-configuration), [Authentication services and login flow](#authentication-services-and-login-flow), and [Group resolution and role administration](#group-resolution-and-role-administration). + +**Scope and files:** Add typed LDAP configuration through `backend/src/config/`, the reviewed dependency in `backend/package.json` and lockfile, and `LdapDirectoryService` under `backend/src/services/`. Implement TLS, lookup/user-bind isolation, status policies, immutable ID codecs, bounded searches, endpoint failover, and direct/nested membership. Add reproducible directory fixtures and update implemented configuration references. + +**Exclusions:** Role-mapping administration, Pabawi token issuance, and frontend login. Keep directory support callable through internal services/tests. + +**Acceptance:** Disabled LDAP leaves existing startup behavior intact. Invalid configuration fails; an unreachable configured directory permits local access. OpenLDAP fixtures verify both TLS modes, binding, eligibility, group classes, limits, and cleanup. AD behavior has protocol-level tests, with actual AD evidence explicitly deferred if unavailable. + +**Checks:** Configuration/client unit tests, real OpenLDAP integration tests, backend build/lint, and documentation contracts. + +**Handoff:** Record the pinned library release, service API, fixture commands, supported policy attributes, TLS/failover evidence, and real AD cases still outstanding. + +### Package 4 RBAC mapping administration + +**Prerequisites:** Packages 1 through 3. Read [Group resolution and role administration](#group-resolution-and-role-administration) and [HTTP and frontend contracts](#http-and-frontend-contracts). + +**Scope and files:** Implement mapping persistence, bounded directory group search, diagnostics, administrative routes, audit events, materialized-grant withdrawal, and cross-process revision invalidation. Main surfaces: `backend/src/services/`, `backend/src/routes/`, server/container wiring, and API documentation. Complete the backend contract here; mapping controls are owned by package 6. + +**Exclusions:** Public LDAP login, token changes, and bulk user import. + +**Acceptance:** Search/test/mapping endpoints enforce `rbac:admin`. Mapping edits preserve grants from other sources, invalidate stale validation state, and cannot be undone by an in-flight old revision. Outages and fabricated group identities produce the agreed failures without leaking credentials. + +**Checks:** Supertest permission/error cases, provenance and revision-race tests on both adapters, backend build/lint, and documentation contracts. + +**Handoff:** Record route/service contracts, mapping revision behavior, audit events, and frontend integration examples using synthetic IDs. + +### Package 5 Authentication and session enforcement + +Read [Session freshness and revocation](#session-freshness-and-revocation), [HTTP and frontend contracts](#http-and-frontend-contracts), and the freshness, concurrency, and transport acceptance rows. Split this package at the following checkpoints when needed. + +#### Package 5A Provider context and shared authentication wiring + +**Prerequisites:** Packages 1, 2, and 4. + +**Scope and files:** Add verified provider/identity context to token creation, validation, and rotation for existing authentication providers. Replace isolated authentication-service construction with shared configured dependencies. Main surfaces: `AuthenticationService.ts`, `EntraIdService.ts`, `authMiddleware.ts`, server/container wiring, and authentication routes. Add the intentional one-time session invalidation in the appropriate forward migration. + +**Exclusions:** Issuing LDAP tokens before 5B is complete. + +**Acceptance:** Local and Entra login/refresh remain functional with explicit context. Forged, mismatched, or invalidated context fails. The legacy-session transition requires reauthentication without guessing provider ownership. All relevant callers can reach the shared eligibility seam. + +**Checks:** Local/Entra login-refresh, revocation and context-binding tests; fresh/upgrade session invalidation on both adapters; backend build/lint. + +**Handoff:** Record token payload contracts, migration/session invalidation behavior, dependency wiring, and exact transport integration points remaining for 5B. + +#### Package 5B LDAP login and all transport checks + +**Prerequisites:** Packages 3, 4, and 5A. + +**Scope and files:** Implement `LdapAuthenticationService`, explicit login and provider discovery, forced refresh verification, persisted freshness/leases/fencing, grant/profile reconciliation, provider-scoped throttling, and revocation. Wire REST, `SessionAuthorization`, SSE, MCP, and console authorization to shared eligibility enforcement. + +**Exclusions:** Login UI and automatic cancellation of already dispatched infrastructure work. + +**Acceptance:** LDAP tokens are issued only after the complete credential/eligibility/role transaction. Every supported transport blocks stale state at the deadline. Refresh forces verification; failed work cannot extend freshness or resurrect grants. Positive revocation remains terminal while transient recovery follows the agreed policy. Local/Entra sessions remain independent of LDAP availability. + +**Checks:** HTTP login/refresh integration tests, fake-clock deadline tests, cross-process coordination and revision-race tests, plus REST/SSE/MCP/console revocation coverage. Run backend regressions, build/lint, and documentation contracts. + +**Handoff:** Record enforcement evidence for each transport, freshness/lease state transitions, throttling keys, outage/recovery behavior, and any remaining interoperability evidence. Package 5 is complete only when both checkpoints pass. + +### Package 6 Frontend and operator documentation + +**Prerequisites:** Packages 4 and 5B, including stable HTTP/DTO contracts. Read [HTTP and frontend contracts](#http-and-frontend-contracts), [Environment configuration](#environment-configuration), and [Failure handling and operations](#failure-handling-and-operations). + +**Scope and files:** Implement common provider discovery, explicit password-provider selection, role-mapping controls, restricted diagnostics, directory source labels, and directory-owned profile editing rules. Main surfaces: `LoginPage.svelte`, `auth.svelte.ts`, `entraIdAuth.svelte.ts`, role/user management pages and dialogs. Finish `docs/integrations/ldap.md`, configuration/env examples, API/OpenAPI, and RBAC documentation. + +**Exclusions:** Reworking the agreed backend identity/security contract or claiming unverified AD interoperability. + +**Acceptance:** Provider selection never falls through; valid short directory credentials reach LDAP; nullable email and read-only profile fields work throughout user management. Mapping and diagnostic controls respect API and page permissions. Local and Entra UI regressions pass. Operator instructions explain status visibility, exclusions, outages, restart, and upgrade reauthentication. + +**Checks:** Focused component/API integration tests, appropriate browser/E2E flows, frontend tests/build/lint, component checking, and documentation contracts. + +**Handoff:** Record UI/browser evidence, operator guide locations, actual implemented defaults, and any remaining end-to-end cases. + +### Package 7 Interoperability and rollout + +**Prerequisites:** Packages 1 through 6. Read the complete [Acceptance tests](#acceptance-tests), [Failure handling and operations](#failure-handling-and-operations), and [Completion criteria](#completion-criteria). + +**Scope and files:** Verify real OpenLDAP and AD behavior, both database adapters, multi-process races, failover, every transport, and existing local/Entra functionality. Fix failures in their owning modules with regression coverage. Finish deployment and upgrade instructions based on observed behavior. + +**Exclusions:** Production deployment, remote pushes, PR creation, destructive cleanup, or sharing real directory data without the confirmations required by repository instructions. + +**Acceptance:** Every acceptance row has passing evidence. Missing real AD or PostgreSQL access is a recorded blocker to completion, not a waived test. Operators can configure either supported directory from the guide and understand the intentional session invalidation. + +**Checks:** The full commands under [Commands for the implementation phase](#commands-for-the-implementation-phase), relevant E2E checks, real directory fixtures, and SQLite/PostgreSQL upgrade scenarios. Record unavailable tools and their effect on completion. + +**Handoff:** Record release readiness, exact environment/version evidence without secrets or personal records, unresolved blockers, and the deployment procedure. + +### Progress and handoff records + +Update this table as work proceeds. Status values: `pending`, `in_progress`, `blocked`, or `complete`. A package can remain `in_progress` across several agent sessions. + +| Package | Status | Completion commit or working tree reference | Latest handoff | +| --- | --- | --- | --- | +| 1 Identity and schema | complete | Commit `a739cf2`, migration 031 and consumers | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-1) | +| 2 Shared provisioning | complete | Commit `2d37548`, verified against current source | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-2) | +| 3 Directory configuration and service | complete | Commit `4fac169`, verified against current source | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-3) | +| 4 RBAC mapping administration | complete | Commit `4a5c2b4`, verified against current source | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-4) | +| 5A Provider context and wiring | complete | Commit `7f58092`, verified against current source | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-5a) | +| 5B LDAP login and transport enforcement | complete | Commit `56ea384`, verified against current source | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-5b) | +| 6 Frontend and operator documentation | complete | Commit `55c8107`, verified against current source | [2026-10-21 Codex](#handoff-2026-10-21-codex-package-6) | +| 7 Interoperability and rollout | blocked | Branch `151`, current base `7389784`; CI integration, opt-in AD harness and runner lifecycle regressions implemented; [acceptance evidence](ldap-acceptance.md) | [2026-10-21 Codex CI and harness](#handoff-2026-10-21-codex-package-7-ci-and-harness) | + +Append a record using the following fields after each implementation session. Use an actual commit hash when available, otherwise identify the branch/base and changed paths explicitly. Preserve prior records and correct outdated findings with a new entry. + +```text +Date and agent: +Package and checkpoint: +Branch, base commit, completion commit or uncommitted paths: +Completed scope and changed interfaces: +Verification: exact commands, outcomes, and external log reference: +Pre-existing failures: +Remaining work and blockers: +Decisions or discoveries affecting the next package: +Next action and acceptance criterion still to satisfy: +``` + +For a new agent session, use: "Read AGENTS.md and docs/internal/plans/ldap-authentication.md. Resume package from its latest handoff. Complete its scope and acceptance checks, then update the progress table and append a handoff record. Follow the current command-log instructions." + +## Acceptance tests + +Use existing Vitest, Supertest, migration fixtures, security tests, and frontend conventions. Place backend unit tests under `backend/test/unit/`, HTTP flows under `backend/test/integration/`, revocation cases under `backend/test/security/`, and database upgrade/concurrency tests under `backend/test/database/`. Co-locate Svelte tests with their components. + +| Area | Required evidence | +| --- | --- | +| Configuration | Disabled LDAP requires no credentials; enabled invalid configuration fails; malformed JSON, DNs, attributes, filters, TLS mode, missing CA files, and inconsistent anonymous settings fail | +| TLS and failover | Trusted LDAPS and StartTLS succeed; untrusted CA, hostname mismatch, forbidden wildcard, failed upgrade, and plaintext attempts fail; connection failover works without credential replay | +| Credentials | Empty passwords never bind; correct credentials succeed; wrong credentials, zero/multiple matches, missing immutable IDs, injection input, partial searches, and timeouts issue no tokens | +| Identity | Renamed/moved users retain identity; reused names/DNs do not inherit accounts; duplicate/missing external emails work; local names/emails retain their rules; concurrent logins create one account | +| Profiles | Directory changes refresh safely; missing names/email render; profile sync does not revoke valid sessions or undo local suspension; LDAP password/profile writes fail server-side | +| Authorization | No default role; zero-role user gets no token; manual assignment enables subsequent login; multiple mappings union roles; one removed mapping preserves other provenance | +| Groups | Direct and nested OpenLDAP/AD membership, cycle detection, scope, depth/result limits, group rename/recreation, and unsupported AD matching-rule behavior | +| Status | AD observable disabled/expired/locked states; OpenLDAP positive policy including missing attributes; bind-only limitations documented | +| Freshness | Fake-clock tests at the exact deadline; refresh forces verification; outage does not extend freshness; transient recovery resumes valid sessions; positive revocation remains terminal | +| Concurrency | Cross-process leases, fencing, stale completion, mapping-revision races, and simultaneous refresh cannot restore obsolete grants or timestamps | +| Transports | REST, refresh, SSE, MCP, and console websocket reject stale/invalid LDAP state while local and Entra remain independent | +| Administration | Every search/mapping/test endpoint rejects missing permissions; request fields cannot override endpoints or fabricate group identity; mutations audit and invalidate permissions | +| Migrations | Fresh and upgraded SQLite/PostgreSQL preserve users, Entra enrollments, grants, foreign keys, triggers/views, uniqueness, and intentional session invalidation | +| UI | Provider selection never falls through; LDAP accepts directory-valid short credentials; directory fields are read-only; null email, mappings, empty results, and outages render correctly | + +Run real OpenLDAP integration tests for both TLS modes and supported group classes with an explicit eligibility policy. Test real AD for GUID handling, account state, nested matching rules, large/ranged membership, and failover. A mock LDAP server or Samba-only result is insufficient evidence of real AD compatibility. + +### Commands for the implementation phase + +Run from the repository root unless stated otherwise. These are planned commands, not commands executed while writing this document. Log commands according to the current repository instructions in `~/.agents/logs/pabawi.jsonl`, outside the repository. Create the log directory/file if missing, append one JSON object per line, redact secrets, and record command outcomes after completion. Skip trivial read-only commands as specified in AGENTS.md. + +```bash +# Add the backend dependency through the required package review wrapper. +socket npm install ldapts --workspace=backend + +# Run focused new tests first, using their actual implementation filenames. +# Then check the complete workspace and documentation contracts. +npm run test --workspace=backend +npm run test --workspace=frontend +npm run build +npm run lint +npm run check:components +node --test scripts/documentation/contracts.test.mjs +bash scripts/quality/secret-scan.sh +git diff --check +``` + +Use a reproducible directory test fixture with its own documented startup and cleanup commands during implementation. Scan downloaded fixture artifacts with ClamAV after use as required by the project instructions. Do not commit directory secrets, real user records, or production CA private keys. The CA bundle contains public certificates only. + +## Completion criteria + +The implementation is complete when both supported directory types authenticate and authorize through the agreed configuration, users can be managed without identity collisions or implicit linking, directory eligibility controls every supported transport within the freshness bound, migrations preserve existing local/Entra behavior, and the acceptance matrix passes on SQLite and PostgreSQL. The operator guide must state observable status limitations, group scope exclusions, restart requirements, outage behavior, and the one-time reauthentication required on upgrade. + + +## Handoff 2026-10-21 Codex package 1 + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 1, identity and schema, complete. LDAP network access, provider discovery, login routes, token context, and runtime eligibility enforcement remain assigned to later packages. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base `2c23a95b81a2492d6dec5f3a76ea0b3afe06e76f`. No completion commit was created. The plan was already untracked at the start of this session. All implementation changes remain in the working tree: + +```text +backend/src/database/migrations/031_external_identity_boundaries.postgres.sql +backend/src/database/migrations/031_external_identity_boundaries.sqlite.sql +backend/src/services/AuthenticationService.ts +backend/src/services/EntraIdService.ts +backend/src/services/GroupService.ts +backend/src/services/UserService.ts +backend/test/UserService.password.test.ts +backend/test/database/BatchLifecycleMigration.test.ts +backend/test/database/external-identity-boundaries.test.ts +backend/test/database/migration-integration.test.ts +backend/test/database/rbac-schema.test.ts +backend/test/database/sso-concurrency.test.ts +backend/test/properties/EntraIdAuthCode.property.test.ts +backend/test/properties/EntraIdCallback.property.test.ts +backend/test/properties/EntraIdGroupSync.property.test.ts +backend/test/properties/EntraIdProvisioning.property.test.ts +backend/test/properties/user/email-uniqueness.property.test.ts +backend/test/services/AuthenticationService.bruteforce.test.ts +backend/test/unit/services/EntraIdService.test.ts +docs/api.md +docs/internal/plans/ldap-authentication.md +docs/openapi.yaml +frontend/src/components/GroupDetailDialog.svelte +frontend/src/components/UserDetailDialog.svelte +frontend/src/components/user-contact-nullability.test.ts +frontend/src/lib/auth.svelte.ts +frontend/src/lib/auth.test.ts +frontend/src/lib/permission-state.test.ts +frontend/src/pages/UserManagementPage.svelte +``` + +**Completed scope and changed interfaces:** + +- Added forward migration `031_external_identity_boundaries.sqlite.sql` and its PostgreSQL counterpart. Fresh schemas and populated migration-030 upgrades retain user IDs, identity IDs, explicit Entra enrollments, original profile data, session versions, manual/group assignments, revoked tokens, audit links, and journal links. Historic migration-016 upgrade fixtures also pass through 031. +- Identity uniqueness is now `(provider, issuer, subject)`. Added composite parent keys to enforce grant-to-user ownership and LDAP metadata-to-directory ownership. Mutable LDAP login/DN locators are stored in `ldap_identity_metadata`; they are deliberately nonunique and are never identity keys. +- `users.local_auth_enabled` is the local account/credential scope. Backfill sets it to 1 when a password hash exists and 0 otherwise, including explicitly enrolled Entra users with local passwords. External-only rows require a null password hash. Local rows require nonempty contact email, with uniqueness enforced by the partial `idx_users_local_email` index. Existing usernames are preserved; local creation reserves the case-insensitive `ldap:` prefix. New Entra creation explicitly uses scope 0 and stores absent email as null. +- Added nullable `display_name`; backend/auth/frontend user DTOs expose `displayName: string | null` and `email: string | null`. Internal password hashes are consistently nullable. Group member contact email is nullable. User filtering, user details, and group member rendering handle absent contact email. API/OpenAPI documentation describes these implemented fields. +- Removed ambiguous singular email lookup. `UserService.findLocalByEmail(email)` returns the unique local-scoped account, while `findAllByEmail(email)` returns every contact match. Entra provisioning rejects any existing email match without linking. Entra creation serializes its collision checks using the existing default-role configuration row inside its transaction; independent-connection tests cover simultaneous subjects sharing one email. +- `federated_user_roles` now has primary key `(identity_id, role_id, source_key)`. Group-derived LDAP grants also reference `mapping_id` and `directory_id`, with composite foreign keys binding the role, mapping, directory, identity, and user. Existing materialized Entra grants are backfilled to each existing Entra identity for that user with source key `legacy`. Detached historical grants with no remaining Entra identity are preserved in manual `user_roles`, with a database timestamp, rather than discarded. Existing migration-027 legacy markers retain their established first-reconciliation cleanup semantics. +- `EntraIdService.syncGroupRoles(identityId, groups)` now requires an Entra identity from the configured issuer, deletes only that identity's grants, and stores `group:` source keys. Multiple groups granting one role retain separate provenance. The callback resolves its authenticating identity before reconciliation. Manual assignments and grants owned by other identities survive. `effective_user_roles` retains its UNION deduplication; existing PermissionService and token role queries already consume this view, so no separate permission-query rewrite was needed. +- Added `ldap_directory_state`, `external_group_mappings`, `ldap_validation_state`, and `ldap_validation_leases`. Mapping uniqueness is `(directory_id, group_subject, role_id)`. Mapping mutation triggers increment persisted directory revision, invalidate directory validation timestamps, and change authorization revision on both adapters. A BEFORE UPDATE trigger withdraws attributable grants before a role/scope composite-key edit; AFTER triggers handle revision changes. Deletion cascades only attributable grants. Validation timestamps/lease expiry are Unix milliseconds in BIGINT fields; generation fields are nonnegative BIGINTs. PostgreSQL returns BIGINT values as strings through the current adapter. Lease/fencing and freshness algorithms are still package 5B work. +- SQLite rebuilds use the existing runner's foreign-key suspension, atomic transaction, and pre-commit foreign-key check. Application indexes, user/session triggers, external-role revision triggers, and the effective-role view are recreated. Failed rebuild rollback, restored enforcement, profile updates without revocation, sensitive-field revocation, mapping rollback, role edits, identity cascade cleanup, and cross-connection cache invalidation are covered. +- Compatibility adjustment: explicitly administrated password attachment for an existing Entra-only account enables its local scope atomically. LDAP identities cannot acquire local passwords through that path. Complete LDAP profile ownership and shared provider-neutral provisioning remain package 2. + +**Verification: exact commands, outcomes, and external log reference:** + +Commands ran from the repository root. The append-only command log is `~/.agents/logs/pabawi.jsonl`. PostgreSQL used the already-present `postgres:17` image, version 17.11; SQLite was 3.52.0. No dependencies or fixture artifacts were downloaded. Host Node was 26.8.1; the repository declares Node >=24.21.0 and <25, so the supported-engine release check remains separate evidence. + +- `docker run --detach --name pabawi-ldap-p1-postgres --pull never -e POSTGRES_HOST_AUTH_METHOD=trust -p 127.0.0.1::5432 postgres:17`: isolated local test server, loopback port 63167. Fresh acceptance databases avoided checksum reuse while 031 was being finalized. The fixture was stopped with `docker stop pabawi-ldap-p1-postgres` after final verification; the stopped container was retained. +- `TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:63167/ldap_package1_verified npm run test --workspace=backend > /tmp/pabawi-ldap-p1-backend-final.log 2>&1 && npm run build:backend > /tmp/pabawi-ldap-p1-build-final.log 2>&1`: PASS, 239 test files passed, one skipped; 3863 tests passed, two skipped, one todo. The backend artifact includes the final migration files. +- `TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:63167/ldap_package1_final npm run test --workspace=backend -- test/database/external-identity-boundaries.test.ts`: PASS after the PostgreSQL BEFORE UPDATE fix, 17 tests. The final full run also includes these tests against the final timestamp SQL. +- `npm run test --workspace=frontend > /tmp/pabawi-ldap-p1-frontend-tests-final.log 2>&1`: PASS, 60 files and 1046 tests, including null email rendering/filtering and user/group detail dialogs. +- `npm run build && npm run check:components > /tmp/pabawi-ldap-p1-components.log 2>&1`: PASS, both production builds and zero component errors. Subsequent `npm run build:backend && npm run lint && npm run check:components > /tmp/pabawi-ldap-p1-components-acceptance.log 2>&1 && git diff --check` also passed; frontend source did not change after its successful production build. Vite retained its existing large-chunk warning. +- `node --test --test-name-pattern='every declared REST|API guide|OpenAPI version|public exchanges|configuration inventory|architecture registry' scripts/documentation/contracts.test.mjs`: PASS, six contracts covering routes, API/OpenAPI, auth boundaries, configuration, and architecture. +- Changed/new-file `detect-secrets scan` with the existing pre-commit environment, followed by a comparison against reviewed baseline hashes: PASS, zero new unreviewed findings. Exact file arguments and comparison command are in the external log. Synthetic credential fixtures are explicitly annotated. The baseline was not changed. +- `git diff --check`: PASS. The command log parses as JSON Lines. + +**Pre-existing failures:** + +- Unfiltered `node --test scripts/documentation/contracts.test.mjs` reports six passes and one failure: package metadata is 1.5.1, but CHANGELOG.md lacks a dated 1.5.1 entry and begins with 1.6.0 Unreleased. The relevant version/changelog files match the starting commit. +- `bash scripts/quality/secret-scan.sh` initially could not find detect-secrets on PATH. Using `PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh` runs the scanner and reports four pre-existing findings across unchanged `backend/package.json`, `backend/src/cli/resetUserPassword.ts`, and `backend/test/unit/cli/resetUserPassword.test.ts`. These files match HEAD; the LDAP change adds none. +- One repeated full backend run returned an intermittent 404 in the unchanged `test/security/workload-limits.test.ts`. `npm run test --workspace=backend -- test/security/workload-limits.test.ts` passed all five tests in isolation, and the subsequent final complete run passed. No unrelated workload-limit code was modified. + +**Remaining work and blockers:** No package-1 acceptance blocker remains. The unrelated release-documentation and tracked secret-scan failures above remain unresolved. Directory interoperability, supported-engine release evidence, runtime mapping administration, and session enforcement belong to later packages. No LDAP authentication is advertised or enabled. + +**Decisions or discoveries affecting the next package:** Use provider `ldap` and stable directory ID as issuer when creating LDAP identities. Reserve deterministic internal usernames beneath `ldap:` and use immutable subjects, not DN or login. Preserve the explicit local scope and the scoped email APIs. Entra's default role remains a manual `user_roles` assignment, and its legacy-marker behavior is unchanged. Mapping updates already withdraw old grants and invalidate persisted state through database triggers; callers must use a transaction and later add revision/fencing comparisons rather than relying only on cached permissions. Existing sessions are preserved by 031; intentional release invalidation remains package 5A. Validation and lease tables exist without any enabled runtime LDAP enforcement. + +**Next action and acceptance criterion still to satisfy:** Start package 2. Extract shared transactional provisioning, implement deterministic immutable LDAP account creation without default roles or implicit linking, preserve suspension/manual grants and Entra enrollment behavior, and enforce complete LDAP profile/password ownership. Verify concurrent first login creates one account, zero-role LDAP provisioning issues no tokens, and local/Entra regressions still pass. + + +## Handoff 2026-10-21 Codex package 2 + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 2, shared provisioning, complete. Package 3 is the next eligible package. LDAP network access, public authentication, group reconciliation and session freshness enforcement remain in their assigned later packages. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base `a739cf296fb01b872ed4b234eba971e51f0bb783`. The initial working tree was clean. Package 1's previously uncommitted changes are now committed in that base; its schema and compatibility claims were verified against the current source and both database adapters. No package-2 completion commit was created. The package-2 working tree contains: + +```text +backend/src/routes/auth.ts +backend/src/routes/users.ts +backend/src/services/EntraIdService.ts +backend/src/services/UserService.ts +backend/test/database/federated-provisioning.test.ts +backend/test/integration/ldap-account-ownership.test.ts +backend/test/properties/EntraIdProvisioning.property.test.ts +backend/test/unit/services/EntraIdService.test.ts +docs/api.md +docs/internal/plans/ldap-authentication.md +docs/openapi.yaml +``` + +**Completed scope and changed interfaces:** + +- `UserService.createFederatedUser(input: FederatedProvisioningInput): Promise` is now provider-neutral and idempotent. Its input contains immutable `provider`, `issuer`, `subject` and explicit nullable contact/display name plus given name/surname. The discriminated input requires `defaultRole: 'configured'` and a provider-derived username for Entra, or `defaultRole: 'none'` and current `loginName`/`dn` for LDAP. The shared service no longer imports Entra token claims. +- This method owns the transaction. SQLite serializes through the adapter's existing BEGIN IMMEDIATE transaction; PostgreSQL provisioning writers lock the shared default-role configuration row before rereading identity and checking collisions. An upsert ensures the lock exists even if the configuration row is absent, preserving SetupService's existing Viewer fallback without overwriting configured values. Independent-connection tests start without that row and converge twelve simultaneous LDAP calls to one account. +- New LDAP usernames are `ldap:` followed by SHA-256 of the JSON tuple `[provider, issuer, subject]`. Mutable login/DN and email never select an account. Reused locators, shared or absent email, equal subjects in different directories and local/Entra contact matches create separate accounts. Missing issuer, immutable subject or locators fail before writes. Direct LDAP linking to existing users is forbidden; LDAP-owned accounts also reject subsequent federated enrollment. +- User, identity, configured initial Entra role, LDAP metadata and initially unvalidated LDAP state are committed atomically. LDAP creates no default/manual/federated grant and issues no token. Its validation timestamp remains null, generation 0 and config revision empty. The primitive does not claim directory eligibility or freshness. Metadata write failures roll back all newly created records. +- Returning LDAP identities refresh email, display name, given name, surname, login and DN. They preserve internal username, Pabawi suspension, administrative status, manual grants, credentials and existing validation state. Profile refresh preserves existing valid sessions. A provisioned zero-role account remains available for manual assignment and subsequent provisioning retains the assignment. +- EntraIdService is the only production caller migrated from raw token claims to the shared input. Username derivation moved into that caller. Existing Entra profile immutability, default-role policy, explicit local-account enrollment and local password administration remain intact. Shared identity conflicts use `FederatedAccountError`; Entra translates collision errors to its established error code. Both the initial and transactional returning paths still check suspension. +- `UserService.requireLocalProfileOwnership(userId)` rejects LDAP-owned contact/name/password writes, including legacy mixed accounts and administrators. `updateUser` uses that guard before any mutation, protecting HTTP administration and the existing password-reset CLI. Authenticated password changes check ownership before password verification or lockout accounting. The affected user/password routes return HTTP 403 with `DIRECTORY_ACCOUNT_READ_ONLY`. Suspension, admin status and manual roles remain locally editable. +- Updated API/OpenAPI user update contracts, Entra unit/property assertions and two new acceptance files. LDAP remains absent from provider discovery and has no public login route. No dependency or migration was added. + +**Verification: exact commands, outcomes, and external log reference:** + +All commands ran from the repository root and were recorded in `~/.agents/logs/pabawi.jsonl`. Host Node was 26.8.1, outside the declared >=24.21.0 and <25 engine range; supported-engine release evidence remains outstanding. PostgreSQL was 17.11, using the already-present package-1 fixture. No packages or fixture artifacts were downloaded. + +- `npm run test --workspace=backend -- test/database/external-identity-boundaries.test.ts test/database/sso-concurrency.test.ts > /tmp/pabawi-ldap-p2-baseline.log 2>&1`: PASS before edits, ten SQLite tests; nine PostgreSQL tests skipped until starting the fixture. +- `docker start pabawi-ldap-p1-postgres`: restarted the existing isolated fixture, now exposed at loopback port 55612. `docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package2_verified` created a fresh acceptance database. The fixture was stopped with `docker stop pabawi-ldap-p1-postgres` after verification; the stopped container and acceptance database were retained. +- `TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55612/postgres npm run test --workspace=backend -- test/database/federated-provisioning.test.ts test/database/external-identity-boundaries.test.ts test/database/sso-concurrency.test.ts > /tmp/pabawi-ldap-p2-focused.log 2>&1`: PASS, 35 tests across SQLite/PostgreSQL. +- `npm run test --workspace=backend -- test/integration/ldap-account-ownership.test.ts test/unit/services/EntraIdService.test.ts test/properties/EntraIdProvisioning.property.test.ts test/integration/EntraIdAuthFlow.test.ts > /tmp/pabawi-ldap-p2-compat-final.log 2>&1`: PASS, four files and 50 tests. +- `TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55612/ldap_package2_verified npm run test --workspace=backend > /tmp/pabawi-ldap-p2-backend-acceptance.log 2>&1`: PASS on the final production code, 241 files passed, one skipped; 3883 tests passed, two skipped, one todo. This includes migration upgrades, PostgreSQL/SQLite concurrency, Entra group synchronization/auth flows, local authentication, user updates and password/CLI regressions. +- `npm run build:backend > /tmp/pabawi-ldap-p2-build-acceptance.log 2>&1 && npm run lint > /tmp/pabawi-ldap-p2-lint-acceptance.log 2>&1`: PASS, backend compilation and both workspace linters. +- `node --test scripts/documentation/contracts.test.mjs > /tmp/pabawi-ldap-p2-doc-contracts.log 2>&1`: six contracts pass; the unchanged release/changelog mismatch fails as recorded below. +- `PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh > /tmp/pabawi-ldap-p2-secrets-full.log 2>&1`: the same four pre-existing findings, detailed below. An additional scanner pass covers all changed and untracked package-2 files and compares their hashes with the reviewed baseline; the baseline is unchanged. PASS, zero new unreviewed findings. Its exact Python/scanner commands and results are in the external command log. +- `npm run test --workspace=backend -- test/integration/ldap-account-ownership.test.ts > /tmp/pabawi-ldap-p2-http-final.log 2>&1`: PASS, four tests after the final synthetic fixture adjustment. +- `git diff --check`: PASS. Frontend source did not change; frontend tests/component checks were not rerun for this backend package. + +Initial new-code verification found a short synthetic JWT secret in the new HTTP test fixture and four lint diagnostics. These were corrected before acceptance. The changed-file scan also identified an inline synthetic test password, which now reuses the annotated fixture constant. + +**Pre-existing failures:** + +- Release metadata remains version 1.5.1, while CHANGELOG.md has no dated 1.5.1 entry and starts with 1.6.0 Unreleased. All six other documentation contracts pass. +- Full tracked-tree secret scan reports four unchanged findings: one in `backend/package.json`, two in `backend/src/cli/resetUserPassword.ts`, and one in `backend/test/unit/cli/resetUserPassword.test.ts`. These files and the relevant version/changelog files match the starting commit. No baseline entries were approved or changed. + +**Remaining work and blockers:** No package-2 acceptance blocker remains. The two repository-wide check failures above remain release blockers outside this package. The supported Node engine, live OpenLDAP and real AD evidence remain outstanding for their later packages. No live directory was accessed. + +**Decisions or discoveries affecting the next package:** Supply LDAP directory ID as issuer and only a proven immutable subject from the future directory service. That service must canonicalize/validate directory identifiers and supply profile fields without splitting display names. The provisioning primitive owns its transaction and the adapters reject nested transactions. Package 5B must extend the same transaction to reconcile LDAP-owned grants and publish revision/fencing-checked freshness atomically; wrapping the current public method in another transaction is invalid. Its current null validation state is intentional and must never be treated as session eligibility. Existing validation rows are preserved during profile refresh. + +**Next action and acceptance criterion still to satisfy:** Start package 3. Add validated disabled-by-default directory configuration, the reviewed/pinned ldapts dependency, bounded read-only directory operations, immutable ID codecs and reproducible real OpenLDAP fixtures for verified LDAPS and StartTLS. Keep public LDAP authentication unavailable. Record real AD evidence still deferred if no actual AD environment is available. + + +## Handoff 2026-10-21 Codex package 3 + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 3, directory configuration and service, complete. Package 4 is next eligible. LDAP provider discovery, login endpoints, Pabawi token issuance, mapping administration and session enforcement remain unavailable until their assigned packages. + +**Branch, base commit, completion commit or uncommitted paths:** Branch 151, base 2d37548. The starting tree was clean. Package 2 is now committed in that base, superseding its previous uncommitted reference. Inspected migrations 031, shared provisioning, profile ownership, Entra callers and authentication boundaries; verified their behavior with SQLite and PostgreSQL tests. No completion commit was created. Changed/new paths: + +~~~text +backend/.env.example +backend/package.json +backend/src/config/ConfigService.ts +backend/src/config/schema.ts +backend/src/config/ldap.ts +backend/src/config/ldapFilter.ts +backend/src/services/LdapDirectoryService.ts +backend/src/services/ldap/LdapDirectoryError.ts +backend/src/services/ldap/identity.ts +backend/src/services/ldap/policy.ts +backend/src/services/ldap/transport.ts +backend/src/types/ldapjs-dn.d.ts +backend/src/types/node-tls.d.ts +backend/test/config/LdapConfig.test.ts +backend/test/unit/services/LdapDirectoryService.test.ts +backend/test/integration/ldap-directory.test.ts +backend/test/fixtures/ldap/Dockerfile +backend/test/fixtures/ldap/entrypoint.sh +backend/test/fixtures/ldap/seed.ldif +backend/test/fixtures/ldap/README.md +docs/configuration.md +docs/internal/plans/ldap-authentication.md +package-lock.json +scripts/documentation/source-inventory.mjs +~~~ + +**Completed scope and changed interfaces:** + +- ConfigService.getLdapConfig(): LdapConfig | null and AppConfig.ldap expose validated configuration. LDAP_ENABLED defaults false and accepts only literal booleans. Disabled mode ignores other directory settings. Enabled mode validates all agreed variables, presets, FQDNs, directory IDs, endpoint JSON, bounds, DN/attribute/filter syntax, anonymous lookup consistency and readable PEM certificates. Configuration construction opens no network connection, preserving startup/local access during directory outages. Directory ID is case-sensitive. Environment access remains inside configuration parsing. +- Pinned ldapts 9.2.0 and @ldapjs/dn 1.1.0 through socket npm install --workspace=backend --save-exact. Both install reviews reported no new risks. ldapts requires Node >=22, compatible with the supported Node 24 range. Parsed DNs support validation, scope and locator comparisons. Maintenance limitation: registry metadata marks @ldapjs/dn and its @ldapjs/asn1 dependency decommissioned. This is recorded for dependency-maintenance review before release, separately from directory interoperability. +- LdapDirectoryService(config, logger, connector?) exposes authenticate(loginName, password, mappedGroupSubjects?), revalidate(subject, mappedGroupSubjects?), searchGroups(query) and resolveGroup(subject). Authentication/revalidation return { user, groupSubjects }; users contain immutable subject, current DN/login, display name, nullable email and given/surname fields. Search/resolve return { subject, dn, name }. These operations perform no database writes, provisioning or token issuance. +- Each transaction has bounded immediate admission and one deadline spanning endpoints, TLS, binds, searches and traversal. Abort closes tracked TCP/TLS sockets, rejects unfinished work and prevents reconnects. Operation/connect timeouts are separately bounded. Lookup and user-bind clients are isolated at the selected endpoint. Empty/oversized credentials fail before connecting; passwords are untrimmed. Automatic rebinding is disabled. Failover ends before credential-bearing lookup binding; user passwords are never retried against another endpoint. +- Both TLS modes require TLS >=1.2, CA verification, endpoint SNI, normal hostname validation and the configured additional wildcard restriction. Extra CA material augments Node's default trust roots, including configured system/extra roots. StartTLS failure cannot fall back to plaintext. A local TLS declaration covers getCACertificates, available in supported Node 24 but absent from the existing Node 20 type package. +- Runtime queries use typed filter objects, including Buffer-valued AD GUID equality. Configured filters receive structural/parser validation and byte restoration before BER encoding. Tests exposed ldapts accepting unbalanced syntax and converting escaped octets through Latin-1. The implementation rejects malformed syntax and preserves binary assertions and escaped/literal UTF-8. No raw client filter or executable template is accepted. +- Subjects are validated non-nil lowercase UUIDs. AD GUID conversion reverses the Windows little-endian fields and reconstructs exact binary assertion bytes. Missing/multivalued/wrongly typed IDs fail closed. After user binding, an immutable-ID search checks subject, parsed DN and current login against the pre-bind object. Replacement, disappearance or moved locators return IDENTITY_CHANGED. Revalidation never selects identity by stored DN/login. +- OpenLDAP applies the configured eligibility filter to every user eligibility search. AD requires readable userAccountControl, msDS-User-Account-Control-Computed, accountExpires, pwdLastSet and msDS-UserPasswordExpiryTimeComputed. It checks disablement, computed lockout/password expiry, forced password change and FILETIME expiration with integer arithmetic/documented sentinels. Missing visibility returns POLICY_UNREADABLE. AD evidence remains protocol/service testing only. +- Group queries are escaped, scoped and bounded. OpenLDAP supports groupOfUniqueNames/uniqueMember and groupOfNames/member. Optional UID suffixes are rejected when encountered. Reverse membership traversal uses immutable visited IDs and parsed locator comparisons, detects cycles, enforces depth/visit/deadline bounds and avoids downloading AD ranged member lists. AD chain-rule results are checked against bounded in-scope traversal; only definitive unsupported-rule responses permit the traversal result alone. Primary groups and out-of-scope memberships remain excluded. +- Searches disable pagination, alias dereferencing and referral following. Referrals, unexpected continuation cookies, missing bases and limited/incomplete results cannot become partial authorization. Real OpenLDAP exposed ldapts suppressing sizeLimitExceeded when a requested size limit exists. The transport observes public response objects before accepting results, preserves server status and interrupts responses exceeding the requested entry bound. +- LoggerService records safe operation/directory IDs, latency, error/limit reason and failover index, without raw exceptions, passwords or full entries. Configuration inventory/examples describe internal support and the unavailable public-login boundary. No migration, infrastructure plugin or frontend source changed. + +**Verification: exact commands, outcomes, and external log reference:** + +All commands ran from the repository root and are recorded in append-only ~/.agents/logs/pabawi.jsonl. Documentation network tools have supplemental records there. Initial host Node was 26.8.1. Final acceptance used an official Node 24.21.0 Darwin arm64 archive under /tmp/pabawi-node24, verified against its official SHA256 list and scanned with ClamAV before extraction. PostgreSQL was 17.11; OpenLDAP was 2.6.10+dfsg-1; the fixture used OpenSSL 3.5.7-1~deb13u3. + +- Before edits, npm run test --workspace=backend -- test/database/federated-provisioning.test.ts test/database/external-identity-boundaries.test.ts test/database/sso-concurrency.test.ts test/integration/ldap-account-ownership.test.ts passed 22 SQLite/HTTP tests with 17 PostgreSQL cases skipped. After docker start pabawi-ldap-p1-postgres, its loopback port was 65056. These prerequisite files plus then-current LDAP tests passed all 112 tests with both adapters and live OpenLDAP (/tmp/pabawi-ldap-p3-focused-fourth.log). +- docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package3_verified created a fresh full-suite acceptance database. +- Full acceptance on final production code, PASS: 244 files passed, one skipped; 3961 tests passed, two skipped, one todo. Includes SQLite/PostgreSQL migration/provisioning boundaries, local/Entra authentication/profile/password regressions and real directory tests: + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:65056/ldap_package3_verified TEST_LDAP_LDAPS_PORT=54547 TEST_LDAP_STARTTLS_PORT=54548 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p3-tls-final/ca.pem npm run test --workspace=backend > /tmp/pabawi-ldap-p3-node24-backend-verified.log 2>&1 +~~~ + +- Focused final acceptance, PASS: 78 tests, including the final annotated/shared GUID vector: + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_LDAP_LDAPS_PORT=54547 TEST_LDAP_STARTTLS_PORT=54548 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p3-tls-final/ca.pem npm run test --workspace=backend -- test/config/LdapConfig.test.ts test/unit/services/LdapDirectoryService.test.ts test/integration/ldap-directory.test.ts > /tmp/pabawi-ldap-p3-node24-focused-acceptance.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p3-node24-build-verified.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p3-node24-lint-verified.log 2>&1 +~~~ + +- Backend build and both workspace linters passed. Frontend source is unchanged; frontend tests/component checks were not rerun. +- Fixture commands are documented in backend/test/fixtures/ldap/README.md. The final Dockerfile/entrypoint passed: + +~~~bash +shellcheck backend/test/fixtures/ldap/entrypoint.sh +docker run --name pabawi-ldap-p3-hadolint-verified --pull never --interactive hadolint/hadolint:latest hadolint --ignore DL3008 --ignore DL3009 - < backend/test/fixtures/ldap/Dockerfile +docker build -t pabawi-ldap-fixture:package3-verified backend/test/fixtures/ldap > /tmp/pabawi-ldap-p3-fixture-build-verified.log 2>&1 +docker run --detach --name pabawi-ldap-p3-openldap-verified --pull never -p 127.0.0.1::1389 -p 127.0.0.1::1636 pabawi-ldap-fixture:package3-verified +~~~ + +- The fixture uses a pinned Debian base, generated two-day TLS certificates, synthetic records and an ACL denying lookup password reads. Final published ports were StartTLS 50326 and LDAPS 50325. The CA was copied to /tmp/pabawi-ldap-p3-verified/tls/ca.pem. After the final Dockerfile adjustment, all ten real-directory tests passed: + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_LDAP_LDAPS_PORT=50325 TEST_LDAP_STARTTLS_PORT=50326 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p3-verified/tls/ca.pem npm run test --workspace=backend -- test/integration/ldap-directory.test.ts > /tmp/pabawi-ldap-p3-openldap-verified.log 2>&1 +~~~ + +- Real evidence covers both verified TLS modes, isolated binds, incorrect/empty credentials, active/inactive/missing policy, Unicode/ambiguous login, absent contact/identity fields, two group schemas, optional UID rejection, direct/nested cycles, limits, failover, CA/hostname failures, failed StartTLS before credentials and deadline socket cleanup. +- ClamAV passed ldapts and its dependency, the DN parser dependencies, the official Node archive and downloaded fixture packages. The final fixture scan checked 19 packages with zero infections (/tmp/pabawi-ldap-p3-fixture-clamav-verified.log). Image digest and exact download/scan commands are in the external log. +- All six relevant documentation contracts passed: + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test --test-name-pattern='every declared REST|API guide|OpenAPI version|public exchanges|configuration inventory|architecture registry' scripts/documentation/contracts.test.mjs > /tmp/pabawi-ldap-p3-doc-contracts-acceptance.log 2>&1 +~~~ + +- The unfiltered documentation check retains the existing version/changelog failure. The required full tracked-tree secret scan retains the four existing findings below. A separate scan includes all 23 changed/new files except the lockfile and compares them with the reviewed baseline and starting-commit content: PASS, zero new findings (/tmp/pabawi-ldap-p3-secret-comparison-verified.json). Synthetic invalid-URL/GUID vectors are annotated. The baseline is unchanged; exact scanner/comparison commands are in the external log. +- git diff --check passed. docker stop pabawi-ldap-p3-openldap-final pabawi-ldap-p3-openldap-verified pabawi-ldap-p1-postgres stopped all remaining acceptance servers. The earlier directory fixture is also stopped. Containers/images/temporary evidence were retained. No remote push, PR, deployment or cleanup deletion occurred. + +**Pre-existing failures:** + +- Release metadata is 1.5.1 and CHANGELOG.md lacks a dated 1.5.1 entry. The unfiltered documentation contract therefore fails. Changelog/version values were not changed. +- PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh reports four existing findings: one in backend/package.json, two in backend/src/cli/resetUserPassword.ts, one in backend/test/unit/cli/resetUserPassword.test.ts. Only dependency entries changed in backend/package.json; its flagged content existed at the starting commit. CLI files and .secrets.baseline are unchanged. + +**Remaining work and blockers:** No package-3 acceptance blocker remains. No real AD environment/credentials were available. Actual AD TLS, status visibility, objectGUID queries, matching-rule behavior and large-directory interoperability remain unverified and block package-7 completion/support claims. Existing release-documentation and tracked-tree secret failures remain release blockers outside this package. The DN parser's decommissioned upstream is recorded for dependency-maintenance review. Supported-engine evidence for this package is now present. Public LDAP authentication remains unavailable. + +**Decisions or discoveries affecting the next package:** Use service-returned immutable subjects and authoritative current DN/name for mappings; never browser labels/locators as identity. Supply the case-sensitive directory ID as issuer. Safe error codes are INVALID_CREDENTIALS, INELIGIBLE, IDENTITY_CHANGED, INVALID_IDENTITY, POLICY_UNREADABLE, INCOMPLETE_RESULT, LIMIT_EXCEEDED, BUSY, TIMEOUT and UNAVAILABLE. Preserve confirmed ineligibility versus transient/incomplete results. Failures change no stored grants. Construction is lazy and does not make startup depend on directory availability. Preserve the transport/filter guards when upgrading ldapts and rerun real truncation, TLS and binary/UTF-8 checks. Package-2 transaction ownership and package-5B atomic reconciliation/fencing requirements remain unchanged. + +**Next action and acceptance criterion still to satisfy:** Start package 4. Implement restricted search/diagnostics and mapping persistence/routes through existing RBAC/container patterns. Require rbac:admin, audit changes, resolve immutable group subjects through this service, and prove revision/fencing-safe grant withdrawal on both adapters. Keep public LDAP login unavailable. Complete permission/error/provenance/revision-race tests and backend contracts before mapping UI or session work. + + +## Handoff 2026-10-21 Codex package 4 + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 4, RBAC mapping administration, complete. Package 5A is next eligible. Public LDAP discovery/login and LDAP token issuance remain unavailable. Mapping UI belongs to package 6. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base `4fac169ef75c9882c106728faa6d2c1717565f3e`. Starting tree was clean. Package 3 is committed in that base, correcting its previous uncommitted progress reference. Read AGENTS.md, code-change/git/Context7 instructions, progress and latest handoffs. Verified migration 031, shared provisioning, local/Entra boundaries, directory configuration/service, container, route guards and audit patterns against current source. KiroGraph reported 204 pending files and could not find LdapDirectoryService, so source inspection supplied the missing context. No completion commit was created. Changed/new paths: + +~~~text +backend/src/container/DIContainer.ts +backend/src/server.ts +backend/src/services/LdapDirectoryService.ts +backend/src/services/LdapMappingService.ts +backend/src/routes/ldapAdministration.ts +backend/test/database/ldap-mappings.test.ts +backend/test/integration/ldap-administration.test.ts +backend/test/integration/ldap-directory.test.ts +backend/test/unit/services/LdapDirectoryService.test.ts +docs/api.md +docs/openapi.yaml +docs/configuration.md +docs/internal/plans/ldap-authentication.md +~~~ + +**Completed scope and changed interfaces:** + +- LdapMappingService(db, directoryId, directory) implements list(), get(id), create(groupSubject, roleId, actor), update(id, { roleId?, enabled? }, actor), remove(id, actor), revision() and withRevision(snapshot, databaseWork). Mappings expose immutable group subject, authoritative stored DN/name, role ID/name, boolean enabled, timestamps and source: ldap. Every lookup is scoped to the configured case-sensitive directory ID. +- Creation and role/re-enable updates resolve the immutable group through the directory service before opening a database transaction. Browser DNs, labels and directory IDs are rejected. Absent roles/mappings return NOT_FOUND; duplicate subject/role mappings return CONFLICT. Disabling alone and deletion need no directory connection, preserving withdrawal during outages. +- Existing migration-031 triggers perform attributable grant withdrawal, mapping-revision increment, persisted timestamp invalidation and global authorization-revision changes in the same transaction. Other mappings, manual roles, local group permissions and Entra-owned grants survive. Creating or enabling a mapping never materializes a grant. +- revision() supplies directory ID and string-preserving mapping/config revisions. withRevision() owns its transaction and conditionally updates the directory row with those revisions, acquiring the PostgreSQL row lock or SQLite writer lock before databaseWork runs. A stale result returns STALE_REVISION before any grant/profile/freshness write. Mapping edits use this same lock and compare the revision captured before directory I/O, preventing stale edits as well as stale validation publication. Scope/config mismatch also fails closed. +- AuditLoggingService records createLdapMapping, updateLdapMapping and deleteLdapMapping atomically with mutation and withdrawal. Payloads include actor, directory/mapping/group/role IDs and enabled state, omitting group locators and personal profiles. Audit persistence failure rolls everything back. Existing middleware audits denied permissions. +- Six implemented endpoints: GET groups, GET mappings, POST mappings, PUT mappings/:id, DELETE mappings/:id and POST test, mounted under /api/auth/ldap. Each independently authenticates and enforces rbac:admin, including delegated non-is_admin roles. Authorized disabled-directory requests return 404. All authorized responses use Cache-Control: no-store. Lazy service/container wiring opens no startup directory connection and does not enter the infrastructure plugin registry. +- Group search matches escaped configured lookup/display-name substrings and accepts only a nonempty query of at most 1024 UTF-8 bytes plus optional opaque cursor. The complete directory result must satisfy the configured search limit before returning anything. Responses are { items, nextCursor }, at most 50 groups per page. Random 256-bit continuation references bind a bounded snapshot to administrator, exact query and configured router lifetime. Expiry is 60 seconds from snapshot creation and paging cannot extend it. At most 64 references are retained per router. Cursors are deliberately process-local: expiry/eviction/restart/another process returns INVALID_CURSOR and requires a new search. This is documented. +- LdapDirectoryService.diagnose({ username?, groupSubjects? }) reports TLS, lookup, identity, eligibility and selected group-resolution stages with status, durationMs and safe error code. It uses one bounded lookup transaction, performs no user bind and always returns authenticated: false. Identity lookup is separate from policy filtering; a visible inactive account differs from a missing/ambiguous identity. Selected group identity is resolved before membership checks. Failed/incomplete work returns no partial membership. Deadline reports are detached from late protocol bookkeeping. +- Diagnostic HTTP input allows no password, arbitrary filter, endpoint or connection override. Group diagnostics require an exact username, at most 20 subjects and enabled mappings. Reports omit profile data, raw directory exceptions and connection configuration. The router uses the existing 100/minute authenticated-user limiter; diagnostics add 10/minute per administrator. Mounting before generic /api/auth prevents administration from consuming the local-login budget. +- Restricted administrative errors use 400 for invalid input/cursor/selected mappings, 404 for disabled support or absent scoped records, 409 for duplicate/stale revision, 422 for invalid directory identity/confirmed ineligibility/identity change, 429 for admission/rate limits and 503 for directory outage, incomplete resolution, policy visibility or lookup credential rejection. Unexpected errors are redacted 500 responses. These restricted diagnostic statuses do not define the future public-login failure behavior. +- API/OpenAPI and configuration references describe the implemented contract. No migration, dependency, token format or frontend source changed. + +**Verification: exact commands, outcomes, and external log reference:** + +All state-changing, tool-network and verification commands are recorded in append-only ~/.agents/logs/pabawi.jsonl. Test evidence is retained under /tmp/pabawi-ldap-p4-*.log. Acceptance used the already verified official Node 24.21.0 archive from package 3, PostgreSQL 17.11 and the already reviewed local OpenLDAP image; no new package/archive/image download was needed. + +- Prerequisites, PASS: 107 tests covering SQLite/PostgreSQL migration boundaries, shared provisioning, Entra concurrency, LDAP profile/password ownership and directory configuration/service. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55751/postgres npm run test --workspace=backend -- test/database/federated-provisioning.test.ts test/database/external-identity-boundaries.test.ts test/database/sso-concurrency.test.ts test/integration/ldap-account-ownership.test.ts test/config/LdapConfig.test.ts test/unit/services/LdapDirectoryService.test.ts > /tmp/pabawi-ldap-p4-prerequisites.log 2>&1 +~~~ + +- Restarting retained pabawi-ldap-p1-postgres succeeded. Restarting the old OpenLDAP container failed because its entrypoint reruns slapadd against the retained database. Its log showed MDB_KEYEXIST. No repository code changed for this fixture limitation. Created a fresh loopback fixture from the existing verified image, which passed: + +~~~bash +docker run --detach --name pabawi-ldap-p4-openldap --pull never -p 127.0.0.1::1389 -p 127.0.0.1::1636 pabawi-ldap-fixture:package3-verified +mkdir -p /tmp/pabawi-ldap-p4-tls && docker cp pabawi-ldap-p4-openldap:/fixture/tls/ca.pem /tmp/pabawi-ldap-p4-tls/ca.pem +~~~ + +Published ports were PostgreSQL 55751, LDAPS 55900 and StartTLS 55899. Containers, image, certificate and evidence were retained. + +- Focused package acceptance, PASS: 76 tests across four files, including 26 mapping tests on both adapters, 14 HTTP cases and live directory behavior. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55751/postgres TEST_LDAP_LDAPS_PORT=55900 TEST_LDAP_STARTTLS_PORT=55899 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p4-tls/ca.pem npm run test --workspace=backend -- test/database/ldap-mappings.test.ts test/integration/ldap-administration.test.ts test/unit/services/LdapDirectoryService.test.ts test/integration/ldap-directory.test.ts > /tmp/pabawi-ldap-p4-focused-acceptance.log 2>&1 +~~~ + +Evidence includes all six endpoint guards before directory work, delegated administration, forged identities/locators, role conflicts, outage-safe withdrawal, opaque cursor actor/query/router/deadline binding, diagnostic limits/redaction and public login/discovery remaining unavailable. Both-adapter tests cover provenance, authorization-cache invalidation, stale revisions after insertion/disablement/replacement/deletion, an edit queued behind validation publication, changes during directory I/O, configuration/scope mismatch and complete audit rollback. Live HTTP search/mapping/diagnostics create no identity, grant, OAuth code or imported user. Real LDAPS/StartTLS diagnostics and previous TLS/bind/membership/limit regressions pass. + +- Full backend acceptance on final production source, PASS: 246 files passed, one skipped; 4005 tests passed, two skipped, one todo. Includes local/Entra authentication, migrations/upgrades, SQLite/PostgreSQL concurrency and real OpenLDAP. + +~~~bash +docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package4_verified +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55751/ldap_package4_verified TEST_LDAP_LDAPS_PORT=55900 TEST_LDAP_STARTTLS_PORT=55899 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p4-tls/ca.pem npm run test --workspace=backend > /tmp/pabawi-ldap-p4-backend-acceptance.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p4-build-acceptance.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p4-lint-acceptance.log 2>&1 +~~~ + +Backend build and both workspace linters pass. Frontend source is unchanged, so frontend tests/component checks were not rerun. Initial verification found forbidden non-null assertions and test-fixture assumptions about default Viewer roles, permission timestamps, PostgreSQL BIGINT strings and a queued one-time mock. These were corrected before acceptance. + +- Documentation contracts: all six route/API/security/configuration/architecture contracts pass. The unfiltered run retains only the pre-existing release/changelog failure. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test scripts/documentation/contracts.test.mjs > /tmp/pabawi-ldap-p4-doc-contracts.log 2>&1 +~~~ + +- The full tracked-tree scan retains exactly the four existing findings below. Additional changed/untracked-file comparison passes with zero new unreviewed findings; .secrets.baseline is unchanged. The comparison also verifies the existing flagged files and release/changelog files byte-for-byte against base 4fac169. + +~~~bash +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh > /tmp/pabawi-ldap-p4-secrets-full.log 2>&1 +python3 /tmp/pabawi-ldap-p4-secret-check.py > /tmp/pabawi-ldap-p4-secret-comparison.log 2>&1 +~~~ + +The comparison script and exact scanner arguments are retained in /tmp and in the external command log. Final documentation-only verification passed all six relevant contracts (/tmp/pabawi-ldap-p4-doc-contracts-final.log) and the changed/untracked secret comparison (/tmp/pabawi-ldap-p4-secret-comparison-final.log). git diff --check passed after removing a trailing blank line in this handoff. docker stop pabawi-ldap-p4-openldap pabawi-ldap-p1-postgres stopped both acceptance servers while retaining containers and evidence. No remote push, PR, deployment, cleanup deletion or real directory access occurred. + +**Pre-existing failures:** + +- Shipped release metadata is 1.5.1; CHANGELOG.md has no dated 1.5.1 entry. This remains the sole failing documentation contract. +- Full tracked-tree scan reports four unchanged unreviewed findings: one in backend/package.json, two in backend/src/cli/resetUserPassword.ts and one in backend/test/unit/cli/resetUserPassword.test.ts. All three files and the reviewed baseline match base 4fac169. No baseline exception was added. + +**Remaining work and blockers:** No package-4 acceptance blocker remains. The two repository-wide check failures above remain release blockers outside this package. Real AD environment/credentials are still unavailable; actual AD TLS/status/GUID/matching-rule/large-directory evidence remains required for package 7. The previously recorded decommissioned DN-parser dependency still needs maintenance review before release. Retained OpenLDAP containers cannot be restarted with the current seed-on-start entrypoint; use a fresh container from the verified fixture image. + +**Decisions or discoveries affecting the next package:** withRevision() owns its transaction, so callers must not nest transactions or call the existing transaction-owning createFederatedUser() inside it. Package 5B must design one atomic provisioning/profile/grant/freshness transaction and combine mapping/config revision checks with identity lease ownership, expiry and fencing-generation checks using database time. This package proves mapping-revision serialization; it does not implement validation leases or treat null/unvalidated state as session eligibility. Capture revision before mapping reads/directory I/O and compare it while holding the directory lock before publishing. Other-source grants and local suspension remain independent. + +Frontend integration example (synthetic group ID, no user import): + +~~~http +GET /api/auth/ldap/groups?query=operators +Authorization: Bearer + +POST /api/auth/ldap/mappings +Authorization: Bearer +Content-Type: application/json + +{"groupSubject":"10112233-4455-6677-8899-aabbccddeeff","roleId":"role-viewer-001"} + +PUT /api/auth/ldap/mappings/ +Authorization: Bearer +Content-Type: application/json + +{"enabled":false} + +POST /api/auth/ldap/test +Authorization: Bearer +Content-Type: application/json + +{"username":"alice"} +~~~ + +Use source/directory/group/role labels returned by the API. Never submit browser locators as identity. Continue local/Entra discovery unchanged until package 5B. + +**Next action and acceptance criterion still to satisfy:** Start package 5A. Add verified provider/identity context for existing local/Entra access and refresh tokens, shared configured authentication dependencies and intentional one-time legacy-session invalidation via a forward migration on both adapters. Keep LDAP tokens/login unavailable until package 5B completes all transport and freshness checks. + + +## Handoff 2026-10-21 Codex package 5A + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 5A, provider context and shared authentication wiring, complete. Package 5B is next eligible. Public LDAP discovery/login and LDAP token issuance remain unavailable. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base `ac2069672962e0c2b723ba8d65534841d8afd461`. Starting tree was clean. Package 4 is committed as `4a5c2b4`; its progress reference has been corrected. Base `ac20696` bumps release metadata to 1.6.0 WIP, so the earlier handoff's single release-documentation failure is no longer an accurate description of the current base. Read AGENTS.md, code-change/git/Context7 instructions, progress and latest handoffs. Verified migration 031, provider-neutral provisioning, scoped identities and grants, directory service and mapping revision/audit routes against source and regression tests. KiroGraph had 208 pending files; used source inspection for missing context and did not change the index. No completion commit was created. Changed/new paths: + +~~~text +backend/src/container/DIContainer.ts +backend/src/database/migrations/032_provider_bound_sessions.postgres.sql +backend/src/database/migrations/032_provider_bound_sessions.sqlite.sql +backend/src/middleware/authMiddleware.ts +backend/src/routes/auth.ts +backend/src/routes/console.ts +backend/src/routes/entraIdAuth.ts +backend/src/routes/groups.ts +backend/src/routes/journal.ts +backend/src/routes/ldapAdministration.ts +backend/src/routes/permissions.ts +backend/src/routes/roles.ts +backend/src/routes/setup.ts +backend/src/routes/users.ts +backend/src/server.ts +backend/src/services/AuthenticationService.ts +backend/src/services/EntraIdService.ts +backend/src/types/express.d.ts +backend/test/AuthenticationService.test.ts +backend/test/database/BatchLifecycleMigration.test.ts +backend/test/database/authorization-state.test.ts +backend/test/database/external-identity-boundaries.test.ts +backend/test/database/federated-provisioning.test.ts +backend/test/database/migration-016-convergence.test.ts +backend/test/database/migration-integration.test.ts +backend/test/database/provider-bound-sessions.test.ts +backend/test/database/sso-concurrency.test.ts +backend/test/integration/EntraIdAuthFlow.test.ts +backend/test/integration/ldap-account-ownership.test.ts +backend/test/integration/ldap-administration.test.ts +backend/test/integration/mcp-authorization.test.ts +backend/test/integration/shared-authentication.test.ts +backend/test/middleware/authMiddleware.test.ts +backend/test/properties/auth/token-validity.property.test.ts +backend/test/properties/consoleRbacCreation.property.test.ts +backend/test/properties/consoleRbacTermination.property.test.ts +backend/test/routes/auth.test.ts +backend/test/routes/aws.test.ts +backend/test/routes/groups.test.ts +backend/test/routes/journal.test.ts +backend/test/routes/permissions.test.ts +backend/test/routes/roles-permissions.test.ts +backend/test/routes/users.test.ts +backend/test/security/console-lifecycle.test.ts +backend/test/security/entitlement-administration.test.ts +backend/test/security/route-authorization.test.ts +backend/test/security/session-revocation.test.ts +docs/api.md +docs/internal/plans/ldap-authentication.md +~~~ + +**Completed scope and changed interfaces:** + +- Access and refresh JWTs require signed `authContext`. Local context is `{ provider: 'local', identityId: null }`; Entra context is `{ provider: 'entra-id', identityId: '' }`. Missing, malformed, unknown-provider and extra-field contexts fail closed, including LDAP contexts at this checkpoint. No provider inference from email, username or enrollment takes place. Existing issuer/audience `pabawi`, HS256 restriction, token purpose, expiry/JTI/session-version checks and token lifetimes remain. +- `generateToken(user, context, expectedVersion?)`, `generateRefreshToken(user, context, expectedVersion?)` and `generateTokenPair(user, context, expectedVersion?)` require an explicit context argument. Expected session version is the third argument. Local login explicitly selects local context. Entra callback passes the exact identity ID resolved by authenticated issuer/subject, not an arbitrary identity attached to the account. Refresh retains the verified inbound context in both replacement tokens. +- `assertSessionEligible(userId, context, expectedVersion?)` is the shared account/provider eligibility seam and returns the current session version. It validates context, requires an active account and the expected version, then requires enabled local scope or an existing identity matching ID, user ID and provider. It runs at issuance, access verification and refresh. Pair issuance checks the same context/version before and between signing steps and again before returning. Identity removal rejects the associated Entra session while separately issued local sessions remain valid. Account-wide revocation and refresh reuse detection retain existing behavior. +- `InvalidAuthenticationContextError` is a typed safe INVALID_TOKEN failure for context or identity ownership rejection. Client responses retain existing authentication error envelopes and no identity details are exposed. +- DIContainer registers `authentication`; `resolveAuthenticationService(db, container)` creates it once with ConfigService's JWT secret and an audit logger, or returns the explicitly registered instance. Server, setup/auth/user/RBAC/journal/console/LDAP/Entra routers and lifecycle/MCP user provisioning share it. The standalone password-reset CLI still owns its independent process/database service and issues no sessions. +- `createAuthMiddleware(authService)` now takes the configured instance and constructs no service. It exposes verified `req.authContext` separately from the existing user DTO and captures this same instance/token in `req.revalidateAuth`. Static lifecycle/MCP credentials retain their existing separate authentication policy and are not assigned a fabricated password-provider context. +- New dialect-specific migration 032 rotates every existing account's session version and expires pending OAuth state and authorization-code exchanges once. Console credentials fail the existing persisted session-version comparison. Account/profile data, identities, role grants, console records and relationships survive. Re-running migrations does not invalidate freshly issued sessions. Legacy JWTs lacking context are rejected even without version inference. +- Updated API documentation describes context and required upgrade reauthentication. Updated older test call sites to select local explicitly, adjusted historic migration expectations and raw property-test payloads, and replaced direct LDAP token fixtures with persisted-version assertions or correctly scoped Entra tokens. The password-ownership HTTP regression uses a deliberately constructed legacy mixed account and a local token. No LDAP authentication bypass was added. + +**Verification: exact commands, outcomes, and external log reference:** + +All state-changing, network-documentation and verification commands are recorded in append-only `~/.agents/logs/pabawi.jsonl`. Evidence is retained under `/tmp/pabawi-ldap-p5-*`. Used the previously verified Node 24.21.0 archive, PostgreSQL fixture and local OpenLDAP image. No new dependency, image or archive download occurred, so there were no new downloaded artifacts requiring a ClamAV scan. + +- Focused provider/upgrade/shared-service/Entra checks passed: 40 tests in five files, including both adapters. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:62420/ldap_package5a_verified npm run test --workspace=backend -- test/database/provider-bound-sessions.test.ts test/database/migration-016-convergence.test.ts test/properties/auth/token-validity.property.test.ts test/integration/shared-authentication.test.ts test/integration/EntraIdAuthFlow.test.ts > /tmp/pabawi-ldap-p5-focused.log 2>&1 +~~~ + +New evidence includes local/Entra context through issuance and rotation, a real signed Entra callback/code exchange plus HTTP refresh, multiple-provider enrollment without inference, signed malformed/foreign-user context, tampered signatures, identity deletion, local-scope disablement, revocation, null email and shared service use across route guards/MCP/stream revalidation. Fresh SQLite/PostgreSQL and populated pre-032 upgrades prove one-time invalidation while preserving identity, account, grant and console records. Existing regressions cover revoked refresh reuse and revocation between pair signing steps. + +- Fixture startup used existing local artifacts: + +~~~bash +docker start pabawi-ldap-p1-postgres +docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package5a_acceptance +docker run --detach --name pabawi-ldap-p5-openldap --pull never -p 127.0.0.1::1389 -p 127.0.0.1::1636 pabawi-ldap-fixture:package3-verified +mkdir -p /tmp/pabawi-ldap-p5-tls && docker cp pabawi-ldap-p5-openldap:/fixture/tls/ca.pem /tmp/pabawi-ldap-p5-tls/ca.pem +~~~ + +Published ports: PostgreSQL 62420, LDAPS 51397, StartTLS 51396. Earlier retained `postgres` database had migration-031 checksum drift and was not repaired or reset. Fresh disposable databases removed that fixture limitation. Initial test failures from legacy payload/migration assumptions, missing ConfigService test secret length and the local-scope/password-hash constraint were corrected. Build initially found one unused route audit instance, removed before acceptance. + +- Full backend acceptance on final production source passed: 248 files passed, one skipped; 4020 tests passed, two skipped, one todo. Includes local/Entra, authorization and transport regressions, migrations/concurrency on both adapters and live OpenLDAP LDAPS/StartTLS. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:62420/ldap_package5a_acceptance TEST_LDAP_LDAPS_PORT=51397 TEST_LDAP_STARTTLS_PORT=51396 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p5-tls/ca.pem npm run test --workspace=backend > /tmp/pabawi-ldap-p5-backend-final-acceptance.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p5-build-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p5-lint-final.log 2>&1 +~~~ + +Backend build and both workspace linters passed. Frontend source and response DTOs are unchanged, so frontend tests/component checks were not rerun. + +- Documentation contracts pass all five checks independent of pre-existing version consistency. The complete run has the two existing metadata failures described below. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test scripts/documentation/contracts.test.mjs > /tmp/pabawi-ldap-p5-doc-contracts.log 2>&1 +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh > /tmp/pabawi-ldap-p5-secrets-full.log 2>&1 +~~~ + +The tracked scan retains four unchanged findings. Additional scan of all 49 changed/new files passes with zero new unreviewed findings (`/tmp/pabawi-ldap-p5-secret-comparison.log`). Exact scanner/comparison commands are in the external log. Synthetic test credentials are annotated; no baseline exception was added. The comparison proves flagged files, baseline and relevant release metadata match starting commit `ac20696` byte-for-byte. + +Final documentation-only checks retain the same two metadata failures (`/tmp/pabawi-ldap-p5-doc-contracts-final.log`), and the changed/new-file secret comparison passes after handoff publication. `git diff --check` passed. `docker stop pabawi-ldap-p5-openldap pabawi-ldap-p1-postgres` stopped both acceptance servers; containers, databases, public CA and evidence are retained. Prior handoff records are preserved verbatim. No commit, push, PR, deployment or repository cleanup occurred. + +**Pre-existing failures:** + +- Base `ac20696` has package metadata 1.6.0 while lockfile/OpenAPI metadata remains 1.5.1; CHANGELOG.md also lacks the required dated release entry. Two documentation contracts fail: release-version consistency and OpenAPI-version coherence. These are outside package 5A; no release metadata was changed here. +- Full tracked-tree secret scan reports four unchanged findings: one in backend/package.json, two in backend/src/cli/resetUserPassword.ts and one in backend/test/unit/cli/resetUserPassword.test.ts. The reviewed baseline is unchanged. +- One full rerun hit an existing logging property failure, seed 1994789662, path `6:0:0`, vector `['error', ' ', 'z', 'bolt', 'z']`. The field-order property uses `indexOf('[z]')` for both component and operation, so equal labels resolve to the same first marker. LoggerService and this test match base byte-for-byte. Deterministic compiled-logger reproduction confirms two correctly ordered markers while the property's indices are equal (`/tmp/pabawi-ldap-p5-logging-reproducer.log`); its exact command is in the external log. No logging code or property test was changed. The final full acceptance rerun passed. + +**Remaining work and blockers:** No package-5A acceptance blocker remains. Package 5B is pending and blocks public LDAP authentication. The release-documentation and tracked-tree secret failures above remain release blockers; the unrelated logging property remains a known intermittent verification defect. Actual AD environment/credentials remain unavailable and block package-7 interoperability/support claims. The previously recorded decommissioned DN-parser dependency still requires maintenance review before release. The old retained PostgreSQL database has drifted migration checksums; use a new disposable database for acceptance rather than changing migration history. + +**Decisions or discoveries affecting the next package:** + +- Extend the existing AuthenticationContext union/validator and shared assertSessionEligible seam for LDAP only when complete credential, explicit-role and freshness enforcement is ready. Add directory ID to LDAP context, resolve the exact database identity/metadata owner and configured directory, and never infer provider from account enrollments. Refresh must force LDAP validation; pair issuance must reuse the already authoritative login/refresh result without incorrectly extending freshness. Local/Entra paths must remain independent of directory availability. +- REST middleware and `req.revalidateAuth` now use the shared service. StreamingExecutionManager.subscribe installs SessionAuthorization around that callback; journal SSE uses the same request callback. McpRouter captures the opening callback for its stored session, checks it on subsequent requests/idle intervals and exposes it to tool handlers. Add LDAP deadline/race/outage coverage through all these paths in 5B. +- Console REST guards share the service, but websocket authorization still goes through ConsoleSessionManager.assertSessionAuthorized, which checks account session version and console permission only. Console session rows currently retain no authentication context. Package 5B must carry the verified request provider/identity/directory context through reservation and persistence, wire the shared eligibility dependency into the manager, and enforce it during upgrade, initial relay, idle checks and both delivery directions. Do not use account-level identity guessing or rely only on console REST middleware. +- Shared provisioning and LdapMappingService.withRevision still own their transactions. Package 5B must form a single atomic account/profile/grant/freshness publication transaction, combine mapping/config revisions with database-time lease owner/expiry/fencing checks, and prevent stale work from restoring removed grants. Null validation state is never eligibility. Positive revocation remains terminal; transient failures cannot extend freshness or erase authoritative grants. +- Migration 032 is now part of the sequence and intentionally invalidates legacy sessions. Do not edit 031 or 032 when adding console context or other new schema requirements; add another forward migration. + +**Next action and acceptance criterion still to satisfy:** Start package 5B. Implement explicit LDAP login/discovery and provider-aware throttling, atomic grant/profile reconciliation, persisted freshness with cross-process leases/fencing, forced refresh and every REST/SSE/MCP/console enforcement path. Keep LDAP login/token issuance unavailable until all package-5B transport, deadline, revocation and race acceptance checks pass. + + +## Handoff 2026-10-21 Codex package 5B + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 5B, LDAP login and all transport checks, complete. Package 5 is complete. Package 6 is next eligible. LDAP HTTP authentication is now available when configured; frontend provider selection and mapping/diagnostic controls remain package 6 work. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base `3fee4b3ab95ac158a26eaf4110ab3d077a880455`. Starting tree was clean. Package 5A is committed as `7f58092`; its table reference has been corrected. Read AGENTS.md, code-change/git/Context7 instructions, progress and latest handoffs. Verified migration 031, provisioning ownership, mappings/revisions, provider-bound sessions and configured authentication wiring against source and focused tests on both adapters. KiroGraph reported 210 pending files and omitted LDAP services; used filesystem inspection without changing its index. No completion commit was created. Changed/new paths: + +~~~text +backend/.env.example +backend/src/container/DIContainer.ts +backend/src/database/migrations/033_ldap_validation_decisions.postgres.sql +backend/src/database/migrations/033_ldap_validation_decisions.sqlite.sql +backend/src/database/migrations/034_console_authentication_context.postgres.sql +backend/src/database/migrations/034_console_authentication_context.sqlite.sql +backend/src/middleware/authMiddleware.ts +backend/src/middleware/securityMiddleware.ts +backend/src/routes/auth.ts +backend/src/routes/console.ts +backend/src/routes/journal.ts +backend/src/server.ts +backend/src/services/AuthenticationService.ts +backend/src/services/ConsoleSessionManager.ts +backend/src/services/LdapAuthenticationService.ts +backend/src/services/LdapDirectoryService.ts +backend/src/services/LdapMappingService.ts +backend/src/services/SessionAuthorization.ts +backend/src/services/UserService.ts +backend/src/types/express.d.ts +backend/test/database/BatchLifecycleMigration.test.ts +backend/test/database/ldap-authentication.test.ts +backend/test/database/migration-integration.test.ts +backend/test/database/provider-bound-sessions.test.ts +backend/test/helpers/consoleUser.ts +backend/test/helpers/ldapAuthentication.ts +backend/test/integration/ldap-authentication.test.ts +backend/test/integration/shared-authentication.test.ts +backend/test/properties/consoleAuditLog.property.test.ts +backend/test/properties/consoleConcurrentLimit.property.test.ts +backend/test/properties/consoleRbacTermination.property.test.ts +backend/test/properties/consoleSessionRecord.property.test.ts +backend/test/properties/consoleTokenValidation.property.test.ts +backend/test/security/console-lifecycle.test.ts +backend/test/security/ldap-transports.test.ts +backend/test/security/session-revocation.test.ts +backend/test/unit/services/LdapDirectoryService.test.ts +docs/api.md +docs/configuration.md +docs/internal/plans/ldap-authentication.md +docs/openapi.yaml +scripts/documentation/contracts.test.mjs +~~~ + +**Completed scope and changed interfaces:** + +- `LdapAuthenticationService.authenticate(loginName, password)` returns a committed proof containing the account, exact identity/directory and session version only after credential, eligibility and explicit-role validation. It never implements JWT signing. `assertEligible(userId, identityId, directoryId, expectedVersion, force)` verifies exact ownership/configuration and is injected into the existing AuthenticationService through the configured container. There is no provider inference, implicit linking, default LDAP role or credential replay. A proven zero-role account is committed without tokens for later manual assignment. Suspension remains locally owned. +- `UserService.withFederatedUser(input, publish)` owns one transaction for account/identity/profile creation or refresh and the database-only publication callback. `createFederatedUser` delegates to it and preserves existing Entra behavior. `LdapMappingService.lockRevision` participates in that transaction; `withRevision` still owns its standalone transaction. No nested transactions or directory I/O inside database transactions were introduced. Publication reconciles only the authenticating identity's grants and retains separate mapping provenance. Manual grants and other identity sources survive. Effective role and permission-cache invalidation continue through the existing view and database triggers. +- New forward migration 033 adds `decision_started_at` and `decision_sequence` to LDAP validation state and `validation_sequence` to directory state on both adapters. The directory counter orders reads even when timestamps are identical. Migration 034 adds nullable `console_sessions.auth_context`; existing rows survive but cannot upgrade without provable context. Migrations 031/032 and existing identity/grant keys are unchanged. Fresh and populated upgrade tests pass on SQLite and PostgreSQL. Historic migration-count assertions now include 033/034. +- Successful freshness is persisted from database time before directory I/O, with mapping/configuration revisions. Strict freshness is `last_validated_at + interval > database_now`, including the exact deadline. Null state never authorizes access. Config fingerprints include validated settings and configured CA contents; startup initializes the fingerprint once and invalidates incompatible freshness. Serving processes must share configuration; an older running process cannot switch the stored revision back during a request. +- Lookup-only revalidation is single-flight per identity/session version in process. Cross-process conditional leases use database time, owner/expiry and monotonically increasing fencing generation. Remote waiters compare a completed validation generation under the same directory lock before acquiring another lease, closing the publication/reacquisition race found during acceptance. Successful and positive-negative publication checks current mapping/config revisions, account session version, lease ownership/expiry/generation and decision order. Expired or superseded work rolls back profile/grant changes. Release is owner/generation conditional. Credential proofs are independent and fence older work when published. +- Confirmed ineligibility or loss of all explicit roles withdraws LDAP-owned grants, clears freshness, advances the decision generation and rotates the existing account-wide session version. Previously revoked tokens remain invalid after recovery/new login. Transient, incomplete, limited and malformed directory work neither advances freshness nor erases grants. Existing otherwise valid tokens recover after a fresh check. Unchanged periodic validation emits no audit event; entitlement changes and positive revocation emit safe identity/directory/mapping IDs and reason codes. +- Access/refresh context now accepts exactly `{ provider: 'ldap', identityId, directoryId }` in addition to the existing local/Entra shapes. Issuance, verification, refresh, REST request revalidation and console use the shared eligibility dependency. Refresh always forces validation; subsequent pair issuance reuses authoritative persisted freshness without resetting its timestamp. Refresh validation failure leaves the inbound refresh token available for retry. Local and Entra remain independent of directory availability. +- `POST /api/auth/ldap/login` accepts only nonempty username/password with 1024/4096 UTF-8 byte limits, preserves submitted login case/whitespace and password, and never falls through. Its strict schema replaces generic body sanitization for this exact path. Provider discovery advertises only enabled/name/help URL and remains visible during outages. Safe statuses are 401 for generic credential rejection, 403 for proven denied access, 429 for throttling/capacity and 503 for unavailable/incomplete validation; disabled LDAP returns 404. API/OpenAPI/configuration/env contracts are current. +- Existing IP authentication throttling includes LDAP. Existing database failure/temporary-lockout accounting uses a distinct `ldap:` key followed by SHA-256 of JSON `["ldap", directoryId, submittedLogin]`. Five failures in fifteen minutes lock that provider/directory/login key for fifteen minutes. A valid successful login clears its key. Other directories and local accounts have independent counters. LDAP login audit labels include the safe directory ID, not passwords or complete directory entries. +- Console reservations now require verified auth context and the originating session version, check the shared service before reservation, compare that version under the account lock, and persist the context. ConsoleSessionManager receives the shared authentication dependency and revalidates exact persisted context on upgrade, initial relay, idle checks and both delivery directions through the existing proxy/SessionAuthorization path. Legacy/null/malformed context fails closed. +- Corrected the previous handoff's journal claim: the request carried `req.revalidateAuth`, but neither journal SSE send loop invoked it. Both node/global journal streams now use SessionAuthorization for idle and per-delivery checks plus current journal permission. `finish()` drains authorized queued sends before ending a finite response. Execution SSE and MCP already reached the shared seam; LDAP tests now prove blocked pending output, delayed-result rejection and idle enforcement. Already dispatched infrastructure work is not cancelled. +- Prerequisite service review found three boundary errors relevant to public login: TLS/protocol failures previously retried all endpoints, ambiguous immutable revalidation was classified as positive ineligibility, and rejected lookup credentials looked like a bad user password. Failover now permits only known transient transport errors/timeouts; ambiguity is INCOMPLETE_RESULT; lookup credential rejection is UNAVAILABLE and does not consume a submitted user's failure budget. Dedicated directory tests preserve user-bind rejection without retries and diagnostic redaction. + +**Verification: exact commands, outcomes, and external log reference:** + +All state-changing, fixture and verification commands are recorded in append-only `~/.agents/logs/pabawi.jsonl`. Evidence is retained under `/tmp/pabawi-ldap-p5b-*`. Used the retained, previously verified Node 24.21.0 installation, PostgreSQL 17.11 fixture and synthetic OpenLDAP image. No package, image or archive download occurred; no new downloaded artifact required a ClamAV scan. + +- Initial prerequisite run passed 43 tests; 28 PostgreSQL cases were initially skipped until the fixture started. Later focused provisioning/mapping/authentication tests passed all 78 cases across both adapters. Dedicated LDAP HTTP/core/transport acceptance passed 63 tests, including real LDAPS/StartTLS HTTP issuance and refresh. +- Started the retained PostgreSQL fixture and created new `ldap_package5b_verified` and `ldap_package5b_acceptance` databases. Restarting the old OpenLDAP container failed because its entrypoint reseeds an existing database; it was retained unchanged. Created a fresh retained container from the existing image and copied only its generated public CA: + +~~~bash +docker start pabawi-ldap-p1-postgres +docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package5b_verified +docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package5b_acceptance +docker run --detach --name pabawi-ldap-p5b-openldap --pull never -p 127.0.0.1::1389 -p 127.0.0.1::1636 pabawi-ldap-fixture:package3-verified +mkdir -p /tmp/pabawi-ldap-p5b-tls && docker cp pabawi-ldap-p5b-openldap:/fixture/tls/ca.pem /tmp/pabawi-ldap-p5b-tls/ca.pem +~~~ + +Acceptance endpoints were PostgreSQL 49305, LDAP StartTLS 50819 and LDAPS 50820 on loopback. These ports may change when fixtures are restarted; create another fresh OpenLDAP container rather than reseeding retained data. + +- Final full backend acceptance on final production source passed: 251 files passed, one skipped; 4085 tests passed, two skipped, one todo. Includes local/Entra regressions, both database adapters/upgrades/concurrency, real OpenLDAP directory and HTTP flows, fake database-clock deadline tests, revision/fencing races, REST, execution/journal SSE, MCP and VNC/terminal console enforcement. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:49305/ldap_package5b_acceptance TEST_LDAP_LDAPS_PORT=50820 TEST_LDAP_STARTTLS_PORT=50819 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p5b-tls/ca.pem npm run test --workspace=backend > /tmp/pabawi-ldap-p5b-backend-verified.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p5b-build-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p5b-lint-final.log 2>&1 +~~~ + +Build and both workspace linters pass. Frontend source/DTOs are unchanged, so frontend tests/component checks were not rerun. Initial acceptance caught and corrected a remote coalescing race, old migration-count/console-context fixtures, scanner annotation placement and the lookup diagnostic expectation. Initial source lint findings were corrected before final acceptance. + +- All seven documentation contracts pass, including release metadata and public LDAP route coverage. The tracked-tree secret scan is clean with 176 reviewed findings. A separate all-files scan covers all 42 changed/new files, including untracked source/test/migration files, and compares hashes against the unchanged reviewed baseline and starting HEAD. It reports zero new findings. The stronger all-files mode also exposes the unchanged synthetic PostgreSQL URL at backend/.env.example:40, excluded by the default scanner. A retained HEAD copy proves that sample line and finding hash are unchanged; no baseline exception or unrelated sample edit was made. Exact commands and outcomes are in the external log. No new baseline entry was accepted. Final documentation and scan evidence is recorded in `/tmp/pabawi-ldap-p5b-doc-contracts-handoff.log`, `/tmp/pabawi-ldap-p5b-secrets-handoff.log` and `/tmp/pabawi-ldap-p5b-secrets-changed.log`. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test scripts/documentation/contracts.test.mjs > /tmp/pabawi-ldap-p5b-doc-contracts-handoff.log 2>&1 +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh > /tmp/pabawi-ldap-p5b-secrets-handoff.log 2>&1 +~~~ + +**Pre-existing failures:** All-files scanning additionally reports the unchanged synthetic database URL described above; the standard tracked-tree scan passes. The previous handoff's release metadata and tracked-scan blockers were resolved by base commit `3fee4b3`, which updates release metadata and the reviewed secret baseline. They no longer reproduce; neither the baseline nor release metadata was changed in this package. One full run reproduced the already recorded logging field-order property defect: seed -1583974006, path `97:0:0:0`, vector `["error", " ", "R", "bolt", "R"]`. Both LoggerService and its property test match HEAD byte-for-byte. The property uses the same first `indexOf('[R]')` for component and operation; the logger emits both correctly. Deterministic compiled-logger evidence in `/tmp/pabawi-ldap-p5b-logging-reproducer.log` reports component index 33, incorrect property operation index 33, actual operation index 44. No logging source/test was changed. The final full rerun passes; the intermittent verification defect remains recorded. + +Fixture shutdown completed with `docker stop pabawi-ldap-p5b-openldap pabawi-ldap-p1-postgres`; both exited successfully. Containers, databases, public CA and evidence remain retained. Current versions were verified as Node 24.21.0, PostgreSQL 17.11 and Debian OpenLDAP 2.6.10+dfsg-1. `git diff --check` passes and the external command log parses as JSON Lines. + +**Remaining work and blockers:** No package-5B acceptance blocker remains. Package 6 is pending and blocks the login/mapping/diagnostics UI and full operator walkthrough. Actual AD access/credentials remain unavailable and block package-7 interoperability/support claims. The previously recorded decommissioned DN-parser dependency still requires maintenance review before release. Real Proxmox console compatibility remains unverified; local websocket fixtures prove authorization enforcement only. The old retained PostgreSQL database with historic checksum drift must not be reused for acceptance. No push, PR, deployment or destructive repository cleanup occurred. + +**Decisions or discoveries affecting the next package:** Use the implemented discovery metadata and explicit LDAP route, preserve credentials without local password-creation rules, and do not add fallback between providers. User/group identity and mapping labels come from the server. Null contacts and LDAP-owned profile/password restrictions remain server-enforced. The common container must remain the authentication composition root; console callers must supply verified context/version, never infer a provider from enrollments. SQL freshness/decision/lease state is authoritative across workers. Configuration changes require coordinated restart; directory ID remains stable across endpoints. Keep API/configuration contracts aligned while completing frontend/operator docs. + +**Next action and acceptance criterion still to satisfy:** Start package 6. Add common discovery and explicit password-provider selection, role mapping and restricted diagnostics controls, source/profile ownership UI, and the operator guide/RBAC documentation. Verify browser/UI flows, nullable contacts, directory-valid short credentials, permission guards, local/Entra regressions, frontend tests/build/lint, component checks and documentation contracts. Preserve the real AD and dependency-review release blockers until evidence resolves them. + + +## Handoff 2026-10-21 Codex package 6 + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 6, frontend and operator documentation, complete. Package 7 is next eligible. No package-6 acceptance blocker remains. LDAP release readiness still requires the real AD and dependency-maintenance work recorded below. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base `56ea384192f1e9baf53911549b05be20bf257b6d`. Starting tree was clean. Package 5B is now committed as `56ea384`, correcting its earlier working-tree reference. Read AGENTS.md, code-change/git/Context7 instructions, progress and latest handoffs. Verified prerequisite routes, provisioning, ownership, mapping/revision contracts, provider-bound sessions and shared eligibility seams against source and tests. KiroGraph reported 215 pending files and omitted LDAP services; used filesystem inspection without changing its index. No completion commit was created. Changed/new paths: + +~~~text +backend/.env.example +backend/src/routes/users.ts +backend/src/services/UserService.ts +backend/test/database/ldap-mappings.test.ts +backend/test/fixtures/ldap/README.md +backend/test/fixtures/ldap/ui-server.ts +backend/test/integration/ldap-account-ownership.test.ts +docs/api.md +docs/configuration.md +docs/integrations/ldap.md +docs/internal/plans/ldap-authentication.md +docs/openapi.yaml +docs/permissions-rbac.md +e2e/ldap-ui/ldap.spec.ts +frontend/src/components/LdapAdministration.svelte +frontend/src/components/LdapAdministration.test.ts +frontend/src/components/RoleDetailDialog.svelte +frontend/src/components/UserDetailDialog.svelte +frontend/src/components/user-contact-nullability.test.ts +frontend/src/lib/auth.svelte.ts +frontend/src/lib/auth.test.ts +frontend/src/lib/authProviders.svelte.test.ts +frontend/src/lib/authProviders.svelte.ts +frontend/src/lib/entraIdAuth.svelte.test.ts +frontend/src/lib/entraIdAuth.svelte.ts +frontend/src/lib/ldapApi.test.ts +frontend/src/lib/ldapApi.ts +frontend/src/lib/userAdministration.ts +frontend/src/pages/LoginPage.svelte +frontend/src/pages/LoginPage.test.ts +frontend/src/pages/RoleManagementPage.svelte +frontend/src/pages/UserManagementPage.svelte +playwright.config.ts +playwright.ldap.config.ts +~~~ + +**Completed scope and changed interfaces:** + +- `authProviders.svelte.ts` now owns common provider discovery, five-second timeout, disabled-provider reset, safe HTTP(S) help URLs and local emergency fallback on discovery failure. `entraIdAuth.svelte.ts` retains only SSO code exchange and its errors. Login explicitly selects Local or the configured directory; Entra keeps its redirect button. Switching clears password/validation state. LDAP uses nonempty 1024/4096-byte input limits, preserves submitted case/whitespace and accepts short directory credentials. Failed login never changes provider, retries or falls through. +- `authManager.login(credentials, provider = 'local')` uses exactly the selected endpoint and the existing token/localStorage state. Both legacy string and structured error responses render safe messages. Temporary refresh HTTP 429/503 and network errors now retain credentials for a later retry and show a warning; they establish no fresh authorization. Definitive refresh rejection still clears the session. Successful refresh clears the warning. Local/Entra regressions and retry recovery are covered. +- `LdapAdministration.svelte` is mounted in Role Management and role details only with the existing administrator page boundary plus loaded `rbac:admin`. It supports scoped group search, empty results, opaque cursor continuation with the original filter, create/change-role/enable/disable/remove mappings, stored outage labels and reload. Creation submits only group subject and role ID. Diagnostics use configured lookup-only endpoints, exact optional username and up to 20 enabled mapped groups. Passed/failed stages, timings and safe codes remain visible even for HTTP 422/429/503 reports. The dedicated client never replays directory work. UI removal requires confirmation; every backend administration guard remains independently enforced. +- Added protected, additive user-administration DTO fields without schema or authentication-contract changes. `UserService.getAdministrationMetadata(users, directory?)` batches sources, current directory login and profile ownership. `GET /api/users` and `GET /api/users/:id` expose `authentication: { profileReadOnly, sources }` through existing `users:read` guards. Source objects contain server-supplied provider/name and optional directory ID/login; no user subject, DN, token or credential. Public authentication user DTOs remain unchanged. +- User details also expose `roleSources` from manual, identity-owned and retained legacy grants. The UI labels provenance and removes only manual assignments, reloading the effective union so an overlapping LDAP grant survives. LDAP account display/login/source is searchable in user management; null email, absent names and read-only profile/password behavior render correctly. Long reserved usernames wrap without overlapping email. Suspension and manual entitlement controls remain available under their existing permissions. +- Added `docs/integrations/ldap.md` with OpenLDAP/AD examples, actual defaults, positive policy/status visibility, TLS/failover, exclusions, diagnostics, mapping/manual enrollment, outage/recovery and upgrade reauthentication. Configuration/env, API/OpenAPI and RBAC docs link or describe implemented behavior. The guide explicitly retains unverified AD and Proxmox claims and the DN-parser maintenance gate. +- Added a reproducible loopback-only browser fixture using an in-memory database, real auth/session/admin HTTP code and synthetic directory responses. `playwright.ldap.config.ts` starts its own server on 127.0.0.1:3186 and builds the frontend. The default Playwright config excludes this suite. Browser evidence is UI/HTTP contract coverage, not LDAP protocol or AD evidence. No production authentication seam was weakened for fixtures. + +**Verification: exact commands, outcomes, and external log reference:** + +All mutating, fixture, network-documentation and verification commands are recorded in append-only `~/.agents/logs/pabawi.jsonl`. Evidence is retained under `/tmp/pabawi-ldap-p6-*`. Used the retained Node 24.21.0 runtime and PostgreSQL fixture. No packages, archives or images were downloaded; no new artifact required a ClamAV scan. + +- Initial prerequisite check passed 34 tests with three live LDAP cases skipped. Its command and output are in the external log and `/tmp/pabawi-ldap-p6-prerequisites.log`. Focused user HTTP/ownership verification passed 147 tests. +- Restarted the retained PostgreSQL container, created a new acceptance database, and verified its loopback endpoint as 55712. Both-adapter provisioning/session/mapping acceptance, including the new source/provenance case, passed all 56 tests: + +~~~bash +docker start pabawi-ldap-p1-postgres +docker port pabawi-ldap-p1-postgres +docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package6_verified +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55712/ldap_package6_verified npm run test --workspace=backend -- test/database/ldap-mappings.test.ts test/database/federated-provisioning.test.ts test/database/provider-bound-sessions.test.ts > /tmp/pabawi-ldap-p6-adapters.log 2>&1 +~~~ + +- Full backend regression passed: 250 files passed, two skipped; 4075 tests passed, 15 skipped and one todo. Includes SQLite/PostgreSQL migrations and concurrency plus local/Entra/auth/transport regressions. Live OpenLDAP endpoints were not supplied in this session, so the live directory cases were skipped. Earlier package-5B real LDAP evidence remains historical evidence, not a fresh run here. +- Final full frontend regression passed all 63 files and 1079 tests. Focused refresh/provider/API regressions passed 53 tests. Final workspace lint passed with zero warnings; component checking reports zero errors with an unchanged zero baseline. +- Both production builds passed. Used separate frontend/backend build commands; the browser fixture also builds the production frontend. Vite retains its existing large-chunk warning. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:55712/ldap_package6_verified npm run test --workspace=backend > /tmp/pabawi-ldap-p6-backend-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test --workspace=frontend > /tmp/pabawi-ldap-p6-frontend-final-source.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p6-build-backend-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:frontend > /tmp/pabawi-ldap-p6-build-frontend-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p6-lint-complete.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run check:components > /tmp/pabawi-ldap-p6-components-final-source.log 2>&1 +~~~ + +- Browser skill setup and documented recovery reported no available browser connection. Used the existing repository Playwright test runner with the new isolated fixture. All three Chromium cases passed: explicit short LDAP credentials and denial without fallback; local administrator mapping/diagnostics/null-contact profile flows; and denied non-administrator page access. Inspected retained screenshots `/tmp/pabawi-ldap-p6-mappings.png` and `/tmp/pabawi-ldap-p6-profile.png`. +- Browser acceptance found and corrected a restored-session race: provider discovery must not depend on permissions having finished loading at page mount. Public discovery now starts independently; private controls still wait for both guards. Initial fixture startup also exposed CommonJS top-level-await incompatibility; it now uses an async entrypoint. Initial static/scanner findings and a shadowed test variable were corrected before final gates. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node_modules/.bin/playwright test --config playwright.ldap.config.ts > /tmp/pabawi-ldap-p6-browser-final-source.log 2>&1 +~~~ + +- All seven documentation contracts pass. Standard tracked secret scanning passes with 176 reviewed findings. Separate all-files scanning covers all changed and untracked files and reports zero new findings without changing `.secrets.baseline`. It exposes the same pre-existing synthetic PostgreSQL URL at `backend/.env.example:40` previously recorded by package 5B; the exact line matches starting HEAD. The retained scan script/report are `/tmp/pabawi-ldap-p6-final-scan.py` and `/tmp/pabawi-ldap-p6-secrets-changed-report.json`. Password-state/type/string literals flagged by the scanner were annotated as nonsecrets, without adding baseline exceptions. +- `git diff --check` and external JSON Lines log validation pass. The PostgreSQL fixture was stopped with `docker stop pabawi-ldap-p1-postgres`; its container/database and all evidence are retained. Playwright stopped its isolated HTTP server normally. + +**Pre-existing failures:** No blocking repository gate reproduced. The full frontend suite emits existing jsdom document-navigation notices, and Vite emits its existing bundle-size warning. All-files scanning still exposes the unchanged synthetic environment URL described above. The prior handoff's intermittent logger property defect did not reproduce and was not changed. + +**Remaining work and blockers:** No package-6 blocker. Actual AD access/credentials remain unavailable and block package-7 interoperability and support claims. Review or replace the decommissioned DN-parser dependency before release. Live OpenLDAP end-to-end and the full rollout acceptance matrix remain package-7 work in this session. Real Proxmox console interoperability remains unverified separately from authorization fixtures. Do not reuse the historic PostgreSQL database with checksum drift. No push, PR, deployment, real-directory access or destructive repository cleanup occurred. + +**Decisions or discoveries affecting the next package:** Keep provider discovery separate from directory availability and asynchronously loaded permissions. Use server-provided administration metadata, never infer account source from reserved usernames or email. Preserve manual and mapped grant provenance when rendering or editing users. Temporary client refresh failure must not discard the server-retryable credential or imply new eligibility. The browser fixture deliberately tests HTTP/UI contracts with synthetic directory responses; real LDAP and AD evidence must remain separate. + +**Next action and acceptance criterion still to satisfy:** Start package 7. Audit every acceptance row, rerun real OpenLDAP in both TLS modes, obtain real AD access for GUID/account-policy/nested/large-membership/failover cases, verify both adapters and worker/transport races on the final release candidate, resolve dependency maintenance, and finish the observed deployment procedure. Missing real AD evidence is an explicit blocker, not a waived test. + + +## Handoff 2026-10-21 Codex package 7 + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 7, interoperability and rollout, partially implemented and verified. +Status is `blocked`: real AD evidence, DN-parser maintenance and deployment-environment restore/rollout +rehearsal remain open. Passing local acceptance does not complete package 7 or authorize release. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`, base +`55c8107a43401a5709bb0f1635da666c1c01bf86`. Starting tree was clean. Package 6 is committed as +`55c8107`; its previous uncommitted reference in the progress table was corrected. Read AGENTS.md, +code-change/git/Context7 instructions, the progress table, package-7 scope and latest handoffs. +Verified the shared container composition, provider discovery/UI, account/source ownership, schema, +mapping and session contracts against current source and tests. KiroGraph has 225 pending files and +does not index LDAP symbols; used filesystem inspection without changing its index. +No completion commit was created. Changed/new paths: + +~~~text +backend/src/services/AuthenticationService.ts +backend/test/database/ldap-authentication.test.ts +backend/test/database/provider-bound-sessions.test.ts +backend/test/fixtures/ldap/README.md +backend/test/fixtures/ldap/validation-worker.ts +backend/test/integration/ldap-rollout.test.ts +docs/integrations/ldap.md +docs/internal/plans/ldap-acceptance.md +docs/internal/plans/ldap-authentication.md +~~~ + +**Completed scope and changed interfaces:** + +- Added [acceptance evidence](ldap-acceptance.md), mapping all fourteen plan rows to executable cases, + separating live OpenLDAP, synthetic AD/protocol, actual worker-process and browser evidence. +- Added live HTTP rollout cases for SQLite/PostgreSQL and LDAPS/StartTLS. Each creates only uniquely + named synthetic directory entries and removes its own entries at teardown, preserving seed data. + Real bind/provisioning/mapping/refresh code proves zero-role enrollment without tokens, manual + enrollment, mapped-role preservation after manual withdrawal, user move/rename with the same + immutable account, profile refresh/null contacts, terminal policy revocation, group rename/recreation, + remapping by new immutable subject and separate identity after user DN/login recreation. +- Added a separate Node worker fixture and six both-adapter process-boundary cases. These exercise + the unchanged production authentication algorithm through distinct OS processes and independent + database connections, proving overlapping forced-check coalescing, expired-lease fencing and + mapping-revision rejection. Worker directory responses are controlled synthetic data. They provide + real process coordination evidence, separate from LDAP protocol evidence. +- The live rollout exposed an existing PostgreSQL security defect: the shared failed-login upsert + used an ambiguous unqualified counter. PostgreSQL rejected the statement before temporary-lockout + enforcement, affecting both local and provider-scoped LDAP login. The new both-adapter regression + reproduced the failure on starting production source, then passed after qualifying + `login_attempt_counters.cumulative_failed_attempts`. SQLite behavior is preserved. No migration, + dependency version, public API, environment setting or token contract changed. +- Expanded the fixture guide and operator staged upgrade procedure. It explains consistent backups + including SQLite WAL contents, coordinated worker replacement, automatic migrations through 034, + provider reauthentication, mapping/policy tests, outage/recovery, equivalent endpoint failover, + matched backup/artifact restoration and the deployment rehearsal still required. +- Rechecked pinned primary registry metadata: `@ldapjs/dn@1.1.0` and transitive + `@ldapjs/asn1@2.0.0` remain explicitly decommissioned. The installed `ldapts@9.2.0` + DN export is a builder/equality class without the current string-parser/scope API; replacing it + directly would change the security contract. No dependency-maintenance exception was accepted. + A maintained replacement or explicit maintenance ownership, with DN-semantics regression coverage, + remains required before release. + +**Verification: exact commands, outcomes, and external log reference:** + +All mutating, fixture, network metadata and verification commands are in append-only +`~/.agents/logs/pabawi.jsonl`. Evidence is retained under `/tmp/pabawi-ldap-p7-*`. +Used the retained supported Node 24.21.0 runtime, PostgreSQL 17.11 and OpenLDAP +2.6.10+dfsg-1. Fixture image: +`sha256:69cef797be2e96d15304a4f632d34639d8c5caa47a61bbd307c7c49bd99377dc`. +No package, archive or image was downloaded. Primary registry JSON metadata was downloaded; +ClamAV 1.5.4 scanned it and the copied public fixture CA, two files, zero infections. + +Fixture commands: + +~~~bash +docker start pabawi-ldap-p1-postgres +docker exec pabawi-ldap-p1-postgres createdb -U postgres ldap_package7_verified +docker run --detach --name pabawi-ldap-p7-openldap --pull never -p 127.0.0.1::1389 -p 127.0.0.1::1636 pabawi-ldap-fixture:package3-verified +mkdir -p /tmp/pabawi-ldap-p7-tls && docker cp pabawi-ldap-p7-openldap:/fixture/tls/ca.pem /tmp/pabawi-ldap-p7-tls/ca.pem && docker port pabawi-ldap-p7-openldap && docker port pabawi-ldap-p1-postgres +~~~ + +Acceptance endpoints were PostgreSQL 61764, LDAP StartTLS 61777 and LDAPS 61778 on loopback. +Use another fresh OpenLDAP container for the next session; its seed-on-start entrypoint does not +support reusing a populated fixture database. The old historical PostgreSQL database with migration +checksum drift was not reused. + +- Prerequisite run: five files, all 85 cases passed with real TLS endpoints and both adapters. +- Live mutation matrix: all four adapter/TLS combinations passed. +- Lockout regression: starting PostgreSQL source failed and allowed a correct local password after + five failures, with the ambiguous-column error in `lockout-red.log`. After the fix, both-adapter + counter plus live mutation run passed all 18 cases (`lockout-green.log`). +- Focused database authentication passed all 50 cases, including the six actual process-boundary + cases (`workers.log`). +- Final full backend acceptance passed: 252 files passed, one skipped; 4100 tests passed, two skipped, + one todo. Includes live directory/HTTP mutation, both database adapters, upgrades, shared local/Entra + regressions, races and every protected transport fixture. +- Full frontend regression passed all 63 files and 1079 tests. All three isolated Chromium UI/HTTP + cases passed. Browser fixture setup built the production frontend; backend production build passed. + Separate build commands preserve the established package-6 approach. +- Both workspace linters passed with zero warnings; component check reported zero errors and an + unchanged zero baseline. + +Final commands: + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH TEST_DATABASE_URL=postgresql://postgres@127.0.0.1:61764/ldap_package7_verified TEST_LDAP_LDAPS_PORT=61778 TEST_LDAP_STARTTLS_PORT=61777 TEST_LDAP_CA_FILE=/tmp/pabawi-ldap-p7-tls/ca.pem npm run test --workspace=backend > /tmp/pabawi-ldap-p7-backend.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test --workspace=frontend > /tmp/pabawi-ldap-p7-frontend.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p7-build-backend.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p7-lint.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run check:components > /tmp/pabawi-ldap-p7-components.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node_modules/.bin/playwright test --config playwright.ldap.config.ts > /tmp/pabawi-ldap-p7-browser.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test scripts/documentation/contracts.test.mjs > /tmp/pabawi-ldap-p7-contracts.log 2>&1 +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh > /tmp/pabawi-ldap-p7-secrets.log 2>&1 +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH python3 /tmp/pabawi-ldap-p7-final-scan.py > /tmp/pabawi-ldap-p7-secrets-changed.log 2>&1 +~~~ + +All seven documentation contracts passed. Standard tracked secret scan passes with 176 reviewed +findings. Explicit all-files scanning covers all nine changed/new files and reports zero new findings +without changing `.secrets.baseline`. Unlike earlier sessions, this change does not touch the +environment example containing the previously recorded synthetic URL, so that unrelated finding is +outside its explicit changed-file scan. + +Fixture shutdown completed successfully: + +~~~bash +docker stop pabawi-ldap-p7-openldap pabawi-ldap-p1-postgres +~~~ + +Containers, the fresh database, public CA, image and logs are retained. Final `git diff --check` and +external JSON Lines validation pass. Initial fixture-only failures (missing accepted test signing key +and reuse of a rotated refresh credential) were corrected before final acceptance; they were not +production authentication regressions. + +**Pre-existing failures:** The PostgreSQL counter defect was reproduced and fixed in scope. +No repository-wide blocking gate reproduced on final source. Existing frontend jsdom navigation +notices remain; the earlier logger property defect did not reproduce. Historic AD/parser release +blockers remain unresolved. No baseline entry, historical migration or unrelated logging code changed. + +**Remaining work and blockers:** No authorized real AD environment/configuration was supplied or used. +Real AD TLS and equivalent-controller failover, binary GUID queries, policy/status visibility, +nested matching rules and large/ranged membership remain mandatory acceptance blockers. +The DN-parser maintenance gate remains open after current metadata review. Deployment-environment +backup restoration and the complete staged rollout have not been rehearsed; no production procedure +is claimed as observed. Real Proxmox provider compatibility remains separately unverified. +No remote push, PR, production deployment, real-directory access or destructive repository cleanup occurred. + +**Decisions or discoveries affecting the next package:** Shared PostgreSQL counter SQL must remain +qualified to preserve both local and LDAP throttling. Actual OS-process tests now supplement the +earlier independent-connection evidence. Live mutation fixtures must preserve shared seed objects and +use unique records. Keep AD evidence separate from OpenLDAP, protocol mocks and browser fixtures. +The new acceptance report is the current audit index, not a release waiver. + +**Next action and acceptance criterion still to satisfy:** Resume package 7 from its blocked gates. +Obtain an authorized actual AD test environment through local secret references; complete its +matrix without exporting personal directory data. Resolve parser maintenance with preserved parsed-DN +semantics, rerun the current candidate checks after any source/dependency change, and rehearse +backup/restore and coordinated upgrade in the target staging environment. Mark complete only when +every acceptance row has the required real evidence and the operational rehearsal passes. + + +## Handoff 2026-10-21 Codex package 7 continuation + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 7 continuation. Available local work is implemented and verified: +owned DN parsing, populated backup/restore/upgrade rehearsals, real LDAP transport outages on both +adapters/TLS modes and an executable acceptance runner. Package 7 remains blocked on actual AD. +Packaging cleanup also awaits the explicit deletion confirmation described below. + +**Branch, base commit, completion commit or uncommitted paths:** Branch 151, base +55c8107a43401a5709bb0f1635da666c1c01bf86. This session started with the preceding package-7 working +tree and preserved it. No commit was created. Current changed/new files are the preceding handoff's +paths plus: + +~~~text +backend/src/config/ldap.ts +backend/src/config/ldapDn.ts +backend/src/services/LdapDirectoryService.ts +backend/test/config/LdapDn.test.ts +backend/test/database/ldap-upgrade-recovery.test.ts +backend/test/helpers/ldapAuthentication.ts +backend/test/helpers/ldapTransport.ts +backend/test/security/ldap-transports.test.ts +e2e/ldap-ui/ldap.spec.ts +package.json +playwright.ldap.config.ts +scripts/acceptance/ldap.mjs +~~~ + +The combined working tree has 21 changed/new files. Read current AGENTS.md, the progress/acceptance +tables, latest handoffs, code discipline and Context7 instructions. The existing graph remains +incomplete for LDAP; direct source inspection covered every changed production caller. + +**Completed scope and changed interfaces:** + +- Runtime configuration, bind locator comparisons, scope checks and nested-group identity checks + now use project-owned config/ldapDn.ts. Reviewed current primary standards, registry metadata, + pinned ldapts source and a community fork before choosing a narrow owned module rather than a + second complete LDAP stack. No new npm package was installed. +- The parser bounds input to 8192 bytes, validates attribute descriptors/OIDs and escaped UTF-8, + preserves empty values and unordered multi-valued RDN assertions, rejects duplicates/malformed + syntax and compares parsed suffixes. Descriptor case normalizes; values remain exact, without + guessing schema matching, OID aliases or broad case folding. Complete definite-length BER with + single-octet tags stays opaque and is never guessed to equal text; unsupported encodings fail + closed. Tests include RFC-style vectors, invalid Unicode/BER/syntax, escaped scope injection and + 200 randomized Unicode cases. This is conservative locator equality, not a full directory schema + matching engine. Pabawi owns maintenance of this module. +- The obsolete @ldapjs/dn dependency/lock entries and backend/src/types/ldapjs-dn.d.ts are deliberately + unchanged pending confirmation. The user-supplied instructions explicitly require confirmation + before deleting files. A concrete asynchronous approval request named the file and dependency; + no affirmative reply has arrived. Do not infer approval from elapsed time. Runtime imports are + removed, but do not report dependency cleanup or its release gate complete yet. +- Added ldap-upgrade-recovery.test.ts. Populated migration-030 SQLite state includes committed data + in a nonempty WAL and uses VACUUM INTO; PostgreSQL uses matching-version pg_dump custom format and + pg_restore with exit-on-error/single-transaction into another fresh database. The cases preserve + identities, explicit Entra enrollment, roles, group membership and audit links; verify upgrades + through 034, legacy reauthentication, local login, Entra-bound issuance/rotation, and restart + without repeated session invalidation. They prove rollback of an intentionally failing fixture-only + migration, restore the exact original snapshot, then successfully repeat the upgrade. + Backups, databases and evidence are retained. No shipped migration changed. +- The transport suite now runs nine scenarios in five configurations: synthetic SQLite plus actual + LDAPS/StartTLS on SQLite/PostgreSQL. The new helper uses a loopback TCP relay for actual connection + interruption and creates unique directory entries for positive-policy mutations. Eligibility is + not mocked in live cases. REST/refresh, execution/journal SSE, delayed MCP results, VNC/terminal + delivery and idle/upgrade checks fail closed. It verifies unchanged failed freshness, retained + retryable refresh credentials, local emergency login and transient recovery. Infrastructure + payloads/upstream adapters remain local fixtures; no real Proxmox claim is made. +- Added npm run test:ldap and scripts/acceptance/ldap.mjs. The runner creates unique isolated local + containers, discovers loopback ports, scans retained fixture artifacts, records image IDs/versions, + runs backend/frontend/browser/build/lint/component/contracts/secrets, appends exact commands to + the external log and stops its own fixtures in finally without deleting containers or data. + --focused supports iterations; --build-fixture is an explicit source build. Existing local images + are used without pull by default. Playwright screenshots/results now live with runner evidence. +- Updated fixture/operator documentation and the acceptance matrix with actual local recovery + instructions, parser semantics and remaining release boundaries. + +**Verification: exact commands, outcomes, and external log reference:** + +Append-only command log: ~/.agents/logs/pabawi.jsonl. Subcommands started by the runner and PostgreSQL +backup/restore tests also append there. No pushes, PRs, production deployment or personal-directory +access occurred. + +Focused parser/configuration/service acceptance passed 111 cases, including randomized Unicode. +The first runner passed 210 focused checks; the first live TLS transport expansion passed 226. +Both adapter recovery result manifests report all nine rehearsal stages passed. + +The final complete runner command was: + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH:/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin npm run test:ldap -- --ldap-image pabawi-ldap-fixture:package3-verified --output-root /tmp > /tmp/pabawi-ldap-p7b-full-run.log 2>&1 +~~~ + +Result: passed=true in /tmp/pabawi-ldap-acceptance-sGktn2/result.json. + +- Full backend: 254 files passed, one skipped; 4176 tests passed, two skipped and one todo. + Includes both adapters, live TLS/HTTP/mutations, all 45 transport cases, independent OS workers, + populated upgrades and actual backup/restore. Evidence: 015-npm.log. +- Full frontend: 63 files and 1079 cases passed (016-npm.log). +- All three Chromium cases and the production frontend build passed; screenshots are retained + under browser-results in that evidence directory (017-node.log). +- Backend production build, both workspace linters, zero-error component gate, all seven + documentation contracts and tracked-tree secret scan passed (018 through 022 logs). +- Environment manifest records Node 24.21.0, OpenLDAP 2.6.10+dfsg-1 and PostgreSQL 17.11. + LDAP image ID remains sha256:69cef797be2e96d15304a4f632d34639d8c5caa47a61bbd307c7c49bd99377dc; + PostgreSQL image ID is sha256:2d2b8998d31037bf721cfdf764d76ba74171b4fab3431b7f72c27c56ddbdf9e3. + Dynamic ports and retained container/database names are in environment.json and the recovery + result manifests. Historical PostgreSQL data with checksum drift was never reused. +- Runner startup scanned 20 retained fixture/package/CA files with ClamAV 1.5.4, zero infections. + Only primary registry JSON metadata was downloaded this session, no new npm archives/images. + Its two retained JSON files also pass real ClamAV scanning. +- Failure cleanup was tested with an isolated temporary scanner returning 19. The runner exited 1, + retained a failed result, ran no acceptance tests and stopped both of its fixtures. Expected + rejection evidence: /tmp/pabawi-ldap-acceptance-IjDzAQ/result.json and + /tmp/pabawi-ldap-p7b-failure-cleanup.log. Real ClamAV subsequently scanned those copied artifacts + successfully. Docker inspection confirmed all normal/failure-path containers are exited. +- Explicit all-files scanning over all 21 changed/new files reports no new findings; baseline + remains unchanged. Final documentation/whitespace/log checks and scans are in the external log + and /tmp/pabawi-ldap-p7b-* artifacts. + +**Pre-existing failures:** No blocking repository gate reproduced. Existing jsdom navigation notices +and browser color-environment warnings remain. The first parser fixture had an incorrectly written +dangling-escape literal, and initial lint rejected a non-null assertion; both were corrected before +the final full run. The intentional scanner rejection is expected failure-path evidence, not malware +or a release-candidate test failure. Previously recorded logger intermittency did not reproduce. + +**Remaining work and blockers:** Actual AD is unavailable, as the user explicitly confirmed. +Its GUID, policy/status visibility, nested matching-rule, large membership and equivalent-controller +failover evidence remains mandatory for the original plan. Dependency/declaration removal awaits +explicit deletion approval. Local database recovery and actual LDAP transport rehearsals now pass; +target-environment storage/service/secret handling still requires its own staging validation before +any deployment. Actual Proxmox provider compatibility remains separately unverified. + +**Decisions or discoveries affecting the next package:** Keep client DN values exact and directory +identity immutable; do not replace parsed scope with lowercased strings or assume unknown BER matches +text. The maintained code is intentionally narrow and has no new package graph. The runner retains +its containers/databases and uses fresh names every run, avoiding seed-on-restart and checksum drift. +An expected readiness probe can be nonzero before success; result.json distinguishes final acceptance +status. Both normal shutdown and scanner-failure shutdown are now observed. + +**Next action and acceptance criterion still to satisfy:** On explicit approval, remove only the named +obsolete type declaration and unused @ldapjs/dn dependency/lock entries, confirm its transitive packages +are no longer required, and verify the resulting package graph plus parser/build/LDAP regressions. +Then update this approval gate in the progress/evidence documents. Obtain actual AD later and complete +every outstanding AD matrix row. Do not mark package 7 complete or claim real AD support until that +evidence exists. Production deployment still requires the repository's separate confirmation. + + +## Handoff 2026-10-21 Codex package 7 approved cleanup + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 7 approved parser packaging cleanup, complete. The user replied +"approved" to removal of the obsolete declaration and unused dependency. This supersedes the pending +approval statements in earlier handoffs. Package 7 remains blocked on real AD interoperability; +local OpenLDAP, transport, worker and recovery evidence remains passing. + +**Branch, base commit, completion commit or uncommitted paths:** Branch 151, base 55c8107. +Preserved all earlier uncommitted work. This cleanup additionally changes backend/package.json +and package-lock.json, deletes backend/src/types/ldapjs-dn.d.ts, and updates the current acceptance, +operator and progress documents. No commit was created. + +**Completed scope and changed interfaces:** Removed @ldapjs/dn, its unused @ldapjs/asn1 and +process-warning transitives, and the obsolete declaration. Runtime code already uses the owned +bounded parser and did not change in this cleanup. The before/after lockfile assertion proves exactly +those three package entries were removed, no package was added, and the only surviving entry change +is removal of @ldapjs/dn from the backend workspace dependencies. Every remaining package entry is +byte-for-byte equivalent as parsed JSON. The three unused installed package directories are absent. +No historic migration, provider/session contract or parser semantics changed. + +**Verification: exact commands, outcomes, and external log reference:** + +All mutation and verification commands append to ~/.agents/logs/pabawi.jsonl. Before snapshots and +the structural graph comparison are retained in /tmp/pabawi-ldap-p7c-*. + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm uninstall @ldapjs/dn --workspace=backend --ignore-scripts --offline --no-audit --no-fund > /tmp/pabawi-ldap-p7c-uninstall.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test:ldap -- --focused --ldap-image pabawi-ldap-fixture:package3-verified --output-root /tmp > /tmp/pabawi-ldap-p7c-acceptance.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-ldap-p7c-build.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-ldap-p7c-lint.log 2>&1 +~~~ + +- Offline removal reports exactly three packages removed. No downloads or lifecycle scripts ran. + Graph proof: /tmp/pabawi-ldap-p7c-lock-verified.json. +- Focused post-removal acceptance passes all ten files and 247 cases. Includes owned parser/config, + real OpenLDAP in both TLS modes, both database adapters, all transport scenarios, independent + worker processes and populated backup/restore/upgrade rehearsals. + /tmp/pabawi-ldap-acceptance-3jP2T7/result.json reports passed=true; command and case outputs, + actual environment, image IDs and recovery backups are retained in that directory. +- Backend production build and both workspace linters pass without the obsolete declaration or + installed packages. Frontend source is unchanged; its preceding 1079-test/three-browser-case + full-run evidence remains applicable and was not needlessly rerun. +- The runner scanned 20 retained fixture/CA files with ClamAV and stopped both isolated containers + successfully. Containers and databases remain retained; no new image or archive was downloaded. +- Final documentation contracts, whitespace checks, tracked-tree scan, changed-file scan and + external JSON Lines validation pass. The generated lockfile has removal-only changes and is + covered by the exact structural graph assertion; the explicit content scanner covers the other + 22 existing changed/new files. The deleted declaration has no remaining content to scan. + No reviewed secret-baseline entry was added or changed. + +**Pre-existing failures:** No repository verification blocker reproduced. KiroGraph context returned +an FTS syntax error for the task description; the already known stale LDAP index was not changed, +and targeted source/manifest inspection supplied the required context. + +**Remaining work and blockers:** Parser maintenance/packaging approval is resolved. Actual AD +GUID/account-state/nested/large-membership/failover evidence remains unavailable and blocks completing +the original plan. Target-environment staging and production deployment remain separate operational +work. Real Proxmox provider compatibility remains unverified. No push, PR, deployment or unrelated +deletion occurred. + +**Decisions or discoveries affecting the next package:** Keep the project-owned parser and its +regressions. Do not reinstall the decommissioned packages as a workaround. Existing earlier handoffs +describe the former approval gate for history; current progress and acceptance documents record it +closed. + +**Next action and acceptance criterion still to satisfy:** Obtain an authorized real AD environment +when available and complete every outstanding AD acceptance row. Keep package 7 blocked until that +evidence exists. Use the reproducible acceptance runner for candidate changes and rehearse the target +deployment's storage/service/secret procedures before deployment. + + +## Handoff 2026-10-21 Codex package 7 CI and harness + +**Date and agent:** 2026-10-21, Codex. + +**Package and checkpoint:** Package 7 CI integration, opt-in AD harness and runner failure/interruption +checks implemented. Package 7 remains blocked until actual AD evidence exists. No AD configuration +was requested, no actual directory was accessed and no remote infrastructure was provisioned. + +**Branch, base commit, completion commit or uncommitted paths:** Branch `151`. Initial HEAD was +`55c8107`; the existing package-7 work was committed concurrently as `7389784` during this session. +Preserved the original staged changes, the concurrent commit and later staging activity. This agent +created no commit and did not change the index. Additional changed/new paths: + +- `.github/workflows/ci.yml`, `package.json`, `playwright.ldap.config.ts`. +- `scripts/acceptance/ldap.mjs`, `ldap-report.mjs`, `ldap.test.mjs`, `ci.test.mjs`, `ad.mjs`, + `ad-config.mjs` and `ad.test.mjs`, all under `scripts/acceptance/`. +- `backend/test/fixtures/ldap/README.md`, `ad-lab.ts`, `ad-lab.example.json`, `tsconfig.ad.json`, + plus `backend/test/unit/ad-lab.test.ts`. +- `docs/internal/plans/ldap-authentication.md` and `ldap-acceptance.md`. + +**Completed scope and changed interfaces:** + +CI uses a fail-fast=false PostgreSQL 15/17 matrix and the existing approved npm-install pattern. +The owned acceptance runner builds OpenLDAP, exercises both TLS modes with SQLite/PostgreSQL and +runs the separate LDAP Chromium configuration with `--focused --browser`. It checks actual server +major version with `--postgres-major`, rejects missing/skipped/failed live and browser results, and +retains JSON/JUnit, recovery archives/manifests, browser HTML and failure screenshots/traces on all +outcomes. Upload scope is synthetic acceptance data only, with private keys, downloads and CA files +excluded. No AD configuration or data enters this CI job. + +`npm run test:ldap:ad` provides strict explicit lab configuration and private local secret-file +references. Absent configuration returns unavailable/not-run, adVerified=false, exit 1. Offline mode +validates settings, CA, secret permissions/resolved paths and parsed OU boundaries without connecting. +Only `--execute` opens a directory connection. The worker prepares both TLS modes, binary GUID +queries, user/group rename/recreation, observable disabled/expired/password-expired/locked accounts, +nested matching-rule/traversal, ranged large membership and controlled primary-transport failover to +an equivalent actual controller. Mutations require generated-child scope, an ownership marker and +unchanged GUID. Cleanup touches only owned objects and records incomplete work as failure. Synthetic +ownership journals retain relative object names for manual investigation without directory topology +or credentials. Actual execution and AD compatibility remain unverified. + +`npm run test:ldap:runner` automates scanner/readiness/subprocess/deadline failures and SIGINT/SIGTERM, +including interrupted Docker creation and detached descendants that ignore SIGTERM. The optional +LDAP_RUNNER_REAL_FAILURES=1 mode uses actual Docker containers. Fixes record attempted creation before +Docker returns, give each readiness operation a separate deadline, preserve environment evidence on +failure, stop new work after cancellation, terminate descendants across process groups and inspect +shutdown. Signal exits are retained separately from numeric exit codes. Containers, volumes/data, +archives and evidence are never removed automatically. + +**Verification: exact commands, outcomes, and external log reference:** + +Every mutation/network/verification command is recorded in `~/.agents/logs/pabawi.jsonl`, including +runner child commands. The external `/tmp/pabawi-p7-command.py` wrapper logs literal multiline shell +commands after completion. Documentation/source/status reads were read-only. No npm package was +added or installed and no lockfile dependency changed. Actionlint 1.7.12 was downloaded from its +upstream release, verified against the published SHA-256 and scanned with real ClamAV after execution. + +Commands from the repository root (supported Node prefix is explicit): + +~~~bash +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test:ldap -- --focused --browser --ldap-image pabawi-ldap-fixture:package3-verified --postgres-image postgres:15 --postgres-major 15 --output-root /tmp/pabawi-p7-candidate15 > /tmp/pabawi-p7-candidate15.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test:ldap -- --focused --browser --ldap-image pabawi-ldap-fixture:package3-verified --postgres-image postgres:17 --postgres-major 17 --output-root /tmp/pabawi-p7-candidate17 > /tmp/pabawi-p7-candidate17.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test:ldap -- --focused --browser --build-fixture --ldap-image pabawi-ldap-fixture:acceptance-ci-p7 --postgres-image postgres:17 --postgres-major 17 --output-root /tmp/pabawi-p7-built17 > /tmp/pabawi-p7-built17.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test scripts/acceptance/*.test.mjs > /tmp/pabawi-p7-runner-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH LDAP_RUNNER_REAL_FAILURES=1 node --test scripts/acceptance/ldap.test.mjs > /tmp/pabawi-p7-runner-real-final.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run test --workspace=backend -- test/unit/ad-lab.test.ts > /tmp/pabawi-p7-ad-unit.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node backend/node_modules/typescript/bin/tsc --project backend/test/fixtures/ldap/tsconfig.ad.json > /tmp/pabawi-p7-ad-types.log 2>&1 +/tmp/pabawi-p7-actionlint/actionlint .github/workflows/ci.yml > /tmp/pabawi-p7-actionlint.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:backend > /tmp/pabawi-p7-next-build-backend.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run build:frontend > /tmp/pabawi-p7-next-build-frontend.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run lint > /tmp/pabawi-p7-next-lint.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH npm run check:components > /tmp/pabawi-p7-next-components.log 2>&1 +PATH=/tmp/pabawi-node24/node-v24.21.0-darwin-arm64/bin:$PATH node --test scripts/documentation/contracts.test.mjs > /tmp/pabawi-p7-next-contracts.log 2>&1 +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH bash scripts/quality/secret-scan.sh > /tmp/pabawi-p7-next-secrets.log 2>&1 +PATH=/Users/al/.cache/pre-commit/repovdso_3ip/py_env-python3/bin:$PATH python3 /tmp/pabawi-ldap-p7-final-scan.py > /tmp/pabawi-p7-next-secrets-changed.log 2>&1 +git diff HEAD --check +~~~ + +Each of the three live runs passes 252 cases, zero skipped, and all three dedicated browser cases. +They used OpenLDAP 2.6.10 with PostgreSQL 15.17/17.11 and the supported Node 24.21.0 runtime. A later +standalone ownership/cancellation regression increases the AD fixture-only suite to six passing cases. +The default Node contracts cover 14 cases including a complete valid offline AD configuration, strict +secret references, unavailable reporting, workflow wiring, report enforcement and lifecycle failures. +Actual-Docker regressions additionally cover real fixture shutdown and interrupted creation. Test +counts and retained case paths are in the final logs. Builds, workspace lint, component checks, +fixture typechecking, actionlint and all seven documentation contracts pass. The tracked secret scan +passes with 176 reviewed findings; the explicit changed/untracked-file scan finds zero new findings +without modifying `.secrets.baseline`. Whitespace and external JSON Lines validation pass. + +Retained successful evidence: + +- `/tmp/pabawi-p7-candidate15/pabawi-ldap-acceptance-BP4dyF`. +- `/tmp/pabawi-p7-candidate17/pabawi-ldap-acceptance-mmfqO5`. +- `/tmp/pabawi-p7-built17/pabawi-ldap-acceptance-FMdXtp`. +- `/tmp/pabawi-p7-session-evidence.json` indexes versions, image IDs and independent shutdown + verification. The real failure log contains exact additional `/var/folders/...` evidence paths; + synthetic CLI regression directories also remain retained there. No private keys were copied. +- `/tmp/pabawi-p7-failure-clamav.log` records an independent real scan including intentionally + scanner-rejected downloads. Fixture copies are otherwise scanned by the runner itself. + +The workflow was validated locally, including fixture build, real protocols, browser commands and +artifact generation. No GitHub-hosted Actions execution, remote workflow trigger or deployment occurred. + +**Pre-existing failures:** KiroGraph omitted the acceptance scripts and LDAP context, consistent with +its previously stale/incomplete index; targeted source/caller inspection supplied context without +reindexing. Direct ad-hoc tsc initially selected root TypeScript 6/Node 20 declarations; using the +backend compiler and existing Node TLS declarations passes. The detached-grandchild red regression +confirmed a real intermediate orchestration defect; its log is `/tmp/pabawi-p7-detached-red.log`. +The first real failure-suite rerun used an unrealistically short normal readiness budget under load, +so one subprocess case failed before its intended injection. Separating normal startup from the +readiness-failure budget resolves it. Scanner findings on synthetic invalid-config vectors were +reviewed and line-locally annotated. No unresolved repository gate reproduced on the final candidate. + +**Remaining work and blockers:** Actual Microsoft AD DS protocol/schema/policy/replication and +large-directory evidence remain unavailable. The opt-in harness is prepared and locally tested, +not actual AD acceptance. Target-environment staging and production operations remain separate work; +real Proxmox interoperability is separately unverified. Package 7 stays blocked. No push, PR, +deployment, remote workflow trigger, real-directory access, branch/file deletion or destructive +repository cleanup was performed by this agent. + +**Decisions or discoveries affecting the next package:** The runtime authentication implementation, +owned parser, migrations and dependency cleanup remain intact. Preserve all historical handoffs and +this distinction between actual protocols, simulated provider/browser responses, harness safety and +actual AD compatibility. Keep secret-bearing AD configuration outside CI artifacts and the repository. + +**Next action and acceptance criterion still to satisfy:** When separately authorized actual AD +access exists, review the opt-in fixture guide and run the prepared matrix in that disposable lab. +Keep actual AD evidence separate from mocks, OpenLDAP and Samba. Complete package 7 only when every +required AD acceptance row has real passing evidence and the target deployment rehearsal is satisfied. diff --git a/docs/mcp.md b/docs/mcp.md index d8be8520..02fd5b92 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -29,6 +29,10 @@ When enabled, Pabawi: 3. Assigns the role to the service user 4. Starts the MCP server and registers the `/mcp` endpoint +Startup reuses existing service users and roles, and repairs a missing role or +role assignment after incomplete provisioning. Only newly created roles receive +the default read permissions; existing role permissions retain any customizations. + All MCP endpoints require bearer authentication, using an access JWT or the configured static token. The MCP server calls services directly within the backend process. Every tool uses the authenticated caller's current permissions. JWT callers use their own account; only the configured static credential uses `mcp-service`. ## Authentication diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 830f7e2d..04e2adbc 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -41,7 +41,7 @@ info: enabled sources. Subscribe to `/journal/global/stream` for a live SSE feed, or query `/journal/{nodeId}` for a node's history. - version: 1.5.0 + version: 1.6.0 contact: name: Pabawi Support url: https://pabawi.example42.com @@ -108,6 +108,244 @@ tags: description: Frontend log collection and troubleshooting paths: + /auth/ldap/groups: + get: + tags: [RBAC] + summary: Search configured LDAP groups + description: >- + Requires rbac:admin. Complete bounded snapshot paged in batches of 50. + Opaque process-local cursors expire after 60 seconds, are bound to caller, + query and configuration, and return INVALID_CURSOR on another process or after eviction. + No LDAP login or account import occurs. + parameters: + - in: query + name: query + required: true + schema: { type: string, minLength: 1, maxLength: 1024 } + description: Literal substring, maximum 1024 UTF-8 bytes + - in: query + name: cursor + schema: { type: string, pattern: '^[a-f0-9]{64}$' } + responses: + '200': + description: Complete search snapshot page + content: + application/json: + schema: + $ref: '#/components/schemas/LdapGroupPage' + '400': + description: Invalid request or cursor + '401': + description: Authentication required + '403': + description: Requires rbac admin permission + '404': + description: LDAP disabled or mapping or role absent + '409': + description: Duplicate mapping or stale revision + '422': + description: Invalid group identity or diagnostic policy denial + '429': + description: Request rate or directory capacity exceeded + '503': + description: Directory unavailable or incomplete resolution + '500': + description: Redacted internal server error + + + /auth/ldap/mappings: + get: + tags: [RBAC] + summary: List stored LDAP role mappings + description: Requires rbac:admin. Lists the configured directory only, including during an outage. + responses: + '200': + description: Stored mappings with source and role labels + content: + application/json: + schema: + type: object + required: [items] + properties: + items: + type: array + items: + $ref: '#/components/schemas/LdapGroupMapping' + '400': + description: Invalid request or cursor + '401': + description: Authentication required + '403': + description: Requires rbac admin permission + '404': + description: LDAP disabled or mapping or role absent + '409': + description: Duplicate mapping or stale revision + '422': + description: Invalid group identity or diagnostic policy denial + '429': + description: Request rate or directory capacity exceeded + '503': + description: Directory unavailable or incomplete resolution + '500': + description: Redacted internal server error + + post: + tags: [RBAC] + summary: Create verified LDAP group role mapping + description: >- + Requires rbac:admin. Resolves immutable group subject against configured + directory. Browser labels and locators are rejected. Does not materialize grants. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LdapMappingCreate' + responses: + '201': + description: Mapping and audit committed atomically + content: + application/json: + schema: + $ref: '#/components/schemas/LdapGroupMapping' + '400': + description: Invalid request or cursor + '401': + description: Authentication required + '403': + description: Requires rbac admin permission + '404': + description: LDAP disabled or mapping or role absent + '409': + description: Duplicate mapping or stale revision + '422': + description: Invalid group identity or diagnostic policy denial + '429': + description: Request rate or directory capacity exceeded + '503': + description: Directory unavailable or incomplete resolution + '500': + description: Redacted internal server error + + + /auth/ldap/mappings/{id}: + parameters: + - in: path + name: id + required: true + schema: { type: string } + put: + tags: [RBAC] + summary: Update LDAP group role mapping + description: >- + Requires rbac:admin and at least one field. Revalidates group identity for + role edits and enabling. Disabling alone works during outages. + Atomically withdraws attributable grants and invalidates directory validation. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LdapMappingUpdate' + responses: + '200': + description: Updated mapping with authoritative stored labels + content: + application/json: + schema: + $ref: '#/components/schemas/LdapGroupMapping' + '400': + description: Invalid request or cursor + '401': + description: Authentication required + '403': + description: Requires rbac admin permission + '404': + description: LDAP disabled or mapping or role absent + '409': + description: Duplicate mapping or stale revision + '422': + description: Invalid group identity or diagnostic policy denial + '429': + description: Request rate or directory capacity exceeded + '503': + description: Directory unavailable or incomplete resolution + '500': + description: Redacted internal server error + + delete: + tags: [RBAC] + summary: Delete LDAP group role mapping + description: >- + Requires rbac:admin. Works during directory outages and atomically removes + only attributable grants, invalidates validation and records an audit event. + responses: + '204': + description: Deleted with attributable grants withdrawn + '400': + description: Invalid request or cursor + '401': + description: Authentication required + '403': + description: Requires rbac admin permission + '404': + description: LDAP disabled or mapping or role absent + '409': + description: Duplicate mapping or stale revision + '422': + description: Invalid group identity or diagnostic policy denial + '429': + description: Request rate or directory capacity exceeded + '503': + description: Directory unavailable or incomplete resolution + '500': + description: Redacted internal server error + + + /auth/ldap/test: + post: + tags: [RBAC] + summary: Diagnose configured LDAP read-only access + description: >- + Requires rbac:admin. Limited to 10 requests per minute per administrator. + Tests configured TLS and lookup; optional exact user checks immutable + identity and eligibility. Optional group subjects must be enabled mapped + groups and require username. No user bind, profile output, grants or tokens. + Failure reports retain completed stages and a safe failed-stage code. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/LdapDiagnosticInput' + responses: + '200': + description: All requested diagnostic stages passed + content: + application/json: + schema: + $ref: '#/components/schemas/LdapDiagnosticReport' + '400': + description: Invalid request or cursor + '401': + description: Authentication required + '403': + description: Requires rbac admin permission + '404': + description: LDAP disabled or mapping or role absent + '409': + description: Duplicate mapping or stale revision + '422': + description: Invalid group identity or diagnostic policy denial + '429': + description: Request rate or directory capacity exceeded + '503': + description: Directory unavailable or incomplete resolution + '500': + description: Redacted internal server error + + /health: get: summary: Health check @@ -2889,6 +3127,45 @@ paths: $ref: '#/components/schemas/Error' security: [] + /auth/ldap/login: + post: + summary: Authenticate explicitly with the configured LDAP directory + description: Available when LDAP is enabled. Preserves submitted credentials, applies provider/directory/login + and IP throttling, and never falls through to another provider. Requires a successful user bind, + complete eligibility validation and at least one explicit role before issuing tokens. UTF-8 byte + limits are 1024 for username and 4096 for password. No automatic role is assigned. + tags: [Auth] + security: [] + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [username, password] + properties: + username: { type: string, minLength: 1, maxLength: 1024 } + password: { type: string, format: password, minLength: 1, maxLength: 4096 } + responses: + '200': + description: Provider-bound token pair and current directory-owned profile + content: + application/json: + schema: { $ref: '#/components/schemas/AuthenticationResult' } + '400': + description: Invalid login payload + '401': + description: Invalid or ambiguous credentials, without account-existence details + '403': + description: Proven account has no explicit access grant or is suspended + '404': + description: LDAP authentication is not enabled + '429': + description: IP, provider-login or directory capacity limit reached + '503': + description: Directory validation unavailable or incomplete; no tokens issued + /auth/permissions: get: summary: Get the caller's effective permissions @@ -2971,6 +3248,18 @@ paths: responses: '200': description: Users retrieved successfully + content: + application/json: + schema: + type: object + properties: + users: + type: array + items: + type: object + properties: + authentication: + $ref: '#/components/schemas/UserAdministrationMetadata' '401': description: Unauthorized content: @@ -2992,6 +3281,17 @@ paths: responses: '200': description: User retrieved successfully + content: + application/json: + schema: + type: object + properties: + authentication: + $ref: '#/components/schemas/UserAdministrationMetadata' + roleSources: + type: array + items: + $ref: '#/components/schemas/UserRoleSource' '404': description: User not found content: @@ -3000,6 +3300,10 @@ paths: $ref: '#/components/schemas/Error' put: summary: Update user + description: > + Directory-owned profile and password writes return 403 with + DIRECTORY_ACCOUNT_READ_ONLY, including for administrators. + Suspension remains locally managed. tags: - RBAC parameters: @@ -3013,15 +3317,33 @@ paths: application/json: schema: type: object + additionalProperties: false properties: - username: + email: type: string + format: email + firstName: + type: string + minLength: 1 + maxLength: 100 + lastName: + type: string + minLength: 1 + maxLength: 100 + isActive: + type: boolean password: type: string format: password responses: '200': description: User updated successfully + '403': + description: Missing permissions or directory-owned profile/password write + content: + application/json: + schema: + $ref: '#/components/schemas/Error' '404': description: User not found content: @@ -3647,7 +3969,9 @@ paths: /auth/refresh: post: summary: Rotate token pair - description: Accepts only a refresh token; revocation and account status are checked. Store both returned + description: Accepts only a refresh token; revocation and account status are checked. LDAP forces fresh + directory eligibility and explicit role validation while retaining exact authentication context. + A temporary failure preserves the inbound token for retry and does not extend freshness. Store both returned tokens. tags: - Auth @@ -3662,6 +3986,12 @@ paths: description: Invalid body '401': description: Invalid or revoked refresh token + '403': + description: LDAP eligibility or explicit access was positively revoked + '429': + description: LDAP validation capacity limit reached + '503': + description: LDAP validation temporarily unavailable; the inbound refresh remains available for retry security: [] requestBody: required: true @@ -3678,7 +4008,8 @@ paths: /auth/providers: get: summary: Discover authentication methods - description: Public provider discovery. + description: Public provider discovery. LDAP remains advertised during outages. No connection, directory + identifier, search configuration or credentials are exposed. tags: - Auth responses: @@ -3693,6 +4024,14 @@ paths: type: boolean entraId: type: object + ldap: + type: object + required: [enabled, name, loginHelpUrl] + additionalProperties: false + properties: + enabled: { type: boolean, enum: [true] } + name: { type: string } + loginHelpUrl: { type: string } security: [] /auth/register: @@ -4299,6 +4638,87 @@ components: default: false schemas: + LdapDirectoryGroup: + type: object + required: [subject, dn, name] + properties: + subject: { type: string, format: uuid } + dn: { type: string } + name: { type: string } + LdapGroupPage: + type: object + required: [items, nextCursor] + properties: + items: + type: array + maxItems: 50 + items: + $ref: '#/components/schemas/LdapDirectoryGroup' + nextCursor: { type: string, nullable: true, pattern: '^[a-f0-9]{64}$' } + LdapGroupMapping: + type: object + required: [id, source, directoryId, groupSubject, groupDn, groupName, roleId, roleName, enabled, createdAt, updatedAt] + properties: + id: { type: string, format: uuid } + source: { type: string, enum: [ldap] } + directoryId: { type: string } + groupSubject: { type: string, format: uuid } + groupDn: { type: string } + groupName: { type: string } + roleId: { type: string } + roleName: { type: string } + enabled: { type: boolean } + createdAt: { type: string, format: date-time } + updatedAt: { type: string, format: date-time } + LdapMappingCreate: + type: object + additionalProperties: false + required: [groupSubject, roleId] + properties: + groupSubject: { type: string, format: uuid } + roleId: { type: string, minLength: 1, maxLength: 128 } + LdapMappingUpdate: + type: object + additionalProperties: false + minProperties: 1 + properties: + roleId: { type: string, minLength: 1, maxLength: 128 } + enabled: { type: boolean } + LdapDiagnosticInput: + type: object + additionalProperties: false + properties: + username: + type: string + minLength: 1 + maxLength: 1024 + description: Exact login name, maximum 1024 UTF-8 bytes + groupSubjects: + type: array + maxItems: 20 + description: Requires username and only enabled mapped immutable group subjects + items: { type: string, format: uuid } + LdapDiagnosticReport: + type: object + required: [authenticated, stages] + properties: + authenticated: { type: boolean, enum: [false] } + stages: + type: array + items: + type: object + required: [stage, status, durationMs] + properties: + stage: { type: string, enum: [tls, lookup, identity, eligibility, groups] } + status: { type: string, enum: [passed, failed] } + durationMs: { type: number, minimum: 0 } + code: + type: string + enum: [INVALID_CREDENTIALS, INELIGIBLE, IDENTITY_CHANGED, INVALID_IDENTITY, POLICY_UNREADABLE, INCOMPLETE_RESULT, LIMIT_EXCEEDED, BUSY, TIMEOUT, UNAVAILABLE] + groupSubjects: + type: array + items: { type: string, format: uuid } + Node: type: object properties: @@ -4836,6 +5256,32 @@ components: powerState: running osType: Linux + UserAdministrationMetadata: + type: object + required: [profileReadOnly, sources] + properties: + profileReadOnly: + type: boolean + sources: + type: array + items: + type: object + required: [provider, name] + properties: + provider: { type: string, enum: [local, ldap, entra-id] } + name: { type: string } + directoryId: { type: string } + loginName: { type: string } + + UserRoleSource: + type: object + required: [roleId, source] + properties: + roleId: { type: string } + source: { type: string, enum: [manual, ldap, entra-id] } + directoryId: { type: string } + groupName: { type: string } + AuthenticationResult: type: object properties: @@ -4848,6 +5294,15 @@ components: user: type: object description: User DTO, excludes password hash + properties: + email: + type: string + nullable: true + description: Contact email, not an identity key. May be shared by external accounts. + displayName: + type: string + nullable: true + description: Directory display name when available, separate from given name and surname. required: - token - refreshToken diff --git a/docs/permissions-rbac.md b/docs/permissions-rbac.md index 5c0efcde..ce6c22ea 100644 --- a/docs/permissions-rbac.md +++ b/docs/permissions-rbac.md @@ -301,3 +301,27 @@ The `mcp-service` user: - Is reused on subsequent restarts (idempotent provisioning) To grant additional permissions to MCP tools, assign more permissions to the `MCP Service` role via the Role Management page or API. + +## LDAP grants and administration + +LDAP groups map directly to roles in **Role Management** or a role detail dialog. +There is no full-directory import, local-group mirror or default LDAP role. +Enabled mapping grants combine with explicit manual roles. Removing one source preserves +other grants for that role. + +Every LDAP search, mapping and diagnostic API requires `rbac:admin`. Existing +administrator page guards remain in force. Delegated API administration alone does not +bypass them. Controls check loaded permissions and stay unavailable until grants load. + +User administration requires `users:read` and shows source, current directory login, +display name and profile ownership. LDAP profile/password writes are rejected server-side, +including for administrators. Suspension and explicit manual roles remain local. +User details distinguish manual/external grants and allow removal of manual assignments. + +Mapping mutations audit and invalidate affected validation state across workers, withdrawing +attributable grants transactionally. New grants require fresh membership proof. Stored +labels remain readable during outages. Diagnostics use configured endpoints and the lookup +account, never a user password. + +See [LDAP authentication](integrations/ldap.md) for setup, limits, status visibility, +outages, provider-bound sessions and upgrade reauthentication. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index df6a7c15..a906da77 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -245,6 +245,28 @@ color: false | "JWT malformed" | Token expired or tampered. Log out and log in again | | No login prompt | Check whether a valid session is already stored. REST authentication is mandatory; test an API call without Authorization to verify rejection. | +### Reset a local user's password (account recovery) + +Run on the host that owns the database, with the same environment as the server (`backend/.env`, `JWT_SECRET`, `DATABASE_PATH` or `DATABASE_URL`): + +```bash +# from a source checkout +npm run reset-password --workspace=backend -- --username admin + +# built install or Docker image +node dist/cli/reset-password.js --username admin +docker exec -it pabawi node dist/cli/reset-password.js --username admin +``` + +| Flag | Effect | +|---|---| +| `--username ` | Account to reset (default `admin`) | +| `--generate` | Generate a random password and print it once | +| `--password-stdin` | Read the password from stdin instead of the hidden prompt | +| `--activate` | Also reactivate a disabled account (off by default) | + +The password is never accepted as an argument. The command applies the normal password policy, clears lockouts and failed-login counters, revokes every issued token and refresh token for the account, and writes a `cli_password_reset` audit entry (no password included). Access to the shell and database is the trust boundary. + --- ## FAQ diff --git a/docs/upgrading.md b/docs/upgrading.md index d360b678..e1cbd317 100644 --- a/docs/upgrading.md +++ b/docs/upgrading.md @@ -124,9 +124,9 @@ For production, pin to tags. ```bash # 1. Pull the new image -docker pull example42/pabawi:latest +docker pull example42/pabawi:batteries # or a specific version: -# docker pull example42/pabawi:1.4.0 +# docker pull example42/pabawi:batteries-1.4.0 # 2. Stop and remove the old container docker stop pabawi @@ -142,7 +142,7 @@ docker run -d \ -v "$(pwd)/data:/opt/pabawi/data" \ -v "$(pwd)/bolt-project:/opt/pabawi/bolt-project:ro" \ --env-file .env \ - example42/pabawi:latest + example42/pabawi:batteries ``` Your data persists in the mounted volumes. The new container applies any diff --git a/e2e/ldap-ui/ldap.spec.ts b/e2e/ldap-ui/ldap.spec.ts new file mode 100644 index 00000000..d682e51c --- /dev/null +++ b/e2e/ldap-ui/ldap.spec.ts @@ -0,0 +1,80 @@ +import { test, expect, type Page } from '@playwright/test'; + +const localPassword = 'LocalTest123!'; // pragma: allowlist secret +const directoryPassword = 'x'; // pragma: allowlist secret + +async function localLogin(page: Page, username = 'browseradmin'): Promise { + await page.goto('/login'); + await page.getByLabel('Username', { exact: true }).fill(username); + await page.getByLabel('Password', { exact: true }).fill(localPassword); + await page.getByRole('button', { name: 'Sign in', exact: true }).click(); + await expect(page).toHaveURL('http://127.0.0.1:3186/'); +} + +test('LDAP uses short credentials, denies without fallback, and preserves an explicit provider choice', async ({ page }) => { + const logins: string[] = []; + page.on('request', request => { + if (request.method() === 'POST' && /auth\/(ldap\/)?login$/.test(request.url())) logins.push(request.url()); + }); + await page.goto('/login'); + await page.getByLabel('Sign in using').selectOption('ldap'); + await page.getByLabel('Username', { exact: true }).fill('missing'); + await page.getByLabel('Password', { exact: true }).fill(directoryPassword); + await page.getByRole('button', { name: 'Sign in', exact: true }).click(); + await expect(page.getByLabel('Password', { exact: true })).toHaveValue(''); + await expect(page.getByLabel('Sign in using')).toHaveValue('ldap'); + expect(logins).toEqual(['http://127.0.0.1:3186/api/auth/ldap/login']); + await page.getByLabel('Username', { exact: true }).fill('a'); + await page.getByLabel('Password', { exact: true }).fill(directoryPassword); + await page.getByRole('button', { name: 'Sign in', exact: true }).click(); + await expect(page).toHaveURL('http://127.0.0.1:3186/'); + expect(logins.every(url => url.endsWith('/ldap/login'))).toBe(true); +}); + +test('administrator manages mappings, sees failed diagnostic stages and reads nullable directory profiles', async ({ page }) => { + await localLogin(page); + await page.goto('/roles'); + const panel = page.getByRole('region', { name: 'LDAP administration' }); + await expect(panel.getByText('Operators to Viewer: Enabled')).toBeVisible(); + await panel.getByLabel('Search directory groups', { exact: true }).fill('empty'); + await panel.getByRole('button', { name: 'Search groups', exact: true }).click(); + await expect(panel.getByText('No directory groups found.')).toBeVisible(); + await panel.getByLabel('Search directory groups', { exact: true }).fill('op'); + await panel.getByRole('button', { name: 'Search groups', exact: true }).click(); + await panel.getByLabel('Directory group', { exact: true }).selectOption('10112233-4455-6677-8899-aabbccddeeff'); + await panel.getByLabel('Pabawi role', { exact: true }).selectOption('role-operator-001'); + await panel.getByRole('button', { name: 'Create mapping', exact: true }).click(); + await expect(panel.getByText('Operators to Operator: Enabled')).toBeVisible(); + await panel.getByLabel('Exact directory username (optional)').fill('outage'); + await panel.getByRole('button', { name: 'Run directory diagnostics', exact: true }).click(); + await expect(panel.getByText('tls: failed (2 ms), UNAVAILABLE')).toBeVisible(); + await panel.getByLabel('Exact directory username (optional)').fill('a'); + await panel.getByRole('checkbox', { name: 'Operators', exact: true }).check(); + await panel.getByRole('button', { name: 'Run directory diagnostics', exact: true }).click(); + await expect(panel.getByText('Matched selected groups: 1')).toBeVisible(); + await page.screenshot({ path: test.info().outputPath('mappings.png'), fullPage: true }); + + const operator = panel.getByRole('listitem').filter({ hasText: 'Operators to Operator: Enabled' }); + await operator.getByRole('button', { name: /Disable mapping/ }).click(); + await expect(panel.getByText('Operators to Operator: Disabled')).toBeVisible(); + const disabled = panel.getByRole('listitem').filter({ hasText: 'Operators to Operator: Disabled' }); + page.once('dialog', dialog => dialog.accept()); + await disabled.getByRole('button', { name: /Remove mapping/ }).click(); + await expect(panel.getByText('Operators to Operator: Disabled')).toHaveCount(0); + + await page.goto('/users'); + const row = page.getByRole('row').filter({ hasText: 'Directory A' }); + await expect(row.getByText('Not provided', { exact: true })).toBeVisible(); + await row.getByTitle('Edit user').click(); + await expect(page.getByRole('region', { name: 'Authentication source' })).toContainText('Corporate directory / browser-directory: a'); + await expect(page.getByText(/Directory profile fields are read-only/)).toBeVisible(); + await expect(page.getByLabel('Password', { exact: true })).toHaveCount(0); + await page.screenshot({ path: test.info().outputPath('profile.png'), fullPage: true }); +}); + +test('non-administrator cannot enter the role management page', async ({ page }) => { + await localLogin(page, 'browserviewer'); + await page.goto('/roles'); + await expect(page.getByRole('region', { name: 'LDAP administration' })).toHaveCount(0); + await expect(page.getByRole('heading', { name: 'Role Management', exact: true })).toHaveCount(0); +}); diff --git a/frontend/package.json b/frontend/package.json index 08bbbb28..9ed6ab6c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "1.5.0", + "version": "1.6.0", "description": "Pabawi frontend web interface", "type": "module", "scripts": { diff --git a/frontend/src/components/GroupDetailDialog.svelte b/frontend/src/components/GroupDetailDialog.svelte index 24ba5595..77dd18bb 100644 --- a/frontend/src/components/GroupDetailDialog.svelte +++ b/frontend/src/components/GroupDetailDialog.svelte @@ -17,7 +17,7 @@ interface UserDTO { id: string; username: string; - email: string; + email: string | null; firstName: string; lastName: string; } @@ -341,7 +341,7 @@ {member.username}

- {member.firstName} {member.lastName} • {member.email} + {member.firstName} {member.lastName} • {member.email ?? 'Not provided'}

+
{ event.preventDefault(); void run(() => search()); }} class="space-y-2"> + + + +
+ {#if searched && groups.length === 0}

No directory groups found.

{/if} + {#if groups.length} +
{ event.preventDefault(); void run(create); }} class="space-y-2"> + + + {#if !roleId} + + + {/if} + +
+ {/if} + {#if cursor}{/if} + +

Stored group mappings

+ {#if visibleMappings.length === 0}

No directory mappings for this role selection.

{/if} +
    + {#each visibleMappings as mapping (mapping.id)} +
  • +

    {mapping.groupName} to {mapping.roleName}: {mapping.enabled ? 'Enabled' : 'Disabled'}

    +

    LDAP / {mapping.directoryId} / {mapping.groupSubject}
    {mapping.groupDn}

    + {#if !roleId} + + {/if} +
    + + +
    +
  • + {/each} +
+ +

Restricted directory diagnostics

+

Uses the configured lookup account. This does not verify a user password or sign the user in.

+
{ event.preventDefault(); void run(diagnose); }} class="space-y-2"> + + +
+ Check membership in enabled mapped groups (up to 20) + {#each diagnosticGroups as mapping (mapping.groupSubject)} + + {/each} +
+ +
+ {#if busy}

Directory operation in progress...

{/if} + {#if report} +
+

Lookup diagnostic result. No password authentication performed.

+
    + {#each report.stages as stage} +
  • {stage.stage}: {stage.status} ({stage.durationMs} ms){stage.code ? ', ' + stage.code : ''}
  • + {/each} +
+ {#if report.groupSubjects} +

Matched selected groups: {report.groupSubjects.length}

+
    {#each report.groupSubjects as subject}
  • {diagnosticGroups.find(m => m.groupSubject === subject)?.groupName ?? subject}
  • {/each}
+ {/if} +
+ {/if} + +{/if} diff --git a/frontend/src/components/LdapAdministration.test.ts b/frontend/src/components/LdapAdministration.test.ts new file mode 100644 index 00000000..457dec1b --- /dev/null +++ b/frontend/src/components/LdapAdministration.test.ts @@ -0,0 +1,127 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/svelte'; +import LdapAdministration from './LdapAdministration.svelte'; +import { authManager } from '../lib/auth.svelte'; +import * as ldap from '../lib/ldapApi'; + +const guard = vi.hoisted(() => ({ admin: true })); +vi.mock('../lib/auth.svelte', () => ({ authManager: { get isAdmin() { return guard.admin; }, hasPermission: vi.fn(() => true) } })); +vi.mock('../lib/authProviders.svelte', () => ({ authProviders: { ldap: { name: 'Corporate directory' } } })); +vi.mock('../lib/api', () => ({ get: vi.fn().mockResolvedValue({ + roles: [{ id: 'viewer', name: 'Viewer' }, { id: 'operator', name: 'Operator' }], pagination: { totalPages: 1 }, +}) })); +vi.mock('../lib/ldapApi', () => ({ + listLdapMappings: vi.fn(), searchLdapGroups: vi.fn(), createLdapMapping: vi.fn(), + updateLdapMapping: vi.fn(), removeLdapMapping: vi.fn(), diagnoseLdap: vi.fn(), +})); + +const subject = '00112233-4455-6677-8899-aabbccddeeff'; +const mapping: ldap.LdapMapping = { id: 'mapping', directoryId: 'corporate', groupSubject: subject, + groupName: 'Operators', groupDn: 'cn=operators,dc=example,dc=test', + roleId: 'viewer', roleName: 'Viewer', enabled: true, source: 'ldap' }; + +beforeEach(() => { + vi.clearAllMocks(); + guard.admin = true; + vi.mocked(authManager.hasPermission).mockReturnValue(true); + vi.mocked(ldap.listLdapMappings).mockResolvedValue({ items: [mapping] }); + vi.mocked(ldap.searchLdapGroups).mockResolvedValue({ items: [], nextCursor: null }); +}); + +async function ready(): Promise { + await screen.findByText('Operators to Viewer: Enabled'); + await waitFor(() => expect((screen.getByRole('button', { name: 'Search groups' }) as HTMLButtonElement).disabled).toBe(true)); + await waitFor(() => expect((screen.getByRole('button', { name: 'Reload mappings' }) as HTMLButtonElement).disabled).toBe(false)); +} + +describe('LDAP role mapping administration', () => { + it.each(['page', 'permission'])('does no directory work when the %s guard denies access', async gate => { + if (gate === 'page') guard.admin = false; + else vi.mocked(authManager.hasPermission).mockReturnValue(false); + render(LdapAdministration); + expect(screen.queryByRole('region', { name: 'LDAP administration' })).toBeNull(); + expect(ldap.listLdapMappings).not.toHaveBeenCalled(); + }); + + it('renders empty search results without discarding stored mappings', async () => { + render(LdapAdministration); + await ready(); + await fireEvent.input(screen.getByLabelText('Search directory groups'), { target: { value: 'absent' } }); + await fireEvent.click(screen.getByRole('button', { name: 'Search groups' })); + expect(await screen.findByText('No directory groups found.')).toBeTruthy(); + expect(screen.getByText('Operators to Viewer: Enabled')).toBeTruthy(); + }); + + it('retains the searched filter with its cursor and creates a mapping using only immutable IDs', async () => { + vi.mocked(ldap.searchLdapGroups).mockResolvedValueOnce({ + items: [{ subject, dn: mapping.groupDn, name: mapping.groupName }], nextCursor: 'opaque', + }).mockResolvedValueOnce({ items: [], nextCursor: null }); + render(LdapAdministration); + await ready(); + await fireEvent.input(screen.getByLabelText('Search directory groups'), { target: { value: 'op' } }); + await fireEvent.click(screen.getByRole('button', { name: 'Search groups' })); + await screen.findByLabelText('Directory group'); + await fireEvent.input(screen.getByLabelText('Search directory groups'), { target: { value: 'edited' } }); + await fireEvent.click(screen.getByRole('button', { name: 'More groups' })); + expect(ldap.searchLdapGroups).toHaveBeenLastCalledWith('op', 'opaque'); + await waitFor(() => expect((screen.getByLabelText('Directory group') as HTMLSelectElement).disabled).toBe(false)); + await fireEvent.change(screen.getByLabelText('Directory group'), { target: { value: subject } }); + await fireEvent.change(screen.getByLabelText('Pabawi role'), { target: { value: 'operator' } }); + await fireEvent.click(screen.getByRole('button', { name: 'Create mapping' })); + expect(ldap.createLdapMapping).toHaveBeenCalledExactlyOnceWith(subject, 'operator'); + }); + + it('supports role replacement and outage-safe disablement, preserving labels on failure', async () => { + render(LdapAdministration); + await ready(); + await fireEvent.change(screen.getByLabelText('Mapped role'), { target: { value: 'operator' } }); + expect(ldap.updateLdapMapping).toHaveBeenLastCalledWith('mapping', { roleId: 'operator' }); + await waitFor(() => expect((screen.getByRole('button', { name: /Disable mapping/ }) as HTMLButtonElement).disabled).toBe(false)); + vi.mocked(ldap.updateLdapMapping).mockRejectedValueOnce(new Error('LDAP directory operation failed')); + await fireEvent.click(screen.getByRole('button', { name: /Disable mapping/ })); + expect(ldap.updateLdapMapping).toHaveBeenLastCalledWith('mapping', { enabled: false }); + expect((await screen.findByRole('alert')).textContent).toContain('LDAP directory operation failed'); + expect(screen.getByText('Operators to Viewer: Enabled')).toBeTruthy(); + }); + + it('requires confirmation for removal and only removes the selected mapping', async () => { + vi.spyOn(window, 'confirm').mockReturnValue(false); + render(LdapAdministration); + await ready(); + await fireEvent.click(screen.getByRole('button', { name: /Remove mapping/ })); + expect(ldap.removeLdapMapping).not.toHaveBeenCalled(); + vi.mocked(window.confirm).mockReturnValue(true); + await fireEvent.click(screen.getByRole('button', { name: /Remove mapping/ })); + expect(ldap.removeLdapMapping).toHaveBeenCalledExactlyOnceWith('mapping'); + }); + + it('shows failed stages and sends exact lookup input with selected mapped group subjects', async () => { + vi.mocked(ldap.diagnoseLdap).mockResolvedValue({ authenticated: false, stages: [ + { stage: 'tls', status: 'passed', durationMs: 2 }, + { stage: 'eligibility', status: 'failed', durationMs: 3, code: 'INELIGIBLE' }, + ] }); + render(LdapAdministration); + await ready(); + await fireEvent.input(screen.getByLabelText('Exact directory username (optional)'), { target: { value: ' a ' } }); + await fireEvent.click(screen.getByLabelText('Operators')); + await fireEvent.click(screen.getByRole('button', { name: 'Run directory diagnostics' })); + expect(ldap.diagnoseLdap).toHaveBeenCalledExactlyOnceWith({ username: ' a ', groupSubjects: [subject] }); + expect(await screen.findByText('eligibility: failed (3 ms), INELIGIBLE')).toBeTruthy(); + expect(screen.getByText('Lookup diagnostic result. No password authentication performed.')).toBeTruthy(); + }); + + it('uses the current role when opened from its detail dialog', async () => { + vi.mocked(ldap.searchLdapGroups).mockResolvedValue({ items: [ + { subject, dn: mapping.groupDn, name: mapping.groupName }, + ], nextCursor: null }); + render(LdapAdministration, { roleId: 'viewer' }); + await ready(); + await fireEvent.input(screen.getByLabelText('Search directory groups'), { target: { value: 'op' } }); + await fireEvent.click(screen.getByRole('button', { name: 'Search groups' })); + await screen.findByLabelText('Directory group'); + expect(screen.queryByLabelText('Pabawi role')).toBeNull(); + await fireEvent.change(screen.getByLabelText('Directory group'), { target: { value: subject } }); + await fireEvent.click(screen.getByRole('button', { name: 'Create mapping' })); + expect(ldap.createLdapMapping).toHaveBeenCalledWith(subject, 'viewer'); + }); +}); diff --git a/frontend/src/components/Navigation.svelte b/frontend/src/components/Navigation.svelte index 3e401d39..33dbade9 100644 --- a/frontend/src/components/Navigation.svelte +++ b/frontend/src/components/Navigation.svelte @@ -148,7 +148,7 @@

Pabawi

- v1.5.0 + v1.6.0
diff --git a/frontend/src/components/RoleDetailDialog.svelte b/frontend/src/components/RoleDetailDialog.svelte index 5f8e3267..c21d2ce0 100644 --- a/frontend/src/components/RoleDetailDialog.svelte +++ b/frontend/src/components/RoleDetailDialog.svelte @@ -11,6 +11,8 @@ type PermissionResource, type PermissionAction, } from '../lib/permissions'; + import LdapAdministration from './LdapAdministration.svelte'; + import { authProviders } from '../lib/authProviders.svelte'; import LoadingSpinner from './LoadingSpinner.svelte'; interface Props { @@ -374,6 +376,10 @@ {/if}
+ {#if authManager.isAdmin && canManageEntitlements && authProviders.ldap?.enabled && roleId} + + {/if} +
- {#if entraIdAuth.isEntraIdEnabled} - + {#if authProviders.entraId?.enabled} +
@@ -167,8 +184,8 @@
- {#if entraIdAuth.isEntraIdEnabled} - + {#if authProviders.entraId?.enabled} +
@@ -182,7 +199,7 @@ {/if} - {#if entraIdAuth.providerDiscoveryError} + {#if authProviders.error}
@@ -192,7 +209,7 @@

- SSO availability could not be determined. You can still sign in with your local credentials. + Authentication provider availability could not be determined. You can still sign in with your local credentials.

@@ -202,8 +219,19 @@ {/if} - {#if !entraIdAuth.isExchangingCode} + {#if !entraIdAuth.isExchangingCode && (authProviders.local || authProviders.ldap?.enabled)}
+
+ + + {#if provider === 'ldap' && authProviders.ldapHelpUrl} + Directory sign-in help + {/if} +
@@ -217,7 +245,7 @@ autocomplete="username" required bind:value={username} - disabled={isSubmitting} + disabled={isSubmitting || authProviders.isDiscovering} class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm bg-white dark:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed" placeholder="Enter your username" /> @@ -240,7 +268,7 @@ autocomplete="current-password" required bind:value={password} - disabled={isSubmitting} + disabled={isSubmitting || authProviders.isDiscovering} class="appearance-none relative block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 placeholder-gray-500 dark:placeholder-gray-400 text-gray-900 dark:text-white rounded-md focus:outline-none focus:ring-primary-500 focus:border-primary-500 focus:z-10 sm:text-sm bg-white dark:bg-gray-800 disabled:opacity-50 disabled:cursor-not-allowed" placeholder="Enter your password" /> @@ -274,7 +302,7 @@
- {#if !checkingConfig && selfRegistrationAllowed} + {#if provider === 'local' && !checkingConfig && selfRegistrationAllowed}

Don't have an account? diff --git a/frontend/src/pages/LoginPage.test.ts b/frontend/src/pages/LoginPage.test.ts index d976f047..f964d588 100644 --- a/frontend/src/pages/LoginPage.test.ts +++ b/frontend/src/pages/LoginPage.test.ts @@ -1,15 +1,11 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen } from '@testing-library/svelte'; +import { render, screen, fireEvent, waitFor } from '@testing-library/svelte'; vi.mock('../lib/entraIdAuth.svelte', () => ({ entraIdAuth: { - isEntraIdEnabled: false, - entraIdProviderName: 'Microsoft Entra ID', - providerDiscoveryError: false, isExchangingCode: false, exchangeError: null as string | null, isDiscovering: false, - discoverProviders: vi.fn().mockResolvedValue(undefined), handleSsoCallback: vi.fn().mockResolvedValue(false), clearExchangeError: vi.fn(), }, @@ -42,6 +38,14 @@ vi.mock('../lib/api', () => ({ getErrorGuidance: vi.fn(() => ({ guidance: undefined })), })); +vi.mock('../lib/authProviders.svelte', () => ({ + authProviders: { local: true, entraId: undefined as { enabled: boolean; name: string } | undefined, + ldap: undefined as { enabled: boolean; name: string; loginHelpUrl: string } | undefined, + ldapHelpUrl: null as string | null, error: false, isDiscovering: false, discover: vi.fn().mockResolvedValue(undefined) }, +})); + +import { authProviders } from '../lib/authProviders.svelte'; +import { authManager } from '../lib/auth.svelte'; import LoginPage from './LoginPage.svelte'; import { entraIdAuth } from '../lib/entraIdAuth.svelte'; @@ -49,13 +53,14 @@ describe('LoginPage', () => { beforeEach(() => { vi.clearAllMocks(); // Reset mock state - entraIdAuth.isEntraIdEnabled = false; - entraIdAuth.entraIdProviderName = 'Microsoft Entra ID'; - entraIdAuth.providerDiscoveryError = false; + authProviders.local = true; + authProviders.entraId = undefined; + authProviders.ldap = undefined; + authProviders.error = false; entraIdAuth.isExchangingCode = false; entraIdAuth.exchangeError = null; vi.mocked(entraIdAuth.handleSsoCallback).mockResolvedValue(false); - vi.mocked(entraIdAuth.discoverProviders).mockResolvedValue(undefined); + vi.mocked(authProviders.discover).mockResolvedValue(undefined); }); afterEach(() => { @@ -64,7 +69,7 @@ describe('LoginPage', () => { describe('SSO button conditional rendering', () => { it('shows SSO button when entraIdAuth.isEntraIdEnabled is true', () => { - entraIdAuth.isEntraIdEnabled = true; + authProviders.entraId = { enabled: true, name: 'Microsoft Entra ID' }; render(LoginPage); @@ -72,7 +77,7 @@ describe('LoginPage', () => { }); it('hides SSO button when entraIdAuth.isEntraIdEnabled is false', () => { - entraIdAuth.isEntraIdEnabled = false; + authProviders.entraId = undefined; render(LoginPage); @@ -82,19 +87,19 @@ describe('LoginPage', () => { describe('Provider discovery error', () => { it('shows warning when providerDiscoveryError is true', () => { - entraIdAuth.providerDiscoveryError = true; + authProviders.error = true; render(LoginPage); - expect(screen.getByText(/SSO availability could not be determined/)).toBeTruthy(); + expect(screen.getByText(/Authentication provider availability could not be determined/)).toBeTruthy(); }); it('does not show warning when providerDiscoveryError is false', () => { - entraIdAuth.providerDiscoveryError = false; + authProviders.error = false; render(LoginPage); - expect(screen.queryByText(/SSO availability could not be determined/)).toBeNull(); + expect(screen.queryByText(/Authentication provider availability could not be determined/)).toBeNull(); }); }); @@ -128,7 +133,7 @@ describe('LoginPage', () => { it('shows SSO button below error when entraId is enabled', () => { entraIdAuth.exchangeError = 'Something went wrong'; - entraIdAuth.isEntraIdEnabled = true; + authProviders.entraId = { enabled: true, name: 'Microsoft Entra ID' }; render(LoginPage); @@ -139,7 +144,7 @@ describe('LoginPage', () => { describe('Local login form always present', () => { it('shows local login form when SSO is disabled', () => { - entraIdAuth.isEntraIdEnabled = false; + authProviders.entraId = undefined; render(LoginPage); @@ -149,7 +154,7 @@ describe('LoginPage', () => { }); it('shows both SSO button and local login form when SSO is enabled', () => { - entraIdAuth.isEntraIdEnabled = true; + authProviders.entraId = { enabled: true, name: 'Microsoft Entra ID' }; render(LoginPage); @@ -159,3 +164,51 @@ describe('LoginPage', () => { }); }); }); + +describe('explicit password provider selection', () => { + beforeEach(() => { + vi.clearAllMocks(); + authProviders.local = true; + authProviders.ldap = { enabled: true, name: 'Corporate directory', loginHelpUrl: '' }; + authProviders.error = false; + entraIdAuth.isExchangingCode = false; + entraIdAuth.exchangeError = null; + vi.mocked(entraIdAuth.handleSsoCallback).mockResolvedValue(false); + vi.mocked(authProviders.discover).mockResolvedValue(undefined); + }); + + async function submit(username: string, password: string): Promise { + await fireEvent.input(screen.getByLabelText('Username'), { target: { value: username } }); + await fireEvent.input(screen.getByLabelText('Password'), { target: { value: password } }); + await fireEvent.submit(screen.getByRole('button', { name: /^sign in$/i }).closest('form')!); + } + + it('submits short LDAP credentials unchanged without falling through after denial', async () => { + render(LoginPage); + await waitFor(() => expect(authProviders.discover).toHaveBeenCalled()); + await fireEvent.change(screen.getByLabelText('Sign in using'), { target: { value: 'ldap' } }); + await submit(' a ', ' x '); + expect(authManager.login).toHaveBeenCalledExactlyOnceWith({ username: ' a ', password: ' x ' }, 'ldap'); + expect((screen.getByLabelText('Sign in using') as HTMLSelectElement).value).toBe('ldap'); + expect((screen.getByLabelText('Password') as HTMLInputElement).value).toBe(''); + }); + + it('keeps local validation and clears credentials when provider changes', async () => { + render(LoginPage); + await submit('a', 'x'); + expect(authManager.login).not.toHaveBeenCalled(); + expect(screen.getByText('Password must be at least 8 characters')).toBeTruthy(); + await fireEvent.change(screen.getByLabelText('Sign in using'), { target: { value: 'ldap' } }); + expect((screen.getByLabelText('Password') as HTMLInputElement).value).toBe(''); + expect(screen.queryByText('Password must be at least 8 characters')).toBeNull(); + }); + + it('rejects oversized UTF-8 directory inputs before submission', async () => { + render(LoginPage); + await fireEvent.change(screen.getByLabelText('Sign in using'), { target: { value: 'ldap' } }); + await submit('é'.repeat(513), 'é'.repeat(2049)); + expect(authManager.login).not.toHaveBeenCalled(); + expect(screen.getByText('Username must be at most 1024 bytes')).toBeTruthy(); + expect(screen.getByText('Password must be at most 4096 bytes')).toBeTruthy(); + }); +}); diff --git a/frontend/src/pages/RoleManagementPage.svelte b/frontend/src/pages/RoleManagementPage.svelte index 290b0d06..657e56e2 100644 --- a/frontend/src/pages/RoleManagementPage.svelte +++ b/frontend/src/pages/RoleManagementPage.svelte @@ -4,6 +4,8 @@ import { showError, showSuccess } from '../lib/toast.svelte'; import { authManager } from '../lib/auth.svelte'; import { router } from '../lib/router.svelte'; + import LdapAdministration from '../components/LdapAdministration.svelte'; + import { authProviders } from '../lib/authProviders.svelte'; import LoadingSpinner from '../components/LoadingSpinner.svelte'; import RoleDetailDialog from '../components/RoleDetailDialog.svelte'; import CreateRoleDialog from '../components/CreateRoleDialog.svelte'; @@ -60,6 +62,7 @@ return; } + void authProviders.discover(); // Load initial data loadRoles(); }); @@ -167,6 +170,10 @@

+ {#if authManager.isAdmin && authManager.hasPermission('rbac', 'admin') && authProviders.ldap?.enabled && !isRoleDialogOpen} + + {/if} +
diff --git a/frontend/src/pages/SetupPage.svelte b/frontend/src/pages/SetupPage.svelte index 90f3213e..e94cd61b 100644 --- a/frontend/src/pages/SetupPage.svelte +++ b/frontend/src/pages/SetupPage.svelte @@ -170,7 +170,7 @@ -

Enter the token configured by the installation operator.

+

Value of PABAWI_BOOTSTRAP_TOKEN, set by the installation operator in the backend environment.

diff --git a/frontend/src/pages/UserManagementPage.svelte b/frontend/src/pages/UserManagementPage.svelte index 7f30df0d..078e6476 100644 --- a/frontend/src/pages/UserManagementPage.svelte +++ b/frontend/src/pages/UserManagementPage.svelte @@ -1,4 +1,5 @@