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.

test: split WP suites — extension-owned move to serverkit-wordpress

Juan Denisba3bc685feaf
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 356648b8..765e26d0 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -211,3 +211,58 @@ def scoping_rbac(app):
viewer=_scope_token(viewer.id),
foreign=_scope_token(foreign.id),
)
+
+
+# --- WordPress extension (plan 52 Phase 5) -----------------------------------
+# WordPress left the tree into the standalone serverkit-wordpress repo. Core
+# suites that exercise core features THROUGH the WP surface (domains, site
+# routing, url swap, authz, workspace scoping, …) load it from a sibling
+# checkout when one is available and skip cleanly when it isn't — a fresh
+# ServerKit clone's suite must pass without the extension source.
+
+
+def _wp_ext_tests_dir():
+ """The standalone serverkit-wordpress repo's tests/ dir, or None."""
+ env = os.environ.get('SERVERKIT_WORDPRESS_DIR')
+ candidates = [env] if env else []
+ # default sibling checkout: <workspace>/serverkit-wordpress next to
+ # <workspace>/ServerKit
+ candidates.append(os.path.join(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(
+ os.path.abspath(__file__))))), 'serverkit-wordpress'))
+ for cand in candidates:
+ if cand and os.path.isfile(os.path.join(cand, 'tests', '_wp_support.py')):
+ return os.path.join(cand, 'tests')
+ return None
+
+
+def wp_extension(app):
+ """Mount the WordPress extension on the test app from its standalone repo
+ (active row + blueprint mounts + core_hooks seams), or skip when the
+ source isn't available. Set SERVERKIT_WORDPRESS_DIR to its checkout."""
+ tests_dir = _wp_ext_tests_dir()
+ if not tests_dir:
+ pytest.skip('serverkit-wordpress source not available '
+ '(set SERVERKIT_WORDPRESS_DIR to its checkout)')
+ if tests_dir not in sys.path:
+ sys.path.insert(0, tests_dir)
+ import _wp_support
+ return _wp_support.ensure_plugin(app)
+
+
+def wp_extension_package():
+ """Load just the WordPress extension's backend package (app.plugins
+ .serverkit-wordpress.*) from its standalone repo — enough for the lazy
+ wordpress_bridge to resolve service classes. Skips when the source isn't
+ available. For route-level tests use wp_extension (also mounts
+ blueprints + seeds the active row)."""
+ tests_dir = _wp_ext_tests_dir()
+ if not tests_dir:
+ pytest.skip('serverkit-wordpress source not available '
+ '(set SERVERKIT_WORDPRESS_DIR to its checkout)')
+ if tests_dir not in sys.path:
+ sys.path.insert(0, tests_dir)
+ import _wp_support
+ return _wp_support.load_ext()
diff --git a/backend/tests/test_api_authz_hardening.py b/backend/tests/test_api_authz_hardening.py
index c1a66281..23e3ed30 100644
--- a/backend/tests/test_api_authz_hardening.py
+++ b/backend/tests/test_api_authz_hardening.py
@@ -97,7 +97,7 @@ def _destructive_calls(client, rbac):
@pytest.mark.parametrize('persona', ['viewer', 'foreign'])
-def test_p0_destructive_denied_for_unauthorized(app, client, rbac, persona):
+def test_p0_destructive_denied_for_unauthorized(app, client, rbac, persona, wp_extension):
"""A viewer-grant and a foreign non-member cannot delete/alter any site —
the regression anchor: a viewer cannot delete a site."""
headers = getattr(rbac, persona)
@@ -107,7 +107,7 @@ def test_p0_destructive_denied_for_unauthorized(app, client, rbac, persona):
@pytest.mark.parametrize('persona', ['owner', 'editor', 'admin'])
-def test_p0_destructive_allowed_for_authorized(app, client, rbac, persona):
+def test_p0_destructive_allowed_for_authorized(app, client, rbac, persona, wp_extension):
"""Owner, editor-grantee, and admin all pass the write gate (the operation
itself may 400 without Docker, but it must NOT be the auth 404)."""
headers = getattr(rbac, persona)
@@ -116,7 +116,7 @@ def test_p0_destructive_allowed_for_authorized(app, client, rbac, persona):
assert r.status_code != 404, f'{persona} was denied {label} (got 404)'
-def test_p0_destructive_missing_site_is_404_even_for_admin(app, client, rbac):
+def test_p0_destructive_missing_site_is_404_even_for_admin(app, client, rbac, wp_extension):
"""A non-existent site is 404 for everyone, including admin (no info leak /
no crash) — the guard resolves the app before acting."""
r = client.delete('/api/v1/wordpress/sites/987654', headers=rbac.admin)
@@ -134,7 +134,7 @@ def _sealed_denied(r):
return r.status_code == 404 and (r.get_json() or {}).get('error') == 'Not found'
-def test_sealed_reads_hidden_from_foreign(app, client, rbac):
+def test_sealed_reads_hidden_from_foreign(app, client, rbac, wp_extension):
"""Previously-open <site_id>/<app_id> reads now hide behind the gate for a
foreign caller (404 'Not found') and open for any grant (Decision 5)."""
sid, aid = rbac.site_id, rbac.app_id
@@ -153,7 +153,7 @@ def test_sealed_reads_hidden_from_foreign(app, client, rbac):
assert not _sealed_denied(client.get(url, headers=rbac.admin)), f'admin denied {url}'
-def test_convergence_reads_403_for_foreign_grant_opens(app, client, rbac):
+def test_convergence_reads_403_for_foreign_grant_opens(app, client, rbac, wp_extension):
"""The eight formerly-inline `role != 'admin'` feature reads keep their 403 on
denial (Decision 5) but now honor grants (Decision 3): a viewer-grant reaches
them, exactly as it already reaches the app's volumes/deployments."""
@@ -336,7 +336,7 @@ def test_raw_docker_processes_admin_only(app, client, scoping_rbac, persona):
@pytest.mark.parametrize('persona', ['viewer', 'member', 'foreign'])
-def test_wordpress_standalone_host_ops_admin_only(app, client, scoping_rbac, persona):
+def test_wordpress_standalone_host_ops_admin_only(app, client, scoping_rbac, persona, wp_extension):
"""#3 — the standalone install/uninstall/start/stop/restart host ops predate
the per-app model and touch the host → admin-only (plan 19's host-touching
matrix). A non-admin is 403 on every one; admin passes the gate."""
diff --git a/backend/tests/test_app_wordpress_surface.py b/backend/tests/test_app_wordpress_surface.py
deleted file mode 100644
index 8bb2dbdc..00000000
--- a/backend/tests/test_app_wordpress_surface.py
+++ /dev/null
@@ -1,89 +0,0 @@
-"""§7 unification — WordPress reachable through the generic /apps surface.
-
-A WordPress site is a 1:1 extension of an Application. These additive routes
-expose the linkage (/apps/:id/wordpress) and the WP DB snapshots
-(/apps/:id/db-snapshots) under the app id WITHOUT changing app_type, so the
-docker-compose paths that key on app_type=='docker' are unaffected.
-"""
-import pytest
-
-from app.services import wordpress_bridge
-
-
-def _seed_app(app, *, wordpress=True):
- from app import db
- from app.models import User
- from app.models.application import Application
- from app.models.wordpress_site import WordPressSite
- with app.app_context():
- admin = User.query.filter_by(username='testadmin').first()
- a = Application(name='wp-app', app_type='docker', status='running',
- root_path='/srv/wp', user_id=admin.id if admin else 1)
- db.session.add(a)
- db.session.commit()
- site_id = None
- if wordpress:
- site = WordPressSite(application_id=a.id, db_name='wpdb', db_user='wpuser',
- db_host='localhost', is_production=True,
- environment_type='production', wp_version='6.5')
- db.session.add(site)
- db.session.commit()
- site_id = site.id
- return a.id, site_id
-
-
-def test_app_wordpress_info_true(app, client, auth_headers):
- app_id, site_id = _seed_app(app, wordpress=True)
- res = client.get(f'/api/v1/apps/{app_id}/wordpress', headers=auth_headers)
- assert res.status_code == 200
- body = res.get_json()
- assert body['is_wordpress'] is True
- assert body['site_id'] == site_id
- assert body['is_production'] is True
-
-
-def test_app_wordpress_info_false_for_plain_app(app, client, auth_headers):
- app_id, _ = _seed_app(app, wordpress=False)
- res = client.get(f'/api/v1/apps/{app_id}/wordpress', headers=auth_headers)
- assert res.status_code == 200
- assert res.get_json()['is_wordpress'] is False
-
-
-def test_db_snapshots_rejects_non_wordpress(app, client, auth_headers):
- app_id, _ = _seed_app(app, wordpress=False)
- res = client.get(f'/api/v1/apps/{app_id}/db-snapshots', headers=auth_headers)
- assert res.status_code == 400
-
-
-def test_db_snapshots_list_empty(app, client, auth_headers):
- app_id, _ = _seed_app(app, wordpress=True)
- res = client.get(f'/api/v1/apps/{app_id}/db-snapshots', headers=auth_headers)
- assert res.status_code == 200
- assert res.get_json()['snapshots'] == []
-
-
-def test_db_snapshot_create_and_delete(app, client, auth_headers, monkeypatch):
- from app.services.db_sync_service import DatabaseSyncService
- WordPressEnvService = wordpress_bridge.get('wordpress_env_service', 'WordPressEnvService')
-
- monkeypatch.setattr(WordPressEnvService, '_get_db_password', staticmethod(lambda site: 'pw'))
- monkeypatch.setattr(DatabaseSyncService, 'create_snapshot', staticmethod(
- lambda **kw: {'success': True, 'snapshot': {
- 'name': kw.get('name'), 'file_path': '/var/backups/snap.sql.gz',
- 'size_bytes': 1234, 'compressed': True, 'tables': ['wp_posts'], 'row_count': 10,
- }}))
- monkeypatch.setattr(DatabaseSyncService, 'upload_snapshot_offsite', staticmethod(lambda p: None))
- monkeypatch.setattr(DatabaseSyncService, 'delete_snapshot', staticmethod(lambda p: True))
-
- app_id, _ = _seed_app(app, wordpress=True)
- created = client.post(f'/api/v1/apps/{app_id}/db-snapshots',
- json={'name': 'nightly', 'tag': 'manual'}, headers=auth_headers)
- assert created.status_code == 201, created.get_json()
- snap_id = created.get_json()['snapshot']['id']
-
- listed = client.get(f'/api/v1/apps/{app_id}/db-snapshots', headers=auth_headers)
- assert listed.get_json()['total'] == 1
-
- deleted = client.delete(f'/api/v1/apps/{app_id}/db-snapshots/{snap_id}', headers=auth_headers)
- assert deleted.status_code == 200
- assert client.get(f'/api/v1/apps/{app_id}/db-snapshots', headers=auth_headers).get_json()['total'] == 0
diff --git a/backend/tests/test_attach_domain.py b/backend/tests/test_attach_domain.py
index a26637e9..abcfe418 100644
--- a/backend/tests/test_attach_domain.py
+++ b/backend/tests/test_attach_domain.py
@@ -96,7 +96,7 @@ def test_ensure_a_record_no_ip(app):
# ── attach orchestration ────────────────────────────────────────────────────
-def test_attach_auto_dns_and_migrate(app, monkeypatch):
+def test_attach_auto_dns_and_migrate(app, monkeypatch, wp_extension_package):
from app import db
from app.services.dns_provider_service import DNSProviderService
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
@@ -125,7 +125,7 @@ def test_attach_auto_dns_and_migrate(app, monkeypatch):
assert res['warning'] is None
-def test_attach_manual_dns_surfaces_record(app, monkeypatch):
+def test_attach_manual_dns_surfaces_record(app, monkeypatch, wp_extension_package):
from app import db
from app.services.dns_provider_service import DNSProviderService
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
@@ -146,7 +146,7 @@ def test_attach_manual_dns_surfaces_record(app, monkeypatch):
assert 'manually' in res['warning'].lower()
-def test_attach_with_ssl_migrates_https(app, monkeypatch):
+def test_attach_with_ssl_migrates_https(app, monkeypatch, wp_extension_package):
from app import db
import app.services.ssl_service as ssl_mod
import app.services.nginx_service as nginx_mod
@@ -173,7 +173,7 @@ def test_attach_with_ssl_migrates_https(app, monkeypatch):
assert captured['url'] == 'https://secure.example.com' # https once the cert is obtained
-def test_attach_without_migrate_sets_primary_domain(app, monkeypatch):
+def test_attach_without_migrate_sets_primary_domain(app, monkeypatch, wp_extension_package):
from app import db
import app.services.nginx_service as nginx_mod
from app.models.domain import Domain
diff --git a/backend/tests/test_authz_structural_sweep.py b/backend/tests/test_authz_structural_sweep.py
index fd2ab319..453b710f 100644
--- a/backend/tests/test_authz_structural_sweep.py
+++ b/backend/tests/test_authz_structural_sweep.py
@@ -39,17 +39,29 @@ def _repo_root():
def _route_files():
- """Every api/*.py file + the WordPress flagship bridge, as (label, abspath)."""
+ """Every api/*.py file + the WordPress extension's route file, as
+ (label, abspath).
+
+ WordPress left the tree in plan 52 Phase 5: its blueprint file is swept
+ from the standalone repo's checkout when one is available (sibling or
+ SERVERKIT_WORDPRESS_DIR) — the same loader the wp_extension fixtures use.
+ Absent, the sweep covers core routes only (the extension repo carries the
+ same sweep for its own file via its symlinked suite)."""
root = _repo_root()
api_dir = os.path.join(root, 'backend', 'app', 'api')
files = []
for fname in sorted(os.listdir(api_dir)):
if fname.endswith('.py') and fname != '__init__.py':
files.append((fname, os.path.join(api_dir, fname)))
- files.append((
- 'wordpress.py',
- os.path.join(root, 'builtin-extensions', 'serverkit-wordpress', 'backend', 'wordpress.py'),
- ))
+ wp_candidates = [
+ os.environ.get('SERVERKIT_WORDPRESS_DIR', ''),
+ os.path.join(os.path.dirname(root), 'serverkit-wordpress'),
+ ]
+ for cand in wp_candidates:
+ wp_file = os.path.join(cand, 'backend', 'wordpress.py') if cand else ''
+ if wp_file and os.path.isfile(wp_file):
+ files.append(('wordpress.py', wp_file))
+ break
return files
diff --git a/backend/tests/test_fail2ban_jail_service.py b/backend/tests/test_fail2ban_jail_service.py
index 8cf71815..e6f4720c 100644
--- a/backend/tests/test_fail2ban_jail_service.py
+++ b/backend/tests/test_fail2ban_jail_service.py
@@ -233,7 +233,7 @@ def test_remove_jail_by_key_targets_serverkit_file():
# ---------- WpSecurityService wrapper ----------
-def test_wp_security_set_brute_force_delegates_to_jail_service():
+def test_wp_security_set_brute_force_delegates_to_jail_service(wp_extension_package):
WpSecurityService = wordpress_bridge.get('wp_security_service', 'WpSecurityService')
app = _app('myblog')
site = types.SimpleNamespace(application=app)
@@ -246,7 +246,7 @@ def test_wp_security_set_brute_force_delegates_to_jail_service():
assert r_on['success'] and r_off['success']
-def test_wp_security_brute_force_handles_missing_application():
+def test_wp_security_brute_force_handles_missing_application(wp_extension_package):
WpSecurityService = wordpress_bridge.get('wp_security_service', 'WpSecurityService')
site = types.SimpleNamespace(application=None)
assert WpSecurityService.set_brute_force(site, True)['success'] is False
diff --git a/backend/tests/test_onboarding_recommendations.py b/backend/tests/test_onboarding_recommendations.py
index c640ff00..bd34d4ec 100644
--- a/backend/tests/test_onboarding_recommendations.py
+++ b/backend/tests/test_onboarding_recommendations.py
@@ -2,8 +2,14 @@
Proves the use-case → extension-slug map has no dead slugs, the recommendation
resolver/endpoint returns real extension metadata, complete-onboarding persists
-what the wizard installed, and wizard-optional flagships (WordPress) are gated on
-fresh installs but kept on completed-setup ones.
+what the wizard installed, and the flagship seeding machinery still works.
+
+WordPress note (plan 52 Phase 5): WP left the tree into the standalone
+serverkit-wordpress repo and now distributes through the registry (the
+k8s/tramo model) — the wizard offers it via the use-case map, but nothing
+auto-seeds it. The wizard-optional flagship list is empty until a future
+in-tree flagship needs it; the gating machinery is proven here with a
+monkeypatched member.
"""
import pytest
@@ -99,56 +105,52 @@ def test_complete_onboarding_still_completes_without_installs(client, auth_heade
# ── wizard-optional flagship gating ──────────────────────────────────────────
-def test_finalize_setup_flagships_marks_uninstalled_when_absent(app):
+def test_finalize_setup_flagships_marks_uninstalled_when_absent(app, monkeypatch):
+ """The wizard-optional gating machinery: an uninstalled member gets the
+ uninstall marker so the boot seeder never re-adds it. (The list is empty
+ post-Phase-5 — WordPress graduated to the registry — so the machinery is
+ proven with a monkeypatched member.)"""
+ monkeypatch.setattr(ps, 'WIZARD_OPTIONAL_FLAGSHIP_SLUGS', ['serverkit-demo-opt'])
with app.app_context():
- InstalledPlugin.query.filter_by(slug='serverkit-wordpress').delete()
- db.session.commit()
ps.finalize_setup_flagships()
- assert 'serverkit-wordpress' in ps._flagship_uninstalled_set()
+ assert 'serverkit-demo-opt' in ps._flagship_uninstalled_set()
-def test_finalize_setup_flagships_keeps_installed(app):
+def test_finalize_setup_flagships_keeps_installed(app, monkeypatch):
+ """An INSTALLED wizard-optional flagship is never marked uninstalled."""
+ monkeypatch.setattr(ps, 'WIZARD_OPTIONAL_FLAGSHIP_SLUGS', ['serverkit-cloudflare-ops'])
with app.app_context():
- # fixture seeds WordPress under the TESTING bypass; finalize must not
- # mark an installed flagship as uninstalled
- assert InstalledPlugin.query.filter_by(slug='serverkit-wordpress').first()
+ # the flagship seeder keeps cloudflare-ops installed under TESTING
+ assert InstalledPlugin.query.filter_by(slug='serverkit-cloudflare-ops').first()
ps.finalize_setup_flagships()
- assert 'serverkit-wordpress' not in ps._flagship_uninstalled_set()
+ assert 'serverkit-cloudflare-ops' not in ps._flagship_uninstalled_set()
-def test_wordpress_flagship_skipped_on_fresh_install(app):
- """With the TESTING bypass off, a fresh install (no setup) skips WordPress."""
+def test_wordpress_not_seeded_post_extraction(app):
+ """Plan 52 Phase 5: WordPress is a registry extension now — the boot-time
+ flagship seeder never installs it (fresh OR completed setup), while the
+ remaining in-tree flagship (cloudflare-ops) still seeds. The wizard offers
+ WP through the use-case map instead (proven above)."""
with app.app_context():
InstalledPlugin.query.filter_by(slug='serverkit-wordpress').delete()
db.session.commit()
app.config['TESTING'] = False
try:
- assert SettingsService.needs_setup() is True
ps.seed_flagship_extensions()
assert InstalledPlugin.query.filter_by(
slug='serverkit-wordpress').first() is None
- # cloudflare-ops (not wizard-optional) is still seeded
assert InstalledPlugin.query.filter_by(
slug='serverkit-cloudflare-ops').first() is not None
finally:
app.config['TESTING'] = True
-def test_wordpress_flagship_seeded_on_completed_setup(app):
- """An existing/completed-setup install keeps seeding WordPress (no regression)."""
+def test_wordpress_offered_via_registry_in_recommendations(app):
+ """The wizard's WP path post-extraction: the bundled registry index
+ carries the entry, so the use-case map resolves it as a registry install."""
with app.app_context():
- InstalledPlugin.query.filter_by(slug='serverkit-wordpress').delete()
- db.session.commit()
- user = User(email='[email protected]', username='admin', is_active=True,
- role=User.ROLE_ADMIN, password_hash=generate_password_hash('x'))
- db.session.add(user)
- db.session.commit()
- SettingsService.complete_setup(user_id=user.id)
- app.config['TESTING'] = False
- try:
- assert SettingsService.needs_setup() is False
- ps.seed_flagship_extensions()
- assert InstalledPlugin.query.filter_by(
- slug='serverkit-wordpress').first() is not None
- finally:
- app.config['TESTING'] = True
+ recs = ps.recommend_extensions_for_use_cases(['wordpress'])
+ wp = next((r for r in recs if r['slug'] == 'serverkit-wordpress'), None)
+ assert wp is not None, 'WP must stay offered during onboarding'
+ assert wp['source'] == 'registry'
+ assert wp['installed'] is False
diff --git a/backend/tests/test_resource_grants.py b/backend/tests/test_resource_grants.py
index dc0080e3..128f284e 100644
--- a/backend/tests/test_resource_grants.py
+++ b/backend/tests/test_resource_grants.py
@@ -208,7 +208,7 @@ def test_grant_opens_python_read_gate(app, client):
assert client.get(url, headers=_token(grantee.id)).status_code != 403
-def test_grant_enables_wordpress_per_site_routes(app, client):
+def test_grant_enables_wordpress_per_site_routes(app, client, wp_extension):
from app import db
from app.models import Application, WordPressSite
from app.services.resource_grant_service import ResourceGrantService
diff --git a/backend/tests/test_setup_reconcile.py b/backend/tests/test_setup_reconcile.py
index be44daff..9b1f63c9 100644
--- a/backend/tests/test_setup_reconcile.py
+++ b/backend/tests/test_setup_reconcile.py
@@ -243,7 +243,7 @@ class _FakeWP:
return {'success': True, 'old_url': 'http://localhost:8300', 'new_url': new_url}
-def test_url_fix_preview_detects_localhost_site(app, wp_site, monkeypatch):
+def test_url_fix_preview_detects_localhost_site(app, wp_site, monkeypatch, wp_extension_package):
import app.services.wordpress_bridge as bridge
_FakeWP.current = 'http://localhost:8300'
monkeypatch.setattr(bridge, 'wordpress_service', lambda: _FakeWP)
@@ -256,7 +256,7 @@ def test_url_fix_preview_detects_localhost_site(app, wp_site, monkeypatch):
assert item['total'] == 12
-def test_url_fix_apply_swaps_then_is_idempotent(app, wp_site, monkeypatch):
+def test_url_fix_apply_swaps_then_is_idempotent(app, wp_site, monkeypatch, wp_extension_package):
import app.services.wordpress_bridge as bridge
_FakeWP.current = 'http://localhost:8300'
_FakeWP.swapped = []
diff --git a/backend/tests/test_site_routing.py b/backend/tests/test_site_routing.py
index 7eeecaeb..2449edbb 100644
--- a/backend/tests/test_site_routing.py
+++ b/backend/tests/test_site_routing.py
@@ -57,7 +57,7 @@ def test_runtime_setting_overrides_config(app):
# ── routing provisioning ────────────────────────────────────────────────────
-def test_provision_routing_creates_primary_domain_and_docker_vhost(app, monkeypatch):
+def test_provision_routing_creates_primary_domain_and_docker_vhost(app, monkeypatch, wp_extension_package):
from app import db
from app.models.domain import Domain
from app.services import nginx_service
@@ -90,7 +90,7 @@ def test_provision_routing_creates_primary_domain_and_docker_vhost(app, monkeypa
assert 'blog.lvh.me' in captured['domains']
-def test_provision_routing_warns_when_nginx_unavailable(app, monkeypatch):
+def test_provision_routing_warns_when_nginx_unavailable(app, monkeypatch, wp_extension_package):
from app import db
from app.models.domain import Domain
from app.services import nginx_service
@@ -108,7 +108,7 @@ def test_provision_routing_warns_when_nginx_unavailable(app, monkeypatch):
assert res['warning'] and 'nginx' in res['warning']
-def test_canonical_site_url_prefers_primary_domain(app):
+def test_canonical_site_url_prefers_primary_domain(app, wp_extension_package):
from app import db
from app.models.domain import Domain
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
diff --git a/backend/tests/test_sites_https.py b/backend/tests/test_sites_https.py
index a45def9d..8ae306af 100644
--- a/backend/tests/test_sites_https.py
+++ b/backend/tests/test_sites_https.py
@@ -186,7 +186,7 @@ def test_setup_warns_without_server_ip(app, monkeypatch):
# ── vhost wiring ────────────────────────────────────────────────────────────
-def test_write_vhost_uses_wildcard_cert_when_https_enabled(app, monkeypatch):
+def test_write_vhost_uses_wildcard_cert_when_https_enabled(app, monkeypatch, wp_extension_package):
from app import db
from app.models.system_settings import SystemSettings
from app.services import nginx_service
@@ -207,7 +207,7 @@ def test_write_vhost_uses_wildcard_cert_when_https_enabled(app, monkeypatch):
assert captured['ssl_key'] == '/etc/letsencrypt/live/lvh.me/privkey.pem'
-def test_write_vhost_no_wildcard_for_custom_domain(app, monkeypatch):
+def test_write_vhost_no_wildcard_for_custom_domain(app, monkeypatch, wp_extension_package):
from app import db
from app.models.domain import Domain
from app.models.system_settings import SystemSettings
diff --git a/backend/tests/test_url_swap.py b/backend/tests/test_url_swap.py
index 63cb5ebd..10d08b75 100644
--- a/backend/tests/test_url_swap.py
+++ b/backend/tests/test_url_swap.py
@@ -31,7 +31,7 @@ def _mk_site_app(db, user_id, name='blog', port=8300, host='blog.lvh.me'):
# ── pure helpers ────────────────────────────────────────────────────────────
-def test_normalize_url():
+def test_normalize_url(wp_extension_package):
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
assert WordPressService._normalize_url('example.com') == 'http://example.com'
assert WordPressService._normalize_url('https://example.com/') == 'https://example.com'
@@ -40,7 +40,7 @@ def test_normalize_url():
assert WordPressService._normalize_url('') is None
-def test_url_swap_pairs():
+def test_url_swap_pairs(wp_extension_package):
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
# Host change -> full-URL pair (covers scheme) + host-only pair.
assert WordPressService._url_swap_pairs('http://old.com', 'https://new.com') == [
@@ -50,7 +50,7 @@ def test_url_swap_pairs():
('http://a.com', 'https://a.com')]
-def test_parse_sr_count():
+def test_parse_sr_count(wp_extension_package):
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
assert WordPressService._parse_sr_count('Success: 12 replacements to be made.') == 12
assert WordPressService._parse_sr_count('Table\tx\nSuccess: Made 1,234 replacements.') == 1234
@@ -60,7 +60,7 @@ def test_parse_sr_count():
# ── preview ─────────────────────────────────────────────────────────────────
-def test_preview_counts_per_pair(app, monkeypatch):
+def test_preview_counts_per_pair(app, monkeypatch, wp_extension_package):
from app import db
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
@@ -84,7 +84,7 @@ def test_preview_counts_per_pair(app, monkeypatch):
assert res['total'] == 10 # 5 per pair
-def test_preview_rejects_same_url(app, monkeypatch):
+def test_preview_rejects_same_url(app, monkeypatch, wp_extension_package):
from app import db
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
user = _mk_user(db, 'o2')
@@ -98,7 +98,7 @@ def test_preview_rejects_same_url(app, monkeypatch):
# ── apply ───────────────────────────────────────────────────────────────────
-def test_change_url_happy_path_repoints_domain(app, monkeypatch):
+def test_change_url_happy_path_repoints_domain(app, monkeypatch, wp_extension_package):
from app import db
from app.models.domain import Domain
from app.services import nginx_service
@@ -134,7 +134,7 @@ def test_change_url_happy_path_repoints_domain(app, monkeypatch):
assert names == {'new.example.com': True}
-def test_change_url_rolls_back_on_failure(app, monkeypatch):
+def test_change_url_rolls_back_on_failure(app, monkeypatch, wp_extension_package):
from app import db
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
@@ -166,7 +166,7 @@ def test_change_url_rolls_back_on_failure(app, monkeypatch):
assert 'boom' in res['error']
-def test_change_url_aborts_if_backup_fails(app, monkeypatch):
+def test_change_url_aborts_if_backup_fails(app, monkeypatch, wp_extension_package):
from app import db
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
@@ -183,7 +183,7 @@ def test_change_url_aborts_if_backup_fails(app, monkeypatch):
assert 'backup failed' in res['error'].lower()
-def test_repoint_keep_old_demotes_but_keeps(app):
+def test_repoint_keep_old_demotes_but_keeps(app, wp_extension_package):
from app import db
from app.models.domain import Domain
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
@@ -199,7 +199,7 @@ def test_repoint_keep_old_demotes_but_keeps(app):
# ── API wiring ──────────────────────────────────────────────────────────────
-def test_url_preview_api_smoke(app, client, auth_headers, monkeypatch):
+def test_url_preview_api_smoke(app, client, auth_headers, monkeypatch, wp_extension):
from app import db
from app.models import User
WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
diff --git a/backend/tests/test_wordpress_extraction.py b/backend/tests/test_wordpress_extraction.py
deleted file mode 100644
index 68306348..00000000
--- a/backend/tests/test_wordpress_extraction.py
+++ /dev/null
@@ -1,85 +0,0 @@
-"""Prove the WordPress extraction (Phase 5, #38).
-
-WordPress physically moved out of core into the bundled, default-installed
-``serverkit-wordpress`` extension (a flagship, D4). Unlike a niche extension it
-ships installed on every panel, so the proof is the mirror of the Email one:
-
-* the WordPress *services* are gone from ``app.services`` (physical move);
-* they load instead from the dashed package ``app.plugins.serverkit-wordpress``
- via the importlib bridge — in-place, no copy (dev/test loadability);
-* a stock panel has the ``/api/v1/wordpress`` blueprints registered *from the
- extension* (seeded flagship), including the ``/pipelines`` alias and
- ``/projects`` mounts (D9);
-* uninstall records the user's choice and NEVER deletes the tracked builtin /
- pre-bundled files.
-"""
-import importlib
-import os
-
-import pytest
-
-from app.models.plugin import InstalledPlugin
-from app.services import plugin_service, wordpress_bridge
-
-SLUG = 'serverkit-wordpress'
-
-
-def test_wordpress_services_left_core():
- """The WordPress service files no longer exist under app.services."""
- for mod in ('wordpress_service', 'git_wordpress_service',
- 'wordpress_env_service', 'wp_update_service'):
- with pytest.raises(ModuleNotFoundError):
- importlib.import_module(f'app.services.{mod}')
-
-
-def test_core_services_pkg_drops_wordpress_export():
- import app.services as services_pkg
- assert 'WordPressService' not in getattr(services_pkg, '__all__', [])
- assert not hasattr(services_pkg, 'WordPressService')
-
-
-def test_bridge_resolves_from_extension_in_place():
- """The bridge loads WordPressService from the dashed extension package,
- without the plugin being copy-installed under app/plugins/."""
- WordPressService = wordpress_bridge.wordpress_service()
- assert WordPressService.__name__ == 'WordPressService'
- assert WordPressService.__module__.startswith(f'app.plugins.{SLUG}')
-
-
-def test_wordpress_seeded_as_flagship(app):
- """A stock panel ships WordPress installed-by-default (D4)."""
- plugin = InstalledPlugin.query.filter_by(slug=SLUG).first()
- assert plugin is not None, 'WordPress flagship should be seeded on boot'
- assert plugin.status == InstalledPlugin.STATUS_ACTIVE
- assert plugin.has_backend is True
- assert plugin.url_prefix == '/api/v1/wordpress'
-
-
-def test_wordpress_blueprints_registered_from_extension(app):
- rules = [r.rule for r in app.url_map.iter_rules()]
- wp_rules = [r for r in rules if r.startswith('/api/v1/wordpress')]
- assert wp_rules, 'WordPress API should be registered from the extension'
- # D9: the /projects and /pipelines (alias) mounts both survive the move.
- assert any(r.startswith('/api/v1/wordpress/projects') for r in wp_rules)
- assert any(r.startswith('/api/v1/wordpress/pipelines') for r in wp_rules)
-
-
-def test_wordpress_api_responds_not_404_or_503(app, client, auth_headers):
- """The extension's blueprint is live: /sites is wired (not 404) and its
- status guard passes for the active flagship (not 503)."""
- resp = client.get('/api/v1/wordpress/sites', headers=auth_headers)
- assert resp.status_code not in (404, 503), resp.status_code
-
-
-def test_uninstall_flagship_keeps_tracked_files_and_marks(app):
- plugin = InstalledPlugin.query.filter_by(slug=SLUG).first()
- assert plugin is not None
- builtin_init = os.path.join(
- plugin_service.BUILTIN_EXTENSIONS_DIR, SLUG, 'backend', '__init__.py')
- assert os.path.isfile(builtin_init)
-
- assert plugin_service.uninstall_plugin(plugin.id) is True
- # Row gone, marker set, and the tracked builtin source is untouched.
- assert InstalledPlugin.query.filter_by(slug=SLUG).first() is None
- assert SLUG in plugin_service._flagship_uninstalled_set()
- assert os.path.isfile(builtin_init), 'uninstall must not delete builtin files'
diff --git a/backend/tests/test_workspace_scope.py b/backend/tests/test_workspace_scope.py
index 6811020d..8eb828b9 100644
--- a/backend/tests/test_workspace_scope.py
+++ b/backend/tests/test_workspace_scope.py
@@ -321,7 +321,7 @@ def test_servers_list_global_without_context(app, client):
assert any(s['name'] == 'srv-a' for s in r.get_json())
-def test_wordpress_sites_scoping_api(app, client):
+def test_wordpress_sites_scoping_api(app, client, wp_extension):
from app import db
from app.services.workspace_service import WorkspaceService
from app.models import Application, WordPressSite
diff --git a/backend/tests/test_wp_hook_inversions.py b/backend/tests/test_wp_hook_inversions.py
index c8c2ce80..cba0b9fa 100644
--- a/backend/tests/test_wp_hook_inversions.py
+++ b/backend/tests/test_wp_hook_inversions.py
@@ -6,8 +6,11 @@ every boot by ``extension_lifecycle.register_capabilities``).
Every hook is exercised twice:
-* WP present — the flagship seeds on every test boot, so ``app`` boots with
- the seams filled; behavior must be identical to the pre-inversion core.
+* WP present — the ``wp_extension`` fixture mounts the extension from its
+ standalone repo (plan 52 Phase 5: it left the tree; sibling checkout or
+ SERVERKIT_WORDPRESS_DIR), so the test app boots with the seams filled;
+ behavior must be identical to the pre-inversion core. When the extension
+ source is unavailable these tests SKIP — the absent halves still run.
* WP absent — the extension's seam registrations are dropped (simulating an
uninstalled/disabled extension); the feature must be absent *gracefully*:
clear "provider missing" errors, hidden cards/types, no crashes.
@@ -62,8 +65,8 @@ def _wp_site(name='hook-site'):
# The seam itself: manifest core_hooks → registrations at boot
# --------------------------------------------------------------------------- #
-def test_core_hooks_registered_at_boot(app):
- """A stock boot (flagship seeded) fills all three seams via the manifest
+def test_core_hooks_registered_at_boot(app, wp_extension):
+ """Mounting the extension fills all three seams via the manifest
core_hooks entry — this is what makes 'WP present' behavior identical to
the pre-inversion core."""
plugin_manifest_hooks = 'core_hooks:register'
@@ -77,7 +80,7 @@ def test_core_hooks_registered_at_boot(app):
assert plugin.manifest.get('core_hooks') == plugin_manifest_hooks
-def test_core_hooks_registration_is_idempotent(app):
+def test_core_hooks_registration_is_idempotent(app, wp_extension):
hooks = _core_hooks()
hooks.register()
hooks.register()
@@ -89,7 +92,7 @@ def test_core_hooks_registration_is_idempotent(app):
# Task 13 — backup target type 'wordpress_site'
# --------------------------------------------------------------------------- #
-def test_backup_kind_present_resolves_like_before(app):
+def test_backup_kind_present_resolves_like_before(app, wp_extension):
site = _wp_site()
policy = BackupPolicyService.get_or_create_policy('wordpress_site', site.id)
target = BackupPolicyService._resolve_target(policy)
@@ -101,7 +104,7 @@ def test_backup_kind_present_resolves_like_before(app):
assert backup_kind_registry.supports_restore('wordpress_site') is True
-def test_backup_kind_absent_is_a_clear_provider_missing(app):
+def test_backup_kind_absent_is_a_clear_provider_missing(app, wp_extension):
site = _wp_site()
# Row created directly — with the provider gone, validation alone refuses.
policy = BackupPolicy(target_type='wordpress_site', target_id=site.id)
@@ -115,7 +118,7 @@ def test_backup_kind_absent_is_a_clear_provider_missing(app):
BackupPolicyService._resolve_target(policy)
-def test_backup_target_types_endpoint_reflects_provider(app, client, auth_headers):
+def test_backup_target_types_endpoint_reflects_provider(app, client, auth_headers, wp_extension):
resp = client.get('/api/v1/backups/target-types', headers=auth_headers)
assert resp.status_code == 200
types = {t['target_type']: t for t in resp.get_json()['target_types']}
@@ -131,7 +134,7 @@ def test_backup_target_types_endpoint_reflects_provider(app, client, auth_header
assert 'wordpress_site' not in gone
-def test_policy_list_flags_provider_missing(app, client, auth_headers):
+def test_policy_list_flags_provider_missing(app, client, auth_headers, wp_extension):
site = _wp_site()
BackupPolicyService.get_or_create_policy('wordpress_site', site.id)
@@ -151,7 +154,7 @@ def test_policy_list_flags_provider_missing(app, client, auth_headers):
# Task 15 — event catalog
# --------------------------------------------------------------------------- #
-def test_wp_event_types_present(app):
+def test_wp_event_types_present(app, wp_extension):
types = {e['type'] for e in EventService.get_available_events()}
assert {'wordpress.created', 'wordpress.site_down', 'wordpress.deployed',
'wordpress.update_rolled_back'} <= types
@@ -160,7 +163,7 @@ def test_wp_event_types_present(app):
assert not {t for t in core_types if t.startswith('wordpress.')}
-def test_wp_event_types_absent_graceful(app, client, auth_headers):
+def test_wp_event_types_absent_graceful(app, client, auth_headers, wp_extension):
with wp_hooks_absent():
types = {e['type'] for e in EventService.get_available_events()}
assert not {t for t in types if t.startswith('wordpress.')}
@@ -175,13 +178,13 @@ def test_wp_event_types_absent_graceful(app, client, auth_headers):
# Task 16 — templates
# --------------------------------------------------------------------------- #
-def test_wp_templates_listed_when_present(app):
+def test_wp_templates_listed_when_present(app, wp_extension):
ids = {t['id'] for t in TemplateService.list_local_templates()}
assert {'wordpress', 'wordpress-external-db'} <= ids
assert TemplateService.get_template('wordpress')['success'] is True
-def test_wp_templates_hidden_when_absent(app):
+def test_wp_templates_hidden_when_absent(app, wp_extension):
with wp_hooks_absent():
ids = {t['id'] for t in TemplateService.list_local_templates()}
assert 'wordpress' not in ids
@@ -193,14 +196,14 @@ def test_wp_templates_hidden_when_absent(app):
assert 'serverkit-wordpress' in result['error']
-def test_wp_template_install_refused_when_absent(app):
+def test_wp_template_install_refused_when_absent(app, wp_extension):
with wp_hooks_absent():
result = TemplateService.install_template('wordpress', 'wp-x')
assert result['success'] is False
assert 'serverkit-wordpress' in result['error']
-def test_external_db_preflight_flows_through_provider(app, monkeypatch):
+def test_external_db_preflight_flows_through_provider(app, monkeypatch, wp_extension):
"""The wordpress-external-db connection preflight used to be a hardcoded
core branch; now core dispatches to the provider's validate hook."""
calls = []
@@ -265,7 +268,15 @@ def test_no_core_or_wp_module_references_analytics_extension():
side feature-detects it — there is nothing to route through core."""
import os
repo_root = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)
- wp_backend = os.path.join(repo_root, 'builtin-extensions', SLUG, 'backend')
+ # The WP backend left the tree (plan 52 Phase 5): scan it from the
+ # standalone repo when a checkout is available; core files always scan.
+ wp_candidates = [
+ os.environ.get('SERVERKIT_WORDPRESS_DIR', ''),
+ os.path.join(os.path.dirname(repo_root), 'serverkit-wordpress'),
+ ]
+ wp_backend = next(
+ (os.path.join(c, 'backend') for c in wp_candidates
+ if c and os.path.isdir(os.path.join(c, 'backend'))), None)
core_files = [
'app/services/event_service.py',
'app/services/backup_policy_service.py',
@@ -275,9 +286,10 @@ def test_no_core_or_wp_module_references_analytics_extension():
]
backend_root = os.path.join(repo_root, 'backend')
targets = []
- for name in os.listdir(wp_backend):
- if name.endswith('.py'):
- targets.append(os.path.join(wp_backend, name))
+ if wp_backend:
+ for name in os.listdir(wp_backend):
+ if name.endswith('.py'):
+ targets.append(os.path.join(wp_backend, name))
targets.extend(os.path.join(backend_root, f) for f in core_files)
for path in targets:
diff --git a/backend/tests/test_wp_import_zip.py b/backend/tests/test_wp_import_zip.py
deleted file mode 100644
index 73f95211..00000000
--- a/backend/tests/test_wp_import_zip.py
+++ /dev/null
@@ -1,132 +0,0 @@
-"""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
-
-from app.services import wordpress_bridge
-
-
-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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- wp_mod = wordpress_bridge.load('wordpress_service')
- 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):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- wp_mod = wordpress_bridge.load('wordpress_service')
- 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):
- WordPressService = wordpress_bridge.get('wordpress_service', '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/backend/tests/test_wp_php_errors.py b/backend/tests/test_wp_php_errors.py
deleted file mode 100644
index 0118a5ed..00000000
--- a/backend/tests/test_wp_php_errors.py
+++ /dev/null
@@ -1,88 +0,0 @@
-"""Tests for #25 PHP-fatals ingest — parsing the WP_DEBUG log (docker exec mocked)."""
-from app.services import wordpress_bridge
-
-_SAMPLE = (
- '__SK_WPDEBUG__\n'
- '[15-Jun-2026 12:00:01 UTC] PHP Fatal error: Uncaught Error: Call to undefined '
- 'function foo() in /var/www/html/wp-content/plugins/x/x.php:12\n'
- 'Stack trace:\n'
- '#0 /var/www/html/index.php(17): require()\n'
- '#1 {main}\n'
- ' thrown in /var/www/html/wp-content/plugins/x/x.php on line 12\n'
- '[15-Jun-2026 12:05:00 UTC] PHP Warning: Undefined array key "k" in /t/functions.php on line 5\n'
- '[15-Jun-2026 12:06:00 UTC] PHP Deprecated: Function xyz() is deprecated in /x on line 1\n'
- '[15-Jun-2026 12:07:00 UTC] PHP Notice: Undefined variable $z in /x on line 2\n'
-)
-
-
-class _Res:
- def __init__(self, rc, out):
- self.returncode = rc
- self.stdout = out
- self.stderr = ''
-
-
-def _mock_run(monkeypatch, rc, out):
- mod = wordpress_bridge.load('wp_analytics_service')
- monkeypatch.setattr(mod.subprocess, 'run', lambda *a, **k: _Res(rc, out))
-
-
-def test_classify_php_levels():
- W = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- assert W._classify_php('Fatal error') == 'fatal'
- assert W._classify_php('Parse error') == 'fatal'
- assert W._classify_php('Recoverable fatal error') == 'fatal'
- assert W._classify_php('Warning') == 'warning'
- assert W._classify_php('Deprecated') == 'deprecated'
- assert W._classify_php('Notice') == 'notice'
- assert W._classify_php('Strict standards') == 'other'
-
-
-def test_get_php_errors_parses_and_skips_stack_traces(monkeypatch):
- WpAnalyticsService = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- _mock_run(monkeypatch, 0, _SAMPLE)
- out = WpAnalyticsService.get_php_errors('site')
- assert out['available'] is True and out['enabled'] is True
- assert out['total'] == 4 # stack-trace / "thrown in" lines are skipped
- assert out['counts'] == {'fatal': 1, 'warning': 1, 'notice': 1, 'deprecated': 1, 'other': 0}
- # Most-recent first: the Notice (12:07) leads.
- assert out['recent'][0]['severity'] == 'notice'
- assert 'Uncaught Error' in out['recent'][-1]['message']
-
-
-def test_get_php_errors_logging_off(monkeypatch):
- WpAnalyticsService = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- _mock_run(monkeypatch, 0, '') # no marker => log file absent
- out = WpAnalyticsService.get_php_errors('site')
- assert out['available'] is False
- assert 'logging is off' in out['note']
-
-
-def test_get_php_errors_on_but_empty(monkeypatch):
- WpAnalyticsService = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- _mock_run(monkeypatch, 0, '__SK_WPDEBUG__\n') # log exists, no entries
- out = WpAnalyticsService.get_php_errors('site')
- assert out['available'] is True and out['total'] == 0
- assert 'no PHP errors recorded' in out['note']
-
-
-def test_get_php_errors_container_unavailable(monkeypatch):
- WpAnalyticsService = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- _mock_run(monkeypatch, 1, '') # docker exec non-zero (stopped / missing)
- out = WpAnalyticsService.get_php_errors('site')
- assert out['available'] is False and 'unavailable' in out['note']
-
-
-def test_get_php_errors_no_container():
- WpAnalyticsService = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- out = WpAnalyticsService.get_php_errors(None)
- assert out['available'] is False and out['total'] == 0
-
-
-def test_message_truncation(monkeypatch):
- WpAnalyticsService = wordpress_bridge.get('wp_analytics_service', 'WpAnalyticsService')
- long = 'x' * 500
- _mock_run(monkeypatch, 0, f'__SK_WPDEBUG__\n[1 UTC] PHP Fatal error: {long}\n')
- out = WpAnalyticsService.get_php_errors('site')
- assert out['counts']['fatal'] == 1
- assert len(out['recent'][0]['message']) == 300 # capped
diff --git a/backend/tests/test_wp_php_limits.py b/backend/tests/test_wp_php_limits.py
deleted file mode 100644
index b6e8e745..00000000
--- a/backend/tests/test_wp_php_limits.py
+++ /dev/null
@@ -1,107 +0,0 @@
-"""Tests for #24 per-site PHP limit writes — validation + durable conf.d ini /
-bind-mount. The Docker apply step is mocked (no Docker on the dev/CI host); the
-file-rendering, compose-mutation, merge, and injection-rejection logic is real."""
-import os
-import yaml
-
-from app.services import wordpress_bridge
-
-
-def _compose_site(tmp_path):
- """A minimal Docker-stack WP site dir with a docker-compose.yml."""
- (tmp_path / 'docker-compose.yml').write_text(
- "services:\n"
- " wordpress:\n"
- " image: wordpress:6.4-apache\n"
- " volumes:\n"
- " - wordpress_html:/var/www/html\n"
- )
- return str(tmp_path)
-
-
-def _mock_docker(monkeypatch):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- from app.services.docker_service import DockerService
- monkeypatch.setattr(DockerService, 'compose_up', lambda *a, **k: {'success': True})
- monkeypatch.setattr(DockerService, 'compose_restart', lambda *a, **k: {'success': True})
- monkeypatch.setattr(WordPressService, '_wait_for_wp_ready', staticmethod(lambda p: None))
- monkeypatch.setattr(WordPressService, 'get_php_info', staticmethod(lambda p: {'limits': {}}))
-
-
-# ---- validation / injection rejection (no Docker needed) -------------------
-
-def test_rejects_unknown_directive(tmp_path):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- res = WordPressService.set_php_limits(_compose_site(tmp_path), {'evil_directive': '1'})
- assert res['success'] is False and 'Unknown PHP limit' in res['error']
-
-
-def test_rejects_injection_value(tmp_path):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- # A newline-smuggled extra directive must not pass validation.
- res = WordPressService.set_php_limits(_compose_site(tmp_path),
- {'memory_limit': '256M\nevil = 1'})
- assert res['success'] is False and 'Invalid value' in res['error']
- # ...and nothing was written.
- assert not os.path.exists(os.path.join(_compose_site(tmp_path), 'php-conf', 'zz-serverkit.ini'))
-
-
-def test_rejects_non_stack_site(tmp_path):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- res = WordPressService.set_php_limits(str(tmp_path), {'memory_limit': '256M'})
- assert res['success'] is False and 'Not a Docker-stack site' in res['error']
-
-
-# ---- durable write + bind-mount (Docker mocked) ----------------------------
-
-def test_writes_ini_and_injects_single_file_mount(tmp_path, monkeypatch):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- _mock_docker(monkeypatch)
- path = _compose_site(tmp_path)
-
- res = WordPressService.set_php_limits(path, {'memory_limit': '512M', 'max_execution_time': '120'})
- assert res['success'] is True
-
- ini = os.path.join(path, 'php-conf', 'zz-serverkit.ini')
- content = open(ini).read()
- assert 'memory_limit = 512M' in content
- assert 'max_execution_time = 120' in content
-
- vols = yaml.safe_load(open(os.path.join(path, 'docker-compose.yml')))['services']['wordpress']['volumes']
- assert any('php-conf/zz-serverkit.ini:/usr/local/etc/php/conf.d/zz-serverkit.ini' in v for v in vols)
-
-
-def test_partial_update_merges_and_mount_not_duplicated(tmp_path, monkeypatch):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- _mock_docker(monkeypatch)
- path = _compose_site(tmp_path)
-
- WordPressService.set_php_limits(path, {'memory_limit': '256M'})
- res = WordPressService.set_php_limits(path, {'upload_max_filesize': '64M'})
- assert res['success'] is True
- # The second (partial) update keeps the first directive.
- assert res['limits']['memory_limit'] == '256M'
- assert res['limits']['upload_max_filesize'] == '64M'
-
- # The single-file mount is added once, not duplicated on the second call.
- vols = yaml.safe_load(open(os.path.join(path, 'docker-compose.yml')))['services']['wordpress']['volumes']
- assert len([v for v in vols if 'zz-serverkit.ini' in v]) == 1
-
-
-def test_accepts_unlimited_and_size_suffixes(tmp_path, monkeypatch):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- _mock_docker(monkeypatch)
- path = _compose_site(tmp_path)
- res = WordPressService.set_php_limits(path, {'memory_limit': '-1', 'max_input_time': '-1',
- 'upload_max_filesize': '2G', 'max_input_vars': '5000'})
- assert res['success'] is True
- assert res['limits']['memory_limit'] == '-1'
-
-
-# ---- ini parsing -----------------------------------------------------------
-
-def test_read_php_ini_skips_comments_and_garbage(tmp_path):
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- p = tmp_path / 'x.ini'
- p.write_text('; a comment\nmemory_limit = 128M\n\nno equals here\nmax_input_vars = 2000\n')
- assert WordPressService._read_php_ini(str(p)) == {'memory_limit': '128M', 'max_input_vars': '2000'}
diff --git a/backend/tests/test_wp_pipelines_alias.py b/backend/tests/test_wp_pipelines_alias.py
deleted file mode 100644
index 11ee5a0b..00000000
--- a/backend/tests/test_wp_pipelines_alias.py
+++ /dev/null
@@ -1,27 +0,0 @@
-"""§2 unification: /api/v1/wordpress/pipelines aliases /wordpress/projects.
-
-"WordPress Projects" was renamed to "Pipelines" to end the collision with the
-generic /projects surface. The environment-pipeline blueprint is mounted under
-both prefixes, so every route resolves identically during the deprecation
-window.
-"""
-
-
-def test_pipelines_alias_matches_projects_list(client, auth_headers):
- projects_res = client.get('/api/v1/wordpress/projects', headers=auth_headers)
- pipelines_res = client.get('/api/v1/wordpress/pipelines', headers=auth_headers)
-
- assert projects_res.status_code == 200
- assert pipelines_res.status_code == 200
- assert pipelines_res.get_json() == projects_res.get_json()
-
-
-def test_both_pipeline_prefixes_registered():
- from app import create_app
-
- application = create_app('testing')
- rules = {r.rule for r in application.url_map.iter_rules()}
- has_projects = any(r.startswith('/api/v1/wordpress/projects') for r in rules)
- has_pipelines = any(r.startswith('/api/v1/wordpress/pipelines') for r in rules)
- assert has_projects
- assert has_pipelines
diff --git a/backend/tests/test_wp_plugin_library.py b/backend/tests/test_wp_plugin_library.py
deleted file mode 100644
index 6c1359cf..00000000
--- a/backend/tests/test_wp_plugin_library.py
+++ /dev/null
@@ -1,280 +0,0 @@
-"""Tests for the WordPress global plugin library service + API."""
-import os
-import shutil
-
-import pytest
-
-from app.services import wordpress_bridge
-
-
-PLUGIN_PHP = """<?php
-/*
- * Plugin Name: My Custom Plugin
- * Description: Does a very custom thing.
- * Version: 1.2.3
- * Author: Acme Corp
- */
-"""
-
-
-def _make_local_plugin(tmp_path, slug='my-plugin', body=PLUGIN_PHP):
- """Create a local plugin source folder with a header PHP file."""
- src = tmp_path / f'src-{slug}'
- src.mkdir()
- (src / f'{slug}.php').write_text(body, encoding='utf-8')
- return str(src)
-
-
-def _fake_privileged(cmd, *args, **kwargs):
- """Minimal python implementation of the shell verbs the service shells out to."""
- if cmd[:2] == ['rm', '-rf']:
- shutil.rmtree(cmd[2], ignore_errors=True)
- elif cmd[:2] == ['mkdir', '-p']:
- os.makedirs(cmd[2], exist_ok=True)
- elif cmd[:2] == ['cp', '-a']:
- src, dst = cmd[2], cmd[3]
- if os.path.isdir(src):
- shutil.copytree(src, dst, dirs_exist_ok=True)
- else:
- shutil.copy2(src, dst)
- # chown is a no-op off Linux
- return {'success': True}
-
-
-# --------------------------------------------------------------------------
-# Pure helpers
-# --------------------------------------------------------------------------
-def test_slug_validation():
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- PluginLibraryError = wordpress_bridge.get('wordpress_plugin_library_service', 'PluginLibraryError')
- assert S.validate_slug('my-plugin') == 'my-plugin'
- assert S.slugify('My Cool Plugin!') == 'my-cool-plugin'
- with pytest.raises(PluginLibraryError):
- S.validate_slug('Bad Slug')
- with pytest.raises(PluginLibraryError):
- S.validate_slug('')
-
-
-def test_version_behind():
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- assert S._version_behind('1.0.0', '1.0.1') is True
- assert S._version_behind('1.2.0', '1.10.0') is True
- assert S._version_behind('2.0.0', '1.9.9') is False
- assert S._version_behind('1.2.3', '1.2.3') is False
- assert S._version_behind(None, '1.0.0') is False
- assert S._version_behind('1.0.0', None) is False
-
-
-def test_parse_plugin_header(tmp_path):
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- src = _make_local_plugin(tmp_path, 'my-plugin')
- header = S.parse_plugin_header(src, 'my-plugin')
- assert header['name'] == 'My Custom Plugin'
- assert header['version'] == '1.2.3'
- assert header['author'] == 'Acme Corp'
- assert header['description'] == 'Does a very custom thing.'
-
-
-def test_parse_plugin_header_falls_back_to_first_php(tmp_path):
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- src = tmp_path / 'src'
- src.mkdir()
- (src / 'main.php').write_text(PLUGIN_PHP, encoding='utf-8')
- header = S.parse_plugin_header(str(src), 'mismatched-slug')
- assert header['version'] == '1.2.3'
-
-
-# --------------------------------------------------------------------------
-# Service: sync + CRUD (local source)
-# --------------------------------------------------------------------------
-def test_add_and_sync_local_plugin(app, tmp_path, monkeypatch):
- mod = wordpress_bridge.load('wordpress_plugin_library_service')
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
-
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
- src = _make_local_plugin(tmp_path, 'my-plugin')
-
- result = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})
- assert result['slug'] == 'my-plugin'
- assert result['version'] == '1.2.3'
- assert result['name'] == 'My Custom Plugin'
-
- # Cache snapshot exists and is a copy (not the source path)
- cache = S.cache_path('my-plugin')
- assert os.path.isfile(os.path.join(cache, 'my-plugin.php'))
-
- # Duplicate slug rejected
- PluginLibraryError = wordpress_bridge.get('wordpress_plugin_library_service', 'PluginLibraryError')
- with pytest.raises(PluginLibraryError):
- S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})
-
-
-def test_sync_reparses_updated_version(app, tmp_path, monkeypatch):
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
- src_dir = tmp_path / 'src'
- src_dir.mkdir()
- php = src_dir / 'my-plugin.php'
- php.write_text(PLUGIN_PHP, encoding='utf-8')
-
- added = S.add_plugin({'source_type': 'local', 'source_url': str(src_dir), 'slug': 'my-plugin'})
- assert added['version'] == '1.2.3'
-
- # Bump the source version and re-sync
- php.write_text(PLUGIN_PHP.replace('1.2.3', '2.0.0'), encoding='utf-8')
- from app.models import WordPressCustomPlugin
- plugin = WordPressCustomPlugin.query.get(added['id'])
- res = S.sync_plugin(plugin)
- assert res['success'] is True
- assert plugin.version == '2.0.0'
-
-
-# --------------------------------------------------------------------------
-# Service: install on a site + scan
-# --------------------------------------------------------------------------
-def _make_site(app, tmp_path, name='acme'):
- from app import db
- from app.models import Application, WordPressSite, User
- from werkzeug.security import generate_password_hash
- user = User.query.filter_by(username=f'owner-{name}').first()
- if not user:
- user = User(email=f'{name}@test.local', username=f'owner-{name}',
- password_hash=generate_password_hash('x'),
- role=User.ROLE_ADMIN, is_active=True)
- db.session.add(user)
- db.session.commit()
- root = tmp_path / f'site-{name}'
- (root / 'wp-content' / 'plugins').mkdir(parents=True)
- app_row = Application(name=name, app_type='wordpress', user_id=user.id, root_path=str(root))
- db.session.add(app_row)
- db.session.commit()
- site = WordPressSite(application_id=app_row.id, wp_version='6.5')
- db.session.add(site)
- db.session.commit()
- return app_row, site
-
-
-def test_install_on_site_copies_and_records(app, tmp_path, monkeypatch):
- mod = wordpress_bridge.load('wordpress_plugin_library_service')
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- from app.models import WordPressSitePlugin
-
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
- monkeypatch.setattr(mod, 'run_privileged', _fake_privileged)
- calls = []
- monkeypatch.setattr(WordPressService, 'wp_cli',
- classmethod(lambda cls, path, cmd, **kw: (calls.append(cmd) or {'success': True})))
-
- src = _make_local_plugin(tmp_path, 'my-plugin')
- added = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})
-
- from app.models import WordPressCustomPlugin
- plugin = WordPressCustomPlugin.query.get(added['id'])
- _, site = _make_site(app, tmp_path)
-
- res = S.install_on_site(plugin, site, activate=True)
- assert res['success'] is True
- assert res['status'] == 'active'
-
- # File landed in the site's wp-content/plugins/<slug>
- target = os.path.join(site.application.root_path, 'wp-content', 'plugins', 'my-plugin', 'my-plugin.php')
- assert os.path.isfile(target)
-
- # Installation row recorded
- row = WordPressSitePlugin.query.filter_by(
- wordpress_site_id=site.id, custom_plugin_id=plugin.id).first()
- assert row is not None and row.status == 'active'
- assert ['plugin', 'activate', 'my-plugin'] in calls
-
-
-def test_scan_site_tags_managed(app, tmp_path, monkeypatch):
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
-
- src = _make_local_plugin(tmp_path, 'my-plugin')
- added = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'my-plugin'})
- from app.models import WordPressCustomPlugin
- plugin = WordPressCustomPlugin.query.get(added['id'])
- _, site = _make_site(app, tmp_path)
-
- # WP-CLI reports the plugin installed & active, at an older version.
- monkeypatch.setattr(WordPressService, 'get_plugins', classmethod(lambda cls, path: [
- {'name': 'my-plugin', 'status': 'active', 'version': '1.0.0'},
- {'name': 'akismet', 'status': 'inactive', 'version': '5.0'},
- ]))
-
- res = S.scan_site(site)
- assert 'my-plugin' in res['managed_slugs']
-
- managed = S.managed_for_site(site)
- entry = next(m for m in managed if m['slug'] == 'my-plugin')
- assert entry['installed_version'] == '1.0.0'
- assert entry['library_version'] == '1.2.3'
- assert entry['update_available'] is True
-
-
-# --------------------------------------------------------------------------
-# API: CRUD + bulk update
-# --------------------------------------------------------------------------
-def test_api_library_crud(app, client, auth_headers, tmp_path, monkeypatch):
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
- src = _make_local_plugin(tmp_path, 'api-plugin')
-
- # Create
- r = client.post('/api/v1/wordpress/plugins/library',
- json={'source_type': 'local', 'source_url': src, 'slug': 'api-plugin'},
- headers=auth_headers)
- assert r.status_code == 201, r.get_json()
- pid = r.get_json()['id']
-
- # List
- r = client.get('/api/v1/wordpress/plugins/library', headers=auth_headers)
- assert r.status_code == 200
- assert any(p['slug'] == 'api-plugin' for p in r.get_json()['plugins'])
-
- # Detail
- r = client.get(f'/api/v1/wordpress/plugins/library/{pid}', headers=auth_headers)
- assert r.status_code == 200
- assert r.get_json()['version'] == '1.2.3'
-
- # Delete
- r = client.delete(f'/api/v1/wordpress/plugins/library/{pid}', headers=auth_headers)
- assert r.status_code == 200
- r = client.get(f'/api/v1/wordpress/plugins/library/{pid}', headers=auth_headers)
- assert r.status_code == 404
-
-
-def test_api_add_requires_source(app, client, auth_headers, tmp_path, monkeypatch):
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
- r = client.post('/api/v1/wordpress/plugins/library',
- json={'source_type': 'github'}, headers=auth_headers)
- assert r.status_code == 400
-
-
-def test_api_bulk_update(app, client, auth_headers, tmp_path, monkeypatch):
- mod = wordpress_bridge.load('wordpress_plugin_library_service')
- S = wordpress_bridge.get('wordpress_plugin_library_service', 'WordPressPluginLibraryService')
- WordPressService = wordpress_bridge.get('wordpress_service', 'WordPressService')
-
- monkeypatch.setattr(S, 'CACHE_DIR', str(tmp_path / 'cache'))
- monkeypatch.setattr(mod, 'run_privileged', _fake_privileged)
- monkeypatch.setattr(WordPressService, 'wp_cli',
- classmethod(lambda cls, path, cmd, **kw: {'success': True}))
-
- src = _make_local_plugin(tmp_path, 'bulk-plugin')
- added = S.add_plugin({'source_type': 'local', 'source_url': src, 'slug': 'bulk-plugin'})
- from app.models import WordPressCustomPlugin
- plugin = WordPressCustomPlugin.query.get(added['id'])
- _, site = _make_site(app, tmp_path, name='bulk-site')
- S.install_on_site(plugin, site, activate=False)
-
- r = client.post(f'/api/v1/wordpress/plugins/library/{added["id"]}/bulk-update',
- headers=auth_headers)
- assert r.status_code == 200
- body = r.get_json()
- assert body['total'] == 1
- assert body['updated'] == 1
diff --git a/backend/tests/test_wp_promote_deploy_job.py b/backend/tests/test_wp_promote_deploy_job.py
deleted file mode 100644
index 8a95abcb..00000000
--- a/backend/tests/test_wp_promote_deploy_job.py
+++ /dev/null
@@ -1,260 +0,0 @@
-"""WordPress promotion runs as a deployment (kind ``wordpress.promote``).
-
-Promotion used to run in the request thread: no console, no log stream, no
-retry, and a page that could only show a progress bar it had to keep alive
-itself. It is now a registered deployment kind, so it gets all of that from the
-platform — while the PromotionJob rows stay exactly where they were, because
-they carry ``pre_promotion_snapshot_id``, the pointer a rollback needs.
-"""
-
-import pytest
-
-from app import db
-from app.models.application import Application
-from app.models.deployment_job import DeploymentJob, DeploymentJobLog
-from app.models.promotion_job import PromotionJob
-from app.models.wordpress_site import WordPressSite
-from app.services import deploy_kind_registry, wordpress_bridge
-from app.services.deployment_job_service import DeploymentJobService
-from app.services.environment_pipeline_service import EnvironmentPipelineService
-
-
-def pipeline_module():
- """The extension blueprint module, re-contributing its deployment kind.
-
- The registry is a process-wide singleton that other suites clear, and the
- module only registers on first import — so re-register explicitly rather
- than depending on which test file ran first.
- """
- module = wordpress_bridge.load('environment_pipeline')
- module.register_deploy_kinds()
- return module
-
-
-def sites(app, auth_headers):
- """A production site and a staging environment beneath it."""
- from app.models import User
-
- with app.app_context():
- admin = User.query.filter_by(username='testadmin').first()
-
- def _site(name, env_type, production_site_id=None):
- application = Application(name=name, app_type='docker', status='running',
- root_path=f'/srv/{name}', user_id=admin.id)
- db.session.add(application)
- db.session.commit()
- site = WordPressSite(
- application_id=application.id, db_name=f'{name}_db', db_user='wp',
- db_host='localhost', environment_type=env_type,
- is_production=(env_type == 'production'),
- production_site_id=production_site_id,
- )
- db.session.add(site)
- db.session.commit()
- return site.id
-
- prod_id = _site('wp-prod', 'production')
- staging_id = _site('wp-staging', 'staging', production_site_id=prod_id)
- return {'prod': prod_id, 'staging': staging_id}
-
-
-def _promote(client, auth_headers, sites, promotion_type='code', config=None):
- return client.post(
- f'/api/v1/wordpress/pipelines/{sites["prod"]}/promote',
- json={
- 'source_env_id': sites['staging'],
- 'target_env_id': sites['prod'],
- 'type': promotion_type,
- 'config': config or {},
- },
- headers=auth_headers,
- )
-
-
-class TestEndpoint:
- def test_promote_queues_a_deployment_and_returns_its_id(
- self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
- calls = []
- monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
- classmethod(lambda cls, *a, **kw: calls.append(kw) or {'success': True}))
-
- res = _promote(client, auth_headers, sites)
-
- assert res.status_code == 202
- body = res.get_json()
- assert body['queued'] is True
- job_id = body['job_id']
-
- with app.app_context():
- job = DeploymentJob.query.get(job_id)
- assert job.kind == 'wordpress.promote'
- assert job.status == 'pending'
- plan = job.get_plan()
- assert plan['source_env_id'] == sites['staging']
- assert plan['target_env_id'] == sites['prod']
- assert plan['promotion_type'] == 'code'
- # The console reads its heading from the plan, so an unknown kind
- # still gets a sentence instead of "Deployment · wordpress.promote".
- assert plan['title'] == 'Promoting code from staging to production'
- assert [s['name'] for s in plan['steps']] == pipeline_module.PROMOTION_STEPS['code']
-
- # The point of the change: the request no longer does the promoting.
- assert calls == []
-
- def test_full_promotion_plans_both_halves(
- self, app, client, auth_headers, sites, pipeline_module):
- res = _promote(client, auth_headers, sites, promotion_type='full')
- assert res.status_code == 202
-
- with app.app_context():
- job = DeploymentJob.query.get(res.get_json()['job_id'])
- names = [s['name'] for s in job.get_plan()['steps']]
- assert len(names) == 10
- assert names[0].startswith('Code · ')
- assert names[5].startswith('Database · ')
-
- def test_unknown_promotion_type_is_still_rejected(
- self, client, auth_headers, sites, pipeline_module):
- res = _promote(client, auth_headers, sites, promotion_type='everything')
- assert res.status_code == 400
-
- def test_a_locked_environment_is_refused_before_anything_is_queued(
- self, app, client, auth_headers, sites, pipeline_module):
- # Queueing first would send the user to a console that fails a second
- # later; the answer is knowable now.
- with app.app_context():
- site = WordPressSite.query.get(sites['prod'])
- site.is_locked = True
- site.locked_reason = 'Sync in progress'
- db.session.commit()
-
- res = _promote(client, auth_headers, sites)
-
- assert res.status_code == 400
- assert 'locked' in res.get_json()['error']
- with app.app_context():
- assert DeploymentJob.query.filter_by(kind='wordpress.promote').count() == 0
-
-
-class TestHandler:
- def _run(self, client, auth_headers, sites, promotion_type='code'):
- res = _promote(client, auth_headers, sites, promotion_type=promotion_type)
- assert res.status_code == 202
- job_id = res.get_json()['job_id']
- return job_id, DeploymentJobService.run_job(job_id)
-
- def test_promotion_succeeds_and_walks_the_console_steps(
- self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
- def fake_promote(cls, source_id, target_id, config=None, user_id=None,
- progress_callback=None):
- for step, message in enumerate(
- ['Locking environments...', 'Creating pre-promotion snapshot...',
- 'Syncing code files...', 'Flushing caches...', 'Complete'], start=1):
- EnvironmentPipelineService._emit_progress(progress_callback, step, 5, message)
- return {'success': True, 'message': 'Code promoted from staging to production'}
-
- monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
- classmethod(fake_promote))
-
- job_id, result = self._run(client, auth_headers, sites)
- assert result['success'] is True
-
- with app.app_context():
- job = DeploymentJob.query.get(job_id)
- assert job.status == 'succeeded'
- assert job.current_step == 5
- # Timings are what the console's step strip renders its durations
- # from; they only survive because the handler and the runner share
- # one log stream.
- assert len(job.get_result()['step_timings']) == 5
- messages = [row.message for row in
- DeploymentJobLog.query.filter_by(job_id=job_id).all()]
- assert 'Syncing code files...' in messages
-
- def test_full_promotion_progress_never_goes_backwards(
- self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
- # promote_full runs two five-step halves and restarts its own numbering
- # at 1 for the second — the console must not rewind to step 1 halfway.
- def fake_full(cls, source_id, target_id, config=None, user_id=None,
- progress_callback=None):
- for _half in range(2):
- for step in range(1, 6):
- EnvironmentPipelineService._emit_progress(
- progress_callback, step, 5, f'Step {step}')
- return {'success': True, 'message': 'Full promotion completed'}
-
- monkeypatch.setattr(EnvironmentPipelineService, 'promote_full',
- classmethod(fake_full))
-
- job_id, result = self._run(client, auth_headers, sites, promotion_type='full')
- assert result['success'] is True
-
- with app.app_context():
- job = DeploymentJob.query.get(job_id)
- assert job.current_step == 10
- assert job.status == 'succeeded'
-
- def test_failed_promotion_fails_the_job_with_the_reason_in_the_console(
- self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
- monkeypatch.setattr(
- EnvironmentPipelineService, 'promote_code',
- classmethod(lambda cls, *a, **kw: {'success': False, 'error': 'rsync refused'}))
-
- job_id, result = self._run(client, auth_headers, sites)
- assert result['success'] is False
-
- with app.app_context():
- job = DeploymentJob.query.get(job_id)
- assert job.status == 'failed'
- assert job.error_message == 'rsync refused'
- messages = [row.message for row in
- DeploymentJobLog.query.filter_by(job_id=job_id).all()]
- assert 'rsync refused' in messages
-
- def test_promotion_rows_are_linked_even_when_the_promotion_fails(
- self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
- # The rollback pointer lives on PromotionJob, and a failed promotion is
- # precisely when someone needs it — so the link can't come from the
- # service's success-only return value.
- def fake_promote(cls, source_id, target_id, config=None, user_id=None,
- progress_callback=None):
- row = PromotionJob(source_site_id=source_id, target_site_id=target_id,
- promotion_type='code', status='failed')
- db.session.add(row)
- db.session.commit()
- return {'success': False, 'error': 'died halfway'}
-
- monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
- classmethod(fake_promote))
-
- job_id, _ = self._run(client, auth_headers, sites)
-
- with app.app_context():
- job = DeploymentJob.query.get(job_id)
- linked = job.get_result()['promotion_job_ids']
- assert len(linked) == 1
- assert PromotionJob.query.get(linked[0]).status == 'failed'
-
- def test_a_raising_promotion_still_ends_the_job(
- self, app, client, auth_headers, sites, pipeline_module, monkeypatch):
- def explode(cls, *args, **kwargs):
- raise RuntimeError('docker went away')
-
- monkeypatch.setattr(EnvironmentPipelineService, 'promote_code',
- classmethod(explode))
-
- job_id, result = self._run(client, auth_headers, sites)
- assert result['success'] is False
-
- with app.app_context():
- job = DeploymentJob.query.get(job_id)
- assert job.status == 'failed'
- assert 'docker went away' in job.error_message
-
-
-def test_promotion_kind_is_contributed_by_the_extension(pipeline_module):
- assert deploy_kind_registry.get('wordpress.promote') is pipeline_module.run_promotion
- # Namespaced, so it can never shadow a core deployment kind.
- assert 'wordpress.promote' in deploy_kind_registry.kinds()
diff --git a/backend/tests/test_wp_reports.py b/backend/tests/test_wp_reports.py
deleted file mode 100644
index 080d7de4..00000000
--- a/backend/tests/test_wp_reports.py
+++ /dev/null
@@ -1,263 +0,0 @@
-"""Tests for the WordPress monthly client reports service + API (#33 slice)."""
-from datetime import datetime, timedelta
-
-import pytest
-
-from app.services import wordpress_bridge
-
-
-def _mk_user(db, username='owner'):
- from app.models import User
- from werkzeug.security import generate_password_hash
- u = User(email=f'{username}@test.local', username=username,
- password_hash=generate_password_hash('x'),
- role=User.ROLE_ADMIN, is_active=True)
- db.session.add(u)
- db.session.commit()
- return u
-
-
-def _mk_site(db, user_id, name='acme-prod', tags=None):
- import json
- from app.models import Application, WordPressSite
- app_row = Application(name=name, app_type='wordpress', user_id=user_id, root_path='/srv/x')
- db.session.add(app_row)
- db.session.commit()
- site = WordPressSite(application_id=app_row.id, wp_version='6.4',
- tags=json.dumps(tags) if tags else None,
- health_status='healthy', last_health_check=datetime.utcnow())
- db.session.add(site)
- db.session.commit()
- return app_row, site
-
-
-def _current_month():
- now = datetime.utcnow()
- return now.year, now.month, now
-
-
-# ---- pure helpers ---------------------------------------------------------
-
-def test_month_bounds_normal_and_december():
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
- start, end = WpReportsService._month_bounds(2026, 5)
- assert start == datetime(2026, 5, 1)
- assert end == datetime(2026, 6, 1)
- # December must roll over the year, not crash.
- start, end = WpReportsService._month_bounds(2026, 12)
- assert start == datetime(2026, 12, 1)
- assert end == datetime(2027, 1, 1)
-
-
-def test_client_from_tags():
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
- assert WpReportsService._client_from_tags(['retainer', 'client-acme']) == 'acme'
- assert WpReportsService._client_from_tags(['client:Globex']) == 'Globex'
- assert WpReportsService._client_from_tags(['php8', 'retainer']) is None
- assert WpReportsService._client_from_tags(None) is None
-
-
-# ---- end-to-end aggregation ----------------------------------------------
-
-def test_generate_aggregates_bound_site(app):
- import json
- from app import db
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
- from app.models.status_page import StatusPage, StatusComponent, HealthCheck
- from app.models.wordpress_site import WordPressUpdateRun, DatabaseSnapshot, WordPressVulnerability
-
- user = _mk_user(db)
- _, site = _mk_site(db, user.id, tags=['client-acme', 'retainer'])
- year, month, now = _current_month()
-
- # Bound status-page component + 10 health checks (8 up, 1 degraded, 1 down) -> 80% uptime.
- page = StatusPage(name='Status', slug='status')
- db.session.add(page)
- db.session.commit()
- comp = StatusComponent(page_id=page.id, name='acme', wordpress_site_id=site.id, uptime_30d=88.5)
- db.session.add(comp)
- db.session.commit()
- statuses = ['up'] * 8 + ['degraded', 'down']
- for s in statuses:
- db.session.add(HealthCheck(component_id=comp.id, status=s, checked_at=now))
- # Update runs in-month: 1 completed (2 comps), 1 rolled_back (1 comp), 1 failed.
- db.session.add(WordPressUpdateRun(site_id=site.id, status='completed', trigger='manual',
- started_at=now, details=json.dumps({'updated': [{'type': 'plugin', 'slug': 'a', 'from': '1', 'to': '2'}, {'type': 'theme', 'slug': 'b', 'from': '1', 'to': '2'}]})))
- db.session.add(WordPressUpdateRun(site_id=site.id, status='rolled_back', trigger='scheduled',
- started_at=now, details=json.dumps({'updated': [{'type': 'plugin', 'slug': 'c', 'from': '1', 'to': '2'}], 'rolled_back': True})))
- db.session.add(WordPressUpdateRun(site_id=site.id, status='failed', trigger='manual',
- started_at=now, details=None, error='boom'))
- # Backups in-month.
- db.session.add(DatabaseSnapshot(site_id=site.id, name='snap1', file_path='/x/1.sql', size_bytes=100, tag='pre-deploy', created_at=now))
- db.session.add(DatabaseSnapshot(site_id=site.id, name='snap2', file_path='/x/2.sql', size_bytes=200, created_at=now))
- # Current vuln posture.
- db.session.add(WordPressVulnerability(site_id=site.id, source='plugin', slug='a', name='Plugin A', severity='high'))
- db.session.add(WordPressVulnerability(site_id=site.id, source='core', slug='', name='WP', severity='medium'))
- site.last_vuln_scan_at = now
- db.session.commit()
-
- res = WpReportsService.generate(site, year=year, month=month)
- assert res['success'] is True
- data = res['report']['data']
-
- assert data['site']['client'] == 'acme'
- assert data['uptime']['bound'] is True
- assert data['uptime']['samples'] == 10
- assert data['uptime']['percent'] == 80.0
- assert data['uptime']['rolling_30d'] == 88.5
-
- u = data['updates']
- assert u['total_runs'] == 3
- assert u['completed'] == 1 and u['rolled_back'] == 1 and u['failed'] == 1
- assert u['components_updated'] == 3
-
- assert data['backups']['count'] == 2
- assert data['backups']['total_bytes'] == 300
-
- assert data['vulnerabilities']['total'] == 2
- assert data['vulnerabilities']['by_severity']['high'] == 1
- assert data['vulnerabilities']['by_severity']['medium'] == 1
- assert data['vulnerabilities']['as_of'] is not None
-
- # A daily series spanning the month, with at least one populated day.
- assert any(d['samples'] > 0 for d in data['uptime_daily'])
-
-
-def test_generate_unbound_site_has_no_uptime_history(app):
- from app import db
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
-
- user = _mk_user(db, 'owner2')
- _, site = _mk_site(db, user.id, name='nobound')
- year, month, _ = _current_month()
-
- res = WpReportsService.generate(site, year=year, month=month)
- assert res['success'] is True
- data = res['report']['data']
- assert data['uptime']['bound'] is False
- assert data['uptime']['percent'] is None
- # The "attach to a status page" note must be present so the gap is explained.
- assert any('Uptime history is unavailable' in n for n in data['notes'])
-
-
-def test_generate_is_upsert(app):
- from app import db
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
- from app.models.wordpress_site import WordPressReport
-
- user = _mk_user(db, 'owner3')
- _, site = _mk_site(db, user.id, name='upsert')
- year, month, _ = _current_month()
-
- WpReportsService.generate(site, year=year, month=month)
- WpReportsService.generate(site, year=year, month=month)
- rows = WordPressReport.query.filter_by(site_id=site.id).all()
- assert len(rows) == 1 # regenerating the same month replaces, not duplicates
-
-
-def test_generate_rejects_future_month(app):
- from app import db
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
-
- user = _mk_user(db, 'owner4')
- _, site = _mk_site(db, user.id, name='future')
- now = datetime.utcnow()
- res = WpReportsService.generate(site, year=now.year + 1, month=1)
- assert res['success'] is False
- assert 'future' in res['error'].lower()
-
-
-def test_daily_series_never_emits_a_future_day(app):
- """Regression: the to-date daily series must stop at today, not tomorrow."""
- from app import db
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
- from app.models.status_page import StatusPage, StatusComponent
-
- user = _mk_user(db, 'owner5')
- _, site = _mk_site(db, user.id, name='daily')
- page = StatusPage(name='S', slug='s-daily')
- db.session.add(page)
- db.session.commit()
- db.session.add(StatusComponent(page_id=page.id, name='c', wordpress_site_id=site.id))
- db.session.commit()
-
- year, month, now = _current_month()
- res = WpReportsService.generate(site, year=year, month=month)
- daily = res['report']['data']['uptime_daily']
- assert daily, 'a bound site should produce a daily series'
- today = now.date().isoformat()
- assert all(d['date'] <= today for d in daily)
- assert daily[-1]['date'] == today # today is included as a partial day
-
-
-def test_ongoing_incident_duration_is_clamped_to_the_month(app):
- """Regression: a still-open incident in a PAST-month report must not bleed
- its full elapsed time (up to now) into that month's attributed duration."""
- from datetime import datetime, timedelta
- from app import db
- WpReportsService = wordpress_bridge.get('wp_reports_service', 'WpReportsService')
- from app.models.status_page import StatusPage, StatusComponent, StatusIncident
-
- now = datetime.utcnow()
- first_this = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
- prev_start = (first_this - timedelta(days=1)).replace(day=1, hour=0, minute=0, second=0, microsecond=0)
- prev_end = first_this
-
- user = _mk_user(db, 'owner6')
- _, site = _mk_site(db, user.id, name='inc')
- page = StatusPage(name='S', slug='s-inc')
- db.session.add(page)
- db.session.commit()
- comp = StatusComponent(page_id=page.id, name='c', wordpress_site_id=site.id)
- db.session.add(comp)
- db.session.commit()
- # An incident opened early in the previous month and never resolved.
- created = prev_start + timedelta(days=1)
- db.session.add(StatusIncident(page_id=page.id, component_id=comp.id, title='down',
- impact='major', created_at=created, resolved_at=None))
- db.session.commit()
-
- res = WpReportsService.generate(site, year=prev_start.year, month=prev_start.month)
- incidents = res['report']['data']['incidents']
- assert len(incidents) == 1
- inc = incidents[0]
- assert inc['ongoing'] is True
- # Duration is capped at the month boundary, NOT (now - created).
- in_month_cap = int((prev_end - created).total_seconds() // 60)
- full_elapsed = int((now - created).total_seconds() // 60)
- assert inc['duration_minutes'] <= in_month_cap
- assert inc['duration_minutes'] < full_elapsed
-
-
-# ---- API route ------------------------------------------------------------
-
-def test_reports_api_roundtrip(app, client, auth_headers):
- from app import db
- from app.models import User
-
- admin = User.query.filter_by(username='testadmin').first()
- _, site = _mk_site(db, admin.id, name='api-site')
- year, month, _ = _current_month()
-
- # Empty before generation.
- r = client.get(f'/api/v1/wordpress/sites/{site.id}/reports', headers=auth_headers)
- assert r.status_code == 200
- assert r.get_json()['reports'] == []
-
- # Generate the current month.
- r = client.post(f'/api/v1/wordpress/sites/{site.id}/reports/generate',
- json={'year': year, 'month': month}, headers=auth_headers)
- assert r.status_code == 200
- body = r.get_json()
- assert body['success'] is True
- report_id = body['report']['id']
-
- # Now listed.
- r = client.get(f'/api/v1/wordpress/sites/{site.id}/reports', headers=auth_headers)
- assert len(r.get_json()['reports']) == 1
-
- # Delete it.
- r = client.delete(f'/api/v1/wordpress/sites/{site.id}/reports/{report_id}', headers=auth_headers)
- assert r.status_code == 200
- r = client.get(f'/api/v1/wordpress/sites/{site.id}/reports', headers=auth_headers)
- assert r.get_json()['reports'] == []
diff --git a/backend/tests/test_wp_ssh_import.py b/backend/tests/test_wp_ssh_import.py
deleted file mode 100644
index 042e8fd5..00000000
--- a/backend/tests/test_wp_ssh_import.py
+++ /dev/null
@@ -1,369 +0,0 @@
-"""Tests for the WordPress-over-SSH pull importer (Panel Improvements #3).
-
-Covers: wp-config probe parsing, host-key fingerprint pinning (mismatch
-rejection), the SSRF host guard (metadata/loopback), tar traversal guards, the
-full job step sequence with every remote exec stubbed, and the admin API
-(auth + happy path with the enqueue stubbed).
-"""
-import io
-import os
-import tarfile
-
-import pytest
-
-from app.services import wordpress_bridge
-
-
-def _svc():
- return wordpress_bridge.get('wp_ssh_import_service', 'WpSshImportService')
-
-
-def _err():
- return wordpress_bridge.get('wp_ssh_import_service', 'WpSshImportError')
-
-
-WP_CONFIG_FIXTURE = """<?php
-define( 'DB_NAME', 'legacy_wp' );
-define('DB_USER', 'legacy_user');
-define("DB_PASSWORD", "s3cr3t-pw");
-define( 'DB_HOST', 'localhost' );
-define( 'WP_HOME', 'https://old.example.com' );
-$table_prefix = 'lw_';
-require_once ABSPATH . 'wp-settings.php';
-"""
-
-
-# ---- probe parsing ---------------------------------------------------------
-
-def test_parse_wp_config_extracts_db_facts():
- svc = _svc()
- cfg = svc.parse_wp_config(WP_CONFIG_FIXTURE)
- assert cfg['db_name'] == 'legacy_wp'
- assert cfg['db_user'] == 'legacy_user'
- assert cfg['db_password'] == 's3cr3t-pw'
- assert cfg['db_host'] == 'localhost'
- assert cfg['wp_home'] == 'https://old.example.com'
- assert cfg['table_prefix'] == 'lw_'
-
-
-def test_parse_wp_config_defaults_prefix():
- svc = _svc()
- cfg = svc.parse_wp_config("define('DB_NAME','x');")
- assert cfg['table_prefix'] == 'wp_'
- assert 'db_password' not in cfg
-
-
-def test_fingerprint_of_is_openssh_sha256():
- import base64
- import hashlib
- svc = _svc()
- blob = b'\x00\x00\x00\x0bssh-ed25519' + b'\x00' * 32
- b64 = base64.b64encode(blob).decode()
- expected = 'SHA256:' + base64.b64encode(
- hashlib.sha256(blob).digest()).decode().rstrip('=')
- assert svc.fingerprint_of(b64) == expected
-
-
-# ---- SSRF host guard -------------------------------------------------------
-
- 'localhost', '127.0.0.1', '::1', '169.254.169.254', '0.0.0.0', '',
- '-oProxyCommand=evil', 'bad host name',
-])
-def test_validate_host_rejects_dangerous_targets(host):
- svc, err = _svc(), _err()
- with pytest.raises(err):
- svc.validate_host(host)
-
-
-def test_validate_host_allows_explicit_private_ip():
- # LAN migrations are legitimate: RFC1918 typed by the operator is allowed.
- svc = _svc()
- assert svc.validate_host('10.11.12.13') == '10.11.12.13'
- assert svc.validate_host('192.168.1.50') == '192.168.1.50'
-
-
-# ---- host-key pinning ------------------------------------------------------
-
-_KEYSCAN = [{'type': 'ssh-ed25519', 'key': 'QUJDREVGRw==',
- 'line': 'h ssh-ed25519 QUJDREVGRw=='}]
-
-
-def test_assert_pinned_rejects_mismatch(monkeypatch):
- svc, err = _svc(), _err()
- monkeypatch.setattr(svc, '_keyscan', lambda host, port: list(_KEYSCAN))
- good = svc.fingerprint_of(_KEYSCAN[0]['key'])
- scan = svc.assert_pinned('10.0.0.9', 22, good)
- assert scan['fingerprint'] == good and 'known_hosts' in scan
- with pytest.raises(err, match='mismatch'):
- svc.assert_pinned('10.0.0.9', 22, 'SHA256:not-the-pinned-key')
-
-
-# ---- tar traversal guards --------------------------------------------------
-
-def _make_tar(path, entries, link=None):
- with tarfile.open(path, 'w:gz') as tf:
- for name, content in entries.items():
- data = content.encode()
- info = tarfile.TarInfo(name=name)
- info.size = len(data)
- tf.addfile(info, io.BytesIO(data))
- if link:
- info = tarfile.TarInfo(name=link[0])
- info.type = tarfile.SYMTYPE
- info.linkname = link[1]
- tf.addfile(info)
-
-
-def test_safe_extract_tar_rejects_parent_traversal(tmp_path):
- svc = _svc()
- t = tmp_path / 'evil.tar.gz'
- _make_tar(str(t), {'../escape.txt': 'x', 'ok.txt': 'y'})
- dest = tmp_path / 'out'
- dest.mkdir()
- res = svc.safe_extract_tar(str(t), str(dest))
- assert res['success'] is False and 'Unsafe path' in res['error']
- assert not (tmp_path / 'escape.txt').exists()
-
-
-def test_safe_extract_tar_rejects_absolute_paths(tmp_path):
- svc = _svc()
- t = tmp_path / 'abs.tar.gz'
- _make_tar(str(t), {'/etc/evil.txt': 'x'})
- dest = tmp_path / 'out2'
- dest.mkdir()
- res = svc.safe_extract_tar(str(t), str(dest))
- assert res['success'] is False
-
-
-def test_safe_extract_tar_drops_escaping_symlink_and_extracts_rest(tmp_path):
- svc = _svc()
- t = tmp_path / 'link.tar.gz'
- _make_tar(str(t), {'wp-content/ok.txt': 'y'}, link=('evil-link', '/etc/passwd'))
- dest = tmp_path / 'out3'
- dest.mkdir()
- res = svc.safe_extract_tar(str(t), str(dest))
- assert res['success'] is True
- assert (dest / 'wp-content' / 'ok.txt').read_text() == 'y'
- assert not (dest / 'evil-link').exists()
-
-
-def test_safe_extract_tar_rejects_garbage(tmp_path):
- svc = _svc()
- bad = tmp_path / 'not.tar.gz'
- bad.write_text('nope')
- dest = tmp_path / 'out4'
- dest.mkdir()
- res = svc.safe_extract_tar(str(bad), str(dest))
- assert res['success'] is False
-
-
-# ---- job step sequence (remote exec fully stubbed) --------------------------
-
-class FakeJob:
- id = 77
-
- def __init__(self, payload):
- self.payload = payload
- self.result = None
-
- def get_payload(self):
- return self.payload
-
- def set_payload(self, p):
- self.payload = p
-
- def set_result(self, r):
- self.result = r
-
- def get_result(self):
- return self.result
-
-
-def _job_payload():
- return {
- 'connection': {'host': '10.20.30.40', 'port': 22, 'username': 'root',
- 'auth': {'private_key': 'FAKE-KEY'}},
- 'fingerprint': 'SHA256:pinned',
- 'target': {'site_name': 'migrated-site', 'admin_email': '[email protected]'},
- 'options': {'wp_path': '/var/www/html', 'old_url': None},
- 'user_id': 1,
- }
-
-
-def _stub_remote(svc, monkeypatch, tmp_path, has_wp_cli=True):
- """Stub every SSH touchpoint; returns the list of remote commands run."""
- calls = []
- monkeypatch.setattr(svc, 'assert_pinned',
- lambda host, port, fp: {'fingerprint': fp, 'key_type': 'ssh-ed25519',
- 'known_hosts': 'h ssh-ed25519 AAAA\n'})
-
- def fake_ssh(conn, kh, cmd, input_bytes=None, timeout=None, stdout_path=None):
- calls.append(cmd)
- if 'wp-config.php' in cmd:
- return {'code': 0, 'stdout': WP_CONFIG_FIXTURE.encode(), 'stderr': b''}
- if 'command -v wp' in cmd:
- out = b'yes' if has_wp_cli else b'no'
- return {'code': 0, 'stdout': out, 'stderr': b''}
- if 'option get siteurl' in cmd:
- return {'code': 0, 'stdout': b'https://old.example.com\n', 'stderr': b''}
- if cmd.startswith('tar czf'):
- src = tmp_path / 'srcroot'
- (src / 'wp-content' / 'plugins').mkdir(parents=True, exist_ok=True)
- (src / 'wp-content' / 'plugins' / 'p.php').write_text('<?php')
- (src / 'index.php').write_text('<?php')
- with tarfile.open(stdout_path, 'w:gz') as tf:
- tf.add(str(src), arcname='.')
- return {'code': 0, 'stdout': b'', 'stderr': b''}
- if 'db export' in cmd or 'mysqldump' in cmd:
- with open(stdout_path, 'wb') as fh:
- fh.write(b'-- dump\nCREATE TABLE lw_options (x int);\n')
- return {'code': 0, 'stdout': b'', 'stderr': b''}
- return {'code': 0, 'stdout': b'', 'stderr': b''}
-
- monkeypatch.setattr(svc, '_ssh_exec', fake_ssh)
- return calls
-
-
-def test_run_import_step_sequence(app, monkeypatch, tmp_path):
- svc = _svc()
- calls = _stub_remote(svc, monkeypatch, tmp_path)
-
- captured = {}
-
- def fake_import(**kwargs):
- captured.update(kwargs)
- return {'success': True, 'site': {'id': 5, 'name': 'migrated-site'},
- 'http_port': 8123, 'new_url': 'http://localhost:8123',
- 'wp_content_imported': True}
-
- monkeypatch.setattr(svc, '_import_into_panel', fake_import)
- monkeypatch.setattr(svc, '_check_homepage', lambda port: True)
-
- job = FakeJob(_job_payload())
- result = svc.run_import(job)
-
- steps = [s['step'] for s in result['steps']]
- assert steps == ['pin_check', 'read_config', 'pull_docroot', 'dump_db',
- 'rebuild_site', 'validate', 'done']
- assert result['success'] is True
- assert result['old_url'] == 'https://old.example.com'
- assert result['new_url'] == 'http://localhost:8123'
- assert result['homepage_ok'] is True
-
- # The rebuild reused the extension's import path with the pulled artifacts.
- assert captured['name'] == 'migrated-site'
- assert captured['old_url'] == 'https://old.example.com'
- assert captured['sql_path'] and os.path.basename(captured['sql_path']) == 'source.sql'
- assert captured['wp_content_zip_path'].endswith('wp-content.zip')
-
- # Secrets scrubbed from the persisted payload once the job ended.
- assert job.payload['connection']['auth'] == {'scrubbed': True}
- # No secrets in the step log.
- flat = str(result['steps'])
- assert 's3cr3t-pw' not in flat and 'FAKE-KEY' not in flat
- assert any('tar czf' in c for c in calls)
-
-
-def test_run_import_pin_mismatch_aborts_before_any_pull(app, monkeypatch, tmp_path):
- svc, err = _svc(), _err()
- pulled = []
- monkeypatch.setattr(svc, 'assert_pinned',
- lambda host, port, fp: (_ for _ in ()).throw(
- err('Host key mismatch: nope')))
- monkeypatch.setattr(svc, '_ssh_exec',
- lambda *a, **k: pulled.append(a) or {'code': 0, 'stdout': b'', 'stderr': b''})
-
- job = FakeJob(_job_payload())
- with pytest.raises(err, match='mismatch'):
- svc.run_import(job)
- assert pulled == [] # nothing touched the remote after the failed pin check
- assert (job.result or {}).get('steps') and job.result['steps'][-1]['step'] == 'failed'
-
-
-# ---- API -------------------------------------------------------------------
-
-def test_probe_requires_auth(client):
- r = client.post('/api/v1/wordpress/ssh-import/probe', json={'host': 'x'})
- assert r.status_code == 401
-
-
-def test_probe_happy_path(client, auth_headers, monkeypatch):
- svc = _svc()
- monkeypatch.setattr(svc, 'probe',
- lambda **kw: {'host_key_fingerprint': 'SHA256:abc',
- 'db_name': 'legacy_wp', 'wp_version': '6.4',
- 'site_url': 'https://old.example.com'})
- r = client.post('/api/v1/wordpress/ssh-import/probe', headers=auth_headers,
- json={'host': '10.0.0.5', 'username': 'root',
- 'auth': {'password': 'x'}, 'wp_path': '/var/www/html'})
- assert r.status_code == 200
- body = r.get_json()
- assert body['host_key_fingerprint'] == 'SHA256:abc'
- assert 'db_password' not in body
-
-
-def test_probe_rejects_metadata_host(client, auth_headers):
- r = client.post('/api/v1/wordpress/ssh-import/probe', headers=auth_headers,
- json={'host': '169.254.169.254', 'username': 'root',
- 'auth': {'password': 'x'}, 'wp_path': '/var/www/html'})
- assert r.status_code == 400
- assert 'error' in r.get_json()
-
-
-def test_start_import_enqueues_job(client, auth_headers, monkeypatch):
- svc = _svc()
-
- class J:
- id = 321
- monkeypatch.setattr(svc, 'enqueue_import',
- lambda **kw: J() if kw['fingerprint'] == 'SHA256:abc' else None)
- r = client.post('/api/v1/wordpress/ssh-import', headers=auth_headers,
- json={'connection': {'host': '10.0.0.5', 'username': 'root',
- 'auth': {'password': 'x'}},
- 'fingerprint': 'SHA256:abc',
- 'target': {'site_name': 'migrated'},
- 'options': {'wp_path': '/var/www/html'}})
- assert r.status_code == 202
- assert r.get_json() == {'success': True, 'job_id': 321}
-
-
-def test_start_import_requires_fingerprint(client, auth_headers):
- r = client.post('/api/v1/wordpress/ssh-import', headers=auth_headers,
- json={'connection': {'host': '10.0.0.5', 'username': 'root',
- 'auth': {'password': 'x'}},
- 'target': {'site_name': 'migrated'},
- 'options': {'wp_path': '/var/www/html'}})
- assert r.status_code == 400
- assert 'fingerprint' in r.get_json()['error']
-
-
-def test_status_endpoint_reads_job(client, auth_headers, app):
- from app import db
- from app.jobs.models import Job
- mod = wordpress_bridge.load('wp_ssh_import_service')
-
- job = Job(kind=mod.JOB_KIND, status='running')
- job.set_payload({'connection': {'auth': {'password': 'never-echoed'}}})
- job.set_result({'steps': [{'step': 'pin_check', 'message': 'ok'}]})
- db.session.add(job)
- other = Job(kind='backup.policy.run', status='running')
- db.session.add(other)
- db.session.commit()
-
- r = client.get(f'/api/v1/wordpress/ssh-import/{job.id}', headers=auth_headers)
- assert r.status_code == 200
- body = r.get_json()
- assert body['status'] == 'running'
- assert body['steps'][0]['step'] == 'pin_check'
- assert 'never-echoed' not in r.get_data(as_text=True) # payload never echoed
-
- r = client.get(f'/api/v1/wordpress/ssh-import/{other.id}', headers=auth_headers)
- assert r.status_code == 404
-
-
-def test_job_kind_registered():
- from app.jobs import registry
- mod = wordpress_bridge.load('wp_ssh_import_service')
- mod.WpSshImportService.register_jobs()
- assert registry.is_registered(mod.JOB_KIND)