Commit Graph

142 Commits

Author SHA1 Message Date
taylanbakircioglu 08c500855e fix: rewrite uninstall scripts - simple and reliable
Replaced overcomplicated 380-line scripts with clean ~125-line versions.
Steps: stop service, kill processes (excluding self), remove binary,
remove config/logs/temps, verify. No emojis, no fragile helpers.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu b7dde62972 fix: prevent uninstall script from killing itself via pgrep
pgrep -f "haproxy-agent" was matching the uninstall script's own
process (uninstall-haproxy-agent-linux.sh contains "haproxy-agent"),
causing the script to terminate itself at step 1/7 before reaching
file cleanup. Now filters out $$ (own PID) and $PPID from kill lists.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu 5cec6cf85a fix: remove emojis from all agent scripts and fix install/uninstall bugs
- Remove all emoji characters from install scripts (linux, macos)
- Rewrite uninstall scripts: remove set -e, fix safe_remove to always
  return 0, replace ((var++)) with $((var + 1)), fix local keyword
  usage, add comprehensive cleanup including config.json
- Fix install script QUIET_MODE/DAEMON_MODE detection to correctly
  handle interactive runs when old config.json exists

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:29 +03:00
taylanbakircioglu 6349f1ad7c fix: exclude disabled (OFF) agents from sync calculations
Disabled agents were blocking apply sync progress indefinitely because
they were counted in total_agents but could never report as synced.

Backend:
- agent-sync endpoint: disabled agents excluded from total/synced/unsynced
  counts, added disabled_agents and total_agents_including_disabled fields
- SSL cert agent-sync endpoint: same disabled agent exclusion
- Both endpoints still return disabled agents in the list with
  sync_excluded: true for UI display

Frontend:
- ApplyManagement: cluster sync complete logic handles 0 enabled agents,
  all updateEntityCounts calls pass disabled count, agent table shows
  OFF/Excluded tags for disabled agents
- GlobalProgress: shows "(X off)" indicator, visible even when all
  agents are disabled
- ProgressContext: agentCounts state supports disabled field
- agentSync utility: verifyRealAgentSync treats null/0-agent sync_status
  as synced (nothing to wait for)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 16:45:28 +03:00
taylanbakircioglu 946b1a8e84 fix: Default Backend select filterOption crash on search
Fixed TypeError "t.children.toLowerCase is not a function" when searching
in Default Backend dropdown after editing a frontend.

Root cause: option.children was a React element array (multiple JSX parts),
not a string, so toLowerCase() failed.

Solution: Added label prop to Option and use optionLabelProp="label" pattern
(consistent with SSL Certificates Select in same file).

Changes:
- Added optionLabelProp="label" to Select component
- Added label={backendLabel} to each Option
- Changed filterOption to use option.label instead of option.children
- Users can now search by backend name, server count, or "No servers"
2026-01-28 16:04:42 +03:00
taylanbakircioglu eac00b3e39 fix: consistent section header detection in listen extraction
Additional fix for listen block extraction:
- Section boundary check now uses ([[:space:]]|$) pattern
- Previously only checked [[:space:]], missing 'defaults' at end of line
- Ensures listen extraction stops correctly at any section header

Pattern consistency verified across all 4 locations:
- Linux install mode: global, defaults, listen extraction ✓
- Linux daemon mode: global, defaults, listen extraction ✓
- macOS install mode: global, defaults, listen extraction ✓
- macOS daemon mode: global, defaults, listen extraction ✓

Edge cases tested:
- Named defaults (defaults http): works correctly
- Multiple listen blocks: all preserved
- Tab characters: handled by [[:space:]]
- User's actual config structure: produces clean merge

No impact on other agent functions (self-upgrade, metrics, etc.)
2026-01-26 15:25:16 +03:00
taylanbakircioglu 25408a618e fix: awk patterns now match keywords at end of line
CRITICAL BUG FIX:
- Previous pattern `/^defaults[[:space:]]/` required whitespace after keyword
- HAProxy allows `defaults` without a name (no trailing whitespace)
- Pattern failed to match, causing global extraction to include defaults section

New pattern uses `([[:space:]]|$)`:
- Matches keyword followed by whitespace OR end of line
- `defaults` (no name) now correctly triggers exit
- `defaults http` (named) also correctly triggers exit

Test results:
- Old pattern: extracted 8 lines (included defaults) 
- New pattern: extracted 4 lines (stopped at defaults) 
2026-01-26 15:25:16 +03:00
taylanbakircioglu 995d87df43 fix: defaults extraction captures only first defaults section
CRITICAL BUG FIX:
- Previous awk pattern allowed multiple defaults sections to be captured
- Pattern `!/^defaults/` meant "don't exit if line IS defaults"
- This caused duplicate defaults when config had listen before defaults

New pattern uses `started` flag:
- First `defaults` line: set started=1, begin capturing
- Second `defaults` line: started is set, EXIT immediately
- Any `frontend/backend/listen`: started is set, EXIT

Also includes: debug logging for validation error storage with fallback

Tested scenarios:
- Normal config (defaults → listen → frontend): ✓
- Listen before defaults: ✓
- Two defaults sections: ✓ Only first captured
- No defaults section: ✓ Empty output
- Defaults at end of file: ✓
- Empty defaults section: ✓
2026-01-26 15:25:15 +03:00
taylanbakircioglu 4a6bc1b139 fix: global section extraction includes listen blocks when listen comes before defaults
Bug: When haproxy.cfg has 'listen stats' BEFORE 'defaults' section,
the global extraction incorrectly included listen stats because it
only stopped at 'defaults', not at any section header.

Fix: Changed extraction to stop at ANY section (defaults/listen/frontend/backend)
This prevents duplicate listen blocks in merged config.

Root cause of 'proxy stats has same name as proxy stats' HAProxy validation error.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 83204c86a8 fix: critical security and UX improvements for config management
SECURITY FIX (agent.py):
- Ensure ONLY APPLIED versions are sent to agents
- Fixed fallback query that could return PENDING versions
- Agents will never receive unapproved configurations

UX FIX (cluster.py):
- Clear validation_error when creating new version via Apply
- Prevents stale validation errors from showing after re-apply

UX FIX (agent.py):
- Clear validation_error when agent successfully applies config
- Clear last_validation_error on agent record after success
2026-01-26 15:25:15 +03:00
taylanbakircioglu 1dcf45b1bb fix: dynamic collision detection in config generation
Query agent preserved_listen_blocks dynamically and skip
conflicting entities to prevent HAProxy validation errors.

Falls back to static reserved list if no agent data available.
2026-01-26 15:25:15 +03:00
taylanbakircioglu e75bfdf706 feat: dynamic HAProxy binary path from cluster configuration
- /api/agents/{name}/config now returns haproxy_bin_path, haproxy_config_path, stats_socket_path from cluster
- Agent daemon uses these dynamic paths from API response for validation
- Fallback to local config file if API values not present
- Allows cluster admin to change paths without reinstalling agents

This fixes validation when HAProxy binary is in non-standard location
2026-01-26 15:25:15 +03:00
taylanbakircioglu 97e32114e0 fix: translate Turkish error messages to English
- Updated SUGGESTION_TEMPLATES in haproxy_error_parser.py
- Fixed fallback error messages in cluster.py
- Product language should be English throughout
2026-01-26 15:25:15 +03:00
taylanbakircioglu 095c682fa3 fix: handle soft-deleted entities in bulk import and frontend deletion
Bulk Import Fix (config.py):
- Check for existing servers (including soft-deleted) before INSERT
- If server exists: UPDATE and reactivate instead of INSERT
- Create snapshot for ALL updated servers (enables reject/rollback)
- Add backend_name to UPDATE for field consistency
- Track updated/reactivated servers in response
- Prevents duplicate key constraint violation on re-import

Frontend Deletion Fix (frontend.py):
- Add hard delete support for already soft-deleted frontends
- Follows same pattern as backend.py hard delete
- Deletes WAF associations and config versions before frontend
- Works with existing orphan cleanup in Apply/Reject flows

Both fixes are safe because:
- Orphan version cleanup handles hard-deleted entities in Apply/Reject
- Consistent with existing backend.py patterns
- Snapshot-based rollback fully supported
2026-01-26 15:25:15 +03:00
taylanbakircioglu ecbaebf451 feat: report invalid config format errors to backend for UI display
When config content doesn't look like valid HAProxy config (missing
global/defaults/frontend/backend/listen keywords), agent now reports
this to backend via config-validation-failed endpoint.

This catches backend-side config generation errors (like Python
exceptions) that prevented actual HAProxy config from being generated.

Changes:
- Add invalid config format detection and reporting in daemon mode
- Use same curl pattern as existing HAProxy validation failure reporting
- Same endpoint, headers, error handling, and spam prevention
- Follows exact existing pattern for consistency
- Does not affect self-upgrade flow (runs before upgrade check)

Both linux and macos scripts updated identically.
2026-01-26 15:25:15 +03:00
taylanbakircioglu d40c701272 fix: resolve Python scoping error in config generation
Remove redundant local 'import json' statements that caused:
"cannot access local variable 'json' where it is not associated with a value"

Root cause: Local import inside try block made 'json' a local variable,
but except clause referenced json.JSONDecodeError before assignment.

Changes:
- Line 197: Remove local import, use global json (line 5)
- Line 514: Remove 'import json as _json', use global json
- Use ValueError instead of json.JSONDecodeError (equivalent, JSONDecodeError
  is a subclass of ValueError)

This was causing config generation to fail completely, returning error
message as config content instead of actual HAProxy configuration.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 5947caa46d fix: move uninstall scripts to backend/utils/agent_scripts for deployment
- Copy uninstall-agent-linux.sh and uninstall-agent-macos.sh to
  backend/utils/agent_scripts/ (same location as install scripts)
- Update generate-uninstall-script endpoint to use the same path
  pattern as working install script endpoint
- Add container-specific fallback paths for robustness
- Add debug logging to track which path is used

Fixes 404 error when fetching uninstall script in production
where /utils/ directory at project root is not deployed.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 8076f3fcfd feat: add intelligent HAProxy validation error display in UI
- Add haproxy_error_parser.py: Parses HAProxy validation errors with
  confidence scoring, extracts entity type/name, line number, error type
- Add ValidationErrorModal.js: Rich modal with parsed error summary,
  quick fix suggestions, and manual troubleshooting guide
- Update cluster.py: Integrate error parser into agent-sync and
  config-versions endpoints with graceful fallback
- Update ApplyManagement.js: Add validation error banner with quick
  navigation buttons and error detail modal
- Update FrontendManagement.js & BackendServers.js: Handle URL params
  for deep-linking to entity edit forms with field highlighting

Enables users to see actionable validation failure details directly
in the UI without needing server access for debugging.
2026-01-26 15:25:15 +03:00
taylanbakircioglu 0c1d68eb01 feat: add uninstall script UI with modern design
- Add new API endpoint to serve uninstall scripts by platform
- Display uninstall script alongside install script in setup wizard
- Add dedicated delete agent modal with 2-step workflow
- Modern UI with gradient banners, platform icons, and info cards
- Enhanced uninstall scripts to clean all agent temp/backup files
- HAProxy service and config remain untouched during uninstall
2026-01-26 15:25:15 +03:00
taylanbakircioglu 851377aedf feat: Add HAProxy proxy name collision prevention system
- Add preserved_listen_blocks column to agents table for storing agent's local listen block names
- Implement reserved names check (stats, monitoring, admin, etc.) for frontend/backend creation
- Add dynamic collision detection against agent's preserved listen blocks
- Apply collision checks to CREATE, UPDATE endpoints and bulk import
- Add debug mode for failed config validation (saves to /tmp/haproxy-failed-*.cfg)
- Fix JSON character stripping for ACL and use_backend rules
- Remove collision protection from agent scripts (now handled by backend)
- All collision checks wrapped in try-except for backwards compatibility
2026-01-26 15:25:15 +03:00
taylanbakircioglu 5d054f3426 feat: Add random and first balance methods support
- Add 'random' and 'first' options to backend balance method selector
- Add balance method validation in config parser with warning for unknown methods
- Update API documentation with all supported balance algorithms
2026-01-26 15:25:15 +03:00
taylanbakircioglu bc8563d455 fix: Update agent token association on config change and improve Security UI
- Fix token-agent relationship not updating when agent config changes
- Agent's api_key now syncs with DB on heartbeat when using different token
- Change Security page badge color from red to blue for better UX
2026-01-26 15:25:15 +03:00
taylanbakircioglu 86c7b3a57f feat: Display HAProxy versions with agent names in Cluster Management
- Add HAProxy Version column to cluster list table
- Show version number with agent names directly (no hover required)
- Fetch agents for each cluster to get haproxy_version info
- Show warning icon (yellow) when agents have different HAProxy versions
- Green color for consistent versions, yellow for mismatched versions
- Agent names displayed below each version in smaller gray text
- UI-only change, no backend modifications
- Safe implementation using existing /api/agents endpoint
2025-12-26 15:26:46 +03:00
taylanbakircioglu 5edf53ec3e Update Docker registry to taylanbakircioglu 2025-12-24 19:11:57 +03:00
taylanbakircioglu 183b4fa9e2 fix: Auto-add 'verify none' for SSL backend servers without CA file
When ssl_enabled is true for a backend server but:
- No ssl_verify option is explicitly set AND
- No CA file (ssl_certificate_id) is specified

HAProxy 2.8+ defaults to 'verify required' which fails without a CA.
Now auto-adding 'verify none' in this case with a warning log.

Users can override this in UI by setting SSL Verification explicitly.

This fix is safe for:
- Bulk Import: Parser already sets ssl_verify='none' when removing ca-file
- Version Diff: Generated config correctly shows 'verify none'
- Restore: DB values unchanged, config regeneration applies same fix

Fixes: 'verify is enabled by default but no CA file specified' error
2025-12-23 13:28:49 +03:00
taylanbakircioglu 81d2b3b8d5 feat: Display HAProxy version in Agent Management page
- Add haproxy_version field to heartbeat payload in Linux agent script
- Add haproxy_version field to heartbeat payload in macOS agent script
- Display HAProxy version below IP address in Registered Agents list
- Safe extraction with fallback to 'unknown' if haproxy command fails
- Version is updated on every heartbeat (30s interval)
- Green color styling for easy visibility

Backend already supports haproxy_version field in AgentHeartbeat model
and saves it to database on each heartbeat.
2025-12-23 13:28:29 +03:00
Taylan Bakırcıoğlu 378710db3f fix(haproxy-config): ACL rules must come before http-request directives
CRITICAL HAProxy Validation Error Fix

Problem:
Generated HAProxy config failed validation with error:
[ALERT] error detected while parsing an 'http-request deny' condition:
no such ACL: 'waf_demo-rule1_path'.

Root Cause:
Config generator was writing http-request directives BEFORE ACL definitions.
HAProxy requires ACLs to be defined before they are referenced.

Generated Config (WRONG ORDER):
  http-request deny if waf_demo-rule1_path   ACL not defined yet!
  acl waf_demo-rule1_path path_reg ^/admin   Too late!

Fix:
Reordered frontend config generation:
1. ACL Rules (Line 339-362) - Define ACLs FIRST
2. HTTP Request Headers (Line 364-371) - Use ACLs AFTER

Generated Config (CORRECT ORDER):
  acl waf_demo-rule1_path path_reg ^/admin         Define first
  acl waf_demo-rule1_method method POST            Define first
  http-request deny if waf_demo-rule1_path waf_demo-rule1_method   Use after

Impact:
- Parsing logic: UNCHANGED (no breaking changes)
- Database storage: UNCHANGED (no schema changes)
- Config generation: FIXED (correct HAProxy syntax)
- Bulk import: Works correctly now
- Agent config apply: Validation passes

Testing:
1. Bulk import config with ACLs and http-request rules
2. Agent applies config successfully
3. HAProxy validation passes

Files Changed:
- backend/services/haproxy_config.py: Reordered ACL and request_headers generation
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 1d17dd8fd5 fix(reject): prevent deletion of existing entities on bulk import reject
CRITICAL DATA LOSS BUG FIX

Problem:
- User updates existing entity via bulk import
- User clicks Reject
- EXPECTED: Entity reverts to old values
- ACTUAL: Entity is COMPLETELY DELETED!

Root Cause:
Reject logic tracked ALL bulk import entities for force deletion.
Did not distinguish between CREATE and UPDATE operations.

Fix:
Added operation check - only track CREATE operations for force deletion.
UPDATE operations are rolled back, not deleted.

Impact:
- CREATE scenarios: No change in behavior
- UPDATE scenarios: Data loss prevented
- Mixed CREATE+UPDATE: Only CREATE entities deleted
- Rollback failures: Safety mechanism preserved

Files Changed:
- backend/routers/cluster.py: Line 4494 added operation check
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 589f865f59 fix(ssl): rollback support + improved ALPN validation error message
PART 1: Rollback Support for SSL Advanced Options
===================================================
Problem: SSL advanced options lost on reject/rollback operations

Root Cause:
- Snapshot creation uses SELECT * (includes all fields) 
- old_values contains SSL advanced options 
- Rollback UPDATE did NOT restore SSL fields 

Impact - Frontend:
- User changes ssl_alpn, then clicks Reject
- Rollback skipped: ssl_alpn, ssl_npn, ssl_ciphers, ssl_ciphersuites, ssl_min_ver, ssl_max_ver, ssl_strict_sni
- Result: All SSL advanced options lost (set to NULL)

Impact - Backend Server:
- User changes ssl_min_ver='TLSv1.2', then clicks Reject
- Rollback skipped: ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers
- Result: Security issue - TLS version constraints removed!

Fix:
- backend/utils/entity_snapshot.py line 285-286: Added 7 frontend SSL fields to rollback UPDATE
- backend/utils/entity_snapshot.py line 458: Added 4 server SSL fields to rollback UPDATE

PART 2: Improved ALPN Validation Error Message
===============================================
Problem: User enters 'http/2' in ALPN field, gets generic error

User feedback: Tried 'h2,http/1.1,http/2' → validation error not clear

Root Cause:
- ALPN standard uses 'h2' for HTTP/2 (not 'http/2')
- Validator rejected 'http/2' but didn't explain the correct format

Fix:
- backend/models/frontend.py line 255-260: Detect common mistakes (http/2, http2, http-2)
- Provide helpful error: 'For HTTP/2, use "h2" (not "http/2")'

Before:
  "Invalid ALPN protocol: http/2. Valid protocols: h2, http/1.1, ..."

After:
  "Invalid ALPN protocol: http/2. For HTTP/2, use 'h2' (not 'http/2'). Valid protocols: ..."

Testing:
1. Rollback test: Edit frontend SSL, reject, verify SSL fields restored
2. Validation test: Enter 'http/2', verify friendly error message

Files Changed:
- backend/utils/entity_snapshot.py: _rollback_update() for frontend and server
- backend/models/frontend.py: validate_alpn() with better error messages
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 8e1a93f873 fix(ssl): add backend server SSL advanced options to haproxy config generation
CRITICAL BUG FIX: Backend server SSL advanced options not in generated HAProxy config

Problem:
- Database has ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers columns 
- Config generation code tries to write them to HAProxy config (line 680-687) 
- BUT SELECT statement did NOT include these fields 
- Result: server.get('ssl_sni') always returned None

Impact:
- User sets 'TLS Min Version: TLSv1.2' for backend server in UI
- Value saved to database correctly
- BUT generated HAProxy config missing 'ssl-min-ver TLSv1.2'
- Agent deploys incomplete config, SSL settings lost!

Solution:
- Added 4 server SSL advanced options to SELECT query (line 616):
  - ssl_sni (for SNI hostname)
  - ssl_min_ver (minimum TLS version)
  - ssl_max_ver (maximum TLS version)
  - ssl_ciphers (cipher suite override)

Config Generation Logic:
- Line 680-687: Code already writes these fields to HAProxy config
- Line 616: Now SELECT actually retrieves the values from database
- Example output: 'server backend1 10.0.0.1:443 ssl sni example.com ssl-min-ver TLSv1.2'

Testing:
- After deployment, bulk import a config with backend server SSL options
- Check generated HAProxy config on agent
- Should now see: 'server X ssl ssl-min-ver TLSv1.2 ciphers ...'

Files Changed:
- backend/services/haproxy_config.py: Line 616 SELECT statement
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu ac5ba4dc58 fix(ssl): add SSL advanced options to GET /api/frontends SELECT queries
CRITICAL BUG FIX: SSL advanced options were not being returned by GET API

Problem:
- Database has ssl_alpn, ssl_npn, ssl_ciphers, etc. columns 
- Response builder tries to access them (Line 341-347) 
- BUT SELECT statements did NOT include these fields 
- Result: f.get('ssl_alpn') returned None for all frontends

Impact:
- Frontend Edit modal always showed empty SSL advanced options fields
- User edits would overwrite existing values with NULL
- Data loss on every frontend edit!

Solution:
- Added all 7 SSL advanced options to ALL 6 SELECT queries:
  1. cluster_id filter (line 174)
  2. cluster_id fallback (line 190)
  3. global include_inactive=True (line 219)
  4. global include_inactive=False (line 231)
  5. global fallback include_inactive=True (line 246)
  6. global fallback include_inactive=False (line 258)

Testing:
- Added debug console.log for SSL advanced options (line 551-559)
- After deployment, check browser console for 'SSL ADVANCED OPTIONS DEBUG'
- Should now show: ssl_alpn: 'h2,http/1.1' etc.

Files Changed:
- backend/routers/frontend.py: All 6 SELECT statements
- frontend/src/components/FrontendManagement.js: Debug logging
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu e8690245af fix(ssl): add change detection and validators for SSL advanced options
Critical additions:
1. Change Detection (backend/routers/config.py)
   - Added SSL advanced options to bulk import change detection logic
   - Detects changes in ssl_alpn, ssl_npn, ssl_ciphers, ssl_ciphersuites
   - Detects changes in ssl_min_ver, ssl_max_ver, ssl_strict_sni
   - Changes will now appear in version diff

2. Pydantic Validators (backend/models/frontend.py, backend/models/backend.py)
   - TLS version validator: Only allows valid versions (SSLv3, TLSv1.0-1.3)
   - ALPN protocol validator: Only allows h2, http/1.1, http/1.0, h2c, spdy/*
   - NPN protocol validator: Only allows http/1.1, http/1.0, spdy/*
   - Prevents invalid values from being saved to database
   - HAProxy validation will not fail due to invalid SSL options

Impact:
- Bulk import will correctly detect SSL option changes
- Apply Management diff will show SSL changes
- User cannot enter invalid TLS versions or protocols
- Improved UX with early validation errors

Previous fixes in this series:
- Frontend GET API: Added SSL fields to response
- Bulk Import UPDATE: Added SSL fields to UPDATE statement
- Backend Server GET API: Added SSL fields to response

Test: Bulk import with ALPN change → Should see change in version diff
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 3e2f3e3d9f fix(ssl): comprehensive SSL advanced options handling across all endpoints
Critical fixes for SSL advanced options (alpn, npn, ciphers, ciphersuites, min-ver, max-ver, strict-sni):

1. Frontend GET API (backend/routers/frontend.py)
   - Added all 7 SSL advanced option fields to response
   - Frontend Edit modal will now display these fields
   - Prevents NULL overwrite when user edits frontend

2. Bulk Import Frontend UPDATE (backend/routers/config.py)
   - Added all 7 SSL advanced option fields to UPDATE statement
   - Previously skipped with comment 'MVP: DON'T update SSL settings'
   - Now bulk import re-runs preserve SSL settings

3. Backend Server GET API (backend/routers/backend.py)
   - Added 4 server SSL fields (ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers)
   - SQL SELECT query updated
   - Response object updated
   - Backend Server Edit modal will now display these fields

Root cause: GET APIs were not returning SSL advanced options, causing:
- UI forms to show empty fields
- User edits to overwrite with NULL
- Data loss on subsequent updates

All other endpoints (POST, PUT, INSERT) were already correct.

Impact:
- No more accidental data loss when editing frontends/servers
- Bulk import now preserves SSL advanced options
- UI will correctly display all SSL parameters

Test: Deploy backend, run bulk import, verify ssl_alpn appears in database
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 415439cf17 fix: Move pool_id auto-heal logic before server_statuses check
- Previously auto-heal only ran when agent sent server_statuses (which is empty on first heartbeat)
- Now auto-heal runs on EVERY heartbeat, ensuring pool_id is fixed immediately
- This fixes agents being stuck with NULL pool_id when haproxy config is empty
- Agents will now appear in UI correctly even before applying first config
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu ba09eb70b9 fix: Include pool_id from cluster_id in placeholder-token agent registration path
- Modified auto-registration when using placeholder token to query pool_id from cluster_id in heartbeat
- Previously pool_id was copied from placeholder agent (which was NULL)
- Now correctly fetches pool_id from haproxy_clusters table using cluster_id
- Added extensive debug logging for troubleshooting
- Fixes issue where agents were registered with NULL pool_id and not appearing in UI
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 761e7fae55 debug(agent): add extensive logging for pool_id auto-register troubleshooting
Added debug logs to track:
- cluster_id presence in heartbeat payload
- Auto-register path execution
- Database query results for pool_id lookup
- Missing cluster_id warnings

This will help identify why pool_id remains NULL during registration.
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 8418025744 fix(agent): auto-register agents with pool_id from cluster_id
PROBLEM:
- Agents registered with pool_id = NULL
- UI doesn't show agents without pool assignment
- Auto-healing only works when server_statuses present
- New agents with empty HAProxy config never get pool_id

ROOT CAUSE:
- Agent auto-register INSERT excluded pool_id column
- Auto-healing (line 1417-1422) only triggers inside 'if server_statuses:' block
- Fresh agents send no server_statuses → auto-healing never runs
- Agent sits with pool_id = NULL indefinitely

ANALYSIS:
- Previous commit 1f9d8c2 added auto-healing for edge case (cluster before pool)
- But auto-healing has conditional prerequisite: server_statuses must exist
- New agents: empty HAProxy config → no server_statuses → no healing
- This was working before because agents had config from start

SOLUTION:
- Extract pool_id from cluster_id during registration
- Query haproxy_clusters for pool_id using heartbeat's cluster_id
- Insert agent with pool_id immediately (no wait for auto-heal)
- Two auto-register paths fixed: with API key + without API key

EDGE CASES HANDLED:
1. cluster_id missing → pool_id = NULL → auto-healing fallback 
2. cluster deleted → pool_id = NULL → auto-healing fallback 
3. cluster pool_id NULL → pool_id = NULL → auto-healing works 
4. Old agent script → no cluster_id → auto-healing works 

COMPATIBILITY:
- Auto-healing preserved (line 1417-1422 untouched)
- Two mechanisms work together harmoniously
- Backward compatible with existing agents
- No breaking changes

IMPACT:
- New agents visible in UI immediately
- Faster registration (no wait for auto-heal)
- Reduced heartbeat cycles to full functionality
- Better user experience

TESTING REQUIRED:
1. Delete agent from database
2. Install fresh agent with cluster_id in config
3. Verify pool_id populated on registration
4. Verify agent appears in UI immediately
5. Verify existing agents unaffected
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 132b59bcd7 feat(agent): preserve failed HAProxy configs for debugging (TESTED)
PROBLEM:
- When HAProxy validation fails, /tmp/haproxy-new-config.cfg is deleted
- Admins cannot inspect the failed config to diagnose syntax errors
- Debugging validation failures requires database queries

SOLUTION:
- Save failed configs with timestamp: /tmp/haproxy-failed-{version}-{timestamp}.cfg
- Automatic cleanup: keeps last 5 failed configs, deletes older ones
- Clear log messages with debug commands

IMPLEMENTATION:
- Minimal change in validation failed branch only
- Uses mv instead of rm for failed configs
- Successful configs still cleaned up (already copied to haproxy.cfg)
- TESTED: bash -n syntax validation passed for both scripts

BENEFITS:
- Easy inspection: cat /tmp/haproxy-failed-*.cfg
- Manual validation: haproxy -c -f /tmp/haproxy-failed-*.cfg
- Identifies config generation bugs quickly
- No disk space issues (auto-cleanup)

DEPLOYMENT:
- Zero risk: only affects validation failure path
- Use Script Management UI -> Reset to Default
- Then upgrade agents via Script Management

EXAMPLE LOG:
[INFO] DAEMON: Failed config saved to: /tmp/haproxy-failed-apply-consolidated-1763478044-20251118-150057.cfg
[INFO] DAEMON: Debug: cat /tmp/haproxy-failed-apply-consolidated-1763478044-20251118-150057.cfg
[INFO] DAEMON: Debug: haproxy -c -f /tmp/haproxy-failed-apply-consolidated-1763478044-20251118-150057.cfg
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 2dcdaeeba1 fix(config): robust use_backend_rules parsing with comprehensive type handling
PROBLEM:
- Config generation was producing invalid syntax: use_backend ["..."]
- HAProxy validation failing on agents
- Old code had insufficient type checking for JSONB fields

ROOT CAUSE:
- Missing ELSE branch when use_backend_rules wasn't a list
- No handling for unexpected types (tuple, Record, etc.)
- No debug logging to track type issues

FIX:
- Added comprehensive type checking (str, list, tuple, other)
- Added debug logging to track type and value
- Added fallback parsing for string representation of lists
- Enhanced validation to skip invalid entries
- Prevents generation of invalid HAProxy syntax

IMPACT:
- Fixes validation failure for cluster 7 (demo-cluster)
- Enables proper parsing of JSONB use_backend_rules
- Backward compatible with legacy string format

TESTED:
- Database validation: use_backend_rules is proper JSONB array
- String elements correctly extracted and written
- Invalid types caught and logged
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 35dd8e5d13 Fix KeyError: ssl_name in bulk import parse
CRITICAL BUG: P1 fix broke parse response due to dict format change

ROOT CAUSE:
- P1 changed ssl_auto_assigned_frontends dict format
- Old: {'frontend': ..., 'ssl_name': ..., 'ssl_id': ...}
- New: {'frontend': ..., 'matched_certs': [...], 'total_matched': ...}
- But lines 943, 967 still accessed f['ssl_name'] → KeyError!

SOLUTION:
- Line 944: Loop through matched_certs to extract ssl_names
- Line 969: Build matched_info from matched_certs array
- Multi-SSL format now consistent throughout

EXAMPLE OUTPUT:
SSL AUTO-ASSIGNED: 1 frontend(s) automatically matched
Matched: public_ssl (3 certs: example-cert1, demo-cluster-cert, example-cert3)

IMPACT:
- Parse now completes successfully
- Shows all 3 matched SSL certs in response
- User sees detailed SSL matching info

Ref: demo-cluster parse error
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 7492d85649 FIX: Multiple SSL certificates & advanced params parsing
CRITICAL BUG FIX: Only 1 SSL cert matched instead of 3 for public_ssl

ROOT CAUSE:
- Parser only stored first cert path (ssl_cert_path)
- Bulk import SSL matching only checked single path
- ssl_certificate_ids = [2] (should be [2,3,4] for 3 certs)
- ssl_alpn = NULL (should be 'h2,http/1.1')

SOLUTION:
1. Added ssl_cert_paths List[str] to ParsedFrontend
2. Parser now stores ALL cert paths from bind directive
3. Bulk import loops through all cert paths for matching
4. SSL advanced options (alpn, npn, ciphers, etc.) included in frontends_data

EXAMPLE BIND DIRECTIVE:
bind 0.0.0.0:8443 ssl
  crt /etc/ssl/certs/example-cert1.pem
  crt /etc/ssl/certs/demo-cluster-cert.pem
  crt /etc/ssl/certs/example-cert3.pem
  alpn h2,http/1.1

BEFORE:
- ssl_certificate_ids: [2]  (only first cert)
- ssl_alpn: NULL            (not passed to bulk import)

AFTER:
- ssl_certificate_ids: [2, 3, 4]  (all 3 certs matched)
- ssl_alpn: 'h2,http/1.1'         (parsed & stored)

IMPACT:
- Multi-SSL frontends correctly imported
- SSL advanced params preserved & editable in UI
- SNI-based routing works correctly
- HTTP/2 ALPN negotiation preserved

TESTING:
- Parser: 3 crt paths → ssl_cert_paths = [path1, path2, path3]
- Matching: 3 paths → 3 IDs (if all SYNCED)
- Database: ssl_certificate_ids JSONB = [2,3,4]

Ref: demo-cluster public_ssl frontend issue
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 001b467e42 FIX: Rejected bulk import data corruption
CRITICAL BUG FIX: Rejected bulk import entities were marked APPLIED

ROOT CAUSE:
- Bulk import versions (bulk-import-*) don't match entity-ID regex
- Final cleanup incorrectly marked all PENDING entities as APPLIED
- 594 entities (56 FE + 55 BE + 483 SRV) corrupted in production

SOLUTION:
1. Detect bulk import versions (bulk-import-*, restore-*)
2. Extract entity IDs from metadata bulk_snapshots
3. Verify rollback deleted entities (should be 0 remaining)
4. If rollback failed, force DELETE entities
5. Skip final cleanup for bulk import (entities already handled)

IMPACT:
- Prevents data corruption on rejected bulk imports
- Detects and auto-fixes failed rollbacks
- Maintains data integrity for multi-entity operations
- Preserves existing orphan cleanup for single-entity changes

TESTING:
- Bulk import + reject: Entities deleted (not APPLIED)
- Normal entity + reject: Status updated to APPLIED (rollback)
- Orphan entities: Cleaned only if safe (no bulk versions)

Ref: demo-cluster bulk-import-1763450049 issue
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu a739dd0f95 PRODUCTION FIX v2: Direct JSON Sanitization in Heartbeat Endpoint
CRITICAL ISSUE:
Previous middleware approach failed - Starlette middleware cannot
reliably modify request body after it's consumed by FastAPI.

NEW APPROACH - ENDPOINT-LEVEL SANITIZATION:
Moved JSON sanitization directly into agent heartbeat endpoint for
guaranteed execution before Pydantic validation.

ROOT CAUSE CONFIRMED:
Agent daemon mode sends: "server_statuses": ,
This is INVALID JSON (empty value before comma)
Result: JSON decode error at position 322 -> agents stuck offline

SOLUTION IMPLEMENTATION:
Modified: backend/routers/agent.py
- Read raw request body BEFORE Pydantic processing
- Apply 3 regex fixes:
  1. "field": , -> "field": null,
  2. "field": } -> "field": null}
  3. {field,} -> {field}
- Parse sanitized JSON manually
- Create AgentHeartbeat from clean dict
- Continue with normal heartbeat flow

BENEFITS:
✓ NO AGENT SCRIPT CHANGES (production safe)
✓ Guaranteed execution (not middleware dependent)
✓ Detailed logging of sanitization
✓ Graceful error handling
✓ Backward compatible with all agents
✓ Zero impact on valid JSON

LOGGING:
INFO: "Sanitized malformed JSON from agent 'demo-agent1'"
DEBUG: Shows before/after JSON (first 300 chars)

PRODUCTION IMPACT:
- demo-agent1 & agent3 will go online immediately
- No agent restart required
- No agent script update required
- Self-healing for future similar issues

TESTING:
Deploy backend -> Watch logs for:
"Sanitized malformed JSON from agent"

Removed:
- backend/middleware/json_sanitizer.py (approach failed)

This direct approach guarantees the fix executes BEFORE
FastAPI/Pydantic validation, solving the agent offline issue.
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu dbf5b8d688 PRODUCTION FIX: JSON Sanitizer Middleware for Malformed Agent Heartbeats
CRITICAL FIX - No Agent Script Changes Required

PROBLEM IDENTIFIED:
- demo-agent1/agent3 sending malformed JSON
- Error: server_statuses: , (empty value before comma)
- Invalid JSON syntax causing HTTP 422 validation errors
- Agents stuck offline

ROOT CAUSE:
Agent daemon mode get_server_statuses() returns empty string when
HAProxy stats socket unavailable, resulting in: "server_statuses": ,

SOLUTION - BACKEND MIDDLEWARE (Production Safe):
Created JSONSanitizerMiddleware that automatically fixes common JSON
errors BEFORE FastAPI parses request body:

1. Empty values before comma/brace: field: , -> field: null,
2. Trailing commas: {field: value,} -> {field: value}
3. Only processes /api/agents/heartbeat endpoint
4. Logs what was fixed for auditing

BENEFITS:
- NO AGENT SCRIPT CHANGES (production safe)
- NO AGENT UPGRADE REQUIRED
- Backward compatible with all agent versions
- Zero impact on valid JSON
- Self-healing for future similar issues
- Detailed logging for monitoring

MIDDLEWARE ORDER:
PerformanceMonitoring -> RequestLogging -> JSONSanitizer -> ActivityLog -> CORS

HOW IT WORKS:
1. Intercepts POST /api/agents/heartbeat
2. Reads raw body before FastAPI
3. Applies regex fixes for known patterns
4. Replaces request body with sanitized version
5. FastAPI receives valid JSON

TESTING:
Before: {"server_statuses": ,"system_info": {...}}
After:  {"server_statuses": null,"system_info": {...}}

Result: Pydantic validation passes, agent goes online

This middleware approach is MUCH safer than deploying agent script
changes to production servers.
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu a6b223c0e7 CRITICAL FIX: Enhanced Error Handling for Agent Heartbeat JSON Parse Errors
PRODUCTION STABILITY FIX - Detailed Logging for Malformed Agent Payloads

PROBLEM:
- demo-agent1 and demo-agent2 sending malformed JSON
- Error: JSON decode error at body position 322
- No visibility into WHAT is malformed or WHY
- Impossible to debug without raw payload inspection

ROOT CAUSE:
- FastAPI consumes request body before error handler
- Pydantic validation fails but does not show raw input
- Agent script might be generating invalid JSON
- No logging of actual problematic payload

SOLUTION - ENHANCED ERROR HANDLING:

1. MIDDLEWARE ENHANCEMENT (error_handler.py):
   - Extract RAW body in validation error handler
   - Parse agent name from JSON (even if malformed)
   - Log first 500 chars of problematic payload
   - Add body size to error details
   - Special handling for /heartbeat endpoint
   - Detailed logging for json_invalid errors

2. HEARTBEAT ENDPOINT (agent.py):
   - Added Request parameter for raw body access
   - Enhanced docstring with troubleshooting info

BENEFITS:
- Instant visibility into malformed JSON
- Agent name logged even on parse failure
- Exact payload position + preview
- No performance impact (only on errors)
- Backward compatible (does not change API)

NEXT STEPS (After Deploy):
1. Check logs for CRITICAL JSON PARSE ERROR
2. Identify exact field causing parse failure
3. Fix agent script if needed
4. Or fix backend to be more tolerant

This enables root cause analysis without SSH access to agent servers
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 5bd75c9614 ENHANCEMENT: Robust Multi-Value SSL Parameter Parsing in Bulk Import
🔧 IMPROVEMENT: Handle Quoted and Complex SSL Values

PROBLEM:
- Bulk import parser used simple line.split() for SSL parameters
- Failed to handle quoted values: ciphers "ECDHE-RSA:ECDHE-ECDSA:!MD5"
- Long cipher lists could be incorrectly parsed
- Edge cases with special characters not handled

SOLUTION - SHLEX PARSING:
 Frontend bind parsing:
   - Changed from line.split() to shlex.split()
   - Handles quoted values correctly
   - Removes quotes automatically
   - Fallback to simple split if malformed

 Backend server parsing:
   - Enhanced regex patterns for SSL params
   - Supports both quoted and unquoted values
   - Pattern: (?:"([^"]+)"|(\S+))
   - Applies to: sni, ssl-min-ver, ssl-max-ver, ciphers

EXAMPLES NOW SUPPORTED:

Frontend:
  bind :443 ssl crt cert.pem ciphers "ECDHE-RSA:ECDHE-ECDSA:!MD5:!aNULL" alpn "h2,http/1.1"
  → ciphers: ECDHE-RSA:ECDHE-ECDSA:!MD5:!aNULL (quotes removed)
  → alpn: h2,http/1.1 (quotes removed)

Backend:
  server s1 10.1.1.1:443 ssl sni "backend.example.com" ciphers "ECDHE-RSA:ECDHE-ECDSA"
  → sni: backend.example.com
  → ciphers: ECDHE-RSA:ECDHE-ECDSA

BENEFITS:
-  Production HAProxy configs with quoted values now parse correctly
-  Long cipher lists (100+ chars) handled properly
-  Special characters (!MD5, @STRENGTH) in cipher lists supported
-  Backward compatible (unquoted values still work)
-  Robust error handling (fallback to simple split)

TESTED WITH:
- User's problematic config with multiple crt + alpn
- Quoted cipher suites
- Mixed quoted/unquoted parameters
- Edge cases with special characters

This ensures bulk import handles ALL real-world HAProxy configurations correctly!
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu cb645b5ef9 CRITICAL FIX: Agent Offline Issue - Backend Tolerance for Legacy Agents
🔴 PRODUCTION CRITICAL FIX - Agent HTTP 422 Validation Error

PROBLEM:
- Production agents sending heartbeat with flat system_info fields
- Backend Pydantic model was strict and rejecting unknown fields
- Agents going offline with 'Validation error in request data' (HTTP 422)

ROOT CAUSE:
- Legacy agents embed system_info as flat key-value pairs in heartbeat JSON
- Backend expected only defined fields, rejected extra fields
- No backward compatibility for agent format variations

SOLUTION - BACKEND ONLY (NO AGENT CHANGES):
 Added 'extra = "allow"' to AgentHeartbeat Pydantic Config
 Backend now accepts both formats:
   - Flat format: operating_system, kernel_version, etc. (legacy agents)
   - Nested format: system_info: {...} (future agents)
 Updated comments to clarify backward compatibility

IMPACT:
-  ZERO CHANGES to production agent scripts
-  Existing agents will work immediately after backend deploy
-  Forward compatible with future agent upgrades
-  Tolerant to agent format variations

SAFETY:
- Minimal change (3 lines)
- Pydantic still validates required fields
- Extra fields ignored silently (no breaking changes)
- Production agents continue without restart or upgrade

DEPLOYMENT:
1. Deploy backend (this commit)
2. Agents come online automatically (no action needed)
3. Agent upgrades can happen later (when convenient)

This fix ensures production stability without touching agent scripts.
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 2819eeb515 Fix Backend API endpoints for SSL Advanced Options - Part 2
CRITICAL FIX: All API endpoints now handle SSL advanced options

 FRONTEND ENDPOINTS FIXED:
- create_frontend() - INSERT statement now includes all 7 SSL advanced fields
- update_frontend() - UPDATE statement now includes all 7 SSL advanced fields
- Bulk import frontend INSERT - All SSL params included

 BACKEND SERVER ENDPOINTS FIXED:
- add_server_to_backend() - INSERT now includes 4 SSL server advanced fields
- update_server() - allowed_fields list now includes SSL params (dynamic update)
- Bulk import server INSERT - All SSL params included

FIXED FIELDS:
Frontend: ssl_alpn, ssl_npn, ssl_ciphers, ssl_ciphersuites, ssl_min_ver, ssl_max_ver, ssl_strict_sni
Server: ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers

IMPACT:
- Bulk import now correctly saves parsed SSL parameters to database
- Frontend edit/create now accepts SSL params from UI
- Server edit/create now accepts SSL params from UI
- All CRUD operations fully support SSL advanced options

NEXT: Frontend UI components (FrontendManagement.js & BackendServers.js)
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu b212fb92bc Add SSL Advanced Options support (Backend) - Part 1
FEATURE: Complete SSL Advanced Options implementation for frontend and backend server SSL

 DATABASE:
- Added SSL parameter columns to frontends table:
  * ssl_alpn, ssl_npn, ssl_ciphers, ssl_ciphersuites
  * ssl_min_ver, ssl_max_ver, ssl_strict_sni
- Added SSL parameter columns to backend_servers table:
  * ssl_sni, ssl_min_ver, ssl_max_ver, ssl_ciphers
- Migration functions: add_ssl_advanced_options_to_frontends() and add_ssl_advanced_options_to_servers()

 MODELS:
- FrontendConfig: Added 7 new SSL fields for bind parameters
- ServerConfig: Added 4 new SSL fields for server parameters
- AgentHeartbeat: Added system_info field (fixes HTTP 422 validation error)

 BULK IMPORT PARSER:
- Parse alpn, npn, ciphers, ciphersuites, ssl-min-ver, ssl-max-ver, strict-sni from bind lines
- Parse sni, ssl-min-ver, ssl-max-ver, ciphers from server lines
- Store parsed values in frontend/server objects
- User-friendly warnings about imported SSL parameters

 CONFIG GENERATOR:
- Generate bind lines with SSL advanced options: 'bind :443 ssl crt file.pem alpn h2,http/1.1 ciphers ...'
- Generate server lines with SSL advanced options: 'server s1 addr:port ssl sni hostname ssl-min-ver TLSv1.2'
- Support both NEW MODE (multiple certs) and OLD MODE (single cert)

USER IMPACT:
- Bulk import now correctly parses SSL configs with alpn/npn/ciphers
- SSL parameters preserved during import (not lost anymore)
- Agent heartbeat fixed (no more offline agents)
- Ready for UI implementation (next commit)

EXAMPLE USAGE:
Frontend: bind 0.0.0.0:8443 ssl crt cert1.pem crt cert2.pem alpn h2,http/1.1
Server: server s1 10.1.1.1:443 ssl verify required sni backend.example.com ssl-min-ver TLSv1.2

NEXT: Frontend UI components for editing these SSL options
2025-11-18 21:58:05 +03:00
Taylan Bakırcıoğlu 5c1d2e11f9 Fix agent offline issue and bulk import SSL parsing
CRITICAL FIXES:
1. Agent Heartbeat Validation Error (HTTP 422)
   - Added missing 'system_info' field to AgentHeartbeat model
   - Agents were sending system_info but backend model didn't accept it
   - No agent script update needed - agents already send this field

2. Bulk Import SSL Parser Enhancement
   - Fixed parsing of multiple SSL certificates with alpn/npn parameters
   - Example: 'bind :443 ssl crt cert1.pem crt cert2.pem crt cert3.pem alpn h2,http/1.1'
   - Old parser stopped at first whitespace after crt path
   - New parser extracts all crt paths even with alpn/npn/ciphers after them
   - Added user-friendly warning for SSL parameters (alpn, npn, ciphers) that won't be imported

TECHNICAL DETAILS:
- backend/models/agent.py: Added system_info: Optional[Dict[str, Any]]
- backend/utils/haproxy_config_parser.py: Enhanced SSL bind parsing logic
  * Parse bind line by splitting and iterating through parts
  * Extract all crt paths before hitting SSL parameters
  * Detect and warn about alpn, npn, ciphers, ciphersuites parameters
  * Inform user these advanced options should be configured manually

USER IMPACT:
- Agents will come online after backend deployment (no reinstall needed)
- Bulk import will correctly parse configs with multiple SSL certs + alpn
- Clear warnings shown in UI about SSL parameters not imported
2025-11-18 21:58:05 +03:00