Private
Public Access
1
0

Compare commits

...

25 Commits

Author SHA1 Message Date
f9ca15f7d9 fix(packaging): make .deb install and upgrade actually work end-to-end (#70)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 4s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m22s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
- Generate internal CA + CA-signed web TLS cert in postinst (port 443 was
  falling back to plain HTTP because no cert files existed)
- Repair stale sqlx migration checksums for upgrades from <= 1.1.7
- Restore health check as advisory only (never fails the install)
- Use runuser instead of sudo (sudo is not guaranteed on minimal images)
- Replace predictable /tmp password file with mktemp under /run
- Frontend assets root-owned read-only (security)
- Drop Pre-Depends: postgresql-16 (misuse); drop argon2 dep (unused)
- Add openssl, curl, cron, util-linux as proper dependencies
2026-06-10 09:23:03 -05:00
583db2666a fix: remove postinst migrations, let app handle schema via sqlx (#68)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m20s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 22:39:45 -05:00
f55cfbc7a1 chore: bump version to 1.1.11 (#67)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m22s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 16:06:40 -05:00
0222b1677d fix: run migrations as patch_manager, remove broken reassign_ownership (#66)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 10s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m32s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
Root cause: postinst ran sqlx migrate as postgres (superuser), creating ALL
database objects owned by postgres. When pm-web connects as patch_manager, it
cannot ALTER TABLE during migrations because it does not own them. The
reassign_ownership() function never worked because REASSIGN OWNED BY postgres
TO patch_manager fails for superuser-owned objects.

Fix: Create the database owned by patch_manager (already done) and run all
migrations as patch_manager via PGPASSWORD auth. When all objects are owned by
patch_manager from the start, pm-web can ALTER them during upgrades.

Changes:
- Add psql_run_as_pm() helper that authenticates as patch_manager via PGPASSWORD
- Replace all psql_run_db calls in apply_migrations() with psql_run_as_pm
- Remove reassign_ownership() function entirely (it never worked)
- Remove reassign_ownership call from main()
- Add ALTER DEFAULT PRIVILEGES FOR ROLE postgres in setup_database() as safety
  net for any future migration that might run as postgres
- Upgrade GRANT USAGE/CREATE to GRANT ALL PRIVILEGES on schema public
- Keep pgcrypto extension creation as postgres (requires superuser)
- Renumber sections after removing reassign_ownership

Proven on live LPM system: service active, port 443 listening, all tables
owned by patch_manager.
2026-06-09 15:56:36 -05:00
dda2fd3b0e chore: bump version to 1.1.10 (#65)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m52s
CI Pipeline / Security Audit (push) Successful in 4s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 14:49:54 -05:00
3b3e129663 fix: reassign DB object ownership to patch_manager after migrations (#64)
The postinst script runs migrations as the postgres superuser, which
means all created tables, enum types, and sequences are owned by
postgres. When pm-web connects as patch_manager and tries to ALTER
tables during upgrades, it fails with 'must be owner of table groups'.

Add reassign_ownership() function that runs after apply_migrations()
and before systemctl start. This function:
- REASSIGN OWNED BY postgres TO patch_manager (tables, types, sequences)
- ALTER SCHEMA public OWNER TO patch_manager
- GRANT ALL PRIVILEGES on database, schema, tables, sequences, functions
- ALTER DEFAULT PRIVILEGES for future objects in public schema

Renumbered sections 6-10 to 6-12 to accommodate the new function.
2026-06-09 14:11:20 -05:00
8acff754e8 chore: bump version to 1.1.9 (#63)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m22s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 13:15:05 -05:00
4cac290502 fix: enable services, fix config parsing, make migrations idempotent (#62) 2026-06-09 13:04:11 -05:00
ec41091721 ci: update actions for Node.js 24 compatibility (#61)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 7s
CI Pipeline / Clippy Lints (push) Successful in 50s
CI Pipeline / Rust Unit Tests (push) Failing after 1m28s
CI Pipeline / Security Audit (push) Successful in 4s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 12:49:37 -05:00
26f87ebc20 chore: bump version to 1.1.8 (#60)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m25s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 12:02:50 -05:00
a1a8eab41a fix(postinst): surgical upgrade/fresh-install handling (#59)
- write_config(): Replace CHANGEME placeholder on upgrade instead of
  skipping entirely; preserve existing real passwords unchanged
- setup_database(): When DB user already exists, recover password from
  existing config and sync to PostgreSQL, or generate a fresh password;
  fixes crash-loop when config password diverges from PostgreSQL
- generate_jwt_keys(): Regenerate missing verify.pem from existing
  signing.pem instead of silently skipping
- Password extraction uses @localhost anchor to correctly handle
  passwords containing @ characters
2026-06-09 11:47:22 -05:00
b2ea6b1f7a chore: bump version to 1.1.7 (#58)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 2s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m29s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 09:27:34 -05:00
592ff6a7ee fix(postinst): thorough audit - fix argon2 salt and verify all password generation logic (#57) 2026-06-09 09:10:31 -05:00
0c0f952f7f chore: bump version to 1.1.6 (#56)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 53s
CI Pipeline / Rust Unit Tests (push) Failing after 1m27s
CI Pipeline / Security Audit (push) Successful in 4s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-09 08:21:20 -05:00
2a18276884 fix(postinst): correct argon2 -m parameter from raw KiB to log2 value (#55)
* chore: bump version to 1.1.5

* fix(postinst): correct argon2 -m parameter from raw KiB to log2 value

* trigger CI
2026-06-09 08:10:00 -05:00
2bdbc8af5a fix(ci): remove arm64 from Docker platforms and add timeout (#53)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 6s
CI Pipeline / Clippy Lints (push) Successful in 53s
CI Pipeline / Rust Unit Tests (push) Failing after 1m58s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-08 20:15:13 -05:00
87bd5d2162 fix: remove duplicate version display from sidebar toolbar (#52)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 2s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m53s
CI Pipeline / Security Audit (push) Successful in 4s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-08 17:54:25 -05:00
836d409e3b feat: add version display to sidebar and bump to v1.1.4 (#51)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 7s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m40s
CI Pipeline / Security Audit (push) Successful in 4s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-08 17:44:20 -05:00
e17b740415 fix(docker): complete Dockerfile audit - migrations, deps, openssl (#49)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 5s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m46s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
Three issues fixed in the multi-stage Docker build:

1. CRITICAL: Add COPY migrations/ to rust-builder stage
   - sqlx::migrate!(../../migrations) is a compile-time proc macro
   - Without migrations/ present, cargo build fails with 'no such file or directory'
   - Previously migrations/ was only copied in runtime stage (too late)

2. Copy individual crate Cargo.toml files for dependency caching
   - The dummy-build caching step only copied workspace Cargo.toml/Cargo.lock
   - Without crate-level manifests, cargo couldn't resolve the workspace
   - This meant the cache layer was ineffective (rebuilt everything on code changes)

3. Add openssl package to runtime stage
   - entrypoint.sh uses openssl rand, openssl genpkey, openssl pkey
   - Only libssl3t64 (shared library) was installed, not the CLI tool
   - Runtime would fail on first-run key generation

All stages verified: Ubuntu 24.04   Rust via rustup (1.85+) 
2026-06-07 22:59:32 -05:00
0d151d36b9 chore: bump version to 1.1.2 (#48)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m22s
CI Pipeline / Security Audit (push) Successful in 6s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-07 22:08:55 -05:00
4fbcf3d35a fix(docker): use Ubuntu 24.04 throughout all Dockerfile stages (#47)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 6s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m21s
CI Pipeline / Security Audit (push) Successful in 6s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 16s
CI Pipeline / Build .deb & Release (push) Has been skipped
- Stage 1 (Rust): Replace rust:1.85-bookworm with ubuntu:24.04 + rustup stable
- Stage 2 (Frontend): Replace node:20-bookworm-slim with ubuntu:24.04 + NodeSource Node.js 20
- Stage 3 (Runtime): Already ubuntu:24.04 with libssl3t64 (verified correct)
- docker-compose: Change postgres:16-bookworm to postgres:16 (standard image)

This aligns Docker builds with the project's target OS (Ubuntu 24.04) and
matches the CI environment which runs on ubuntu-latest (24.04).
2026-06-07 21:19:07 -05:00
6d4ec8c9ac chore: bump version to 1.1.1 (#45)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m58s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-07 20:14:45 -05:00
bf91b3c6d2 fix(docker): use ubuntu:24.04 runtime instead of debian:bookworm-slim (#44)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 6s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m54s
CI Pipeline / Security Audit (push) Successful in 7s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 17s
CI Pipeline / Build .deb & Release (push) Has been skipped
* fix(docker): add PostgreSQL APT repo for postgresql-client-16

Debian Bookworm default repos only ship PostgreSQL 15. The Docker
runtime stage needs postgresql-client-16 for the entrypoint script,
so add the official PGDG APT repository.

- Add PGDG GPG key and sources.list entry for bookworm-pgdg
- Install ca-certificates and curl first (needed for repo setup)
- Purge gnupg2 after use to keep image lean
- Verify argon2 package name is correct for Bookworm (it is)

* fix(docker): use ubuntu:24.04 runtime instead of debian:bookworm-slim

The project targets Ubuntu 24.04, not Debian Bookworm. Ubuntu 24.04
includes PostgreSQL 16 in default repos, eliminating the need for the
PGDG APT repo workaround. Also fixes libssl3 → libssl3t64 package name
for the time64 transition in Ubuntu 24.04.
2026-06-07 18:55:45 -05:00
2d3be0955b chore: bump version to 1.1.0 (#43)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 3s
CI Pipeline / Clippy Lints (push) Successful in 52s
CI Pipeline / Rust Unit Tests (push) Failing after 1m25s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 14s
CI Pipeline / Build .deb & Release (push) Has been skipped
2026-06-07 17:01:01 -05:00
a5343760e1 feat: Automated install, Docker deployment, and CI Docker job (#42)
Some checks failed
CI Pipeline / Rust Format Check (push) Successful in 4s
CI Pipeline / Clippy Lints (push) Successful in 51s
CI Pipeline / Rust Unit Tests (push) Failing after 1m20s
CI Pipeline / Security Audit (push) Successful in 5s
CI Pipeline / Frontend Lint & Type Check (push) Successful in 15s
CI Pipeline / Build .deb & Release (push) Has been skipped
- debian/control: add Pre-Depends and Depends on postgresql-16, argon2
- debian/postinst: idempotent automation for PostgreSQL setup,
  DB/user creation, migration tracking, admin password generation,
  config write, and service enable/start
- Dockerfile: multi-stage build (Rust + frontend + slim runtime)
- docker/entrypoint.sh: first-run DB wait, migrations, admin password
- docker-compose.yml: split db/app architecture with healthcheck
- .env.example: template for DB_PASSWORD and TAG
- .dockerignore: exclude build artifacts from Docker context
- .github/workflows/ci.yml: add Docker job for multi-arch
  (amd64/arm64) GHCR push on tag releases with layer caching
- .gitignore: add .env entry
2026-06-07 16:20:08 -05:00
20 changed files with 1144 additions and 182 deletions

40
.dockerignore Normal file
View File

@ -0,0 +1,40 @@
# Build artifacts
target/
*.deb
package-build/
# Frontend build output (rebuilt in Docker)
frontend/dist/
frontend/node_modules/
# Git
.git/
.gitignore
# IDE
.vscode/
.idea/
# Docker
Dockerfile
docker-compose.yml
.dockerignore
# Environment
.env
.env.*
# Documentation
docs/
# Agent Zero project data
.a0proj/
# Python
venv/
__pycache__/
# Misc
*.md
!README.md
LICENSE

8
.env.example Normal file
View File

@ -0,0 +1,8 @@
# Linux Patch Manager — Docker Environment Variables
# Copy this file to .env and edit the values before running docker compose up.
# Required: PostgreSQL password for the patch_manager user
DB_PASSWORD=changeme-to-a-strong-password
# Optional: Docker image tag (defaults to 'latest' if not set)
TAG=latest

View File

@ -9,16 +9,18 @@ on:
env:
CARGO_TERM_COLOR: always
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true
permissions:
contents: write
packages: write
jobs:
rust-format:
name: Rust Format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
@ -29,7 +31,7 @@ jobs:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
@ -42,7 +44,7 @@ jobs:
name: Rust Tests
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Install system dependencies
@ -53,7 +55,7 @@ jobs:
name: Security Audit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
- run: cargo install cargo-audit && cargo audit
@ -61,11 +63,11 @@ jobs:
name: Secret scanning
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Gitleaks
uses: gitleaks/gitleaks-action@v2
uses: gitleaks/gitleaks-action@v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@ -73,9 +75,9 @@ jobs:
name: Frontend Lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: '20'
- name: Install & Lint
@ -86,7 +88,7 @@ jobs:
needs: [rust-format, clippy, rust-test, security-audit, frontend-lint]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Free disk space
@ -102,7 +104,7 @@ jobs:
- name: Strip binaries
run: strip target/release/pm-web target/release/pm-worker
- name: Setup Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v5
with:
node-version: '20'
- name: Build frontend
@ -124,7 +126,51 @@ jobs:
echo "EOF" >> $GITHUB_OUTPUT
- name: Upload to GitHub Release
if: startsWith(github.ref, 'refs/tags/v')
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
body: ${{ steps.release_notes.outputs.notes }}
files: linux-patch-manager_*.deb
docker:
name: Docker Build & Push
needs: [rust-format, clippy, rust-test, security-audit, frontend-lint]
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- uses: actions/checkout@v6
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Log in to GitHub Container Registry
uses: docker/login-action@v4
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@v6
with:
images: ghcr.io/draco-lunaris/linux-patch-manager
tags: |
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=semver,pattern={{major}}
type=sha
- name: Build and push Docker image
uses: docker/build-push-action@v7
with:
context: .
platforms: linux/amd64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max

3
.gitignore vendored
View File

@ -28,6 +28,9 @@ frontend/dist
*.deb
package-build/
# Docker environment
.env
# Private key material - NEVER commit
*.key
*.key.pem

View File

@ -12,7 +12,7 @@ members = [
]
[workspace.package]
version = "1.0.0"
version = "1.1.13"
edition = "2021"
authors = ["Echo <echo@moon-dragon.us>"]
license = "MIT"

141
Dockerfile Normal file
View File

@ -0,0 +1,141 @@
# =============================================================================
# Linux Patch Manager — Multi-stage Docker Build
# =============================================================================
# Build: docker build -t linux-patch-manager .
# Run: docker compose up
# =============================================================================
# ---------------------------------------------------------------------------
# Stage 1: Rust build (Ubuntu 24.04 + rustup)
# ---------------------------------------------------------------------------
FROM ubuntu:24.04 AS rust-builder
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
build-essential \
curl \
pkg-config \
libssl-dev \
libfontconfig1-dev \
&& rm -rf /var/lib/apt/lists/*
# Install Rust via rustup (stable channel, provides 1.85+)
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --default-toolchain stable
ENV PATH="/root/.cargo/bin:${PATH}"
WORKDIR /usr/src/app
# Cache dependencies by building a dummy project first
COPY Cargo.toml Cargo.lock ./
COPY crates/pm-web/Cargo.toml crates/pm-web/Cargo.toml
COPY crates/pm-worker/Cargo.toml crates/pm-worker/Cargo.toml
COPY crates/pm-core/Cargo.toml crates/pm-core/Cargo.toml
COPY crates/pm-agent-client/Cargo.toml crates/pm-agent-client/Cargo.toml
COPY crates/pm-auth/Cargo.toml crates/pm-auth/Cargo.toml
COPY crates/pm-ca/Cargo.toml crates/pm-ca/Cargo.toml
COPY crates/pm-reports/Cargo.toml crates/pm-reports/Cargo.toml
COPY crates/migrate-secrets/Cargo.toml crates/migrate-secrets/Cargo.toml
RUN mkdir -p crates/pm-web/src crates/pm-worker/src crates/pm-core/src \
crates/pm-agent-client/src crates/pm-auth/src crates/pm-ca/src \
crates/pm-reports/src crates/migrate-secrets/src
RUN echo 'fn main(){}' > crates/pm-web/src/main.rs \
&& echo 'fn main(){}' > crates/pm-worker/src/main.rs \
&& echo '' > crates/pm-core/src/lib.rs \
&& echo '' > crates/pm-agent-client/src/lib.rs \
&& echo '' > crates/pm-auth/src/lib.rs \
&& echo '' > crates/pm-ca/src/lib.rs \
&& echo '' > crates/pm-reports/src/lib.rs \
&& echo 'fn main(){}' > crates/migrate-secrets/src/main.rs
RUN cargo build --release 2>/dev/null || true
# Now build the real project
COPY crates/ crates/
COPY migrations/ migrations/
RUN cargo build --release
# Verify binaries exist
RUN ls -la target/release/pm-web target/release/pm-worker
# Strip debug symbols
RUN strip target/release/pm-web target/release/pm-worker
# ---------------------------------------------------------------------------
# Stage 2: Frontend build (Ubuntu 24.04 + Node.js 20)
# ---------------------------------------------------------------------------
FROM ubuntu:24.04 AS frontend-builder
ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && apt-get install -y \
curl \
ca-certificates \
&& rm -rf /var/lib/apt/lists/*
# Install Node.js 20 via NodeSource
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y nodejs \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /usr/src/app/frontend
COPY frontend/package.json frontend/package-lock.json ./
RUN npm ci --production=false
COPY frontend/ ./
RUN npm run build
# ---------------------------------------------------------------------------
# Stage 3: Runtime
# ---------------------------------------------------------------------------
FROM ubuntu:24.04 AS runtime
RUN apt-get update && apt-get install -y \
ca-certificates \
libssl3t64 \
libfontconfig1 \
openssl \
postgresql-client-16 \
argon2 \
curl \
&& rm -rf /var/lib/apt/lists/*
# Create service user
RUN useradd --system --no-create-home --shell /usr/sbin/nologin \
--comment "Linux Patch Manager service account" patch-manager
# Create directories
RUN mkdir -p /etc/patch-manager/ca /etc/patch-manager/certs \
/etc/patch-manager/jwt /etc/patch-manager/tls \
/var/log/patch-manager /opt/patch-manager \
/usr/share/patch-manager/frontend \
/usr/share/patch-manager/migrations
# Copy binaries
COPY --from=rust-builder /usr/src/app/target/release/pm-web /usr/local/bin/pm-web
COPY --from=rust-builder /usr/src/app/target/release/pm-worker /usr/local/bin/pm-worker
# Copy frontend
COPY --from=frontend-builder /usr/src/app/frontend/dist/ /usr/share/patch-manager/frontend/
# Copy migrations
COPY migrations/ /usr/share/patch-manager/migrations/
# Copy entrypoint
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod 755 /usr/local/bin/entrypoint.sh
# Copy config template
COPY config/config.example.toml /usr/share/patch-manager/config.example.toml
# Set ownership
RUN chown -R patch-manager:patch-manager \
/etc/patch-manager /var/log/patch-manager \
/opt/patch-manager /usr/share/patch-manager
# Expose HTTPS port
EXPOSE 443
# Volume for persistent data
VOLUME ["/etc/patch-manager", "/var/log/patch-manager", "/opt/patch-manager"]
ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]

View File

@ -49,7 +49,8 @@ health_check_poll_interval_secs = 300
# Maximum concurrent mTLS agent calls (Tokio Semaphore)
max_concurrent_agent_calls = 64
# Worker heartbeat write interval (seconds)
# Worker heartbeat write interval (seconds). Default: 300 = 5 minutes
heartbeat_interval_secs = 300
# WS relay HTTP polling fallback interval (seconds). When WebSocket connection to
# an agent fails, the relay falls back to polling the agent's HTTP API at this

View File

@ -101,7 +101,8 @@ pub struct WorkerConfig {
pub health_check_poll_interval_secs: u64,
/// Maximum concurrent agent calls
pub max_concurrent_agent_calls: usize,
/// Worker heartbeat interval in seconds
/// Worker heartbeat interval in seconds (default: 300 = 5 min)
#[serde(default = "default_heartbeat_interval")]
pub heartbeat_interval_secs: u64,
/// WS relay HTTP polling fallback interval in seconds (default: 10)
pub ws_relay_poll_interval_secs: u64,
@ -255,6 +256,10 @@ fn default_health_check_poll_interval() -> u64 {
300
}
fn default_heartbeat_interval() -> u64 {
300
}
fn default_sso_callback_url() -> String {
"http://localhost:5173/auth/sso/callback".to_string()
}

78
debian/changelog vendored
View File

@ -1,3 +1,81 @@
linux-patch-manager (1.1.13-1) unstable; urgency=low
* Release v1.1.13
-- git-echo <git-echo@moon-dragon.us> Wed, 10 Jun 2026 09:16:34 -0500
linux-patch-manager (1.1.12-1) unstable; urgency=low
* Release v1.1.12
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 22:14:03 -0500
linux-patch-manager (1.1.11-1) unstable; urgency=low
* Release v1.1.11
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 15:57:10 -0500
linux-patch-manager (1.1.10-1) unstable; urgency=low
* Release v1.1.10
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 14:11:31 -0500
linux-patch-manager (1.1.9-1) unstable; urgency=low
* Release v1.1.9
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 13:05:59 -0500
linux-patch-manager (1.1.8-1) unstable; urgency=low
* Release v1.1.8
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 11:47:58 -0500
linux-patch-manager (1.1.7-1) unstable; urgency=low
* Release v1.1.7
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 09:11:11 -0500
linux-patch-manager (1.1.6-1) unstable; urgency=low
* Release v1.1.6
-- git-echo <git-echo@moon-dragon.us> Tue, 09 Jun 2026 08:10:52 -0500
linux-patch-manager (1.1.5-1) unstable; urgency=low
* Release v1.1.5
-- git-echo <git-echo@moon-dragon.us> Mon, 08 Jun 2026 20:15:50 -0500
linux-patch-manager (1.1.4-1) unstable; urgency=low
* Release v1.1.4
-- git-echo <git-echo@moon-dragon.us> Mon, 08 Jun 2026 17:30:35 -0500
linux-patch-manager (1.1.2-1) unstable; urgency=low
* Release v1.1.2
-- git-echo <git-echo@moon-dragon.us> Sun, 07 Jun 2026 21:19:18 -0500
linux-patch-manager (1.1.1-1) unstable; urgency=low
* Release v1.1.1
-- git-echo <git-echo@moon-dragon.us> Sun, 07 Jun 2026 18:55:59 -0500
linux-patch-manager (1.1.0-1) unstable; urgency=low
* Release v1.1.0
-- git-echo <git-echo@moon-dragon.us> Sun, 07 Jun 2026 16:47:03 -0500
linux-patch-manager (1.0.0-1) unstable; urgency=low
* Release v1.0.0

4
debian/control vendored
View File

@ -1,9 +1,9 @@
Package: linux-patch-manager
Version: 1.0.0-1
Version: 1.1.13-1
Architecture: amd64
Maintainer: Moon Dragon <echo@moon-dragon.us>
Installed-Size: 45000
Depends: postgresql-16, libssl3, libc6 (>= 2.39), libfontconfig1
Depends: postgresql-16, openssl, curl, cron | cron-daemon, util-linux, libssl3, libc6 (>= 2.39), libfontconfig1
Recommends: postgresql-client-16, fonts-dejavu-core
Suggests: gpg
Section: admin

473
debian/postinst vendored Normal file → Executable file
View File

@ -4,91 +4,402 @@ set -e
# =============================================================================
# Linux Patch Manager — Post-install script
# =============================================================================
# Fully automated: apt install ./linux-patch-manager_X.X.X-1_amd64.deb
# results in a running HTTPS service. The service generates and prints the
# initial admin password to its journal on first startup.
#
# All steps are idempotent (safe to re-run on upgrade).
# Migrations are handled by the application via sqlx on startup.
# This script: system user, dirs, DB/role, config, JWT keys, CA + web TLS
# cert, sqlx checksum repair (for upgrades from <= 1.1.7), services.
# =============================================================================
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'
info() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
DB_NAME="patch_manager"
DB_USER="patch_manager"
CONFIG_DIR="/etc/patch-manager"
SERVICE_USER="patch-manager"
# Secure temp file for passing the DB password between functions.
# (Was a predictable, world-readable /tmp/.pm-db-password-new.)
PM_TMP="$(umask 077 && mktemp /run/pm-postinst.XXXXXX)"
cleanup() { rm -f "${PM_TMP}"; }
trap cleanup EXIT
# ---------------------------------------------------------------------------
# PostgreSQL helpers — runuser instead of sudo (sudo is not guaranteed
# to exist and is discouraged in maintainer scripts).
# ---------------------------------------------------------------------------
psql_run() {
runuser -u postgres -- psql -v ON_ERROR_STOP=1 "$@" 2>/dev/null
}
psql_run_db() {
runuser -u postgres -- psql -v ON_ERROR_STOP=1 -d "${DB_NAME}" "$@" 2>/dev/null
}
# ---------------------------------------------------------------------------
# 1. Create service user (idempotent)
# ---------------------------------------------------------------------------
create_service_user() {
if ! id "${SERVICE_USER}" &>/dev/null; then
useradd --system --no-create-home --shell /usr/sbin/nologin \
--comment "Linux Patch Manager service account" "${SERVICE_USER}"
info "Service user '${SERVICE_USER}' created."
else
info "Service user '${SERVICE_USER}' already exists."
fi
}
# ---------------------------------------------------------------------------
# 2. Create required directories (idempotent)
# ---------------------------------------------------------------------------
create_directories() {
mkdir -p "${CONFIG_DIR}/ca" "${CONFIG_DIR}/certs" \
"${CONFIG_DIR}/jwt" "${CONFIG_DIR}/tls" \
/var/log/patch-manager /opt/patch-manager \
/var/backups/patch-manager
chown -R "${SERVICE_USER}:${SERVICE_USER}" \
"${CONFIG_DIR}" /var/log/patch-manager /opt/patch-manager
# Frontend assets stay root-owned and read-only: the service must not be
# able to rewrite the JavaScript it serves (persistence vector if pm-web
# is ever compromised). pm-web only reads these files.
chown -R root:root /usr/share/patch-manager/frontend
chmod -R a+rX /usr/share/patch-manager/frontend
chmod 750 "${CONFIG_DIR}/ca" "${CONFIG_DIR}/jwt"
chmod 700 /var/backups/patch-manager
}
# ---------------------------------------------------------------------------
# 3. Wait for PostgreSQL to be ready (non-fatal failure is impossible here:
# postgresql-16 is a hard dependency and its packaging starts the cluster,
# but give it time on slow first boots).
# ---------------------------------------------------------------------------
wait_for_postgresql() {
info "Waiting for PostgreSQL to be ready..."
local i
for ((i = 1; i <= 30; i++)); do
if pg_isready -q 2>/dev/null; then
info "PostgreSQL is ready."
return 0
fi
warn "PostgreSQL not ready yet (attempt ${i}/30), waiting 2s..."
sleep 2
done
error "PostgreSQL did not become ready after 60 seconds."
return 1
}
# ---------------------------------------------------------------------------
# 4. Create PostgreSQL user, database, and grants (idempotent)
# ---------------------------------------------------------------------------
setup_database() {
info "Setting up PostgreSQL database and user..."
local db_password
db_password=$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 32)
local role_exists
role_exists=$(psql_run -t -A -c "SELECT 1 FROM pg_roles WHERE rolname='${DB_USER}'" 2>/dev/null || echo "")
if [[ "${role_exists}" != "1" ]]; then
psql_run -c "CREATE ROLE ${DB_USER} LOGIN PASSWORD '${db_password}';"
info "PostgreSQL user '${DB_USER}' created."
printf '%s' "${db_password}" > "${PM_TMP}"
else
info "PostgreSQL user '${DB_USER}' already exists."
local config_file="${CONFIG_DIR}/config.toml"
local existing_pw=""
if [[ -f "${config_file}" ]]; then
existing_pw=$(sed -n 's|^url = "postgres://[^:]*:\(.*\)@localhost.*"|\1|p' "${config_file}" | head -1)
fi
if [[ -n "${existing_pw}" && "${existing_pw}" != "CHANGEME" ]]; then
psql_run -c "ALTER ROLE ${DB_USER} WITH PASSWORD '${existing_pw}';" 2>/dev/null || true
printf '%s' "${existing_pw}" > "${PM_TMP}"
info "Synced DB password from existing config to PostgreSQL."
else
psql_run -c "ALTER ROLE ${DB_USER} WITH PASSWORD '${db_password}';" 2>/dev/null || true
printf '%s' "${db_password}" > "${PM_TMP}"
info "Generated new DB password for existing user."
fi
fi
local db_exists
db_exists=$(psql_run -t -A -c "SELECT 1 FROM pg_database WHERE datname='${DB_NAME}'" 2>/dev/null || echo "")
if [[ "${db_exists}" != "1" ]]; then
psql_run -c "CREATE DATABASE ${DB_NAME} OWNER ${DB_USER};"
info "Database '${DB_NAME}' created."
else
info "Database '${DB_NAME}' already exists, skipping creation."
fi
psql_run_db -c "CREATE EXTENSION IF NOT EXISTS pgcrypto;" 2>/dev/null || true
psql_run_db -c "GRANT ALL PRIVILEGES ON SCHEMA public TO ${DB_USER};" 2>/dev/null || true
psql_run_db -c "GRANT ALL PRIVILEGES ON DATABASE ${DB_NAME} TO ${DB_USER};" 2>/dev/null || true
psql_run_db -c "ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON TABLES TO ${DB_USER};" 2>/dev/null || true
psql_run_db -c "ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON SEQUENCES TO ${DB_USER};" 2>/dev/null || true
psql_run_db -c "ALTER DEFAULT PRIVILEGES FOR ROLE postgres IN SCHEMA public GRANT ALL ON FUNCTIONS TO ${DB_USER};" 2>/dev/null || true
}
# ---------------------------------------------------------------------------
# 5. Repair sqlx migration checksums (upgrade from <= 1.1.7 only).
#
# Commit 4cac290 (v1.1.8) rewrote migrations 001/003/007/011/016 in place.
# sqlx::migrate! validates the SHA-384 checksum recorded in _sqlx_migrations
# against the embedded file on every startup, so any database migrated
# before 1.1.8 fails with "migration N was previously applied but has been
# modified" and pm-web crash-loops.
#
# The schema produced by old and new versions of these files is identical
# (the rewrite only added IF-NOT-EXISTS guards), so it is safe to update the
# recorded checksum to match the current embedded content. We only touch
# rows whose checksum matches the known OLD value — fresh installs and
# already-repaired databases are untouched.
#
# NEVER edit an applied migration again; append a new one instead.
# ---------------------------------------------------------------------------
repair_migration_checksums() {
# Skip if the migrations table doesn't exist yet (fresh install).
local has_table
has_table=$(psql_run_db -t -A -c "SELECT to_regclass('public._sqlx_migrations') IS NOT NULL;" 2>/dev/null || echo "f")
[[ "${has_table}" == "t" ]] || { info "No _sqlx_migrations table (fresh install) — checksum repair not needed."; return 0; }
info "Checking for stale sqlx migration checksums (pre-1.1.8 databases)..."
# version | old sha384 | new sha384
local repairs=(
"1|3e7492a3fdedf177d0467b495717b1b3f75894cabbd57a8aa0a0fa2189bacb8832ce69f400356c5f717cc3cd87c47685|2828d99226ba5017e754a8a72bce4f7f6d5535172817c2ba90d8ea9b93ff488787ec840cf43cc0eca7e1f526c8a1c0ef"
"3|097ed9107821f2de4dd3f18b1c1b25aa3110ca4134fe8c37b81049d064357266a8bae05e84edf163bb77a88335943640|e7b6d63f244764184f127234e5b7735c9ea9ee810bd465b06bc9c74370358b56061cec137b7afee91c5417211561164c"
"7|f3218a5b94ae9e009655e66cd4808a7abebdfae81675bccfbb079567df192f95cd62eab3b6c4d60b06e8a7dcbb1d9297|95c087779e952333094e6d9e058aaa18dc8a898b480152ba7a6d780ccfd3c562525834ea49f19999b1266b0acb9b68e9"
"11|5bb3dabf7caf0a7c31998e74b03b312d1867a948643084b9253acabe0388bc00831d2a157379eacae971298fa9bc481e|f07ac98ae905b9a9730ec302aafbcce3d56eacf80a8fb0904a9cfd0e7c36fdc38bb21129054d6f0765131ce6fa1cdc2e"
"16|e5450925e570cbd522cf5edd6990f5e8e010466c494bc39484fcf72651037440083a104eea0d217d65c5625b91bfb514|11d77a7097fe3a212786c55cf5c0b64c44a792ce18ace665aec4336efee1544f41568c0ba4605b9daedbf4ac12e91e6f"
)
local entry version old new updated
for entry in "${repairs[@]}"; do
IFS='|' read -r version old new <<< "${entry}"
updated=$(psql_run_db -q -t -A -c \
"UPDATE _sqlx_migrations SET checksum = '\\x${new}'::bytea \
WHERE version = ${version} AND checksum = '\\x${old}'::bytea \
RETURNING version;" 2>/dev/null || echo "")
if [[ -n "${updated}" ]]; then
info "Repaired checksum for migration ${version}."
fi
done
}
# ---------------------------------------------------------------------------
# 6. Write config.toml with DB URL
# ---------------------------------------------------------------------------
write_config() {
local config_file="${CONFIG_DIR}/config.toml"
local db_password=""
[[ -s "${PM_TMP}" ]] && db_password=$(cat "${PM_TMP}")
if [[ -f "${config_file}" ]]; then
if grep -q 'CHANGEME' "${config_file}"; then
if [[ -z "${db_password}" ]]; then
db_password=$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 32)
psql_run -c "ALTER ROLE ${DB_USER} WITH PASSWORD '${db_password}';" 2>/dev/null || true
fi
info "Replacing CHANGEME placeholder in existing config with real DB password."
sed -i "s|postgres://patch_manager:CHANGEME@localhost/patch_manager|postgres://${DB_USER}:${db_password}@localhost/${DB_NAME}|" "${config_file}"
else
info "Config file ${config_file} already exists with a real password, leaving it unchanged."
return 0
fi
else
if [[ -z "${db_password}" ]]; then
db_password=$(openssl rand -base64 48 | tr -dc 'A-Za-z0-9' | head -c 32)
psql_run -c "ALTER ROLE ${DB_USER} WITH PASSWORD '${db_password}';" 2>/dev/null || true
fi
info "Writing configuration file..."
cp /usr/share/patch-manager/config.example.toml "${config_file}"
sed -i "s|postgres://patch_manager:CHANGEME@localhost/patch_manager|postgres://${DB_USER}:${db_password}@localhost/${DB_NAME}|" "${config_file}"
fi
chown "${SERVICE_USER}:${SERVICE_USER}" "${config_file}"
chmod 640 "${config_file}"
info "Configuration written to ${config_file}"
}
# ---------------------------------------------------------------------------
# 7. Generate JWT keys (idempotent)
# ---------------------------------------------------------------------------
generate_jwt_keys() {
if [[ ! -f "${CONFIG_DIR}/jwt/signing.pem" ]]; then
info "Generating Ed25519 JWT signing key..."
openssl genpkey -algorithm ed25519 -out "${CONFIG_DIR}/jwt/signing.pem" 2>/dev/null
openssl pkey -in "${CONFIG_DIR}/jwt/signing.pem" -pubout -out "${CONFIG_DIR}/jwt/verify.pem" 2>/dev/null
chown "${SERVICE_USER}:${SERVICE_USER}" "${CONFIG_DIR}/jwt/signing.pem" "${CONFIG_DIR}/jwt/verify.pem"
chmod 600 "${CONFIG_DIR}/jwt/signing.pem"
chmod 644 "${CONFIG_DIR}/jwt/verify.pem"
info "JWT keys generated."
elif [[ ! -f "${CONFIG_DIR}/jwt/verify.pem" ]]; then
info "Regenerating missing JWT verification key from existing signing key..."
openssl pkey -in "${CONFIG_DIR}/jwt/signing.pem" -pubout -out "${CONFIG_DIR}/jwt/verify.pem" 2>/dev/null
chown "${SERVICE_USER}:${SERVICE_USER}" "${CONFIG_DIR}/jwt/verify.pem"
chmod 644 "${CONFIG_DIR}/jwt/verify.pem"
info "JWT verification key regenerated."
else
info "JWT keys already exist, skipping."
fi
}
# ---------------------------------------------------------------------------
# 8. Generate internal CA and CA-signed web TLS certificate (idempotent).
#
# This was previously only done by scripts/setup.sh, which the package does
# not ship — so .deb installs had no /etc/patch-manager/tls/web.{crt,key},
# pm-web fell back to PLAIN HTTP on port 443, and the old HTTPS-only
# health check could never pass. Generating these here makes the package
# self-contained and HTTPS-by-default.
# ---------------------------------------------------------------------------
generate_tls_certs() {
local ca_key="${CONFIG_DIR}/ca/ca.key"
local ca_cert="${CONFIG_DIR}/ca/ca.crt"
local tls_cert="${CONFIG_DIR}/tls/web.crt"
local tls_key="${CONFIG_DIR}/tls/web.key"
local tls_csr="${CONFIG_DIR}/tls/web.csr"
if [[ ! -f "${ca_cert}" ]]; then
info "Generating internal Certificate Authority (ECDSA P-256, 10-year validity)..."
openssl ecparam -genkey -name prime256v1 -noout -out "${ca_key}"
openssl req -new -x509 -key "${ca_key}" -out "${ca_cert}" \
-days 3650 \
-subj "/CN=Patch Manager Root CA/O=Patch Manager" \
-addext "basicConstraints=critical,CA:true" \
-addext "keyUsage=critical,keyCertSign,cRLSign"
chown "${SERVICE_USER}:${SERVICE_USER}" "${ca_key}" "${ca_cert}"
chmod 600 "${ca_key}"
chmod 644 "${ca_cert}"
info "Internal CA generated."
else
info "Internal CA already exists, skipping."
fi
if [[ ! -f "${tls_cert}" ]]; then
info "Generating CA-signed web server certificate (valid 365 days)..."
local fqdn short host_ip san
fqdn=$(hostname -f 2>/dev/null || echo "localhost")
short=$(hostname -s 2>/dev/null || echo "localhost")
host_ip=$(ip -4 route get 1.1.1.1 2>/dev/null | awk '{print $7; exit}' || true)
san="DNS:${fqdn},DNS:${short},DNS:localhost,IP:127.0.0.1,IP:::1"
[[ -n "${host_ip}" ]] && san="${san},IP:${host_ip}"
openssl ecparam -genkey -name prime256v1 -noout -out "${tls_key}"
openssl req -new -key "${tls_key}" -out "${tls_csr}" \
-subj "/CN=${fqdn}/O=Patch Manager" \
-addext "subjectAltName=${san}"
openssl x509 -req -in "${tls_csr}" -CA "${ca_cert}" -CAkey "${ca_key}" \
-CAcreateserial -days 365 -out "${tls_cert}" \
-extfile <(printf "subjectAltName=%s\nextendedKeyUsage=serverAuth\n" "${san}")
rm -f "${tls_csr}"
chown "${SERVICE_USER}:${SERVICE_USER}" "${tls_cert}" "${tls_key}"
chmod 644 "${tls_cert}"
chmod 600 "${tls_key}"
info "CA-signed web server certificate generated for ${fqdn}."
else
info "TLS certificate already exists, skipping."
fi
}
# ---------------------------------------------------------------------------
# 9. Enable and start services
# ---------------------------------------------------------------------------
enable_and_start_services() {
systemctl daemon-reload
systemctl enable patch-manager.target 2>/dev/null || true
systemctl enable patch-manager-web.service patch-manager-worker.service 2>/dev/null || true
if systemctl is-active --quiet patch-manager.target 2>/dev/null; then
info "Restarting patch-manager services (upgrade)..."
systemctl restart patch-manager.target 2>/dev/null || true
else
info "Starting patch-manager services..."
systemctl start patch-manager.target 2>/dev/null || true
fi
}
# ---------------------------------------------------------------------------
# 10. Verify the service came up — ADVISORY ONLY, never fails the install.
# A failed probe prints diagnostics instead of leaving dpkg half-configured.
# ---------------------------------------------------------------------------
report_service_status() {
info "Waiting up to 30s for pm-web to come up (migrations run on startup)..."
local i
for ((i = 1; i <= 30; i++)); do
if curl -skf https://localhost:443/ >/dev/null 2>&1 || \
curl -skf https://localhost:8443/ >/dev/null 2>&1 || \
curl -sf http://localhost:443/ >/dev/null 2>&1 || \
curl -sf http://localhost:8443/ >/dev/null 2>&1; then
echo ""
echo -e "${CYAN}=================================================================${NC}"
echo -e "${GREEN} Linux Patch Manager is up.${NC}"
echo ""
echo -e " Web UI: ${GREEN}https://$(hostname -f 2>/dev/null || echo localhost)/${NC}"
echo -e " Username: ${GREEN}admin${NC}"
echo -e " Password: generated on first startup — retrieve it with:"
echo -e " ${YELLOW}journalctl -u patch-manager-web | grep -A2 'INITIAL ADMIN PASSWORD' | tail -3${NC}"
echo ""
echo -e " You will be forced to change it on first login."
echo -e " The internal CA cert (for trusting the web UI) is at:"
echo -e " ${CONFIG_DIR}/ca/ca.crt"
echo -e "${CYAN}=================================================================${NC}"
echo ""
return 0
fi
sleep 1
done
warn "pm-web did not respond within 30s. The install itself succeeded;"
warn "the service may still be starting, or it may have failed. Check:"
warn " systemctl status patch-manager-web.service"
warn " journalctl -u patch-manager-web -n 50"
return 0
}
# ---------------------------------------------------------------------------
# 11. Install backup cron (idempotent)
# ---------------------------------------------------------------------------
install_backup_cron() {
if ! crontab -l 2>/dev/null | grep -qF "backup.sh"; then
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/backup.sh >> /var/log/patch-manager/backup.log 2>&1") | crontab -
info "Nightly backup cron installed."
fi
}
# =============================================================================
# Main
# =============================================================================
case "$1" in
configure)
# Create service user if not exists
if ! id patch-manager &>/dev/null; then
useradd --system --no-create-home --shell /usr/sbin/nologin \
--comment "Linux Patch Manager service account" patch-manager
fi
create_service_user
create_directories
wait_for_postgresql
setup_database
repair_migration_checksums
write_config
generate_jwt_keys
generate_tls_certs
enable_and_start_services
report_service_status
install_backup_cron
# Create required directories
mkdir -p /etc/patch-manager/ca /etc/patch-manager/certs \
/etc/patch-manager/jwt /etc/patch-manager/tls \
/var/log/patch-manager /opt/patch-manager \
/var/backups/patch-manager
chown -R patch-manager:patch-manager \
/etc/patch-manager /var/log/patch-manager \
/opt/patch-manager /usr/share/patch-manager/frontend
chmod 750 /etc/patch-manager/ca /etc/patch-manager/jwt
chmod 700 /var/backups/patch-manager
# Generate JWT signing key if not present
if [[ ! -f /etc/patch-manager/jwt/signing.pem ]]; then
openssl genpkey -algorithm ed25519 -out /etc/patch-manager/jwt/signing.pem 2>/dev/null
openssl pkey -in /etc/patch-manager/jwt/signing.pem -pubout -out /etc/patch-manager/jwt/verify.pem 2>/dev/null
chown patch-manager:patch-manager /etc/patch-manager/jwt/signing.pem /etc/patch-manager/jwt/verify.pem
chmod 600 /etc/patch-manager/jwt/signing.pem
chmod 644 /etc/patch-manager/jwt/verify.pem
fi
# Write default config if not present
if [[ ! -f /etc/patch-manager/config.toml ]]; then
cp /usr/share/patch-manager/config.example.toml /etc/patch-manager/config.toml
chown patch-manager:patch-manager /etc/patch-manager/config.toml
chmod 640 /etc/patch-manager/config.toml
fi
# Install backup cron if not present
if ! crontab -l 2>/dev/null | grep -qF "backup.sh"; then
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/backup.sh >> /var/log/patch-manager/backup.log 2>&1") | crontab -
fi
# Reload systemd
systemctl daemon-reload
# Restart services if this is an upgrade (not a fresh install)
if systemctl is-active --quiet patch-manager-web 2>/dev/null; then
systemctl restart patch-manager-web || true
fi
if systemctl is-active --quiet patch-manager-worker 2>/dev/null; then
systemctl restart patch-manager-worker || true
fi
# Run pending database migrations
MIGRATION_DIR="/usr/share/patch-manager/migrations"
if [[ -d "$MIGRATION_DIR" ]]; then
echo "Applying database migrations..."
for sql_file in $(ls "$MIGRATION_DIR"/*.sql 2>/dev/null | sort); do
echo " Applying: $(basename "$sql_file")"
done
echo "Note: Migrations must be applied manually: sudo -u patch_manager psql -d patch_manager -f <migration_file>"
fi
echo ""
echo "Linux Patch Manager installed successfully!"
echo "==========================================="
echo ""
echo "Next steps:"
echo " 1. Install and configure PostgreSQL:"
echo " apt install postgresql-16"
echo " 2. Create the database:"
echo " sudo -u postgres createdb -O patch_manager patch_manager"
echo " 3. Edit /etc/patch-manager/config.toml with your database URL"
echo " 4. Enable and start services:"
echo " systemctl enable --now patch-manager.target"
echo " 5. Access the web UI at https://localhost"
echo " Default admin credentials are set via the seed migration."
echo ""
echo "IMPORTANT: Change the default admin password immediately after first login!"
echo ""
echo "If this is an upgrade, services have been restarted automatically."
echo "Apply any new database migrations:"
echo " sudo -u patch_manager psql -d patch_manager -f /usr/share/patch-manager/migrations/<NNN_migration>.sql"
echo ""
info "Linux Patch Manager installation complete."
;;
abort-upgrade|abort-remove|abort-deconfigure)

58
docker-compose.yml Normal file
View File

@ -0,0 +1,58 @@
# =============================================================================
# Linux Patch Manager — Docker Compose Deployment
# =============================================================================
# Usage:
# cp .env.example .env # Edit DB_PASSWORD
# docker compose up -d
# =============================================================================
services:
db:
image: postgres:16
restart: unless-stopped
environment:
POSTGRES_USER: patch_manager
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: patch_manager
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U patch_manager -d patch_manager"]
interval: 5s
timeout: 5s
retries: 10
start_period: 10s
networks:
- patch-manager-net
app:
image: ghcr.io/draco-lunaris/linux-patch-manager:${TAG:-latest}
restart: unless-stopped
depends_on:
db:
condition: service_healthy
ports:
- "443:443"
environment:
DATABASE_URL: postgres://patch_manager:${DB_PASSWORD}@db:5432/patch_manager
PATCH_MANAGER_CONFIG: /etc/patch-manager/config.toml
volumes:
- pm-config:/etc/patch-manager
- pm-logs:/var/log/patch-manager
- pm-data:/opt/patch-manager
networks:
- patch-manager-net
volumes:
pgdata:
driver: local
pm-config:
driver: local
pm-logs:
driver: local
pm-data:
driver: local
networks:
patch-manager-net:
driver: bridge

232
docker/entrypoint.sh Executable file
View File

@ -0,0 +1,232 @@
#!/bin/bash
set -e
# =============================================================================
# Linux Patch Manager — Docker Entrypoint
# =============================================================================
# Handles first-run: wait for DB, run migrations, generate admin password,
# start pm-web and pm-worker services.
# =============================================================================
MIGRATION_DIR="/usr/share/patch-manager/migrations"
CONFIG_DIR="/etc/patch-manager"
ADMIN_PASSWORD_FILE="/etc/patch-manager/admin-password.txt"
# ---------------------------------------------------------------------------
# Parse DATABASE_URL into PG* env vars for psql compatibility
# ---------------------------------------------------------------------------
parse_database_url() {
# DATABASE_URL format: postgres://user:password@host:port/dbname
local url="${DATABASE_URL}"
# Extract components
DB_PASS=$(echo "$url" | sed -n 's|postgres://[^:]*:\([^@]*\)@.*|\1|p')
DB_HOST=$(echo "$url" | sed -n 's|.*@\([^:/]*\).*|\1|p')
DB_PORT=$(echo "$url" | sed -n 's|.*:\([0-9]*\)/.*|\1|p')
DB_USER=$(echo "$url" | sed -n 's|postgres://\([^:]*\):.*|\1|p')
DB_NAME=$(echo "$url" | sed -n 's|.*/\([^?]*\).*|\1|p')
# Default port
DB_PORT="${DB_PORT:-5432}"
export PGHOST="${DB_HOST}"
export PGPORT="${DB_PORT}"
export PGUSER="${DB_USER}"
export PGPASSWORD="${DB_PASS}"
export PGDATABASE="${DB_NAME}"
}
# ---------------------------------------------------------------------------
# Wait for PostgreSQL to be ready
# ---------------------------------------------------------------------------
wait_for_db() {
echo "[entrypoint] Waiting for PostgreSQL at ${PGHOST}:${DB_PORT}..."
local retries=60
local delay=2
local i
for ((i = 1; i <= retries; i++)); do
if pg_isready -q -h "${PGHOST}" -p "${DB_PORT}" -U "${DB_USER}" 2>/dev/null; then
echo "[entrypoint] PostgreSQL is ready."
return 0
fi
echo "[entrypoint] PostgreSQL not ready (attempt ${i}/${retries}), waiting ${delay}s..."
sleep "${delay}"
done
echo "[entrypoint] ERROR: PostgreSQL did not become ready after $((retries * delay)) seconds." >&2
return 1
}
# ---------------------------------------------------------------------------
# Run database migrations (idempotent)
# ---------------------------------------------------------------------------
run_migrations() {
echo "[entrypoint] Applying database migrations..."
# Ensure pgcrypto extension
psql -v ON_ERROR_STOP=1 -c "CREATE EXTENSION IF NOT EXISTS pgcrypto;" 2>/dev/null || true
# Create migration tracking table
psql -v ON_ERROR_STOP=1 <<'EOSQL'
CREATE TABLE IF NOT EXISTS _migrations (
id SERIAL PRIMARY KEY,
filename TEXT NOT NULL UNIQUE,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
EOSQL
# Handle upgrade from pre-migration-tracking versions
local migration_count
migration_count=$(psql -t -A -c "SELECT COUNT(*) FROM _migrations;" 2>/dev/null || echo "0")
migration_count="${migration_count// /}"
local tables_exist
tables_exist=$(psql -t -A -c "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public' AND table_name='users';" 2>/dev/null || echo "0")
tables_exist="${tables_exist// /}"
if [[ "${migration_count}" == "0" && "${tables_exist}" -gt 0 ]]; then
echo "[entrypoint] Existing database detected — marking all shipped migrations as already applied."
for sql_file in $(ls "${MIGRATION_DIR}"/*.sql 2>/dev/null | sort); do
local fname
fname=$(basename "${sql_file}")
psql -v ON_ERROR_STOP=1 -c "INSERT INTO _migrations (filename) VALUES ('${fname}') ON CONFLICT (filename) DO NOTHING;" 2>/dev/null || true
done
fi
# Apply each migration in sorted order
local applied=0
local skipped=0
for sql_file in $(ls "${MIGRATION_DIR}"/*.sql 2>/dev/null | sort); do
local fname
fname=$(basename "${sql_file}")
local already_applied
already_applied=$(psql -t -A -c "SELECT COUNT(*) FROM _migrations WHERE filename='${fname}';" 2>/dev/null || echo "0")
already_applied="${already_applied// /}"
if [[ "${already_applied}" -gt 0 ]]; then
skipped=$((skipped + 1))
continue
fi
echo "[entrypoint] Applying migration: ${fname}"
if psql -v ON_ERROR_STOP=1 -f "${sql_file}"; then
psql -v ON_ERROR_STOP=1 -c "INSERT INTO _migrations (filename) VALUES ('${fname}');" 2>/dev/null || true
applied=$((applied + 1))
else
echo "[entrypoint] ERROR: Failed to apply migration: ${fname}" >&2
return 1
fi
done
if [[ "${applied}" -gt 0 ]]; then
echo "[entrypoint] Applied ${applied} new migration(s), skipped ${skipped}."
else
echo "[entrypoint] All migrations up to date (${skipped} already applied)."
fi
}
# ---------------------------------------------------------------------------
# Generate admin password on first run
# ---------------------------------------------------------------------------
generate_admin_password() {
echo "[entrypoint] Checking admin password status..."
# Generate a random 24-character password
local admin_password
admin_password=$(openssl rand -base64 32 | tr -dc 'A-Za-z0-9!@#%^&*' | head -c 24)
# Hash with argon2 (PHC format)
local password_hash
password_hash=$(echo -n "${admin_password}" | argon2 salt -id -t 3 -m 65536 -p 1 -l 32 -e)
# Update admin user — only if placeholder hash is still present
# The placeholder starts with: $argon2id$v=19$m=65536,t=3,p=1$AAAAAAAAAAAAAAAA
# Using single-quoted variable to preserve $ signs in the SQL LIKE pattern
local placeholder_pattern
placeholder_pattern='$argon2id$v=19$m=65536,t=3,p=1$AAAAAAAAAAAAAAAA%'
local updated
updated=$(psql -t -A -c \
"UPDATE users SET password_hash = '${password_hash}', force_password_reset = TRUE \
WHERE username = 'admin' AND password_hash LIKE '${placeholder_pattern}' \
RETURNING id;" 2>/dev/null || echo "")
if [[ -n "${updated}" ]]; then
echo "${admin_password}" > "${ADMIN_PASSWORD_FILE}"
chmod 600 "${ADMIN_PASSWORD_FILE}"
chown root:root "${ADMIN_PASSWORD_FILE}"
echo ""
echo "============================================="
echo " Linux Patch Manager — Admin Credentials"
echo "============================================="
echo " Username: admin"
echo " Password: ${admin_password}"
echo ""
echo " IMPORTANT: Save this password! It will not be shown again."
echo " Password also saved to: ${ADMIN_PASSWORD_FILE}"
echo "============================================="
echo ""
else
echo "[entrypoint] Admin password already set (not a fresh install)."
fi
}
# ---------------------------------------------------------------------------
# Generate JWT keys if not present
# ---------------------------------------------------------------------------
generate_jwt_keys() {
if [[ ! -f "${CONFIG_DIR}/jwt/signing.pem" ]]; then
echo "[entrypoint] Generating Ed25519 JWT signing key..."
openssl genpkey -algorithm ed25519 -out "${CONFIG_DIR}/jwt/signing.pem" 2>/dev/null
openssl pkey -in "${CONFIG_DIR}/jwt/signing.pem" -pubout -out "${CONFIG_DIR}/jwt/verify.pem" 2>/dev/null
chown patch-manager:patch-manager "${CONFIG_DIR}/jwt/signing.pem" "${CONFIG_DIR}/jwt/verify.pem"
chmod 600 "${CONFIG_DIR}/jwt/signing.pem"
chmod 644 "${CONFIG_DIR}/jwt/verify.pem"
echo "[entrypoint] JWT keys generated."
else
echo "[entrypoint] JWT signing key already exists."
fi
}
# ---------------------------------------------------------------------------
# Write config.toml if not present
# ---------------------------------------------------------------------------
write_config() {
local config_file="${CONFIG_DIR}/config.toml"
if [[ -f "${config_file}" ]]; then
echo "[entrypoint] Config file already exists, not overwriting."
return 0
fi
echo "[entrypoint] Writing configuration file..."
cp /usr/share/patch-manager/config.example.toml "${config_file}"
sed -i "s|postgres://patch_manager:CHANGEME@localhost/patch_manager|${DATABASE_URL}|" "${config_file}"
chown patch-manager:patch-manager "${config_file}"
chmod 640 "${config_file}"
echo "[entrypoint] Configuration written."
}
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
echo "[entrypoint] Linux Patch Manager Docker entrypoint starting..."
parse_database_url
wait_for_db
run_migrations
generate_admin_password
generate_jwt_keys
write_config
echo "[entrypoint] Starting pm-web and pm-worker..."
# Start pm-worker in background
pm-worker &
WORKER_PID=$!
# Start pm-web in foreground (main process)
export PATCH_MANAGER_CONFIG="${CONFIG_DIR}/config.toml"
exec pm-web

View File

@ -1,7 +1,7 @@
{
"name": "patch-manager-ui",
"private": true,
"version": "1.0.0",
"version": "1.1.13",
"type": "module",
"scripts": {
"dev": "vite",

View File

@ -12,31 +12,63 @@ CREATE EXTENSION IF NOT EXISTS "pg_trgm"; -- fuzzy text search on host names
-- Enumerations
-- ============================================================
CREATE TYPE user_role AS ENUM ('admin', 'operator');
CREATE TYPE auth_provider AS ENUM ('local', 'azure_sso');
CREATE TYPE host_health_status AS ENUM ('pending', 'healthy', 'degraded', 'unreachable');
CREATE TYPE job_status AS ENUM ('queued', 'pending', 'running', 'succeeded', 'failed', 'cancelled');
CREATE TYPE job_kind AS ENUM ('patch_apply', 'patch_remove', 'reboot', 'rollback');
CREATE TYPE window_recurrence AS ENUM ('once', 'daily', 'weekly', 'monthly');
CREATE TYPE cert_status AS ENUM ('active', 'revoked', 'expired');
CREATE TYPE audit_action AS ENUM (
'user_login', 'user_logout', 'user_login_failed',
'user_created', 'user_deleted', 'user_updated',
'host_registered', 'host_removed',
'group_created', 'group_deleted',
'group_membership_changed',
'patch_job_created', 'patch_job_cancelled', 'patch_job_rollback',
'maintenance_window_created', 'maintenance_window_updated', 'maintenance_window_deleted',
'certificate_issued', 'certificate_renewed', 'certificate_revoked', 'certificate_downloaded',
'config_changed',
'discovery_scan_started'
);
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'user_role') THEN
CREATE TYPE user_role AS ENUM ('admin', 'operator');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'auth_provider') THEN
CREATE TYPE auth_provider AS ENUM ('local', 'azure_sso');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'host_health_status') THEN
CREATE TYPE host_health_status AS ENUM ('pending', 'healthy', 'degraded', 'unreachable');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'job_status') THEN
CREATE TYPE job_status AS ENUM ('queued', 'pending', 'running', 'succeeded', 'failed', 'cancelled');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'job_kind') THEN
CREATE TYPE job_kind AS ENUM ('patch_apply', 'patch_remove', 'reboot', 'rollback');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'window_recurrence') THEN
CREATE TYPE window_recurrence AS ENUM ('once', 'daily', 'weekly', 'monthly');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'cert_status') THEN
CREATE TYPE cert_status AS ENUM ('active', 'revoked', 'expired');
END IF;
END $$;
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'audit_action') THEN
CREATE TYPE audit_action AS ENUM (
'user_login', 'user_logout', 'user_login_failed',
'user_created', 'user_deleted', 'user_updated',
'host_registered', 'host_removed',
'group_created', 'group_deleted',
'group_membership_changed',
'patch_job_created', 'patch_job_cancelled', 'patch_job_rollback',
'maintenance_window_created', 'maintenance_window_updated', 'maintenance_window_deleted',
'certificate_issued', 'certificate_renewed', 'certificate_revoked', 'certificate_downloaded',
'config_changed',
'discovery_scan_started'
);
END IF;
END $$;
-- ============================================================
-- Groups (defined before users/hosts for FK ordering)
-- ============================================================
CREATE TABLE groups (
CREATE TABLE IF NOT EXISTS groups (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
name TEXT NOT NULL UNIQUE,
description TEXT NOT NULL DEFAULT '',
@ -44,13 +76,13 @@ CREATE TABLE groups (
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_groups_name ON groups (name);
CREATE INDEX IF NOT EXISTS idx_groups_name ON groups (name);
-- ============================================================
-- Users
-- ============================================================
CREATE TABLE users (
CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
username TEXT NOT NULL UNIQUE,
display_name TEXT NOT NULL DEFAULT '',
@ -73,28 +105,28 @@ CREATE TABLE users (
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users (email);
CREATE INDEX idx_users_azure_oid ON users (azure_oid) WHERE azure_oid IS NOT NULL;
CREATE INDEX idx_users_role ON users (role);
CREATE INDEX IF NOT EXISTS idx_users_email ON users (email);
CREATE INDEX IF NOT EXISTS idx_users_azure_oid ON users (azure_oid) WHERE azure_oid IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_users_role ON users (role);
-- ============================================================
-- User <-> Group membership
-- ============================================================
CREATE TABLE user_groups (
CREATE TABLE IF NOT EXISTS user_groups (
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (user_id, group_id)
);
CREATE INDEX idx_user_groups_group ON user_groups (group_id);
CREATE INDEX IF NOT EXISTS idx_user_groups_group ON user_groups (group_id);
-- ============================================================
-- Refresh Tokens
-- ============================================================
CREATE TABLE refresh_tokens (
CREATE TABLE IF NOT EXISTS refresh_tokens (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
-- Stored as Argon2id hash of the opaque token bytes
@ -109,14 +141,14 @@ CREATE TABLE refresh_tokens (
ip_address INET
);
CREATE INDEX idx_refresh_tokens_user ON refresh_tokens (user_id);
CREATE INDEX idx_refresh_tokens_expires ON refresh_tokens (expires_at) WHERE revoked = FALSE;
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_user ON refresh_tokens (user_id);
CREATE INDEX IF NOT EXISTS idx_refresh_tokens_expires ON refresh_tokens (expires_at) WHERE revoked = FALSE;
-- ============================================================
-- Hosts
-- ============================================================
CREATE TABLE hosts (
CREATE TABLE IF NOT EXISTS hosts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
fqdn TEXT NOT NULL,
ip_address INET NOT NULL,
@ -136,28 +168,28 @@ CREATE TABLE hosts (
CONSTRAINT hosts_fqdn_ip_unique UNIQUE (fqdn, ip_address)
);
CREATE INDEX idx_hosts_health_status ON hosts (health_status);
CREATE INDEX idx_hosts_fqdn ON hosts USING gin (fqdn gin_trgm_ops);
CREATE INDEX idx_hosts_ip ON hosts (ip_address);
CREATE INDEX IF NOT EXISTS idx_hosts_health_status ON hosts (health_status);
CREATE INDEX IF NOT EXISTS idx_hosts_fqdn ON hosts USING gin (fqdn gin_trgm_ops);
CREATE INDEX IF NOT EXISTS idx_hosts_ip ON hosts (ip_address);
-- ============================================================
-- Host <-> Group membership
-- ============================================================
CREATE TABLE host_groups (
CREATE TABLE IF NOT EXISTS host_groups (
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
group_id UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (host_id, group_id)
);
CREATE INDEX idx_host_groups_group ON host_groups (group_id);
CREATE INDEX IF NOT EXISTS idx_host_groups_group ON host_groups (group_id);
-- ============================================================
-- Host Health Data (cached results from 5-min polls)
-- ============================================================
CREATE TABLE host_health_data (
CREATE TABLE IF NOT EXISTS host_health_data (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
polled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
@ -166,14 +198,14 @@ CREATE TABLE host_health_data (
payload JSONB NOT NULL DEFAULT '{}'
);
CREATE INDEX idx_host_health_host ON host_health_data (host_id, polled_at DESC);
CREATE INDEX IF NOT EXISTS idx_host_health_host ON host_health_data (host_id, polled_at DESC);
-- Retained for 30 days (pruned by worker)
-- ============================================================
-- Host Patch Data (cached results from 30-min polls)
-- ============================================================
CREATE TABLE host_patch_data (
CREATE TABLE IF NOT EXISTS host_patch_data (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
polled_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
@ -184,14 +216,14 @@ CREATE TABLE host_patch_data (
cve_count INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX idx_host_patch_host ON host_patch_data (host_id, polled_at DESC);
CREATE INDEX IF NOT EXISTS idx_host_patch_host ON host_patch_data (host_id, polled_at DESC);
-- Retained for 30 days (pruned by worker)
-- ============================================================
-- Maintenance Windows
-- ============================================================
CREATE TABLE maintenance_windows (
CREATE TABLE IF NOT EXISTS maintenance_windows (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
label TEXT NOT NULL DEFAULT '',
@ -207,14 +239,14 @@ CREATE TABLE maintenance_windows (
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_mw_host ON maintenance_windows (host_id);
CREATE INDEX idx_mw_start ON maintenance_windows (start_at) WHERE enabled = TRUE;
CREATE INDEX IF NOT EXISTS idx_mw_host ON maintenance_windows (host_id);
CREATE INDEX IF NOT EXISTS idx_mw_start ON maintenance_windows (start_at) WHERE enabled = TRUE;
-- ============================================================
-- Patch Jobs
-- ============================================================
CREATE TABLE patch_jobs (
CREATE TABLE IF NOT EXISTS patch_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
kind job_kind NOT NULL DEFAULT 'patch_apply',
status job_status NOT NULL DEFAULT 'queued',
@ -233,15 +265,15 @@ CREATE TABLE patch_jobs (
completed_at TIMESTAMPTZ
);
CREATE INDEX idx_patch_jobs_status ON patch_jobs (status);
CREATE INDEX idx_patch_jobs_created ON patch_jobs (created_at DESC);
CREATE INDEX idx_patch_jobs_user ON patch_jobs (created_by_user_id);
CREATE INDEX IF NOT EXISTS idx_patch_jobs_status ON patch_jobs (status);
CREATE INDEX IF NOT EXISTS idx_patch_jobs_created ON patch_jobs (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_patch_jobs_user ON patch_jobs (created_by_user_id);
-- ============================================================
-- Patch Job Hosts (per-host status within a batch job)
-- ============================================================
CREATE TABLE patch_job_hosts (
CREATE TABLE IF NOT EXISTS patch_job_hosts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
job_id UUID NOT NULL REFERENCES patch_jobs(id) ON DELETE CASCADE,
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
@ -257,15 +289,15 @@ CREATE TABLE patch_job_hosts (
UNIQUE (job_id, host_id)
);
CREATE INDEX idx_pjh_job ON patch_job_hosts (job_id);
CREATE INDEX idx_pjh_host ON patch_job_hosts (host_id);
CREATE INDEX idx_pjh_status ON patch_job_hosts (status);
CREATE INDEX IF NOT EXISTS idx_pjh_job ON patch_job_hosts (job_id);
CREATE INDEX IF NOT EXISTS idx_pjh_host ON patch_job_hosts (host_id);
CREATE INDEX IF NOT EXISTS idx_pjh_status ON patch_job_hosts (status);
-- ============================================================
-- Certificates
-- ============================================================
CREATE TABLE certificates (
CREATE TABLE IF NOT EXISTS certificates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- NULL = root CA cert
host_id UUID REFERENCES hosts(id) ON DELETE CASCADE,
@ -279,15 +311,15 @@ CREATE TABLE certificates (
cert_pem TEXT NOT NULL
);
CREATE INDEX idx_certs_host ON certificates (host_id);
CREATE INDEX idx_certs_status ON certificates (status);
CREATE INDEX idx_certs_expires ON certificates (expires_at);
CREATE INDEX IF NOT EXISTS idx_certs_host ON certificates (host_id);
CREATE INDEX IF NOT EXISTS idx_certs_status ON certificates (status);
CREATE INDEX IF NOT EXISTS idx_certs_expires ON certificates (expires_at);
-- ============================================================
-- Audit Log (tamper-evident, hash-chained)
-- ============================================================
CREATE TABLE audit_log (
CREATE TABLE IF NOT EXISTS audit_log (
id BIGSERIAL PRIMARY KEY,
action audit_action NOT NULL,
actor_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
@ -302,17 +334,17 @@ CREATE TABLE audit_log (
row_hash TEXT NOT NULL DEFAULT ''
);
CREATE INDEX idx_audit_created ON audit_log (created_at DESC);
CREATE INDEX idx_audit_actor ON audit_log (actor_user_id);
CREATE INDEX idx_audit_action ON audit_log (action);
CREATE INDEX idx_audit_target ON audit_log (target_type, target_id);
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_log (created_at DESC);
CREATE INDEX IF NOT EXISTS idx_audit_actor ON audit_log (actor_user_id);
CREATE INDEX IF NOT EXISTS idx_audit_action ON audit_log (action);
CREATE INDEX IF NOT EXISTS idx_audit_target ON audit_log (target_type, target_id);
-- Retained for 6 months (pruned by worker)
-- ============================================================
-- Azure SSO Configuration
-- ============================================================
CREATE TABLE azure_sso_config (
CREATE TABLE IF NOT EXISTS azure_sso_config (
id INTEGER PRIMARY KEY DEFAULT 1, -- singleton row
enabled BOOLEAN NOT NULL DEFAULT FALSE,
tenant_id TEXT NOT NULL DEFAULT '',
@ -329,7 +361,7 @@ CREATE TABLE azure_sso_config (
-- System Configuration (key/value runtime settings)
-- ============================================================
CREATE TABLE system_config (
CREATE TABLE IF NOT EXISTS system_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
@ -351,13 +383,14 @@ INSERT INTO system_config (key, value, description) VALUES
('smtp_from', '', 'From address for notifications'),
('smtp_tls_mode', 'starttls', 'SMTP TLS mode: none, starttls, tls'),
('web_tls_strategy', 'internal_ca', 'Web UI TLS cert strategy: internal_ca or operator_supplied'),
('ip_whitelist', '[]', 'JSON array of allowed CIDR/IP strings; empty = allow all');
('ip_whitelist', '[]', 'JSON array of allowed CIDR/IP strings; empty = allow all')
ON CONFLICT (key) DO NOTHING;
-- ============================================================
-- Worker Heartbeat
-- ============================================================
CREATE TABLE worker_heartbeat (
CREATE TABLE IF NOT EXISTS worker_heartbeat (
id INTEGER PRIMARY KEY DEFAULT 1, -- singleton row
last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(),
worker_version TEXT NOT NULL DEFAULT '',
@ -368,7 +401,7 @@ CREATE TABLE worker_heartbeat (
-- Discovery Results (transient; cleared before each scan)
-- ============================================================
CREATE TABLE discovery_results (
CREATE TABLE IF NOT EXISTS discovery_results (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
scan_id UUID NOT NULL,
ip_address INET NOT NULL,
@ -381,5 +414,5 @@ CREATE TABLE discovery_results (
registered BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX idx_discovery_scan ON discovery_results (scan_id);
CREATE INDEX idx_discovery_ip ON discovery_results (ip_address);
CREATE INDEX IF NOT EXISTS idx_discovery_scan ON discovery_results (scan_id);
CREATE INDEX IF NOT EXISTS idx_discovery_ip ON discovery_results (ip_address);

View File

@ -8,11 +8,11 @@
-- When the retry engine should next attempt this host; NULL = not scheduled
ALTER TABLE patch_job_hosts
ADD COLUMN retry_next_at TIMESTAMPTZ;
ADD COLUMN IF NOT EXISTS retry_next_at TIMESTAMPTZ;
-- Last failure reason captured by the worker for display in the UI
ALTER TABLE patch_job_hosts
ADD COLUMN last_error TEXT;
ADD COLUMN IF NOT EXISTS last_error TEXT;
-- ============================================================
-- pg_notify trigger: fires when an immediate job is inserted
@ -30,15 +30,21 @@ BEGIN
END;
$$;
CREATE TRIGGER trg_job_enqueued
AFTER INSERT ON patch_jobs
FOR EACH ROW
EXECUTE FUNCTION notify_job_enqueued();
DO $$ BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_trigger WHERE tgname = 'trg_job_enqueued'
) THEN
CREATE TRIGGER trg_job_enqueued
AFTER INSERT ON patch_jobs
FOR EACH ROW
EXECUTE FUNCTION notify_job_enqueued();
END IF;
END $$;
-- ============================================================
-- Index: efficiently find hosts due for retry
-- ============================================================
CREATE INDEX idx_pjh_retry
CREATE INDEX IF NOT EXISTS idx_pjh_retry
ON patch_job_hosts (retry_next_at)
WHERE retry_next_at IS NOT NULL;

View File

@ -1,7 +1,7 @@
-- Migration 007: Health check configuration and results
-- Health checks configured per host (1-5 per host)
CREATE TABLE host_health_checks (
CREATE TABLE IF NOT EXISTS host_health_checks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
name VARCHAR(100) NOT NULL,
@ -27,10 +27,10 @@ CREATE TABLE host_health_checks (
)
);
CREATE INDEX idx_health_checks_host ON host_health_checks (host_id);
CREATE INDEX IF NOT EXISTS idx_health_checks_host ON host_health_checks (host_id);
-- Health check poll results (4-day retention, pruned by worker)
CREATE TABLE host_health_check_results (
CREATE TABLE IF NOT EXISTS host_health_check_results (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
check_id UUID NOT NULL REFERENCES host_health_checks(id) ON DELETE CASCADE,
healthy BOOLEAN NOT NULL,
@ -39,4 +39,4 @@ CREATE TABLE host_health_check_results (
checked_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_health_results_check ON host_health_check_results (check_id, checked_at DESC);
CREATE INDEX IF NOT EXISTS idx_health_results_check ON host_health_check_results (check_id, checked_at DESC);

View File

@ -4,7 +4,7 @@
-- FK with ON DELETE SET NULL: if target host deleted, revert to default.
ALTER TABLE host_health_checks
ADD COLUMN target_host_id UUID REFERENCES hosts(id) ON DELETE SET NULL;
ADD COLUMN IF NOT EXISTS target_host_id UUID REFERENCES hosts(id) ON DELETE SET NULL;
CREATE INDEX idx_health_checks_target_host ON host_health_checks (target_host_id)
CREATE INDEX IF NOT EXISTS idx_health_checks_target_host ON host_health_checks (target_host_id)
WHERE target_host_id IS NOT NULL;

View File

@ -1,7 +1,7 @@
-- Migration: 016_enrollment_requests
-- Description: Create enrollment_requests table for host self-enrollment
CREATE TABLE enrollment_requests (
CREATE TABLE IF NOT EXISTS enrollment_requests (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
machine_id TEXT NOT NULL UNIQUE,
fqdn TEXT NOT NULL,
@ -12,5 +12,5 @@ CREATE TABLE enrollment_requests (
expires_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '24 hours'
);
CREATE INDEX idx_enrollment_requests_token ON enrollment_requests (polling_token);
CREATE INDEX idx_enrollment_requests_expires ON enrollment_requests (expires_at);
CREATE INDEX IF NOT EXISTS idx_enrollment_requests_token ON enrollment_requests (polling_token);
CREATE INDEX IF NOT EXISTS idx_enrollment_requests_expires ON enrollment_requests (expires_at);

View File

@ -22,7 +22,7 @@ warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; exit 1; }
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VERSION="1.0.0"
VERSION="1.1.13"
RELEASE="1"
PKG_NAME="linux-patch-manager"
DEB_NAME="${PKG_NAME}_${VERSION}-${RELEASE}_amd64.deb"