Problem: "Failed to backup file before replacement" error when using API key authentication.
Root Cause:
- The externalApp field (which contains the system user for file operations) was sometimes None
- When using API key authentication, the code couldn't determine which user to run commands as
Solution:
- Added fallback logic to ensure we always have a valid user for file operations:
1. First try wp_site.owner.externalApp
2. If not set, try Websites.objects.get(domain).externalApp
3. If still not set, fall back to admin username
- Added detailed error messages and logging throughout backup operations
- Enhanced error reporting to include user context and operation details
- Added validation for backup directory creation with proper error handling
Changes:
- Modified validate_access_token() OPTION 2 and OPTION 3 to ensure external_app is always set
- Enhanced backup and replace operations with better error messages
- Added detailed logging for debugging file operation failures
- Include user context in error messages for easier troubleshooting
This ensures file operations work correctly even when externalApp field is not properly configured.
Problem: File fixes were failing with "Invalid token" even though the platform was sending the correct API key.
Solution:
- Updated validate_access_token() to accept CyberPanel's own API keys for file operations
- Added three validation options:
1. FileAccessToken (temporary tokens for active scans)
2. API key validation with less restrictive admin check
3. Simple validation for platform callbacks (any valid API key + valid scan)
- Added extract_auth_token() helper to support both Bearer and X-API-Key headers
- Created debug endpoints for testing authentication (/api/ai-scanner/test-auth)
- Added test script for validation testing (supports remote servers via env vars)
This fix allows the platform to use CyberPanel's API key to fix files for any scan,
solving the "File access token has expired" issue for older scans.
Usage for remote testing:
CYBERPANEL_SERVER=http://your-server:8001 \
CYBERPANEL_API_KEY=cp_your_key \
CYBERPANEL_SCAN_ID=your-scan-id \
./test_api_key_fix.sh