Skip to content

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.

feat(wordpress): Phase-A glue — WP-CLI actions UI, sanitization wiring, promotion rollback, deep-links

Juan Denisdc54273ef0f3
diff --git a/backend/app/api/environment_pipeline.py b/backend/app/api/environment_pipeline.py
index dce8d270..689a5a6f 100644
--- a/backend/app/api/environment_pipeline.py
+++ b/backend/app/api/environment_pipeline.py
@@ -739,6 +739,55 @@ def get_promotions(prod_id):
})
+@environment_pipeline_bp.route('/<int:prod_id>/promotions/<int:promotion_id>/rollback', methods=['POST'])
+@jwt_required()
[email protected]("5 per minute")
+def rollback_promotion(prod_id, promotion_id):
+ """Restore a promotion's pre-promotion snapshot into its target environment."""
+ user_id = get_jwt_identity()
+
+ site, error = _get_production_site(prod_id, user_id)
+ if error:
+ return error
+
+ job = PromotionJob.query.get(promotion_id)
+ if not job:
+ return jsonify({'error': 'Promotion not found'}), 404
+
+ # The promotion must belong to this project (its source or target env).
+ env_ids = [prod_id] + [e.id for e in site.environments]
+ if job.source_site_id not in env_ids and job.target_site_id not in env_ids:
+ return jsonify({'error': 'Promotion does not belong to this project'}), 400
+
+ # Verify ownership of the target environment being restored.
+ _, error = _get_environment_site(job.target_site_id, user_id)
+ if error:
+ return error
+
+ _emit_pipeline_event(prod_id, 'rollback_started', {
+ 'promotion_id': promotion_id,
+ 'target_env_id': job.target_site_id,
+ 'message': f'Rolling back promotion #{promotion_id}...',
+ })
+
+ result = EnvironmentPipelineService.rollback_promotion(
+ promotion_id=promotion_id,
+ user_id=user_id,
+ )
+
+ _emit_pipeline_event(prod_id, 'rollback_completed' if result.get('success') else 'rollback_failed', {
+ 'promotion_id': promotion_id,
+ 'target_env_id': job.target_site_id,
+ 'success': result.get('success', False),
+ 'message': result.get('message') or result.get('error'),
+ })
+
+ if result.get('success'):
+ return jsonify(result)
+ else:
+ return jsonify(result), 500
+
+
# =============================================================================
# Environment Status (single environment detail)
# =============================================================================
diff --git a/backend/app/services/environment_pipeline_service.py b/backend/app/services/environment_pipeline_service.py
index 93adff6c..196ff088 100644
--- a/backend/app/services/environment_pipeline_service.py
+++ b/backend/app/services/environment_pipeline_service.py
@@ -483,6 +483,11 @@ class EnvironmentPipelineService:
'anonymize': options.get('sanitize', False),
}
+ # Apply sanitization profile rules if a profile was selected (sync)
+ cls._apply_sanitization_profile_options(
+ clone_options, options.get('sanitization_profile_id'), user_id=user_id
+ )
+
# Auto-add domain search-replace
prod_domain = cls._get_primary_domain(prod_site)
env_domain = cls._get_primary_domain(env_site)
@@ -885,6 +890,11 @@ class EnvironmentPipelineService:
'anonymize': config.get('sanitize', False),
}
+ # Apply sanitization profile rules if a profile was selected (promote)
+ cls._apply_sanitization_profile_options(
+ clone_options, config.get('sanitization_profile_id'), user_id=user_id
+ )
+
# Auto-add domain search-replace
source_domain = cls._get_primary_domain(source_site)
target_domain = cls._get_primary_domain(target_site)
@@ -969,6 +979,102 @@ class EnvironmentPipelineService:
cls._finish_activity(activity, 'failed', str(e), start_time)
return {'success': False, 'error': str(e)}
+ @classmethod
+ def rollback_promotion(cls, promotion_id: int, user_id: int = None) -> Dict:
+ """Restore a promotion's pre-promotion snapshot into its target environment DB.
+
+ Finds the PromotionJob's pre_promotion_snapshot (a DatabaseSnapshot of the
+ target taken just before the promotion) and restores that dump into the
+ target environment's database — container import when the target runs in
+ Docker, host restore otherwise — then sets job.status='rolled_back'.
+ """
+ job = PromotionJob.query.get(promotion_id)
+ if not job:
+ return {'success': False, 'error': 'Promotion not found'}
+
+ if not job.pre_promotion_snapshot_id:
+ return {'success': False, 'error': 'No pre-promotion snapshot available for this promotion'}
+
+ snapshot = DatabaseSnapshot.query.get(job.pre_promotion_snapshot_id)
+ if not snapshot or not snapshot.file_path:
+ return {'success': False, 'error': 'Pre-promotion snapshot record not found'}
+
+ if not os.path.exists(snapshot.file_path):
+ return {'success': False, 'error': f'Snapshot file not found: {snapshot.file_path}'}
+
+ target_site = WordPressSite.query.get(job.target_site_id)
+ if not target_site:
+ return {'success': False, 'error': 'Target environment not found'}
+
+ if target_site.is_locked:
+ return {'success': False, 'error': f'Target environment is locked: {target_site.locked_reason}'}
+
+ start_time = time.time()
+ activity = cls._create_activity(
+ site_id=job.target_site_id,
+ user_id=user_id,
+ action='rolled_back_promotion',
+ description=f'Rolling back promotion #{promotion_id} on {target_site.environment_type}',
+ status='running'
+ )
+
+ cls._lock_environment(target_site, 'Promotion rollback in progress', user_id)
+ try:
+ target_compose = cls._get_compose_path(target_site)
+ if target_compose:
+ target_vars = cls._read_env_vars(target_site)
+ restore_result = DatabaseSyncService.import_to_container(
+ compose_path=target_compose,
+ snapshot_path=snapshot.file_path,
+ db_name=target_site.db_name,
+ db_user=target_vars.get('DB_USER', target_site.db_user),
+ db_password=target_vars.get('DB_PASSWORD') or cls._get_env_password(target_site),
+ )
+ else:
+ restore_result = DatabaseSyncService.restore_snapshot(
+ file_path=snapshot.file_path,
+ target_db=target_site.db_name,
+ host=target_site.db_host or 'localhost',
+ user=target_site.db_user,
+ password=cls._get_db_password_from_config(target_site),
+ create_db=True,
+ )
+
+ if not restore_result.get('success'):
+ cls._unlock_environment(target_site)
+ cls._finish_activity(activity, 'failed', restore_result.get('error'), start_time)
+ return {'success': False, 'error': f"Rollback restore failed: {restore_result.get('error')}"}
+
+ # Flush caches on the target if it is containerized
+ if target_compose:
+ EnvironmentDockerService.exec_in_container(
+ target_compose, 'wordpress', 'wp cache flush --allow-root'
+ )
+
+ job.status = 'rolled_back'
+ db.session.commit()
+
+ cls._unlock_environment(target_site)
+ cls._finish_activity(activity, 'completed', None, start_time, {
+ 'promotion_job_id': job.id,
+ 'restored_snapshot_id': snapshot.id,
+ })
+
+ cls._send_notification('Promotion Rolled Back', {
+ 'message': f'Promotion #{promotion_id} rolled back on {target_site.environment_type}',
+ }, user_id)
+
+ return {
+ 'success': True,
+ 'message': f'Promotion #{promotion_id} rolled back',
+ 'promotion_job': job.to_dict(),
+ }
+
+ except Exception as e:
+ cls._unlock_environment(target_site)
+ cls._finish_activity(activity, 'failed', str(e), start_time)
+ return {'success': False, 'error': str(e)}
+
# ==================== FULL PROMOTION ====================
@classmethod
@@ -1415,6 +1521,44 @@ class EnvironmentPipelineService:
# ==================== PRIVATE HELPERS ====================
+ @classmethod
+ def _apply_sanitization_profile_options(cls, clone_options: Dict, profile_id,
+ user_id: int = None) -> None:
+ """Resolve a SanitizationProfile id and merge its rules into clone_options in place.
+
+ Composes with the boolean ``sanitize`` flag: profile anonymize flags win,
+ table lists are unioned, and search-replace maps are merged. No-ops when
+ ``profile_id`` is falsy or the profile is not found / not owned by the user.
+ """
+ if not profile_id:
+ return
+ try:
+ from app.models.sanitization_profile import SanitizationProfile
+ query = SanitizationProfile.query.filter_by(id=int(profile_id))
+ if user_id is not None:
+ query = query.filter_by(user_id=user_id)
+ profile = query.first()
+ if not profile:
+ return
+ profile_opts = DatabaseSyncService.apply_sanitization_profile(profile.get_config())
+ for key in ('anonymize', 'anonymize_names', 'reset_passwords', 'remove_transients'):
+ if profile_opts.get(key):
+ clone_options[key] = True
+ for key in ('truncate_tables', 'exclude_tables'):
+ if profile_opts.get(key):
+ existing = list(clone_options.get(key, []) or [])
+ for table in profile_opts[key]:
+ if table not in existing:
+ existing.append(table)
+ clone_options[key] = existing
+ if profile_opts.get('search_replace'):
+ merged = dict(clone_options.get('search_replace', {}) or {})
+ merged.update(profile_opts['search_replace'])
+ clone_options['search_replace'] = merged
+ except Exception:
+ # Best-effort: never break a clone because profile resolution failed.
+ pass
+
@classmethod
def _get_compose_path(cls, site: WordPressSite) -> Optional[str]:
"""Get the docker-compose.yml path for a site's environment."""
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 8de06597..b0186fc3 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -91,7 +91,7 @@ These are bugs the rest of the roadmap stands on. **Estimated cluster: half a da
Every task here reuses a service that already exists and is verified present. **This is the highest "managed feel" per hour.** Many run in parallel. **Estimated cluster: 1–2 days, parallelizable.**
-### #5 — Surface the orphaned WP-CLI actions in the UI `[S]` 🟡
+### #5 — Surface the orphaned WP-CLI actions in the UI `[S]` 🟡 — ✅ Done
- **Today:** Routes exist and work — `harden` (`api/wordpress.py:499`), `search-replace` (`:513`, serialized-safe), `flush-cache` (`:550`) — but `services/wordpress.js` has **no** `harden`/`searchReplace`/`flushCache` methods, so there's no button.
- **Do:** Add the three `ApiService` methods + controls on `WordPressDetail` (a "Purge Cache" button, a guarded search-replace dialog, a "Harden" action).
- **Reuse:** `WordPressService.harden_wordpress/search_replace/flush_cache` (`:497,609,626`).
@@ -115,13 +115,13 @@ Every task here reuses a service that already exists and is verified present. **
- **Reuse:** `ssl_service`, `advanced_ssl_service`, `security.js`.
- **Done when:** Creating/attaching a domain provisions TLS and the health card shows SSL status.
-### #9 — Stop dropping the sanitization profile `[S]` 🟡
+### #9 — Stop dropping the sanitization profile `[S]` 🟡 — ✅ Done
- **Today:** `PromoteModal`/`SyncModal` send `sanitization_profile_id`; `db_sync_service.apply_sanitization_profile` exists — but `api/environment_pipeline.py` / `EnvironmentPipelineService` never resolve the id; only the boolean `options['sanitize']` is honored. The profile (incl. WooCommerce payment-table stripping) is silently ignored.
- **Do:** Resolve `SanitizationProfile` by id in `promote_database`/`sync_from_production` and pass it to `_transform_dump`.
- **Reuse:** `apply_sanitization_profile`, `SanitizationProfile` model.
- **Done when:** A selected profile demonstrably rewrites/strips data on sync.
-### #10 — Close the rollback loop on promotions `[M]` 🟡
+### #10 — Close the rollback loop on promotions `[M]` 🟡 — ✅ Done
- **Today:** `PromotionJob.pre_promotion_snapshot_id` and status `rolled_back` exist; `db_sync_service.restore_snapshot` exists; pre-promotion snapshots are captured on **every** promote — but **nothing ever calls restore** and `rolled_back` is never set. The safety net is captured and never used.
- **Do:** Add `POST /promotions/<id>/rollback` that restores the linked snapshot and flips status; optionally auto-trigger on failed promote.
- **Reuse:** `restore_snapshot`, `PromotionJob`.
@@ -133,7 +133,7 @@ Every task here reuses a service that already exists and is verified present. **
- **Reuse:** `storage_provider_service`, `backup_service`, the cron scheduler.
- **Done when:** Snapshots replicate to configured object storage and age out per policy.
-### #12 — Deep-link DB, files, and logs from the site `[S]` 🟡
+### #12 — Deep-link DB, files, and logs from the site `[S]` 🟡 — ✅ Done
- **Today:** `QueryRunner.jsx` + `api/databases.py` and the File Manager + host log viewer exist but are reached only by raw DB-name / manual path; none deep-link to a site's `db_name` / docroot / `debug.log`.
- **Do:** Add "Open Database", "Open Files", and "View Logs" buttons that pass the site's `db_name`/`root_path`.
- **Reuse:** `QueryRunner`, File Manager, log viewer.
diff --git a/frontend/src/pages/Databases.jsx b/frontend/src/pages/Databases.jsx
index f6716b08..81218e52 100644
--- a/frontend/src/pages/Databases.jsx
+++ b/frontend/src/pages/Databases.jsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react';
-import { useParams } from 'react-router-dom';
+import { useParams, useSearchParams } from 'react-router-dom';
import useTabParam from '../hooks/useTabParam';
import api from '../services/api';
import { useToast } from '../contexts/ToastContext';
@@ -167,6 +167,7 @@ const MySQLTab = ({ status }) => {
const [showCreateUserModal, setShowCreateUserModal] = useState(false);
const [selectedDb, setSelectedDb] = useState(null);
const [queryDb, setQueryDb] = useState(null);
+ const [searchParams, setSearchParams] = useSearchParams();
useEffect(() => {
if (status?.running) {
@@ -183,8 +184,21 @@ const MySQLTab = ({ status }) => {
api.getMySQLDatabases(),
api.getMySQLUsers()
]);
- setDatabases(dbData.databases || []);
+ const dbList = dbData.databases || [];
+ setDatabases(dbList);
setUsers(userData.users || []);
+ // Deep-link support: open the QueryRunner for a ?db= database (e.g. from a WordPress site)
+ const wanted = searchParams.get('db');
+ if (wanted) {
+ const match = dbList.find(d => d.name === wanted);
+ if (match) {
+ setView('databases');
+ setQueryDb(match);
+ }
+ const next = new URLSearchParams(searchParams);
+ next.delete('db');
+ setSearchParams(next, { replace: true });
+ }
} catch (err) {
console.error('Failed to load MySQL data:', err);
} finally {
diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsx
index adfef93c..c90807df 100644
--- a/frontend/src/pages/WordPressDetail.jsx
+++ b/frontend/src/pages/WordPressDetail.jsx
@@ -1,9 +1,10 @@
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
-import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive } from 'lucide-react';
+import { ExternalLink, Settings, RefreshCw, Plus, Database, GitBranch, Package, Palette, Archive, Trash2, Replace, ShieldCheck, FolderOpen, FileText } from 'lucide-react';
import useTabParam from '../hooks/useTabParam';
import wordpressApi from '../services/wordpress';
import { useToast } from '../contexts/ToastContext';
+import { useLogsDrawer } from '../contexts/LogsDrawerContext';
import { EnvironmentCard, SnapshotTable, GitConnectForm, CommitList } from '../components/wordpress';
import { ErrorBoundary, ErrorState } from '../components/ErrorBoundary';
import { Button } from '@/components/ui/button';
@@ -70,6 +71,7 @@ const WordPressDetail = () => {
const { id } = useParams();
const navigate = useNavigate();
const toast = useToast();
+ const { openDrawer } = useLogsDrawer();
const [site, setSite] = useState(null);
const [loading, setLoading] = useState(true);
const [activeTab, setActiveTab] = useTabParam(`/wordpress/${id}`, VALID_TABS);
@@ -117,6 +119,33 @@ const WordPressDetail = () => {
<span className="current">{site.name}</span>
</div>
<div className="app-detail-actions">
+ <Button
+ variant="ghost"
+ onClick={() => navigate(`/files?path=${encodeURIComponent(site.application?.root_path || '/')}`)}
+ disabled={!site.application?.root_path}
+ title={site.application?.root_path ? `Open ${site.application.root_path} in the File Manager` : 'No root path configured for this site'}
+ >
+ <FolderOpen size={16} />
+ Open Files
+ </Button>
+ {site.db_name && (
+ <Button
+ variant="ghost"
+ onClick={() => navigate(`/databases/mysql?db=${encodeURIComponent(site.db_name)}`)}
+ title={`Open ${site.db_name} in the Database manager`}
+ >
+ <Database size={16} />
+ Open Database
+ </Button>
+ )}
+ <Button
+ variant="ghost"
+ onClick={() => openDrawer({ name: site.name, containerId: site.application_id, appType: 'docker' })}
+ title="View live container logs"
+ >
+ <FileText size={16} />
+ View Logs
+ </Button>
{site.url && (
<>
<Button variant="ghost" asChild>
@@ -245,6 +274,9 @@ const OverviewTab = ({ site, onUpdate }) => {
const [creatingSnapshot, setCreatingSnapshot] = useState(false);
const [showEnvModal, setShowEnvModal] = useState(false);
const [syncingAll, setSyncingAll] = useState(false);
+ const [flushingCache, setFlushingCache] = useState(false);
+ const [hardening, setHardening] = useState(false);
+ const [showSearchReplace, setShowSearchReplace] = useState(false);
async function handleQuickSnapshot() {
setCreatingSnapshot(true);
@@ -294,6 +326,51 @@ const OverviewTab = ({ site, onUpdate }) => {
}
}
+ async function handleFlushCache() {
+ setFlushingCache(true);
+ toast.info('Flushing cache...', { duration: 2000 });
+ try {
+ const res = await wordpressApi.flushCache(site.id);
+ toast.success(res.message || 'Cache flushed');
+ } catch (err) {
+ toast.error(err.message || 'Failed to flush cache');
+ } finally {
+ setFlushingCache(false);
+ }
+ }
+
+ async function handleHarden() {
+ if (!window.confirm('Apply security hardening? This disables file editing, the XML-RPC endpoint, forces SSL on wp-admin, tightens file permissions, and regenerates security keys (logs users out).')) {
+ return;
+ }
+ setHardening(true);
+ toast.info('Applying security hardening...', { duration: 4000 });
+ try {
+ const res = await wordpressApi.harden(site.id);
+ toast.success(res.message || 'Security hardening applied');
+ } catch (err) {
+ toast.error(err.message || 'Failed to harden site');
+ } finally {
+ setHardening(false);
+ }
+ }
+
+ async function handleSearchReplace(data) {
+ // data = { search, replace, dry_run }
+ toast.info(data.dry_run ? 'Running search-replace preview...' : 'Running search-replace...', { duration: 3000 });
+ try {
+ const res = await wordpressApi.searchReplace(site.id, data);
+ if (res.success === false) {
+ toast.error(res.error || res.message || 'Search-replace failed');
+ return;
+ }
+ toast.success(data.dry_run ? 'Dry run complete - no changes written' : 'Search-replace complete');
+ if (!data.dry_run) setShowSearchReplace(false);
+ } catch (err) {
+ toast.error(err.message || 'Search-replace failed');
+ }
+ }
+
return (
<div className="app-overview-grid">
<div className="app-overview-left">
@@ -438,6 +515,29 @@ const OverviewTab = ({ site, onUpdate }) => {
{syncingAll ? 'Syncing...' : 'Sync All Envs'}
</button>
)}
+ <button
+ className="quick-action-btn"
+ onClick={handleFlushCache}
+ disabled={flushingCache}
+ >
+ <Trash2 size={16} />
+ {flushingCache ? 'Flushing...' : 'Purge Cache'}
+ </button>
+ <button
+ className="quick-action-btn"
+ onClick={() => setShowSearchReplace(true)}
+ >
+ <Replace size={16} />
+ Search &amp; Replace
+ </button>
+ <button
+ className="quick-action-btn"
+ onClick={handleHarden}
+ disabled={hardening}
+ >
+ <ShieldCheck size={16} />
+ {hardening ? 'Hardening...' : 'Harden'}
+ </button>
</div>
</div>
</div>
@@ -457,6 +557,79 @@ const OverviewTab = ({ site, onUpdate }) => {
/>
);
})()}
+
+ {showSearchReplace && (
+ <SearchReplaceModal
+ onClose={() => setShowSearchReplace(false)}
+ onSubmit={handleSearchReplace}
+ />
+ )}
+ </div>
+ );
+};
+
+// Search & Replace Modal (DB string replacement, guarded by dry-run)
+const SearchReplaceModal = ({ onClose, onSubmit }) => {
+ const [search, setSearch] = useState('');
+ const [replace, setReplace] = useState('');
+ const [loading, setLoading] = useState(false);
+
+ async function run(dryRun) {
+ if (!search.trim() || !replace.trim()) return;
+ setLoading(true);
+ try {
+ await onSubmit({ search: search.trim(), replace: replace.trim(), dry_run: dryRun });
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="modal-overlay" onClick={onClose}>
+ <div className="modal" onClick={e => e.stopPropagation()}>
+ <div className="modal-header">
+ <h2>Search &amp; Replace</h2>
+ <button className="modal-close" onClick={onClose}>&times;</button>
+ </div>
+
+ <form onSubmit={(e) => { e.preventDefault(); run(false); }}>
+ <p className="hint">Replaces a string across all database tables (e.g. an old domain). Always preview with a dry run first.</p>
+
+ <div className="form-group">
+ <Label>Search for *</Label>
+ <Input
+ type="text"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ placeholder="https://old-domain.com"
+ required
+ />
+ </div>
+
+ <div className="form-group">
+ <Label>Replace with *</Label>
+ <Input
+ type="text"
+ value={replace}
+ onChange={(e) => setReplace(e.target.value)}
+ placeholder="https://new-domain.com"
+ required
+ />
+ </div>
+
+ <div className="modal-actions">
+ <Button type="button" variant="outline" onClick={onClose}>
+ Cancel
+ </Button>
+ <Button type="button" variant="outline" onClick={() => run(true)} disabled={loading || !search.trim() || !replace.trim()}>
+ {loading ? 'Running...' : 'Dry Run'}
+ </Button>
+ <Button type="submit" disabled={loading || !search.trim() || !replace.trim()}>
+ {loading ? 'Running...' : 'Run Replace'}
+ </Button>
+ </div>
+ </form>
+ </div>
</div>
);
};
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index fbdfbb8a..24ff4dd4 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -107,6 +107,20 @@ const wordpressApi = {
method: 'POST'
}),
+ // Maintenance & Security
+ flushCache: (siteId) => api.request(`${BASE_PATH}/${siteId}/flush-cache`, {
+ method: 'POST'
+ }),
+
+ searchReplace: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/search-replace`, {
+ method: 'POST',
+ body: data
+ }),
+
+ harden: (siteId) => api.request(`${BASE_PATH}/${siteId}/harden`, {
+ method: 'POST'
+ }),
+
// Clone Database (for advanced use)
cloneDatabase: (siteId, data) => api.request(`${BASE_PATH}/${siteId}/clone-db`, {
method: 'POST',
@@ -193,6 +207,12 @@ const wordpressApi = {
return api.request(`/wordpress/projects/${prodId}/promotions${query ? `?${query}` : ''}`);
},
+ // Restore a promotion's pre-promotion snapshot into its target environment
+ rollbackPromotion: (prodId, promotionId) => api.request(
+ `/wordpress/projects/${prodId}/promotions/${promotionId}/rollback`,
+ { method: 'POST' }
+ ),
+
// Git branches (for multidev)
getBranches: (prodId) => api.request(`/wordpress/projects/${prodId}/git/branches`),