feat: add bump-version.sh script for version management
Automates version bumps across all version source files: - Cargo.toml (PRIMARY - workspace.package.version) - debian/changelog (prepend new entry) - debian/control (update Version field) - scripts/build-package.sh (update VERSION variable) - frontend/package.json (update version field) - Stale references check after bump Usage: ./scripts/bump-version.sh <new_version> <old_version>
This commit is contained in:
385
migrations/001_initial_schema.sql
Normal file
385
migrations/001_initial_schema.sql
Normal file
@ -0,0 +1,385 @@
|
||||
-- Migration: 001_initial_schema
|
||||
-- Description: Full initial schema for Linux Patch Manager
|
||||
-- All tables, indexes, and constraints in a single initial migration.
|
||||
|
||||
-- ============================================================
|
||||
-- Extensions
|
||||
-- ============================================================
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto"; -- gen_random_bytes, crypt
|
||||
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'
|
||||
);
|
||||
|
||||
-- ============================================================
|
||||
-- Groups (defined before users/hosts for FK ordering)
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE groups (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL UNIQUE,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_groups_name ON groups (name);
|
||||
|
||||
-- ============================================================
|
||||
-- Users
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
email TEXT NOT NULL UNIQUE,
|
||||
role user_role NOT NULL DEFAULT 'operator',
|
||||
auth_provider auth_provider NOT NULL DEFAULT 'local',
|
||||
-- Local auth fields (NULL for SSO-only users)
|
||||
password_hash TEXT,
|
||||
-- MFA
|
||||
totp_secret TEXT, -- NULL = TOTP not configured
|
||||
webauthn_credential JSONB, -- NULL = WebAuthn not configured
|
||||
mfa_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
-- Azure SSO
|
||||
azure_oid TEXT UNIQUE, -- Azure Object ID
|
||||
-- Account state
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
force_password_reset BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
last_login_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
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);
|
||||
|
||||
-- ============================================================
|
||||
-- User <-> Group membership
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE 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);
|
||||
|
||||
-- ============================================================
|
||||
-- Refresh Tokens
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE 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
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
issued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
last_used_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
-- 1-hour sliding inactivity window; updated on each use
|
||||
expires_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + INTERVAL '1 hour',
|
||||
revoked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
user_agent TEXT,
|
||||
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;
|
||||
|
||||
-- ============================================================
|
||||
-- Hosts
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE hosts (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
fqdn TEXT NOT NULL,
|
||||
ip_address INET NOT NULL,
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
os_family TEXT, -- debian, rhel, alpine, arch
|
||||
os_name TEXT, -- e.g. "Ubuntu 24.04"
|
||||
arch TEXT, -- x86_64, aarch64, etc.
|
||||
agent_version TEXT,
|
||||
health_status host_health_status NOT NULL DEFAULT 'pending',
|
||||
last_health_at TIMESTAMPTZ,
|
||||
last_patch_at TIMESTAMPTZ,
|
||||
-- Agent port (default 12443)
|
||||
agent_port INTEGER NOT NULL DEFAULT 12443,
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
registered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
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);
|
||||
|
||||
-- ============================================================
|
||||
-- Host <-> Group membership
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE 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);
|
||||
|
||||
-- ============================================================
|
||||
-- Host Health Data (cached results from 5-min polls)
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE 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(),
|
||||
status host_health_status NOT NULL,
|
||||
-- Raw JSON response from agent GET /api/v1/health
|
||||
payload JSONB NOT NULL DEFAULT '{}'
|
||||
);
|
||||
|
||||
CREATE INDEX 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 (
|
||||
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(),
|
||||
-- Raw JSON response from agent GET /api/v1/patches
|
||||
available_patches JSONB NOT NULL DEFAULT '[]',
|
||||
installed_packages JSONB NOT NULL DEFAULT '[]',
|
||||
patch_count INTEGER NOT NULL DEFAULT 0,
|
||||
cve_count INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX 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 (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
host_id UUID NOT NULL REFERENCES hosts(id) ON DELETE CASCADE,
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
recurrence window_recurrence NOT NULL DEFAULT 'once',
|
||||
-- Start time (UTC)
|
||||
start_at TIMESTAMPTZ NOT NULL,
|
||||
-- Duration in minutes
|
||||
duration_minutes INTEGER NOT NULL DEFAULT 60,
|
||||
-- For recurring windows: day-of-week (0=Sun) or day-of-month
|
||||
recurrence_day INTEGER,
|
||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
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;
|
||||
|
||||
-- ============================================================
|
||||
-- Patch Jobs
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE 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',
|
||||
created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
-- For rollback jobs: reference to original job
|
||||
parent_job_id UUID REFERENCES patch_jobs(id) ON DELETE SET NULL,
|
||||
-- Optional: restrict to a specific maintenance window
|
||||
maintenance_window_id UUID REFERENCES maintenance_windows(id) ON DELETE SET NULL,
|
||||
-- Immediate apply if TRUE; else queued for next window
|
||||
immediate BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
-- Patch selection (list of package names / CVE IDs)
|
||||
patch_selection JSONB NOT NULL DEFAULT '[]',
|
||||
notes TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
started_at TIMESTAMPTZ,
|
||||
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);
|
||||
|
||||
-- ============================================================
|
||||
-- Patch Job Hosts (per-host status within a batch job)
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE 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,
|
||||
status job_status NOT NULL DEFAULT 'queued',
|
||||
-- Agent-assigned async job ID
|
||||
agent_job_id TEXT,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0,
|
||||
-- Output / error from agent
|
||||
output TEXT NOT NULL DEFAULT '',
|
||||
error_message TEXT,
|
||||
started_at TIMESTAMPTZ,
|
||||
completed_at TIMESTAMPTZ,
|
||||
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);
|
||||
|
||||
-- ============================================================
|
||||
-- Certificates
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE certificates (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
-- NULL = root CA cert
|
||||
host_id UUID REFERENCES hosts(id) ON DELETE CASCADE,
|
||||
serial_number TEXT NOT NULL UNIQUE,
|
||||
common_name TEXT NOT NULL,
|
||||
status cert_status NOT NULL DEFAULT 'active',
|
||||
issued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
revoked_at TIMESTAMPTZ,
|
||||
-- PEM-encoded certificate (public cert only, no key)
|
||||
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);
|
||||
|
||||
-- ============================================================
|
||||
-- Audit Log (tamper-evident, hash-chained)
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE audit_log (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
action audit_action NOT NULL,
|
||||
actor_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
|
||||
actor_username TEXT, -- Snapshot at time of action
|
||||
target_type TEXT, -- 'host', 'user', 'group', 'job', etc.
|
||||
target_id TEXT, -- UUID or identifier of affected resource
|
||||
details JSONB NOT NULL DEFAULT '{}',
|
||||
ip_address INET,
|
||||
request_id TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
-- Hash chain: SHA-256(prev_hash || row_data)
|
||||
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);
|
||||
-- Retained for 6 months (pruned by worker)
|
||||
|
||||
-- ============================================================
|
||||
-- Azure SSO Configuration
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE azure_sso_config (
|
||||
id INTEGER PRIMARY KEY DEFAULT 1, -- singleton row
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
tenant_id TEXT NOT NULL DEFAULT '',
|
||||
client_id TEXT NOT NULL DEFAULT '',
|
||||
-- Encrypted at rest via hardware-host FDE; stored as-is in DB
|
||||
client_secret TEXT NOT NULL DEFAULT '',
|
||||
redirect_uri TEXT NOT NULL DEFAULT '',
|
||||
scopes TEXT NOT NULL DEFAULT 'openid email profile',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
CONSTRAINT azure_sso_singleton CHECK (id = 1)
|
||||
);
|
||||
|
||||
-- ============================================================
|
||||
-- System Configuration (key/value runtime settings)
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE system_config (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Seed default system config values
|
||||
INSERT INTO system_config (key, value, description) VALUES
|
||||
('health_poll_interval_secs', '300', 'Agent health check interval in seconds'),
|
||||
('patch_poll_interval_secs', '1800', 'Agent patch data poll interval in seconds'),
|
||||
('max_concurrent_agent_calls', '64', 'Maximum concurrent mTLS agent calls'),
|
||||
('data_retention_days', '30', 'Retention period for operational data (days)'),
|
||||
('audit_retention_days', '180', 'Retention period for audit log (days)'),
|
||||
('smtp_enabled', 'false', 'Enable email notifications'),
|
||||
('smtp_host', '', 'SMTP relay hostname'),
|
||||
('smtp_port', '587', 'SMTP relay port'),
|
||||
('smtp_username', '', 'SMTP auth username'),
|
||||
('smtp_password', '', 'SMTP auth password'),
|
||||
('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');
|
||||
|
||||
-- ============================================================
|
||||
-- Worker Heartbeat
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE worker_heartbeat (
|
||||
id INTEGER PRIMARY KEY DEFAULT 1, -- singleton row
|
||||
last_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
worker_version TEXT NOT NULL DEFAULT '',
|
||||
CONSTRAINT worker_heartbeat_singleton CHECK (id = 1)
|
||||
);
|
||||
|
||||
-- ============================================================
|
||||
-- Discovery Results (transient; cleared before each scan)
|
||||
-- ============================================================
|
||||
|
||||
CREATE TABLE discovery_results (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
scan_id UUID NOT NULL,
|
||||
ip_address INET NOT NULL,
|
||||
fqdn TEXT,
|
||||
agent_version TEXT,
|
||||
os_name TEXT,
|
||||
agent_port INTEGER NOT NULL DEFAULT 12443,
|
||||
discovered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
-- Whether the operator has registered this host
|
||||
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);
|
||||
36
migrations/002_seed_admin.sql
Normal file
36
migrations/002_seed_admin.sql
Normal file
@ -0,0 +1,36 @@
|
||||
-- Migration: 002_seed_admin
|
||||
-- Description: Seed the default admin account.
|
||||
--
|
||||
-- Default credentials (CHANGE BEFORE PRODUCTION USE):
|
||||
-- Username: admin
|
||||
-- Password: ChangeMe123!
|
||||
--
|
||||
-- The password hash below is Argon2id of "ChangeMe123!" with
|
||||
-- m=65536, t=3, p=1. Replace after first login.
|
||||
|
||||
INSERT INTO users (
|
||||
id,
|
||||
username,
|
||||
display_name,
|
||||
email,
|
||||
role,
|
||||
auth_provider,
|
||||
password_hash,
|
||||
mfa_enabled,
|
||||
is_active,
|
||||
force_password_reset
|
||||
)
|
||||
VALUES (
|
||||
gen_random_uuid(),
|
||||
'admin',
|
||||
'Administrator',
|
||||
'admin@localhost',
|
||||
'admin',
|
||||
'local',
|
||||
-- Argon2id hash of "ChangeMe123!" — REPLACE IN PRODUCTION
|
||||
'$argon2id$v=19$m=65536,t=3,p=1$Kv8bkGiE81yIuXARq9fwsw$NrBRFvgL1dVsW7bEK6NxEOzIX2q1p4B0K422idAVIDQ',
|
||||
FALSE, -- MFA disabled by default; admin must set up on first login
|
||||
TRUE,
|
||||
TRUE -- Force password reset on first login
|
||||
)
|
||||
ON CONFLICT (username) DO NOTHING;
|
||||
44
migrations/003_jobs_scheduling.sql
Normal file
44
migrations/003_jobs_scheduling.sql
Normal file
@ -0,0 +1,44 @@
|
||||
-- Migration: 003_jobs_scheduling
|
||||
-- Description: Retry/scheduling columns for patch_job_hosts, and NOTIFY trigger
|
||||
-- for immediate patch job dispatch.
|
||||
|
||||
-- ============================================================
|
||||
-- Add retry-scheduling columns to patch_job_hosts
|
||||
-- ============================================================
|
||||
|
||||
-- When the retry engine should next attempt this host; NULL = not scheduled
|
||||
ALTER TABLE patch_job_hosts
|
||||
ADD COLUMN 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;
|
||||
|
||||
-- ============================================================
|
||||
-- pg_notify trigger: fires when an immediate job is inserted
|
||||
-- ============================================================
|
||||
|
||||
CREATE OR REPLACE FUNCTION notify_job_enqueued()
|
||||
RETURNS TRIGGER
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
BEGIN
|
||||
IF NEW.immediate = TRUE THEN
|
||||
PERFORM pg_notify('job_enqueued', NEW.id::text);
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
CREATE TRIGGER trg_job_enqueued
|
||||
AFTER INSERT ON patch_jobs
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION notify_job_enqueued();
|
||||
|
||||
-- ============================================================
|
||||
-- Index: efficiently find hosts due for retry
|
||||
-- ============================================================
|
||||
|
||||
CREATE INDEX idx_pjh_retry
|
||||
ON patch_job_hosts (retry_next_at)
|
||||
WHERE retry_next_at IS NOT NULL;
|
||||
25
migrations/004_maintenance_windows.sql
Normal file
25
migrations/004_maintenance_windows.sql
Normal file
@ -0,0 +1,25 @@
|
||||
-- Migration: 004_maintenance_windows
|
||||
-- Description: Additional indexes and scheduler-support for maintenance windows.
|
||||
-- The maintenance_windows table and window_recurrence ENUM were
|
||||
-- created in 001_initial_schema.sql. This migration adds composite
|
||||
-- indexes needed by the M6 maintenance_scheduler worker and patches
|
||||
-- the audit_action ENUM to include window events already listed in
|
||||
-- the audit log helper (they were declared there but the ENUM values
|
||||
-- already exist – guarded with a DO block to be idempotent).
|
||||
|
||||
-- ============================================================
|
||||
-- Composite index: scheduler query
|
||||
-- Finds enabled windows by recurrence type + recurrence_day quickly.
|
||||
-- ============================================================
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_mw_enabled_recurrence
|
||||
ON maintenance_windows (recurrence, recurrence_day)
|
||||
WHERE enabled = TRUE;
|
||||
|
||||
-- ============================================================
|
||||
-- Index: quickly find non-immediate queued jobs for a given host
|
||||
-- ============================================================
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_pjh_queued_host
|
||||
ON patch_job_hosts (host_id, status)
|
||||
WHERE status = 'queued';
|
||||
34
migrations/005_audit_hardening.sql
Normal file
34
migrations/005_audit_hardening.sql
Normal file
@ -0,0 +1,34 @@
|
||||
-- Migration: 005_audit_hardening
|
||||
-- Description: Add prev_hash column to audit_log for full hash chaining,
|
||||
-- add notification config defaults to system_config, add new
|
||||
-- audit_action enum values, and add audit_integrity_last_verified.
|
||||
|
||||
-- ============================================================
|
||||
-- 1. Add prev_hash column to audit_log
|
||||
-- ============================================================
|
||||
ALTER TABLE audit_log ADD COLUMN IF NOT EXISTS prev_hash TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- Reset the audit log so the hash chain starts clean.
|
||||
-- Existing rows were inserted before prev_hash existed, so their
|
||||
-- chain is broken. Truncating lets the worker build a valid chain.
|
||||
TRUNCATE audit_log;
|
||||
|
||||
-- ============================================================
|
||||
-- 2. Add notification config defaults to system_config
|
||||
-- ============================================================
|
||||
INSERT INTO system_config (key, value, updated_at)
|
||||
VALUES
|
||||
('notification_email_enabled', 'false', NOW()),
|
||||
('notification_email_from', 'patch-manager@localhost', NOW()),
|
||||
('notification_email_recipients', '[]', NOW()),
|
||||
('audit_integrity_last_verified', '', NOW())
|
||||
ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
-- ============================================================
|
||||
-- 3. Add new audit_action enum values
|
||||
-- ============================================================
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'audit_integrity_verified';
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'email_notification_sent';
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'patch_job_completed';
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'patch_job_failed';
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'maintenance_window_reminder';
|
||||
19
migrations/006_host_patch_data_unique.sql
Normal file
19
migrations/006_host_patch_data_unique.sql
Normal file
@ -0,0 +1,19 @@
|
||||
-- Migration 006: Add UNIQUE constraint on host_id in host_patch_data
|
||||
-- Clean up duplicate rows (keep latest polled_at per host) before adding constraint.
|
||||
|
||||
-- Step 1: Delete duplicate rows, keeping only the most recent poll per host
|
||||
DELETE FROM host_patch_data a
|
||||
USING host_patch_data b
|
||||
WHERE a.host_id = b.host_id
|
||||
AND a.polled_at < b.polled_at;
|
||||
|
||||
-- Step 2: Add UNIQUE constraint on host_id (idempotent)
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_constraint WHERE conname = 'host_patch_data_host_id_key'
|
||||
) THEN
|
||||
ALTER TABLE host_patch_data
|
||||
ADD CONSTRAINT host_patch_data_host_id_key UNIQUE (host_id);
|
||||
END IF;
|
||||
END $$;
|
||||
42
migrations/007_health_checks.sql
Normal file
42
migrations/007_health_checks.sql
Normal file
@ -0,0 +1,42 @@
|
||||
-- Migration 007: Health check configuration and results
|
||||
|
||||
-- Health checks configured per host (1-5 per host)
|
||||
CREATE TABLE 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,
|
||||
check_type VARCHAR(20) NOT NULL CHECK (check_type IN ('service', 'http')),
|
||||
enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
-- Service check fields (Type 1)
|
||||
service_name VARCHAR(200),
|
||||
-- HTTP check fields (Type 2)
|
||||
url TEXT,
|
||||
expected_body VARCHAR(500),
|
||||
ignore_cert_errors BOOLEAN DEFAULT true,
|
||||
basic_auth_user VARCHAR(100),
|
||||
basic_auth_pass_encrypted BYTEA, -- AES-256-GCM encrypted
|
||||
basic_auth_pass_nonce BYTEA, -- nonce for AES-GCM
|
||||
-- Metadata
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
-- Constraint: service checks must have service_name, http checks must have url + expected_body
|
||||
CONSTRAINT valid_service_check CHECK (
|
||||
(check_type = 'service' AND service_name IS NOT NULL AND url IS NULL)
|
||||
OR
|
||||
(check_type = 'http' AND url IS NOT NULL AND expected_body IS NOT NULL AND service_name IS NULL)
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX 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 (
|
||||
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,
|
||||
detail TEXT,
|
||||
latency_ms INTEGER,
|
||||
checked_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX idx_health_results_check ON host_health_check_results (check_id, checked_at DESC);
|
||||
4
migrations/008_health_check_worker.sql
Normal file
4
migrations/008_health_check_worker.sql
Normal file
@ -0,0 +1,4 @@
|
||||
-- Migration 008: Health check worker support
|
||||
-- Adds 'waiting_health_check' to the job_status enum for pre-patch health gates.
|
||||
|
||||
ALTER TYPE job_status ADD VALUE IF NOT EXISTS 'waiting_health_check';
|
||||
4
migrations/009_health_check_audit_actions.sql
Normal file
4
migrations/009_health_check_audit_actions.sql
Normal file
@ -0,0 +1,4 @@
|
||||
-- Add health check audit_action enum values
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'health_check_created';
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'health_check_updated';
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'health_check_deleted';
|
||||
2
migrations/010_cert_reissued_audit_action.sql
Normal file
2
migrations/010_cert_reissued_audit_action.sql
Normal file
@ -0,0 +1,2 @@
|
||||
-- Add certificate_reissued audit_action enum value
|
||||
ALTER TYPE audit_action ADD VALUE IF NOT EXISTS 'certificate_reissued';
|
||||
10
migrations/011_health_check_target_host.sql
Normal file
10
migrations/011_health_check_target_host.sql
Normal file
@ -0,0 +1,10 @@
|
||||
-- Add target_host_id to health checks, allowing a check on Host A
|
||||
-- to query a service on Host B's agent (for redundant services).
|
||||
-- NULL = check own host (backward compatible).
|
||||
-- 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;
|
||||
|
||||
CREATE INDEX idx_health_checks_target_host ON host_health_checks (target_host_id)
|
||||
WHERE target_host_id IS NOT NULL;
|
||||
3
migrations/012_account_lockout.sql
Normal file
3
migrations/012_account_lockout.sql
Normal file
@ -0,0 +1,3 @@
|
||||
-- Account lockout: track failed login attempts and lockout timestamps
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS failed_login_attempts INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS locked_until TIMESTAMPTZ;
|
||||
8
migrations/013_maintenance_window_auto_apply.sql
Normal file
8
migrations/013_maintenance_window_auto_apply.sql
Normal file
@ -0,0 +1,8 @@
|
||||
-- Migration 013: Add auto_apply flag to maintenance windows
|
||||
-- When true, the maintenance scheduler will automatically create a patch_apply job
|
||||
-- for the host when the window opens and patches are pending.
|
||||
|
||||
ALTER TABLE maintenance_windows
|
||||
ADD COLUMN IF NOT EXISTS auto_apply boolean NOT NULL DEFAULT true;
|
||||
|
||||
COMMENT ON COLUMN maintenance_windows.auto_apply IS 'When true, automatically create a patch_apply job when this window opens and the host has pending patches.';
|
||||
59
migrations/014_oidc_provider.sql
Normal file
59
migrations/014_oidc_provider.sql
Normal file
@ -0,0 +1,59 @@
|
||||
-- 014_oidc_provider.sql
|
||||
-- Migrate from Azure AD-specific SSO to generic OIDC provider support
|
||||
-- Supports Keycloak, Azure AD, and custom OIDC providers
|
||||
|
||||
-- Add new auth_provider enum values for Keycloak and generic OIDC
|
||||
-- Use DO blocks with exception handling for idempotency
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_enum e JOIN pg_type t ON e.enumtypid = t.oid WHERE t.typname = 'auth_provider' AND e.enumlabel = 'keycloak') THEN
|
||||
ALTER TYPE auth_provider ADD VALUE 'keycloak';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_enum e JOIN pg_type t ON e.enumtypid = t.oid WHERE t.typname = 'auth_provider' AND e.enumlabel = 'oidc') THEN
|
||||
ALTER TYPE auth_provider ADD VALUE 'oidc';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
|
||||
-- Add oidc_sub column for Keycloak/custom OIDC subject IDs
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS oidc_sub TEXT;
|
||||
CREATE INDEX IF NOT EXISTS idx_users_oidc_sub ON users (oidc_sub) WHERE oidc_sub IS NOT NULL;
|
||||
|
||||
-- Create oidc_config table (replaces azure_sso_config)
|
||||
CREATE TABLE IF NOT EXISTS oidc_config (
|
||||
id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
provider_type TEXT NOT NULL DEFAULT 'azure' CHECK (provider_type IN ('keycloak', 'azure', 'custom')),
|
||||
display_name TEXT NOT NULL DEFAULT 'Azure AD',
|
||||
discovery_url TEXT NOT NULL DEFAULT '',
|
||||
client_id TEXT NOT NULL DEFAULT '',
|
||||
-- Empty string for public clients (Keycloak); non-empty for confidential clients (Azure AD)
|
||||
client_secret TEXT NOT NULL DEFAULT '',
|
||||
redirect_uri TEXT NOT NULL DEFAULT '',
|
||||
scopes TEXT NOT NULL DEFAULT 'openid profile email',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
-- Migrate data from azure_sso_config if it has a row and oidc_config is empty
|
||||
INSERT INTO oidc_config (enabled, provider_type, display_name, discovery_url, client_id, client_secret, redirect_uri, scopes)
|
||||
SELECT
|
||||
az.enabled,
|
||||
'azure',
|
||||
'Azure AD',
|
||||
CASE
|
||||
WHEN az.tenant_id IS NOT NULL AND az.tenant_id != ''
|
||||
THEN 'https://login.microsoftonline.com/' || az.tenant_id || '/v2.0/.well-known/openid-configuration'
|
||||
ELSE ''
|
||||
END,
|
||||
az.client_id,
|
||||
az.client_secret,
|
||||
az.redirect_uri,
|
||||
az.scopes
|
||||
FROM azure_sso_config az
|
||||
WHERE az.id = 1
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- Ensure a default row exists if no data was migrated
|
||||
INSERT INTO oidc_config (enabled, provider_type, display_name)
|
||||
SELECT FALSE, 'azure', 'Azure AD'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM oidc_config WHERE id = 1);
|
||||
14
migrations/015_reporter_role.sql
Normal file
14
migrations/015_reporter_role.sql
Normal file
@ -0,0 +1,14 @@
|
||||
-- Migration 015: Add 'reporter' role to user_role enum
|
||||
-- Reporter is a read-only role for SSO auto-provisioned users.
|
||||
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM pg_enum e
|
||||
JOIN pg_type t ON t.oid = e.enumtypid
|
||||
WHERE t.typname = 'user_role' AND e.enumlabel = 'reporter'
|
||||
) THEN
|
||||
ALTER TYPE user_role ADD VALUE 'reporter';
|
||||
END IF;
|
||||
END
|
||||
$$;
|
||||
16
migrations/016_enrollment_requests.sql
Normal file
16
migrations/016_enrollment_requests.sql
Normal file
@ -0,0 +1,16 @@
|
||||
-- Migration: 016_enrollment_requests
|
||||
-- Description: Create enrollment_requests table for host self-enrollment
|
||||
|
||||
CREATE TABLE enrollment_requests (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
machine_id TEXT NOT NULL UNIQUE,
|
||||
fqdn TEXT NOT NULL,
|
||||
ip_address INET NOT NULL,
|
||||
os_details JSONB NOT NULL DEFAULT '{}',
|
||||
polling_token TEXT NOT NULL UNIQUE, -- Hashed polling token
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
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);
|
||||
5
migrations/017_enrollment_host_columns.sql
Normal file
5
migrations/017_enrollment_host_columns.sql
Normal file
@ -0,0 +1,5 @@
|
||||
-- Migration: 017_enrollment_host_columns
|
||||
-- Add missing columns for enrollment support
|
||||
ALTER TABLE hosts ADD COLUMN IF NOT EXISTS machine_id TEXT;
|
||||
ALTER TABLE certificates ADD COLUMN IF NOT EXISTS ip_address INET;
|
||||
ALTER TABLE certificates ADD COLUMN IF NOT EXISTS key_pem TEXT;
|
||||
3
migrations/018_add_hostname_to_enrollment.sql
Normal file
3
migrations/018_add_hostname_to_enrollment.sql
Normal file
@ -0,0 +1,3 @@
|
||||
-- Migration: 018_add_hostname_to_enrollment
|
||||
-- Add hostname column to enrollment_requests for proper display name
|
||||
ALTER TABLE enrollment_requests ADD COLUMN IF NOT EXISTS hostname TEXT;
|
||||
Reference in New Issue
Block a user