No description
  • TypeScript 83.8%
  • CSS 10.3%
  • Shell 3.5%
  • JavaScript 1.2%
  • PLpgSQL 0.6%
  • Other 0.6%
Find a file
Leandro Afonso 5bd63bc6f1
Some checks failed
Validate / check (push) Failing after 28s
fix: add explicit error messages
2026-11-10 09:23:23 +00:00
.github/workflows fix: vulns 2026-11-09 13:23:59 +00:00
.superdesign/init fix: text/buttons on some menus + theme change 2026-09-18 10:14:13 +01:00
deploy feat: cert management 2026-09-26 16:16:03 +01:00
dev feat: replaced SSH with an agent based control 2026-09-25 23:19:41 +01:00
docs fix: add explicit error messages 2026-11-10 09:23:23 +00:00
migrations fix: alignment and var stats pages 2026-11-09 14:41:02 +00:00
public inital commit 2026-09-17 17:12:26 +01:00
scripts fix: add explicit error messages 2026-11-10 09:23:23 +00:00
src fix: add explicit error messages 2026-11-10 09:23:23 +00:00
.dockerignore feat: replaced SSH with an agent based control 2026-09-25 23:19:41 +01:00
.env.example inital commit 2026-09-17 17:12:26 +01:00
.gitignore feat: replaced SSH with an agent based control 2026-09-25 23:19:41 +01:00
.prettierignore style: format code with Prettier and add blank-line spacing 2026-11-06 23:45:03 +00:00
.prettierrc.json style: format code with Prettier and add blank-line spacing 2026-11-06 23:45:03 +00:00
compose.development.yaml feat: replaced SSH with an agent based control 2026-09-25 23:19:41 +01:00
compose.production.yaml feat: dedicated HTTPS listener for agents 2026-11-06 23:44:31 +00:00
config.example.yaml feat: dedicated HTTPS listener for agents 2026-11-06 23:44:31 +00:00
deploy.txt feat: replaced SSH with an agent based control 2026-09-25 23:19:41 +01:00
Dockerfile feat: dedicated HTTPS listener for agents 2026-11-06 23:44:31 +00:00
index.html fix: text/buttons on some menus + theme change 2026-09-18 10:14:13 +01:00
openapi.yaml fix: show ip in audit table 2026-11-09 16:01:16 +00:00
package-lock.json fix: vulns 2026-11-09 13:23:59 +00:00
package.json fix: vulns 2026-11-09 13:23:59 +00:00
README.md fix: show ip in audit table 2026-11-09 16:01:16 +00:00
tsconfig.agent.json feat: replaced SSH with an agent based control 2026-09-25 23:19:41 +01:00
tsconfig.json inital commit 2026-09-17 17:12:26 +01:00
tsconfig.server.json inital commit 2026-09-17 17:12:26 +01:00
vite.config.ts inital commit 2026-09-17 17:12:26 +01:00

HAProxy Operations Dashboard

A self-hosted control plane for monitoring and safely operating multiple HAProxy 3.0+ instances. It uses an outbound authenticated agent on each host and writes only to HAProxy's admin-level UNIX runtime socket. It never edits haproxy.cfg, exposes the socket over TCP, or accepts arbitrary shell/runtime commands.

What is included

  • Multi-instance health, stats, backend/server, and connectivity views
  • Typed show info, show stat, show servers state, and on-demand show sess integration
  • Verified, idempotent ready/drain/maintenance operations
  • Preflighted logical operations with explicit per-instance partial failures
  • Local accounts with Argon2id passwords, server-side sessions, CSRF protection, and viewer/operator/administrator roles
  • One-time API tokens stored as SHA-256 hashes, expiration/revocation, last-used tracking, and four-dimensional resource scopes
  • Append-only audit records for successful and failed operations
  • PostgreSQL metric samples, one-minute query aggregation, and configurable cleanup
  • OpenAPI 3.1 specification and authenticated Scalar API reference at /api/docs
  • Docker development fleet with two HAProxy 3.0 instances connected through host agents

Quick start

Requirements: Docker with Compose v2.

docker compose -f compose.development.yaml up --build

Open http://localhost:8080 and use the development-only account:

admin@example.com
development-only-change-me

The included agent tokens and password are intentionally limited to the disposable development environment. Never reuse them in production.

Production configuration

Copy config.example.yaml to a protected location, add each instance, and mount it read-only at runtime. HAPI_CONFIG selects its path. Environment values override the database, listener, public URL, cookie, and polling settings; see .env.example.

Each instance has an agent block with a token_file and command_timeout_ms. Install the HAPI agent on that HAProxy host with the same instance ID and token. The host opens outbound HTTPS requests to HAPI and accesses its local UNIX socket directly; no SSH account, host keys, socat, or inbound agent port is needed. Tokens must be unique per instance and contain at least 32 random characters. Credentials are never returned by the dashboard API.

If the UI's ingress is one of the HAProxies HAPI manages, configure agent_listener so agents connect directly to HAPI over a dedicated HTTPS port instead of through the proxy they control; see agent connectivity.

Install with sudo bash scripts/install-agent.sh --url https://your-hapi-host --instance NODE_ID --token-file /path/to/node-token. See agent deployment for systemd, container, token provisioning, and migration instructions. This version supports one HAPI control-plane process; agent routing across replicas and Keepalived integration are deferred.

The Services view groups targets by service name across HAProxy backends and instances. For richer target labels, name servers using:

<site>_<machine>_<service>
gmr_docker105_authentik

The first segment is displayed as the site, the second as the machine, and the remaining segments as the service name. Existing server names that do not follow this convention remain visible under their backend-derived service name.

Each HAProxy instance opens on a dense runtime statistics view intended to replace the built-in /stats page for routine monitoring. It groups rows by proxy and exposes queue/session rates, cumulative sessions and traffic, denied traffic, errors, retries/redispatches, HTTP response classes, timing, health-check details, weights, downtime, and throttle. Use the Operations tab on the same page for verified state changes. The table is live data from typed show stat parsing; it does not enable HAProxy's HTTP statistics listener or expose raw Runtime API commands.

Set these on first launch to create the first administrator:

BOOTSTRAP_ADMIN_EMAIL
BOOTSTRAP_ADMIN_NAME
BOOTSTRAP_ADMIN_PASSWORD   # at least 14 characters

The insert is idempotent. Remove the bootstrap password from the runtime environment after the administrator exists. Terminate TLS at a trusted ingress and leave SECURE_COOKIES=true.

API use

Administrators create tokens in the UI. The plaintext hap_… value appears once; only its SHA-256 digest is stored. A token's entropy comes from 32 random bytes, so a fast digest does not expose it to practical offline guessing.

Use the same services, destination sites, and local servers as the Operations UI. Discover them with GET /api/v1/services, /api/v1/sites, and /api/v1/servers. The action paths are short; the JSON body selects targets:

# Preview the development service: api01 and api02 on both proxies (four targets).
curl -fsS \
  -H "Authorization: Bearer $HAPROXY_API_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"service":"api","preview":true}' \
  https://haproxy-dashboard.example/api/v1/disable

# Queue the reviewed change.
curl -fsS \
  -H "Authorization: Bearer $HAPROXY_API_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"service":"api"}' \
  https://haproxy-dashboard.example/api/v1/disable

Preview returns 200 and exact target triples. Execution returns 202 with a job id; poll GET /api/v1/operations/{id} until success, partial_failure, failure, or interrupted, and inspect its results. After the disable job finishes successfully, use /api/v1/enable with the same selector to restore the service. /api/v1/drain accepts the same selectors. Jobs continue on the server and recheck authorization and target availability before changes.

Use {"service":"sgm","site":"gmr"} to select a service at a destination site, or {"site":"gmr","confirmSite":"gmr"} for the whole site. These names are illustrative; use discovery for your environment. Whole-site execution requires the canonical site name in confirmSite; preview does not. A server selector such as {"server":"docker105","site":"gmr"} follows the UI's host action: it expands the host's services to all linked targets at that site, including other machines and external ingress. For ambiguous unassigned hosts, add instance to identify the host; linked targets still expand using the same rules.

Compact discovery and actions honor UI exclusions, naming, and site aliases. enable maps to token action ready, disable to maintenance, and drain to drain. Tokens need permission for every resolved instance/backend/server; they never silently operate on only a permitted subset. Discovery requires view. Tokens can inspect jobs created by that token; users retain their existing job access. Cookie requests require an operator account and CSRF token for changes.

Existing raw backend/server and deployment routes remain available for compatibility. Raw read endpoints retain their existing exclusion behavior. See openapi.yaml for the full contract and authenticated Scalar API reference at /api/docs. For copy-paste authentication, preview, job polling, state changes, and error checks, see Test the API with curl.

Development without Docker

Node.js 24 and PostgreSQL 17 are the tested versions.

npm install
cp config.example.yaml config.yaml
npm test
npm run dev

The UI runs on port 5173 and proxies API calls to port 8080. Production builds are served by the API process from port 8080.

Metrics and retention

The poller defaults to 10 seconds and enforces a minimum of 5 seconds. It stores selected numeric fields rather than raw runtime dumps. Historical queries return one-minute buckets. metric_retention_days controls sample deletion; the default is 30 days. For larger fleets, partition metric_samples by time or move the same narrow sample schema to a time-series store.

Runtime compatibility

The implementation follows the HAProxy 3.0 management guide. HAProxy 3.0 supports administrative ready, drain, and maint; forced health up, stopping, and down; and forced agent up and down. It does not advertise health ready or agent ready, so those commands are not emitted.

show sess is deliberately on-demand and operator-only because its output is unstructured, can be very large, and can be expensive on busy proxies.

Tests

npm test covers runtime CSV/info/server-state parsing, backend mapping, resource authorization, role enforcement, invalid actions and resource names, idempotency, verified transitions, runtime/socket rejection, deployment preflight, and partial multi-instance failure reporting. The Compose stack is the integration environment for real agent, UNIX socket, and HAProxy behavior.

Project layout

src/server/runtime/   typed HAProxy client, parsers, agent transport
src/server/agent/     outbound worker, command broker, local socket client
src/server/services/  serialized and multi-instance operations
src/server/           authentication, API, poller, database
src/ui/               React operations console
migrations/           PostgreSQL migrations
dev/haproxy/          integration HAProxy/agent image and sample config
dev/tokens/           disposable development-only agent credentials
openapi.yaml          deployment API contract

Safety and administration updates

Use docker compose -f compose.development.yaml up --build for the disposable demo. Production uses docker compose -f compose.production.yaml up --build after configuring .env, config.yaml, and the mounted agent tokens. There is intentionally no ambiguous default Compose file.

  • Monitoring reads require view and honor instance/backend/server scopes. Restricted reads omit unscoped process and backend totals. Tokens can inspect their own operation jobs without view.
  • Forwarded client addresses are ignored by default. Set TRUSTED_PROXIES to the specific ingress IPs/CIDRs and block access around that ingress.
  • Maintenance, drain, forced health, and agent operations share PostgreSQL-backed serialization. Operations may leave zero READY/UP targets. Resource preflight, authorization, audit recording, and runtime verification still apply.
  • Runtime changes record an audit intent before writing. A failed intent prevents the write. After a timeout, outcome: unknown means inspect runtime state before retrying. changed_audit_failed means the runtime state was verified but its audit outcome was not saved.
  • Site actions preview the whole target list and queue durable server jobs. The Operations page shows progress and results after navigation or reload. Interrupted jobs are marked for inspection and are never automatically replayed.
  • Accounts supports local user creation, role changes, activation/deactivation, and protection of the final administrator. My account changes your password and signs out every session.
  • API tokens supports explicit resource scopes, expiration, and revocation. The API still allows deliberate non-expiring tokens; the UI requires an expiry and defaults to view-only access.
  • Audit displays source IP addresses and supports search (including IP addresses) and cursor pagination. Entries without a recorded IP show a dash. Credential/account mutations and their audit entries commit together.
  • History shows one-minute averages and counter increments, including reset handling. Counter fields returned by the metrics API are now increments per bucket; update clients that previously treated bytes as cumulative totals.
  • Active offline/degraded/stale alerts appear in the dashboard and /api/v1/alerts. External notifications are not configured automatically.

/healthz is process liveness. /readyz checks the database and recent poll completion; remote HAProxy failures remain dashboard alerts, rather than causing application restart loops. ENVIRONMENT_LABEL controls the dashboard heading. Polling overrides are validated (5–300 seconds).

Run npm test, npm run typecheck, and npm run build. npm run test:integration creates a fresh Docker Compose project, exercises PostgreSQL and real HAProxy through outbound agents, and removes only that test project's containers and volume. The runner uses an isolated Docker network without publishing ports and requires Docker Compose v2.

Back up the database before upgrading. New migrations add audit outcome values, metric reset metadata, durable jobs, and case-insensitive account uniqueness. Resolve accounts whose emails differ only in letter case before upgrading; the uniqueness migration deliberately fails on them.

Dashboard navigation and history

The dashboard remembers the current page, selected instance, statistics view, filters, and vertical scroll position in the current browser tab across refreshes. Runtime statistics show all matching rows. Single-target changes use a confirm/cancel dialog; full-site operations still require the site name after preflight.

The recent-actions sidebar lists the last 14 audit outcomes (excluding intent records), newest first, and refreshes every 10 seconds. Administrators see all accounts; other signed-in users see their own actions. API tokens cannot access this history endpoint (GET /api/v1/history).

Resource counters show unique backend names as services and count server targets separately per HAProxy instance. Maintenance is excluded from the Down count; Drain and Down can overlap. Instance views show instance totals; other pages show fleet totals. Status colors follow HAProxy's statistics palette: green READY/UP, brown maintenance, blue drain, and red DOWN.

Internal sites and an external HAProxy

Operations groups local application targets and external entry points by service. The Servers section contains internal hosts only. A state filter selects matching cards while retaining the card's other targets for context. A site filter narrows the targets shown and selected by card-level bulk actions. The top “All SITE” controls always cover every mapped target at that site, including its external routes. Disable means HAProxy maintenance; it does not shut down a host or modify configuration files.

For each entry in haproxy_instances, set tier: internal (the default) or tier: external. An internal proxy can also have site: gmr or site: rda. Existing site_machine_service server names still work. When actual runtime names do not follow that convention, use exact target_labels entries under the owning instance:

# Add beneath the external instance's existing agent settings.
tier: external
target_labels:
  - backend: public_sgm       # actual external backend name
    server: gmr_entry        # actual external server name
    service: sgm             # common service label across all three proxies
    site: gmr               # destination site, not the rented proxy's location
    machine: ha
  - backend: public_sgm
    server: rda_entry
    service: sgm
    site: rda
    machine: ha

These are illustrative names, not production connection details. Add equivalent mappings for other services or nonconforming internal targets. Labels are display/grouping metadata; all commands retain their original instance/backend/server identity. Full-site actions require typed confirmation. Service and server bulk actions preview their exact target list and use button confirmation.

Service operations display one row per machine and destination site; replica copies on multiple local proxies share the row. External ingress routes display as ha · site. Local machine actions submit only the selected machine’s backend/server entries across proxies as one audited job; other machines running the same service are excluded. Third-node targets are included only when their exact runtime backend and server names match the selected machine; differently named ingress routes (such as gmr_ha_ittools for gmr_themis_ittools) remain unchanged. External row actions select matching runtime backend/server copies. Another site's targets are excluded. The preview lists every affected instance/backend/server. Mixed states keep the action available until all linked targets reach the requested state.

The conventional site_ha_service name identifies an external route when no explicit instance tier overrides it. For differing site labels, configure a root-level site_aliases mapping from the legacy label to its canonical destination site. This changes grouping only, never runtime resource names. Destination sites come from target labels or server designations before falling back to the owning proxy's site. Do not infer GMR/RDA from proxy location: each local proxy can contain routes for both sites.

Administrators manage a global exclusion list under Control → Exclusions (initially IPSec, Redis). Each entry is a case-insensitive name fragment; matching backends, frontends, and services are hidden for every user across operations, runtime statistics, backend tables, and resource counters, and are excluded from bulk-action lists. The list is stored in PostgreSQL (GET/PUT /api/v1/settings/exclusions), changes are audited as update_exclusions, and the compact API discovery/action routes apply the same exclusions. Existing raw API reads remain unfiltered by this list. Runtime statistics display the native HAProxy status without a separate READY badge.

Administrators configure the sidebar's HAProxy stats links under Control → Stats pages. Add, edit, or remove labels and HTTP/HTTPS URLs, then select Save for everyone. Links are stored in PostgreSQL (GET/PUT /api/v1/settings/stats-links) and refresh for all users; changes are audited as update_stats_links. Removing every page hides the sidebar section. Migration 006_stats_links.sql preserves the former links as initial editable values.

Certificate renewal through agents

Administrators can use Certificates to discover loaded certificates per proxy, inspect names, issuer, expiry, fingerprint and SNI bindings, upload a leaf-first PEM chain and unencrypted PEM key, select an existing certificate on each proxy, and apply. Each proxy returns its own outcome; a fleet update is not atomic. Refresh before retrying an unknown outcome. No SSH or reload is used.

The dashboard exposes GET /api/v1/certs and PUT /api/v1/certs/{id}. PUT accepts certificate, key, and targets: [{instance, id, expectedFingerprint}] (the URL id is the first target's id). Certificate IDs are SHA-256 hashes of loaded paths. The agent dispatches GET /v1/certs and PUT /v1/certs/{id} over its existing outbound authenticated polling channel; these are logical agent requests, not a new listening HTTP server. Existing agents must be upgraded for this feature. API tokens and non-administrator accounts cannot access these routes.

To enable persistence, provision a dedicated certificate directory on each host:

  • Set HAPI_CERT_DIRS to its absolute canonical path (colon-separated for multiple directories), and add those same directories to systemd ReadWritePaths. See deploy/hapi-agent-certificates.conf.example for a drop-in.
  • The directory and PEM files must be owned by hapi-agent; use directory mode 0750 and file mode 0600 or 0640, with a group readable by HAProxy when needed. The agent preserves file owner/group and permissions. It must be able to create and rename files in the directory. No world access, symlink targets, hard links, or files outside the allowlist are accepted for updates.
  • Restart the agent after changing its environment/systemd settings. Without these settings inventory is available but writes fail closed. On SELinux hosts provision a directory policy that gives new files the HAProxy-readable label, and verify agent and HAProxy access before enabling renewal.
  • Use combined PEM files containing the certificate, chain and private key. Separate .key/OCSP/SCT sidecars and multi-process HAProxy setups require separate operational handling and are not managed by this feature.

The agent validates parsing, chain issuer order/signatures, key matching, validity periods, preservation of existing SAN coverage (or CN fallback), and the expected runtime fingerprint. Trust roots are not validated. It rejects runtime/disk drift. Inventory uses show ssl cert; issuer falls back to the matching on-disk certificate. Binding details use show ssl sni when supported; older HAProxy versions show usage status and explicitly mark binding details unavailable.

Updates stage a private, fsynced file, use set ssl cert, atomically replace the file, then commit ssl cert and verify the active fingerprint. A failure attempts to restore and verify both old copies; failed recovery is reported as unknown. Only one certificate update runs per agent at a time. External certificate writers must be coordinated separately. A host/process crash between disk replacement and runtime commit can leave the new disk certificate awaiting restart; runtime/disk drift prevents another update until reconciled. Audit events record old and new fingerprints, identity, target and outcome, never PEM or private keys. Uploaded key material is not stored in the dashboard database or browser storage.

Run npm run test:certificates with local Docker access and OpenSSL to verify a disposable HAProxy 3.0 hot swap and persistence across restart. No ports are published and the configured fleet is never contacted.