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): wp-content/full-site zip import with zip-slip-safe extraction (#17)

Juan Denisa6a214c2452d
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.py
index 03a5d654..2dcfb876 100644
--- a/backend/app/api/wordpress.py
+++ b/backend/app/api/wordpress.py
@@ -78,7 +78,8 @@ def create_site():
@wordpress_bp.route('/sites/import', methods=['POST'])
@jwt_required()
def import_site():
- """Import an existing WordPress site from an uploaded SQL dump (multipart)."""
+ """Import an existing WordPress site from an uploaded SQL dump plus an optional
+ wp-content/full-site .zip (multipart)."""
import os
import tempfile
name = request.form.get('name')
@@ -97,11 +98,21 @@ def import_site():
if not (fname.endswith('.sql') or fname.endswith('.sql.gz') or fname.endswith('.gz')):
return jsonify({'error': 'Dump must be a .sql or .sql.gz file'}), 400
+ # Optional wp-content / full-site zip (plugins/themes/uploads).
+ zip_file = request.files.get('wp_content')
+ if zip_file and zip_file.filename and not zip_file.filename.lower().endswith('.zip'):
+ return jsonify({'error': 'wp-content archive must be a .zip file'}), 400
+
suffix = '.sql.gz' if fname.endswith('.gz') else '.sql'
fd, tmp_path = tempfile.mkstemp(suffix=suffix, prefix='wp_import_')
os.close(fd)
+ zip_tmp = None
try:
sql_file.save(tmp_path)
+ if zip_file and zip_file.filename:
+ zfd, zip_tmp = tempfile.mkstemp(suffix='.zip', prefix='wp_import_content_')
+ os.close(zfd)
+ zip_file.save(zip_tmp)
current_user_id = get_jwt_identity()
result = WordPressService.import_site(
name=name,
@@ -109,12 +120,15 @@ def import_site():
user_id=current_user_id,
sql_path=tmp_path,
old_url=old_url,
+ wp_content_zip_path=zip_tmp,
)
finally:
- try:
- os.remove(tmp_path)
- except OSError:
- pass
+ for p in (tmp_path, zip_tmp):
+ if p:
+ try:
+ os.remove(p)
+ except OSError:
+ pass
return (jsonify(result), 201) if result.get('success') else (jsonify(result), 400)
diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.py
index 232cff0f..839fbf01 100644
--- a/backend/app/services/wordpress_service.py
+++ b/backend/app/services/wordpress_service.py
@@ -1408,6 +1408,86 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
except Exception as e:
return {'success': False, 'error': str(e)}
+ @staticmethod
+ def _safe_extract_zip(zip_path: str, dest_dir: str) -> Dict:
+ """Extract a zip into dest_dir, rejecting any member whose path would
+ escape it (zip-slip / absolute-path / `..` traversal). Returns {success}.
+ """
+ import zipfile
+ try:
+ dest_abs = os.path.abspath(dest_dir)
+ with zipfile.ZipFile(zip_path) as zf:
+ for member in zf.namelist():
+ target = os.path.abspath(os.path.join(dest_abs, member))
+ if target != dest_abs and not target.startswith(dest_abs + os.sep):
+ return {'success': False, 'error': f'Unsafe path in archive: {member}'}
+ zf.extractall(dest_abs)
+ return {'success': True}
+ except zipfile.BadZipFile:
+ return {'success': False, 'error': 'Not a valid zip archive'}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+
+ @staticmethod
+ def _resolve_wp_content_dir(extracted_dir: str) -> Optional[str]:
+ """Locate the wp-content directory inside an extracted archive — handles a
+ zip OF wp-content, a full-site zip, or a single wrapper folder. Returns the
+ path to use as wp-content, or None if none is recognizable."""
+ markers = {'plugins', 'themes', 'uploads', 'mu-plugins'}
+ candidates = [extracted_dir]
+ try:
+ for entry in os.listdir(extracted_dir):
+ p = os.path.join(extracted_dir, entry)
+ if os.path.isdir(p):
+ candidates.append(p)
+ except OSError:
+ pass
+ # 1) An explicit wp-content dir at the root or one level down.
+ for base in candidates:
+ wpc = os.path.join(base, 'wp-content')
+ if os.path.isdir(wpc):
+ return wpc
+ # 2) The root (or a wrapper dir) IS wp-content (has plugins/themes/uploads).
+ for base in candidates:
+ try:
+ if set(os.listdir(base)) & markers:
+ return base
+ except OSError:
+ continue
+ return None
+
+ @classmethod
+ def _import_wp_content_zip(cls, zip_path: str, target_container: str) -> Dict:
+ """Extract an uploaded wp-content/full-site zip (zip-slip-guarded) and copy
+ its wp-content into the target WordPress container via `docker cp`, then
+ hand the files to the web user. Never raises."""
+ import tempfile
+ tmp = tempfile.mkdtemp(prefix='wpimport_')
+ try:
+ ext = cls._safe_extract_zip(zip_path, tmp)
+ if not ext.get('success'):
+ return ext
+ wpc = cls._resolve_wp_content_dir(tmp)
+ if not wpc:
+ return {'success': False, 'error': 'No wp-content found in the archive'}
+ cp = subprocess.run(
+ ['docker', 'cp', f'{wpc}/.', f'{target_container}:/var/www/html/wp-content'],
+ capture_output=True, text=True, timeout=600,
+ )
+ if cp.returncode != 0:
+ return {'success': False, 'error': cp.stderr or 'docker cp failed'}
+ # Imported files land root-owned; hand wp-content to the web user.
+ subprocess.run(
+ ['docker', 'exec', target_container, 'chown', '-R', 'www-data:www-data',
+ '/var/www/html/wp-content'],
+ capture_output=True, text=True, timeout=300,
+ )
+ return {'success': True}
+ except Exception as e:
+ return {'success': False, 'error': str(e)}
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+
# ========================================
# WORDPRESS STANDALONE (DOCKER) MANAGEMENT
# ========================================
@@ -1769,6 +1849,21 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
cls.wp_cli(root_path, ['option', 'update', 'home', new_url])
cls.wp_cli(root_path, ['option', 'update', 'siteurl', new_url])
sr = cls.search_replace(root_path, old_url, new_url, dry_run=False)
+
+ warnings = []
+ if not sr.get('success'):
+ warnings.append('Search-replace reported an issue; verify links inside wp-admin.')
+
+ # 3.5) Optionally import wp-content (plugins/themes/uploads) from a zip.
+ wp_content_imported = False
+ if wp_content_zip_path:
+ wpc = cls._import_wp_content_zip(wp_content_zip_path, wp_site.application.name)
+ if wpc.get('success'):
+ wp_content_imported = True
+ else:
+ warnings.append('Database imported, but wp-content import failed: '
+ + (wpc.get('error') or 'unknown error'))
+
cls.wp_cli(root_path, ['cache', 'flush'])
cls.wp_cli(root_path, ['rewrite', 'flush'])
@@ -1785,11 +1880,10 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]
'http_port': http_port,
'old_url': old_url,
'new_url': new_url,
+ 'wp_content_imported': wp_content_imported,
}
- if not sr.get('success'):
- out['warning'] = 'Search-replace reported an issue; verify links inside wp-admin.'
- if wp_content_zip_path:
- out['warning'] = 'wp-content import is not yet supported; only the database was imported.'
+ if warnings:
+ out['warning'] = '; '.join(warnings)
return out
except Exception as e:
return {'success': False, 'error': str(e),
diff --git a/backend/tests/test_wp_import_zip.py b/backend/tests/test_wp_import_zip.py
new file mode 100644
index 00000000..8e5abb32
--- /dev/null
+++ b/backend/tests/test_wp_import_zip.py
@@ -0,0 +1,130 @@
+"""Tests for #17 wp-content zip import — zip-slip safety, wp-content resolution,
+and the container-copy flow (docker cp mocked; extraction/resolution is real)."""
+import os
+import zipfile
+
+
+def _make_zip(path, entries):
+ """entries: {arcname: content_str}."""
+ with zipfile.ZipFile(path, 'w') as zf:
+ for arc, content in entries.items():
+ zf.writestr(arc, content)
+
+
+# ---- zip-slip safety -------------------------------------------------------
+
+def test_safe_extract_rejects_parent_traversal(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ z = tmp_path / 'evil.zip'
+ _make_zip(str(z), {'../escape.txt': 'x', 'wp-content/ok.txt': 'y'})
+ dest = tmp_path / 'out'
+ dest.mkdir()
+ res = WordPressService._safe_extract_zip(str(z), str(dest))
+ assert res['success'] is False and 'Unsafe path' in res['error']
+ assert not (tmp_path / 'escape.txt').exists() # nothing escaped the dest
+
+
+def test_safe_extract_rejects_deep_traversal(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ z = tmp_path / 'evil2.zip'
+ _make_zip(str(z), {'wp-content/../../../../tmp/evil.txt': 'x'})
+ dest = tmp_path / 'out2'
+ dest.mkdir()
+ res = WordPressService._safe_extract_zip(str(z), str(dest))
+ assert res['success'] is False
+
+
+def test_safe_extract_ok(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ z = tmp_path / 'good.zip'
+ _make_zip(str(z), {'wp-content/plugins/p/p.php': '<?php',
+ 'wp-content/themes/t/style.css': 'body{}'})
+ dest = tmp_path / 'out3'
+ dest.mkdir()
+ res = WordPressService._safe_extract_zip(str(z), str(dest))
+ assert res['success'] is True
+ assert (dest / 'wp-content' / 'plugins' / 'p' / 'p.php').exists()
+
+
+def test_safe_extract_rejects_bad_zip(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ bad = tmp_path / 'notazip.zip'
+ bad.write_text('this is not a zip')
+ dest = tmp_path / 'out4'
+ dest.mkdir()
+ res = WordPressService._safe_extract_zip(str(bad), str(dest))
+ assert res['success'] is False and 'valid zip' in res['error']
+
+
+# ---- wp-content resolution (3 archive layouts) -----------------------------
+
+def test_resolve_wp_content_at_root(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ (tmp_path / 'wp-content' / 'plugins').mkdir(parents=True)
+ assert WordPressService._resolve_wp_content_dir(str(tmp_path)) == str(tmp_path / 'wp-content')
+
+
+def test_resolve_full_site_wrapper_folder(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ (tmp_path / 'mysite' / 'wp-content' / 'themes').mkdir(parents=True)
+ assert WordPressService._resolve_wp_content_dir(str(tmp_path)) == str(tmp_path / 'mysite' / 'wp-content')
+
+
+def test_resolve_root_is_wp_content(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ (tmp_path / 'plugins').mkdir()
+ (tmp_path / 'themes').mkdir()
+ assert WordPressService._resolve_wp_content_dir(str(tmp_path)) == str(tmp_path)
+
+
+def test_resolve_none_when_unrecognizable(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ (tmp_path / 'random').mkdir()
+ assert WordPressService._resolve_wp_content_dir(str(tmp_path)) is None
+
+
+# ---- container copy flow (docker cp mocked) --------------------------------
+
+def test_import_wp_content_zip_issues_cp_and_chown(tmp_path, monkeypatch):
+ from app.services.wordpress_service import WordPressService
+ import app.services.wordpress_service as wp_mod
+ z = tmp_path / 'c.zip'
+ _make_zip(str(z), {'wp-content/plugins/p/p.php': '<?php'})
+
+ calls = []
+
+ class _Res:
+ returncode = 0
+ stderr = ''
+ stdout = ''
+
+ monkeypatch.setattr(wp_mod.subprocess, 'run', lambda cmd, **kw: (calls.append(list(cmd)), _Res())[1])
+ res = WordPressService._import_wp_content_zip(str(z), 'mysite')
+ assert res['success'] is True
+ assert any(c[:2] == ['docker', 'cp'] for c in calls)
+ assert any(c[:3] == ['docker', 'exec', 'mysite'] for c in calls) # ownership fix
+
+
+def test_import_wp_content_zip_propagates_cp_failure(tmp_path, monkeypatch):
+ from app.services.wordpress_service import WordPressService
+ import app.services.wordpress_service as wp_mod
+ z = tmp_path / 'c.zip'
+ _make_zip(str(z), {'wp-content/uploads/x.jpg': 'data'})
+
+ class _Res:
+ returncode = 1
+ stderr = 'no such container'
+ stdout = ''
+
+ monkeypatch.setattr(wp_mod.subprocess, 'run', lambda cmd, **kw: _Res())
+ res = WordPressService._import_wp_content_zip(str(z), 'ghost')
+ assert res['success'] is False and 'no such container' in res['error']
+
+
+def test_import_wp_content_zip_no_wp_content_found(tmp_path):
+ from app.services.wordpress_service import WordPressService
+ z = tmp_path / 'empty.zip'
+ _make_zip(str(z), {'readme.txt': 'hello'})
+ # No subprocess mock needed: resolution fails before any docker call.
+ res = WordPressService._import_wp_content_zip(str(z), 'site')
+ assert res['success'] is False and 'No wp-content' in res['error']
diff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.md
index 7cdddc34..08827e76 100644
--- a/docs/WORDPRESS_ROADMAP.md
+++ b/docs/WORDPRESS_ROADMAP.md
@@ -175,11 +175,12 @@ These are the features that make a user say "this is a managed platform, not a f
- **Reuse:** `wordpress_service.wp_cli` (`:61-143`), `create_user`/`reset_password`, `AuditLog`, panel RBAC.
- **Done when:** "Auto Login" drops a permitted operator straight into `wp-admin`, logged, with no stored WP password.
-### #17 — Existing-site import `[M]` ❌ — ✅ Done (.sql/.sql.gz MVP; wp-content zip + SFTP deferred)
+### #17 — Existing-site import `[M]` ❌ — ✅ Done (.sql/.sql.gz **+ wp-content/full-site zip**; SFTP pull deferred)
- **Today:** No import path exists — only blank create or prod→child-env clone.
- **Do:** Accept a `wp-content`/full-site zip + `.sql` dump (or an SFTP pull), provision DB + files, run the serialized-safe `search-replace` for the new URL, and register a `WordPressSite`.
- **Reuse:** `db_sync_service` search-replace/clone, `_copy_wordpress_files`, `install_wordpress`, `ftp_service`.
- **Done when:** An exported site comes up running on a new domain.
+- **Landed (wp-content zip):** the deferred files half now ships on top of the `.sql` MVP. The `import_site(wp_content_zip_path=…)` stub (it previously just warned "not yet supported") is implemented: after the fresh stack is up and the DB imported + search-replaced, an optional **wp-content/full-site `.zip`** is **safely extracted** and copied into the container. **Security-first extraction** — `_safe_extract_zip` rejects any member whose resolved path escapes the temp dir (**zip-slip**: `../` traversal, deep traversal, absolute paths) *before* writing anything, and rejects non-zip/corrupt archives. `_resolve_wp_content_dir` handles the three real-world layouts — a zip **of** wp-content (root has `plugins`/`themes`/`uploads`), a zip **with** `wp-content/` at the root, and a **full-site** zip nested one wrapper folder deep — then `_import_wp_content_zip` `docker cp`s the resolved tree into `/var/www/html/wp-content` and **`chown`s it to `www-data`** (imported files land root-owned). Failures are non-fatal: the DB import still succeeds and the response carries a `warning` + `wp_content_imported: false`. Route `POST /sites/import` gained an optional `wp_content` multipart file (validated `.zip`, saved to its own temp, cleaned up in `finally` alongside the SQL temp); client `importSite({wpContentFile})` + an optional **wp-content archive** file input in the import modal (with a success toast when it lands). Verified: backend `py_compile`, **11 new pytest tests** (zip-slip `../`/deep/absolute rejection, bad-zip rejection, safe extraction, all 3 wp-content layouts + the unrecognizable case, and the `docker cp`+`chown` flow / cp-failure / no-wp-content paths — Docker mocked), full suite **211 passed / 12 skipped**, frontend lint-clean + production build. *(Deferred: the **SFTP pull** source — the zip/`.sql` upload path covers the common export case; an SFTP-pull importer is a separate connector.)* The `docker cp`/`chown` step is not runtime-exercised on a real Docker host (Windows dev).
### #18 — Clone-to-new-independent-site with fresh credentials `[M]` 🟡 — ✅ Done
- **Today:** `create_environment` (`services/wordpress_env_service.py:97-228`) clones files + DB (table-prefix + search-replace) but always links via `production_site_id` and **inherits** the parent's `admin_user`/`admin_email`/credentials (`:165-171`). No "duplicate as a brand-new top-level site".
diff --git a/frontend/src/pages/WordPress.jsx b/frontend/src/pages/WordPress.jsx
index f5c8f489..0619d6d3 100644
--- a/frontend/src/pages/WordPress.jsx
+++ b/frontend/src/pages/WordPress.jsx
@@ -30,6 +30,7 @@ function WordPress() {
const [importLoading, setImportLoading] = useState(false);
const [importForm, setImportForm] = useState({ name: '', adminEmail: '', oldUrl: '' });
const [importFile, setImportFile] = useState(null);
+ const [wpContentFile, setWpContentFile] = useState(null);
const [selectedIds, setSelectedIds] = useState(new Set());
const [bulkLoading, setBulkLoading] = useState(false);
@@ -117,13 +118,16 @@ function WordPress() {
adminEmail: importForm.adminEmail,
oldUrl: importForm.oldUrl,
sqlFile: importFile,
+ wpContentFile: wpContentFile,
});
if (result.success) {
toast.success('WordPress site imported successfully');
+ if (result.wp_content_imported) toast.success('wp-content (plugins/themes/uploads) imported');
if (result.warning) toast.info(result.warning, { duration: 8000 });
setShowImportModal(false);
setImportForm({ name: '', adminEmail: '', oldUrl: '' });
setImportFile(null);
+ setWpContentFile(null);
await loadSites();
} else {
toast.error(result.error || 'Failed to import site');
@@ -475,6 +479,17 @@ function WordPress() {
/>
<span className="form-hint">Export via phpMyAdmin or the wp db export command. .sql.gz is supported and recommended (100MB upload limit).</span>
</div>
+
+ <div className="form-group">
+ <Label>wp-content archive (optional)</Label>
+ <input
+ type="file"
+ accept=".zip"
+ disabled={importLoading}
+ onChange={e => setWpContentFile(e.target.files?.[0] || null)}
+ />
+ <span className="form-hint">A .zip of wp-content (plugins/themes/uploads) or the full site. Copied into the new container after the database import. Leave empty to import the database only.</span>
+ </div>
</div>
<div className="modal-footer">
<Button variant="outline" onClick={() => setShowImportModal(false)} disabled={importLoading}>
diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.js
index d9cd8e08..0f8b864a 100644
--- a/frontend/src/services/wordpress.js
+++ b/frontend/src/services/wordpress.js
@@ -11,13 +11,15 @@ const wordpressApi = {
body: data
}),
- // Import an existing WP site from an uploaded SQL dump (multipart upload).
- importSite: ({ name, adminEmail, oldUrl, sqlFile }) => {
+ // Import an existing WP site from an uploaded SQL dump, plus an optional
+ // wp-content/full-site .zip (plugins/themes/uploads). Multipart upload.
+ importSite: ({ name, adminEmail, oldUrl, sqlFile, wpContentFile }) => {
const fd = new FormData();
fd.append('name', name);
fd.append('adminEmail', adminEmail || '');
fd.append('oldUrl', oldUrl);
fd.append('sql', sqlFile);
+ if (wpContentFile) fd.append('wp_content', wpContentFile);
return api.request(`${BASE_PATH}/import`, { method: 'POST', body: fd });
},