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 @@
[](https://hub.docker.com/r/example42/pabawi)
[](https://github.com/example42/pabawi/stargazers)
-## Sponsors
+Sponsored by
-
-| Pabawi's main sponsor is AMS-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
-
-
+## 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