mirror of
https://github.com/taylanbakircioglu/haproxy-openmanager.git
synced 2026-09-20 17:43:29 +00:00
02b1cb2bca
Closes #13, Closes #14. This release squashes the v1.4.0 → v1.5.0 development line. v1.4.0 shipped the ACME stability & enterprise audit (Issues #10/#11/#12). v1.5.0 builds on that foundation with two co-equal headline features plus a 22-round audit campaign hardening the prior configuration surface. License remains MIT for v1.5.0 (relicense to AGPL-3.0 lands in v1.5.2). ------------------------------------------------------------------ HEADLINE FEATURE A — ACME Diagnostic Panel (Issue #13) ------------------------------------------------------------------ A live pre-flight + post-failure diagnostic surface for every ACME order, reachable from the ACME Automation page. The panel exists to make ACME failures legible to operators who do NOT have shell access to the API host. Endpoints (`backend/routers/acme_diagnostics.py`): POST /api/letsencrypt/orders/{order_id}/diagnostics Run the full 5-check suite (DNS / port-80 / routing / account / agents) and humanize the order's `error_detail` (>=11 RFC-8555 problem types, backwards compatible with legacy plain-string failures). POST /api/letsencrypt/orders/{order_id}/diagnostics/ {check_id}/rerun Re-run a single check in place — used by the "Re-run" button on every row of the modal's pre-flight table. GET /api/letsencrypt/orders/{order_id}/events Merged event timeline combining the typed `acme_order_events` rows with correlated `user_activity_logs` entries (resource_type = 'letsencrypt_order' AND resource_id = order_id). The diagnostic modal auto-tails this timeline every 5 seconds while open. Service-level checks (`backend/services/acme_diagnostics.py`): * DNS resolution via stdlib socket.gethostbyname_ex through run_in_executor (intentionally avoiding an aiodns runtime dep for v1.5.0). * Port-80 HEAD probe, target locked to the order's domains, success on HTTP 200 OR 404, warns on egress timeout (corp egress policies routinely blackhole outbound 80 — fail-hard would be too noisy). * SSRF guard: probe refuses non-public IPs and surfaces the skip in the diagnostic result; IPv4-mapped IPv6 normalisation closes the `::ffff:169.254.169.254` cloud-metadata vector. * HAProxy routing presence check: matches the order's cluster_ids to a port-80 HTTP frontend. * ACME account validity check against `letsencrypt_accounts`. * Agent presence check (>=1 active agent in target cluster). * Every sub-check wrapped in a wall-clock timeout to bound impact on the API event loop. RBAC: ssl.read for run, ssl.read for events. Per-user 5/min rate limit on both run and rerun, backed by the (user_id, action, created_at DESC) composite index. Frontend (`frontend/src/components/ACMEAutomation.js`): * "Diagnose" button on every order row + the existing "stuck order" warning row. * Modal with two tabs: - Pre-flight Checks (Antd Table with status pills + Re-run buttons + humanized error banner) - Event Log (Antd Timeline with auto-tail polling, scroll- to-bottom, pause-on-hover) * Correlation IDs surfaced in error banners and individual check fail details for backend-log lookup. ------------------------------------------------------------------ HEADLINE FEATURE B — Site Setup Wizard (Issue #14) ------------------------------------------------------------------ A single guided flow that creates a Backend + Servers + HTTP Frontend (and optional HTTPS Frontend) in one atomic transaction. Endpoints (`backend/routers/site_wizard.py`): POST /api/site-wizard/preview — diff-preview the changeset POST /api/site-wizard/create — atomic execute POST /api/site-wizard/reject — clean rollback (including any wizard_staged ACME orders) GET /api/site-wizard/drafts — draft persistence PUT /api/site-wizard/drafts/{id} — save/update DELETE /api/site-wizard/drafts/{id} Feature surface: * One screen captures both backend (mode + servers) AND frontend (http + optional https + SSL mode) inputs. * SSL modes: ACME (new order, HTTP-01 only for v1.5.0), Upload (existing PEM), Existing (link to a stored cert), or None. * ACME-staged path: wizard_staged_until watermark on the `letsencrypt_orders` row defers finalisation until agent confirmation; per-mode reject cleanly cancels and rolls back the staged order. * Live diff preview against the cluster's current generated config (renderer-evolution noise stripped — track-sc<N> dedup, per-server cookie strip, defaults-cookie inheritance, listen-block flattening). * Draft persistence with PEM stripped at save time (private keys never round-trip through the drafts table). * Per-cluster multi-tenancy: drafts and wizard_staged orders are isolated to the creating user's cluster scope. Frontend (`frontend/src/components/SiteWizard.js`): * 4-step Antd Steps flow: Backend → Frontend → SSL → Review. * Render the live diff preview inline before commit. * Antd Form-level validation mirrors backend Pydantic validators (numeric bounds, HAProxy reserved keywords, ALPN consistency, IPv6 scope-id, domain regex, server name dedup). ------------------------------------------------------------------ AUDIT CAMPAIGN — Rounds 1 → 22 (Bulgu #1 → #82) ------------------------------------------------------------------ v1.5.0 includes 22 adversarial review passes. Each round produced its own commit set in the corporate development line; this squash collapses those into the v1.5.0 release artefact. Highlights: Round 1-4 Site Wizard core: dry-run parity, single-line value injection guard, ACL -f pattern-file block, SSL parity, timeout regex, form-state pin. Round 5-7 defaults-cookie inheritance, server-named-cookie guard, fe/be mode mismatch, duplicate server names, health_check_uri + server_address validators. Round 8-10 cookie_name / cookie_options newline-injection guard, dry-run parity (round 9), TCP-mode HTTP-only feature blockers. Round 11 SSL name path traversal + health-check >= 1. Round 12-13 SSL & ACME deep dive (Bulgu #23-#32). Round 14 single-line value injection (Bulgu #33). Round 15-17 ACME multi-tenant UX, numeric bounds, HAProxy reserved keywords, ALPN/TLS consistency, all-backup, multi-domain & multi-user enterprise edges, drain/HSTS/post-completion (Bulgu #34-#53). Round 18-21 concurrency, agent state, TCP-mode HTTP-only, list size caps, IPv6 scope-id, preview account validation, TCP backend + balance uri reject (Bulgu #54-#61). Round 22 FE error visibility + 3x stale-data lockouts, referential integrity + cascade safety, authentication & authorization, multi-cluster isolation, apply_pending_changes concurrency, script injection + bulk import multi-tenancy, prefix-stripped signature comparison (Bulgu #62-#82). ------------------------------------------------------------------ NO CORPORATE-SPECIFIC ARTIFACTS ------------------------------------------------------------------ This squash deliberately sanitises corporate hostnames, container registry references, and TLS secret names into generic placeholders (`your-registry.example.com/your-org`, `haproxy-openmanager*.example.com`, `wildcard-tls`, `taylanbakircioglu/haproxy-openmanager-*`) so the public artefact contains no internal infrastructure detail. Pilot / development history that retained those values stays in the corporate fork and is NOT part of this commit.
383 lines
14 KiB
Python
383 lines
14 KiB
Python
from fastapi import APIRouter, HTTPException, Header, Query
|
|
from typing import Optional
|
|
from pydantic import BaseModel
|
|
import logging
|
|
from datetime import datetime, timedelta
|
|
|
|
from database.connection import get_database_connection, close_database_connection
|
|
from auth_middleware import get_current_user_from_token, validate_agent_api_key
|
|
from utils.activity_log import log_user_activity
|
|
|
|
router = APIRouter(prefix="/api/configuration", tags=["configuration"])
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# ====== REQUEST/RESPONSE MODELS ======
|
|
|
|
class ConfigResponse(BaseModel):
|
|
request_id: int
|
|
config_content: str
|
|
config_path: str
|
|
|
|
# ====== USER ENDPOINTS (Frontend -> Backend) ======
|
|
|
|
@router.post("/request")
|
|
async def create_config_request(
|
|
agent_name: str = Query(..., description="Agent name"),
|
|
cluster_id: int = Query(..., description="Cluster ID"),
|
|
request_type: str = Query(..., description="Request type: 'view' or 'download'"),
|
|
authorization: str = Header(None)
|
|
):
|
|
"""
|
|
Create a configuration request for an agent.
|
|
User initiates this from the Configuration Management page.
|
|
"""
|
|
try:
|
|
current_user = await get_current_user_from_token(authorization)
|
|
|
|
conn = await get_database_connection()
|
|
|
|
# Get agent info and verify it belongs to the cluster
|
|
agent_info = await conn.fetchrow("""
|
|
SELECT a.id, a.name, a.status, a.pool_id
|
|
FROM agents a
|
|
WHERE a.name = $1
|
|
""", agent_name)
|
|
|
|
if not agent_info:
|
|
await close_database_connection(conn)
|
|
raise HTTPException(status_code=404, detail=f"Agent '{agent_name}' not found")
|
|
|
|
# Verify cluster belongs to agent's pool
|
|
cluster_info = await conn.fetchrow("""
|
|
SELECT id, name, pool_id
|
|
FROM haproxy_clusters
|
|
WHERE id = $1
|
|
""", cluster_id)
|
|
|
|
if not cluster_info:
|
|
await close_database_connection(conn)
|
|
raise HTTPException(status_code=404, detail=f"Cluster ID {cluster_id} not found")
|
|
|
|
if cluster_info['pool_id'] != agent_info['pool_id']:
|
|
await close_database_connection(conn)
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail=f"Agent '{agent_name}' does not belong to cluster '{cluster_info['name']}'"
|
|
)
|
|
|
|
if agent_info['status'] != 'online':
|
|
await close_database_connection(conn)
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail=f"Agent '{agent_name}' is not online (status: {agent_info['status']})"
|
|
)
|
|
|
|
# Check for existing pending requests
|
|
existing_request = await conn.fetchrow("""
|
|
SELECT id FROM agent_config_requests
|
|
WHERE agent_name = $1 AND status IN ('pending', 'processing')
|
|
AND expires_at > CURRENT_TIMESTAMP
|
|
LIMIT 1
|
|
""", agent_name)
|
|
|
|
if existing_request:
|
|
await close_database_connection(conn)
|
|
return {
|
|
"request_id": existing_request['id'],
|
|
"status": "existing",
|
|
"message": "A config request is already pending for this agent"
|
|
}
|
|
|
|
# Create new request
|
|
request_id = await conn.fetchval("""
|
|
INSERT INTO agent_config_requests (
|
|
agent_id, agent_name, cluster_id, request_type, status, requested_by
|
|
) VALUES ($1, $2, $3, $4, 'pending', $5)
|
|
RETURNING id
|
|
""", agent_info['id'], agent_name, cluster_id, request_type, current_user['id'])
|
|
|
|
await close_database_connection(conn)
|
|
|
|
# Log activity
|
|
await log_user_activity(
|
|
user_id=current_user['id'],
|
|
action='config_request',
|
|
resource_type='agent',
|
|
resource_id=str(agent_info['id']),
|
|
details={
|
|
'agent_name': agent_name,
|
|
'cluster_id': cluster_id,
|
|
'cluster_name': cluster_info['name'],
|
|
'request_type': request_type,
|
|
'request_id': request_id
|
|
}
|
|
)
|
|
|
|
logger.info(f"📄 CONFIG REQUEST: Created request #{request_id} for agent '{agent_name}' in cluster '{cluster_info['name']}' (type: {request_type})")
|
|
|
|
return {
|
|
"request_id": request_id,
|
|
"agent_name": agent_name,
|
|
"request_type": request_type,
|
|
"status": "pending",
|
|
"message": "Configuration request created successfully. Agent will process it on next heartbeat."
|
|
}
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Failed to create config request: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.get("/response/{request_id}")
|
|
async def get_config_response(request_id: int, authorization: str = Header(None)):
|
|
"""
|
|
Get configuration response for a request.
|
|
Frontend polls this endpoint to check if agent has responded.
|
|
"""
|
|
try:
|
|
current_user = await get_current_user_from_token(authorization)
|
|
|
|
conn = await get_database_connection()
|
|
|
|
# Get request info
|
|
request_info = await conn.fetchrow("""
|
|
SELECT acr.id, acr.agent_name, acr.request_type, acr.status,
|
|
acr.requested_at, acr.expires_at,
|
|
acresp.config_content, acresp.config_path, acresp.file_size,
|
|
acresp.response_at
|
|
FROM agent_config_requests acr
|
|
LEFT JOIN agent_config_responses acresp ON acr.id = acresp.request_id
|
|
WHERE acr.id = $1
|
|
""", request_id)
|
|
|
|
await close_database_connection(conn)
|
|
|
|
if not request_info:
|
|
raise HTTPException(status_code=404, detail="Config request not found")
|
|
|
|
# Check if request expired
|
|
if request_info['expires_at'] < datetime.now():
|
|
return {
|
|
"request_id": request_id,
|
|
"status": "expired",
|
|
"message": "Request expired. Agent did not respond in time."
|
|
}
|
|
|
|
# Check if response is available
|
|
if request_info['config_content']:
|
|
return {
|
|
"request_id": request_id,
|
|
"agent_name": request_info['agent_name'],
|
|
"request_type": request_info['request_type'],
|
|
"status": "completed",
|
|
"config_content": request_info['config_content'],
|
|
"config_path": request_info['config_path'],
|
|
"file_size": request_info['file_size'],
|
|
"response_at": request_info['response_at'].isoformat() if request_info['response_at'] else None
|
|
}
|
|
else:
|
|
# Still pending
|
|
return {
|
|
"request_id": request_id,
|
|
"status": request_info['status'],
|
|
"message": "Waiting for agent response..."
|
|
}
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Failed to get config response: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
# ====== AGENT ENDPOINTS (Agent -> Backend) ======
|
|
|
|
@router.get("/agents/{agent_name}/pending-requests")
|
|
async def get_pending_config_requests(agent_name: str, x_api_key: Optional[str] = Header(None)):
|
|
"""
|
|
Agent calls this endpoint to check for pending config requests.
|
|
Called during heartbeat.
|
|
"""
|
|
try:
|
|
# Validate agent API key
|
|
agent_auth = await validate_agent_api_key(x_api_key)
|
|
|
|
if x_api_key and not agent_auth:
|
|
logger.warning(f"Invalid API key provided by agent '{agent_name}' for pending requests")
|
|
raise HTTPException(status_code=401, detail="Invalid API key")
|
|
|
|
conn = await get_database_connection()
|
|
|
|
# Get pending requests
|
|
requests = await conn.fetch("""
|
|
SELECT id, request_type, requested_at
|
|
FROM agent_config_requests
|
|
WHERE agent_name = $1
|
|
AND status = 'pending'
|
|
AND expires_at > CURRENT_TIMESTAMP
|
|
ORDER BY requested_at ASC
|
|
LIMIT 5
|
|
""", agent_name)
|
|
|
|
# Mark found requests as processing
|
|
if requests:
|
|
request_ids = [r['id'] for r in requests]
|
|
await conn.execute("""
|
|
UPDATE agent_config_requests
|
|
SET status = 'processing', updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = ANY($1)
|
|
""", request_ids)
|
|
|
|
logger.info(f"📄 CONFIG REQUEST: Agent '{agent_name}' picked up {len(requests)} pending request(s)")
|
|
|
|
await close_database_connection(conn)
|
|
|
|
return {
|
|
"agent_name": agent_name,
|
|
"pending_requests": [
|
|
{
|
|
"request_id": r['id'],
|
|
"request_type": r['request_type'],
|
|
"requested_at": r['requested_at'].isoformat()
|
|
}
|
|
for r in requests
|
|
]
|
|
}
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Failed to get pending config requests for agent '{agent_name}': {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
@router.post("/agents/{agent_name}/config-response")
|
|
async def submit_config_response(
|
|
agent_name: str,
|
|
response: ConfigResponse,
|
|
x_api_key: Optional[str] = Header(None)
|
|
):
|
|
"""
|
|
Agent submits the haproxy.cfg content in response to a request.
|
|
"""
|
|
try:
|
|
# Bulgu #75 (round-22 audit) — same auth-bypass fix as in
|
|
# `routers/agent.py`. Pre-fix the `if x_api_key and not
|
|
# agent_auth` short-circuited when no header was sent at
|
|
# all, letting an unauthenticated caller post arbitrary
|
|
# HAProxy-config content claiming to come from an agent.
|
|
agent_auth = await validate_agent_api_key(x_api_key)
|
|
if not agent_auth:
|
|
logger.warning(
|
|
f"Rejected config-response call for agent {agent_name!r}: "
|
|
f"missing or invalid x-api-key"
|
|
)
|
|
raise HTTPException(status_code=401, detail="Invalid or missing API key")
|
|
|
|
conn = await get_database_connection()
|
|
|
|
# Verify request exists and belongs to this agent
|
|
request_info = await conn.fetchrow("""
|
|
SELECT id, agent_name, status FROM agent_config_requests
|
|
WHERE id = $1 AND agent_name = $2
|
|
""", response.request_id, agent_name)
|
|
|
|
if not request_info:
|
|
await close_database_connection(conn)
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="Config request not found or does not belong to this agent"
|
|
)
|
|
|
|
# Insert response
|
|
file_size = len(response.config_content.encode('utf-8'))
|
|
|
|
await conn.execute("""
|
|
INSERT INTO agent_config_responses (
|
|
request_id, agent_name, config_content, config_path, file_size
|
|
) VALUES ($1, $2, $3, $4, $5)
|
|
ON CONFLICT DO NOTHING
|
|
""", response.request_id, agent_name, response.config_content, response.config_path, file_size)
|
|
|
|
# Update request status
|
|
await conn.execute("""
|
|
UPDATE agent_config_requests
|
|
SET status = 'completed', updated_at = CURRENT_TIMESTAMP
|
|
WHERE id = $1
|
|
""", response.request_id)
|
|
|
|
await close_database_connection(conn)
|
|
|
|
logger.info(f"CONFIG RESPONSE: Agent '{agent_name}' submitted config for request #{response.request_id} (size: {file_size} bytes)")
|
|
|
|
return {
|
|
"status": "ok",
|
|
"message": "Configuration response received successfully",
|
|
"request_id": response.request_id
|
|
}
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"Failed to submit config response from agent '{agent_name}': {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
# ====== CLEANUP ENDPOINT ======
|
|
|
|
@router.delete("/cleanup-expired")
|
|
async def cleanup_expired_requests(authorization: str = Header(None)):
|
|
"""
|
|
Cleanup expired config requests and responses.
|
|
Called by scheduled job or manually.
|
|
|
|
Bulgu #78 (round-22 audit) — pre-fix this endpoint had NO
|
|
auth at all. Any unauthenticated caller could DROP rows
|
|
from `agent_config_requests` / `agent_config_responses`,
|
|
which directly drives the cluster's "what did the operator
|
|
ask the agent to fetch" history. Restrict to admin users —
|
|
legitimate callers are an internal scheduled job (which
|
|
can supply an admin bearer) or a human admin pressing
|
|
Maintenance → Cleanup in the UI.
|
|
"""
|
|
try:
|
|
from auth_middleware import get_current_user_from_token
|
|
current_user = await get_current_user_from_token(authorization)
|
|
if not current_user.get("is_admin", False):
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail="Only admin users can run cleanup-expired"
|
|
)
|
|
conn = await get_database_connection()
|
|
|
|
# Delete expired responses
|
|
deleted_responses = await conn.fetchval("""
|
|
DELETE FROM agent_config_responses
|
|
WHERE expires_at < CURRENT_TIMESTAMP
|
|
RETURNING count(*)
|
|
""")
|
|
|
|
# Delete expired requests
|
|
deleted_requests = await conn.fetchval("""
|
|
DELETE FROM agent_config_requests
|
|
WHERE expires_at < CURRENT_TIMESTAMP
|
|
RETURNING count(*)
|
|
""")
|
|
|
|
await close_database_connection(conn)
|
|
|
|
logger.info(f"🧹 CLEANUP: Deleted {deleted_responses or 0} expired responses and {deleted_requests or 0} expired requests")
|
|
|
|
return {
|
|
"status": "ok",
|
|
"deleted_responses": deleted_responses or 0,
|
|
"deleted_requests": deleted_requests or 0
|
|
}
|
|
|
|
except Exception as e:
|
|
logger.error(f"Failed to cleanup expired data: {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|