ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(wordpress): per-site security depth — integrity, debug, WP-Cron (#30)
Juan Denis5e2d4afbdad4
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex eb74325f..cc7e59eb 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -548,6 +548,110 @@ def scan_site_vulnerabilities(app_id):return jsonify(WpVulnerabilityService.start_scan(wp_site)), 200+# ---- Per-site security depth (#30): file integrity, WP_DEBUG, WP-Cron ----++def _owner_or_admin_app(app_id):+ """Resolve an app and enforce the owner-or-admin read guard. Returns+ (app, None) or (None, (response, status))."""+ current_user_id = get_jwt_identity()+ user = User.query.get(current_user_id)+ app = _resolve_app(app_id)+ if not app:+ return None, (jsonify({'error': 'Application not found'}), 404)+ if user.role != 'admin' and app.user_id != current_user_id:+ return None, (jsonify({'error': 'Access denied'}), 403)+ return app, None+++@wordpress_bp.route('/sites/<int:app_id>/integrity', methods=['GET'])+@jwt_required()+def get_site_integrity(app_id):+ """Return the latest file-integrity result + scan status for a site."""+ from app.services.wp_security_service import WpSecurityService+ app, err = _owner_or_admin_app(app_id)+ if err:+ return err+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ return jsonify(WpSecurityService.get_integrity(wp_site.id)), 200+++@wordpress_bp.route('/sites/<int:app_id>/integrity/scan', methods=['POST'])+@jwt_required()+@admin_required+def scan_site_integrity(app_id):+ """Start a background file-integrity check (wp core/plugin verify-checksums)."""+ from app.services.wp_security_service import WpSecurityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ return jsonify(WpSecurityService.start_integrity_scan(wp_site)), 200+++@wordpress_bp.route('/sites/<int:app_id>/debug', methods=['GET'])+@jwt_required()+def get_site_debug(app_id):+ """Return the site's WP_DEBUG / WP_DEBUG_LOG / SCRIPT_DEBUG state."""+ from app.services.wp_security_service import WpSecurityService+ app, err = _owner_or_admin_app(app_id)+ if err:+ return err+ return jsonify(WpSecurityService.get_debug(app.root_path)), 200+++@wordpress_bp.route('/sites/<int:app_id>/debug', methods=['POST'])+@jwt_required()+@admin_required+def set_site_debug(app_id):+ """Toggle debug logging (WP_DEBUG/WP_DEBUG_LOG/SCRIPT_DEBUG on; display always off)."""+ from app.services.wp_security_service import WpSecurityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ enabled = bool((request.get_json() or {}).get('enabled'))+ return jsonify(WpSecurityService.set_debug(app.root_path, enabled)), 200+++@wordpress_bp.route('/sites/<int:app_id>/cron', methods=['GET'])+@jwt_required()+def get_site_cron(app_id):+ """Return WP-Cron status (DISABLE_WP_CRON + due events)."""+ from app.services.wp_security_service import WpSecurityService+ app, err = _owner_or_admin_app(app_id)+ if err:+ return err+ return jsonify(WpSecurityService.get_cron(app.root_path)), 200+++@wordpress_bp.route('/sites/<int:app_id>/cron/run', methods=['POST'])+@jwt_required()+@admin_required+def run_site_cron(app_id):+ """Run all due WP-Cron events now."""+ from app.services.wp_security_service import WpSecurityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ return jsonify(WpSecurityService.run_cron(app.root_path)), 200+++@wordpress_bp.route('/sites/<int:app_id>/cron', methods=['POST'])+@jwt_required()+@admin_required+def set_site_cron(app_id):+ """Enable/disable WP's pseudo-cron (DISABLE_WP_CRON)."""+ from app.services.wp_security_service import WpSecurityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ disabled = bool((request.get_json() or {}).get('disabled'))+ return jsonify(WpSecurityService.set_cron_disabled(app.root_path, disabled)), 200++@wordpress_bp.route('/sites/<int:app_id>/info', methods=['GET'])@jwt_required()def get_wordpress_info(app_id):diff --git a/backend/app/services/wp_security_service.py b/backend/app/services/wp_security_service.pynew file mode 100644index 00000000..3032519b--- /dev/null+++ b/backend/app/services/wp_security_service.py@@ -0,0 +1,166 @@+"""Per-site WordPress security depth (#30): file-integrity verification,+WP_DEBUG/SCRIPT_DEBUG toggling, and WP-Cron management — all via the Docker-aware+WP-CLI bridge (WordPressService.wp_cli), so containerized sites work.++Integrity runs in a background thread (verify-checksums fetches from wordpress.org+and can be slow) so the single worker never blocks; debug/cron are quick.++Deferred (needs infra absent in the Docker-localhost model): a per-site+wp-login/xmlrpc brute-force rate-limit jail (Fail2ban / nginx limit_req). Managed+sites are localhost:PORT apache containers with no host-side per-site access log+for a jail to watch; revisit once a per-site reverse-proxy/log layer exists.+"""++import json+import logging+import threading+from datetime import datetime++logger = logging.getLogger(__name__)+++class WpSecurityService:+ # In-memory latest integrity result per site (point-in-time, like the Lynis scan).+ _integrity = {}+ _integrity_lock = threading.Lock()++ # ---------- file integrity (background) ----------++ @classmethod+ def get_integrity(cls, site_id):+ with cls._integrity_lock:+ return dict(cls._integrity.get(site_id, {'status': 'idle'}))++ @classmethod+ def start_integrity_scan(cls, site):+ from flask import current_app+ with cls._integrity_lock:+ if cls._integrity.get(site.id, {}).get('status') == 'running':+ return {'success': True, 'status': 'running'}+ cls._integrity[site.id] = {'status': 'running'}+ app = current_app._get_current_object()+ path = site.application.root_path if site.application else None+ threading.Thread(+ target=cls._run_integrity, args=(app, site.id, path), daemon=True,+ name=f'wp-integrity-{site.id}'+ ).start()+ return {'success': True, 'status': 'running'}++ @classmethod+ def _run_integrity(cls, app, site_id, path):+ with app.app_context():+ from app.services.wordpress_service import WordPressService+ try:+ if not path:+ raise RuntimeError('Site has no root path')+ core = WordPressService.wp_cli(path, ['core', 'verify-checksums'])+ plug = WordPressService.wp_cli(path, ['plugin', 'verify-checksums', '--all'])+ issues = cls._parse_checksum_issues(core) + cls._parse_checksum_issues(plug)+ result = {+ 'status': 'completed',+ 'core_ok': bool(core.get('success')),+ 'plugins_ok': bool(plug.get('success')),+ 'issues': issues,+ 'checked_at': datetime.utcnow().isoformat(),+ 'error': None,+ }+ except Exception as e:+ logger.error(f'Integrity scan failed for site {site_id}: {e}')+ result = {'status': 'error', 'error': str(e), 'issues': [],+ 'checked_at': datetime.utcnow().isoformat()}+ with cls._integrity_lock:+ cls._integrity[site_id] = result++ @staticmethod+ def _parse_checksum_issues(res):+ """Extract the Warning/Error lines verify-checksums emits for modified or+ unexpected files. A clean install emits only a 'Success:' line (no issues)."""+ issues = []+ text = (res.get('output') or '') + '\n' + (res.get('error') or '')+ for line in text.splitlines():+ s = line.strip()+ if s.startswith('Warning:') or s.startswith('Error:'):+ issues.append(s.split(':', 1)[1].strip())+ return issues++ # ---------- WP_DEBUG / SCRIPT_DEBUG ----------++ # Log OUTSIDE the web root: the default wp-content/debug.log is served by+ # apache (a public info leak), whereas /tmp is container-writable and never+ # web-accessible. (Ephemeral across container restarts, which is fine for a+ # debug log.)+ DEBUG_LOG_PATH = '/tmp/wp-debug.log'++ @classmethod+ def get_debug(cls, path):+ from app.services.wordpress_service import WordPressService++ def _val(k):+ res = WordPressService.wp_cli(path, ['config', 'get', k])+ return (res.get('output') or '').strip() if res.get('success') else ''++ log_raw = _val('WP_DEBUG_LOG').lower()+ state = {+ 'WP_DEBUG': _val('WP_DEBUG').lower() in ('1', 'true'),+ 'WP_DEBUG_LOG': log_raw not in ('', 'false', '0'), # 'true' OR a path+ 'SCRIPT_DEBUG': _val('SCRIPT_DEBUG').lower() in ('1', 'true'),+ 'WP_DEBUG_DISPLAY': _val('WP_DEBUG_DISPLAY').lower() in ('1', 'true'),+ }+ return {'success': True, 'debug': state, 'enabled': state['WP_DEBUG']}++ @classmethod+ def set_debug(cls, path, enabled):+ from app.services.wordpress_service import WordPressService++ def wp(*args):+ return WordPressService.wp_cli(path, ['config', 'set', *args])++ val = 'true' if enabled else 'false'+ # Gate on the primary write so a read-only wp-config / stopped container+ # reports an honest failure instead of a false "updated".+ primary = wp('WP_DEBUG', val, '--raw')+ if not primary.get('success'):+ return {'success': False,+ 'error': primary.get('error') or 'Failed to update wp-config (is the site running?)'}+ wp('SCRIPT_DEBUG', val, '--raw')+ if enabled:+ wp('WP_DEBUG_LOG', cls.DEBUG_LOG_PATH) # string path (not --raw)+ wp('WP_DEBUG_DISPLAY', 'false', '--raw') # never render errors on the page+ else:+ wp('WP_DEBUG_LOG', 'false', '--raw')+ return cls.get_debug(path)++ # ---------- WP-Cron ----------++ @classmethod+ def get_cron(cls, path):+ from app.services.wordpress_service import WordPressService+ dis = WordPressService.wp_cli(path, ['config', 'get', 'DISABLE_WP_CRON'])+ disabled = (dis.get('output') or '').strip().lower() in ('1', 'true') if dis.get('success') else False+ events = []+ ev = WordPressService.wp_cli(path, ['cron', 'event', 'list', '--format=json'])+ if ev.get('success'):+ try:+ events = json.loads(ev.get('output') or '[]')+ except (ValueError, TypeError):+ events = []+ return {'success': True, 'disabled': disabled, 'events': events}++ @classmethod+ def run_cron(cls, path):+ from app.services.wordpress_service import WordPressService+ res = WordPressService.wp_cli(path, ['cron', 'event', 'run', '--due-now'])+ return {+ 'success': bool(res.get('success')),+ 'output': (res.get('output') or '').strip(),+ 'error': res.get('error'),+ }++ @classmethod+ def set_cron_disabled(cls, path, disabled):+ from app.services.wordpress_service import WordPressService+ val = 'true' if disabled else 'false'+ res = WordPressService.wp_cli(path, ['config', 'set', 'DISABLE_WP_CRON', val, '--raw'])+ if not res.get('success'):+ return {'success': False, 'error': res.get('error')}+ return cls.get_cron(path)diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex f8e03544..31155d08 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -269,11 +269,12 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c- **Reuse:** cron scheduler, `db_sync_service` snapshots, promote pipeline, `restore_snapshot`.- **Done when:** Updates run on a schedule, staging-first, with backup + auto-rollback and a report.-### #30 — Per-site security depth `[L]` 🟡+### #30 — Per-site security depth `[L]` 🟡 — ✅ Done (file integrity + WP_DEBUG toggle + WP-Cron, Docker-correct; brute-force rate-limit jail deferred)- **Today:** ClamAV + file-integrity scan host paths (`/var/www`, `/home`, `/etc`) and can't reach Docker WP volumes; nothing resolves a site to a scannable docroot; integrity never calls `wp ... verify-checksums`; no `wp-login.php`/`xmlrpc` rate-limit jail.- **Do:** Per-site scan-target resolution; file integrity via `wp core/plugin/theme verify-checksums`; a Fail2ban jail/filter (or nginx `limit_req` zone) targeting each site's access log for `wp-login.php`/`xmlrpc.php`; per-site `WP_DEBUG`/`SCRIPT_DEBUG` toggle and WP-Cron list/run/disable.- **Reuse:** `security_service` (Fail2ban jails), `wp_cli`, `cron_service`, `nginx_service` WP template.- **Done when:** A site can be scanned, checksum-verified, brute-force-protected, and debug-toggled.+- **Landed:** New `WpSecurityService` + a per-site **Security tab** (Docker-correct, all via the WP-CLI bridge): **(1) File integrity** — a background `wp core verify-checksums` + `wp plugin verify-checksums --all` (in-container, so it reaches the volume; runs off the request thread and the UI polls), flagging tampered/unexpected files. **(2) Debug toggle** — sets `WP_DEBUG`/`SCRIPT_DEBUG` with `WP_DEBUG_DISPLAY=false` and, crucially, **`WP_DEBUG_LOG=/tmp/wp-debug.log`** — *outside* the web root, so the log is never publicly fetchable (the default `wp-content/debug.log` is apache-served — a real info leak this avoids); the write is gated so a read-only/stopped site reports an honest failure. **(3) WP-Cron** — `DISABLE_WP_CRON` status + due-event list, run-due-now, and enable/disable (with a clear "needs a real system cron" warning). Routes mirror the established per-site pattern (owner-or-admin GET, `@admin_required` mutations). *(Deferred — the brute-force `wp-login`/`xmlrpc` **rate-limit jail**: Fail2ban/nginx `limit_req` both need a host-side per-site access log to watch, which the `localhost:PORT` apache-container model doesn't expose — the same per-site reverse-proxy/log gap as #21/#25/#8-backend. A WP-level login-limiter plugin is the Docker-correct alternative, deferred to honour the WP-CLI-over-plugin thesis.)* Verified: backend `py_compile`, frontend lint-clean + build, focused security review (debug-log web-exposure caught + fixed). Not runtime-exercised on a real host.### #31 — Selective push UI `[S]` 🟡 — ✅ Done (specific-tables selectors added; files-only/db-only/specific-folders already existed)- **Today:** The dump layer already supports table filters / files-only / db-only; `PromoteModal` exposes only coarse code/db/full.diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex 9a215a0b..0a8efebf 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -73,7 +73,7 @@ const DetailPageSkeleton = () => (</div>);-const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities'];+const VALID_TABS = ['overview', 'environments', 'database', 'plugins', 'themes', 'php', 'git', 'backups', 'uptime', 'analytics', 'vulnerabilities', 'security'];const WordPressDetail = () => {const { id } = useParams();@@ -362,6 +362,12 @@ const WordPressDetail = () => {><ShieldCheck size={14} /> Vulnerabilities</div>+ <div+ className={`app-detail-tab ${activeTab === 'security' ? 'active' : ''}`}+ onClick={() => setActiveTab('security')}+ >+ <Lock size={14} /> Security+ </div></div>{/* Clone Site Modal */}@@ -408,6 +414,7 @@ const WordPressDetail = () => {{activeTab === 'uptime' && <UptimeTab siteId={site.id} />}{activeTab === 'analytics' && <AnalyticsTab siteId={site.id} />}{activeTab === 'vulnerabilities' && <VulnerabilitiesTab siteId={site.id} />}+ {activeTab === 'security' && <SecurityTab siteId={site.id} />}</ErrorBoundary></div></div>@@ -640,6 +647,131 @@ const UptimeTab = ({ siteId }) => {);};+// Security Tab — per-site security depth (#30): file-integrity verification,+// WP_DEBUG toggle, and WP-Cron management, all via the Docker-aware WP-CLI bridge.+const SecurityTab = ({ siteId }) => {+ const toast = useToast();+ const [integrity, setIntegrity] = useState(null);+ const [debug, setDebug] = useState(null);+ const [cron, setCron] = useState(null);+ const [loading, setLoading] = useState(true);+ const [busy, setBusy] = useState(false);++ const loadAll = React.useCallback(async () => {+ try {+ const [i, d, c] = await Promise.all([+ wordpressApi.getIntegrity(siteId).catch(() => null),+ wordpressApi.getDebug(siteId).catch(() => null),+ wordpressApi.getCron(siteId).catch(() => null),+ ]);+ setIntegrity(i); setDebug(d); setCron(c);+ } finally {+ setLoading(false);+ }+ }, [siteId]);++ useEffect(() => { loadAll(); }, [loadAll]);+ useEffect(() => {+ if (integrity?.status !== 'running') return undefined;+ const t = setTimeout(() => {+ wordpressApi.getIntegrity(siteId).then(setIntegrity).catch(() => {});+ }, 2500);+ return () => clearTimeout(t);+ }, [integrity, siteId]);++ async function runIntegrity() {+ try {+ await wordpressApi.scanIntegrity(siteId);+ setIntegrity(await wordpressApi.getIntegrity(siteId));+ } catch (err) { toast.error(err.message || 'Failed to start check'); }+ }+ async function toggleDebug() {+ setBusy(true);+ try {+ const res = await wordpressApi.setDebug(siteId, !debug?.enabled);+ if (res.success === false) { toast.error(res.error || 'Failed to update debug setting'); return; }+ setDebug(res);+ toast.success('Debug setting updated');+ } catch (err) { toast.error(err.message || 'Failed to update debug setting'); }+ finally { setBusy(false); }+ }+ async function runCron() {+ setBusy(true);+ try {+ const r = await wordpressApi.runCron(siteId);+ toast[r.success ? 'success' : 'error'](r.success ? 'Ran due events' : (r.error || 'Failed to run cron'));+ setCron(await wordpressApi.getCron(siteId));+ } catch (err) { toast.error(err.message || 'Failed to run cron'); }+ finally { setBusy(false); }+ }+ async function toggleCron() {+ setBusy(true);+ try { setCron(await wordpressApi.setCronDisabled(siteId, !cron?.disabled)); }+ catch (err) { toast.error(err.message || 'Failed to update WP-Cron'); }+ finally { setBusy(false); }+ }++ if (loading) return <div className="tab-loading"><p className="hint">Loading security tools...</p></div>;++ const intRunning = integrity?.status === 'running';+ const issues = integrity?.issues || [];++ return (+ <div className="app-overview-grid">+ <div className="app-overview-left">+ <div className="app-panel">+ <div className="app-panel-header">File integrity</div>+ <div className="app-panel-body">+ <div className="app-detail-actions">+ <Button size="sm" onClick={runIntegrity} disabled={intRunning}>{intRunning ? 'Checking…' : 'Verify checksums'}</Button>+ </div>+ {(!integrity || integrity.status === 'idle') && <p className="hint">Verifies WordPress core and wordpress.org plugins against official checksums to detect tampered or unexpected files.</p>}+ {integrity?.status === 'error' && <p className="hint">Check failed: {integrity.error}</p>}+ {integrity?.status === 'completed' && (+ issues.length === 0+ ? <p className="hint">All core and plugin files verify against official checksums.</p>+ : <>+ <div className="app-detail-actions"><Badge variant="destructive">{issues.length} issue{issues.length === 1 ? '' : 's'}</Badge></div>+ {issues.slice(0, 50).map((line, i) => <div className="form-hint" key={i}>{line}</div>)}+ </>+ )}+ </div>+ </div>++ <div className="app-panel">+ <div className="app-panel-header">Debug mode</div>+ <div className="app-panel-body">+ <div className="app-info-grid">+ <div className="app-info-item"><span className="app-info-label">WP_DEBUG</span><span className="app-info-value"><Badge variant={debug?.debug?.WP_DEBUG ? 'warning' : 'secondary'}>{debug?.debug?.WP_DEBUG ? 'on' : 'off'}</Badge></span></div>+ <div className="app-info-item"><span className="app-info-label">Debug log</span><span className="app-info-value">{debug?.debug?.WP_DEBUG_LOG ? 'on' : 'off'}</span></div>+ <div className="app-info-item"><span className="app-info-label">Script debug</span><span className="app-info-value">{debug?.debug?.SCRIPT_DEBUG ? 'on' : 'off'}</span></div>+ </div>+ <div className="app-detail-actions">+ <Button variant="outline" size="sm" onClick={toggleDebug} disabled={busy}>{debug?.enabled ? 'Disable debugging' : 'Enable debugging'}</Button>+ </div>+ <p className="hint">Logs errors to a private file outside the web root (never to the page or a public URL). Enable to capture PHP fatals; disable in production.</p>+ </div>+ </div>++ <div className="app-panel">+ <div className="app-panel-header">WP-Cron</div>+ <div className="app-panel-body">+ <div className="app-info-grid">+ <div className="app-info-item"><span className="app-info-label">Pseudo-cron</span><span className="app-info-value">{cron?.disabled ? 'disabled' : 'enabled'}</span></div>+ <div className="app-info-item"><span className="app-info-label">Scheduled events</span><span className="app-info-value">{(cron?.events || []).length}</span></div>+ </div>+ <div className="app-detail-actions">+ <Button variant="outline" size="sm" onClick={runCron} disabled={busy}>Run due events</Button>+ <Button variant="outline" size="sm" onClick={toggleCron} disabled={busy}>{cron?.disabled ? 'Enable WP-Cron' : 'Disable WP-Cron'}</Button>+ </div>+ <p className="hint">Disable WP-Cron only if a real system cron hits wp-cron.php — otherwise scheduled tasks (publishing, updates) will not run.</p>+ </div>+ </div>+ </div>+ </div>+ );+};+// Vulnerabilities Tab — cross-references plugin/theme/core versions against the// keyless WPVulnerability community feed (#28). On-demand background scan + poll.const VulnerabilitiesTab = ({ siteId }) => {diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 976357ec..f6d32951 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -189,6 +189,15 @@ const wordpressApi = {getVulnerabilities: (siteId) => api.request(`${BASE_PATH}/${siteId}/vulnerabilities`),scanVulnerabilities: (siteId) => api.request(`${BASE_PATH}/${siteId}/vulnerabilities/scan`, { method: 'POST' }),+ // Security depth (#30): file integrity / debug toggle / WP-Cron+ getIntegrity: (siteId) => api.request(`${BASE_PATH}/${siteId}/integrity`),+ scanIntegrity: (siteId) => api.request(`${BASE_PATH}/${siteId}/integrity/scan`, { method: 'POST' }),+ getDebug: (siteId) => api.request(`${BASE_PATH}/${siteId}/debug`),+ setDebug: (siteId, enabled) => api.request(`${BASE_PATH}/${siteId}/debug`, { method: 'POST', body: { enabled } }),+ getCron: (siteId) => api.request(`${BASE_PATH}/${siteId}/cron`),+ runCron: (siteId) => api.request(`${BASE_PATH}/${siteId}/cron/run`, { method: 'POST' }),+ setCronDisabled: (siteId, disabled) => api.request(`${BASE_PATH}/${siteId}/cron`, { method: 'POST', body: { disabled } }),+// Mint a one-time passwordless wp-admin login URL for the current operator.autoLogin: (siteId) => api.request(`${BASE_PATH}/${siteId}/login`, {method: 'POST'