Merge plan-47 lean-core (wizard installs + 4 backend extractions + security tab-group)

This commit is contained in:
Juan Denis committed 2026-07-15 15:24:07 -04:00
commit b7911026be
51 files changed
+1410 -309

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2588
2623
+5 -31
View File
@@ -248,29 +248,9 @@ def test_env_secret_masking_preserved(app, client, env_rbac):
# Phase 4 — status pages (mutations admin-only, reads open) + raw docker-DB.
# --------------------------------------------------------------------------- #
def test_status_page_mutations_admin_only(app, client):
"""Reads stay open to any authed user; every mutation is admin-only via the
@admin_required decorator (plan 18 Decision 6). A non-admin is 403."""
from app import db
dev = _mk_user(db, 'sp_dev', role='developer')
admin = _mk_user(db, 'sp_admin', role='admin')
# Reads are open to a plain developer.
assert client.get('/api/v1/status/', headers=_token(dev.id)).status_code == 200
# Admin can create a page.
r = client.post('/api/v1/status/', json={'name': 'Ops', 'slug': 'ops'}, headers=_token(admin.id))
assert r.status_code == 201
page_id = r.get_json()['id']
# A developer is denied every mutation.
assert client.post('/api/v1/status/', json={'name': 'X', 'slug': 'x'}, headers=_token(dev.id)).status_code == 403
assert client.put(f'/api/v1/status/{page_id}', json={'name': 'Y'}, headers=_token(dev.id)).status_code == 403
assert client.delete(f'/api/v1/status/{page_id}', headers=_token(dev.id)).status_code == 403
assert client.post(f'/api/v1/status/{page_id}/components', json={'name': 'c', 'check_type': 'http'},
headers=_token(dev.id)).status_code == 403
assert client.post(f'/api/v1/status/{page_id}/incidents', json={'title': 't'},
headers=_token(dev.id)).status_code == 403
# Status-page mutation authz moved to tests/test_status_extraction.py (plan 47) —
# the status blueprint now lives in the serverkit-status extension, so the test
# installs it before exercising the admin-only mutations.
def test_raw_docker_db_routes_admin_only(app, client):
@@ -375,11 +355,5 @@ def test_wordpress_standalone_host_ops_admin_only(app, client, scoping_rbac, per
assert call(url, json={}, headers=scoping_rbac.admin).status_code != 403, f'admin denied {url}'
@pytest.mark.parametrize('persona', ['viewer', 'member', 'foreign'])
def test_status_component_check_admin_only(app, client, scoping_rbac, persona):
"""#4 — `POST /status/components/<id>/check` triggers a live check + persists a
result (write-ish), so it joins its 9 admin-only mutation siblings. A non-admin
is 403; admin passes the gate (the check itself may 404 on a missing id)."""
url = '/api/v1/status/components/999999/check'
assert client.post(url, headers=getattr(scoping_rbac, persona)).status_code == 403, persona
assert client.post(url, headers=scoping_rbac.admin).status_code != 403
# test_status_component_check_admin_only moved to tests/test_status_extraction.py
# (plan 47) — the status blueprint is now in the serverkit-status extension.
@@ -0,0 +1,116 @@
"""Prove the Cloud Provisioning extraction (plan 47 Phase 2).
A fresh panel no longer carries the cloud-provider API in core; installing the
serverkit-cloud-provision builtin registers `/api/v1/cloud`. The CloudProvider
model stays core (G2). Also covers the one-shot backend re-acquisition that keeps
upgraded panels (which installed the extension frontend-only) from losing the API.
"""
import importlib
import sys
import pytest
from app import db
from app.models.plugin import InstalledPlugin
from app.services import plugin_service
SLUG = 'serverkit-cloud-provision'
_PKG = f'app.plugins.{SLUG}'
def test_core_has_no_cloud_routes(app):
rules = [r.rule for r in app.url_map.iter_rules()]
assert [r for r in rules if r.startswith('/api/v1/cloud/')] == []
def test_core_import_of_cloud_service_is_gone():
with pytest.raises(ModuleNotFoundError):
importlib.import_module('app.services.cloud_provisioning_service')
def test_cloud_in_converted_builtin_slugs():
from app.services.extension_migration import CONVERTED_BUILTIN_SLUGS
assert SLUG in CONVERTED_BUILTIN_SLUGS
def test_cloud_model_stays_core():
"""G2: the CloudProvider/CloudServer models remain importable from core."""
from app.models.cloud_server import CloudProvider, CloudServer # noqa: F401
@pytest.fixture
def install_dirs(tmp_path, monkeypatch):
backend = tmp_path / 'plugins_backend'
frontend = tmp_path / 'plugins_frontend'
backend.mkdir()
frontend.mkdir()
monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))
monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))
added = str(backend)
app_pkg_plugins = importlib.import_module('app.plugins')
if added not in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.append(added)
yield {'backend': backend, 'frontend': frontend}
if added in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.remove(added)
for name in list(sys.modules):
if name == _PKG or name.startswith(_PKG + '.'):
del sys.modules[name]
def test_install_cloud_extension_registers_routes(app, client, auth_headers, install_dirs):
available = {e['slug'] for e in plugin_service.list_builtin_extensions()}
assert SLUG in available
plugin = plugin_service.install_builtin_extension(SLUG)
assert plugin.status == InstalledPlugin.STATUS_ACTIVE
assert plugin.has_backend is True
assert plugin.url_prefix == '/api/v1/cloud'
resp = client.get('/api/v1/cloud/providers', headers=auth_headers)
assert resp.status_code not in (404, 503), resp.status_code
def test_cloud_provider_secret_encrypted_at_rest(app, install_dirs):
"""The extracted service still encrypts provider secrets at rest (moved here
from test_provider_secret_encryption.py)."""
plugin_service.install_builtin_extension(SLUG)
from app.models.cloud_server import CloudProvider
from app.utils.crypto import is_encrypted, decrypt_secret_safe
svc_mod = importlib.import_module(f'{_PKG}.cloud_provisioning_service')
CloudProvisioningService = svc_mod.CloudProvisioningService
p = CloudProvisioningService.create_provider(
{'provider_type': 'digitalocean', 'name': 'do', 'api_key': 'do-token-xyz'})
row = CloudProvider.query.get(p.id)
assert row.api_key_encrypted != 'do-token-xyz'
assert is_encrypted(row.api_key_encrypted) is True
assert decrypt_secret_safe(row.api_key_encrypted) == 'do-token-xyz'
assert CloudProvisioningService._auth_headers(row)['Authorization'] == 'Bearer do-token-xyz'
def test_backend_acquisition_upgrades_frontend_only_install(app, install_dirs):
"""An upgraded panel that installed the extension frontend-only re-acquires
the now-extracted backend (plan 47 Phase 2 migration)."""
from app.services import extension_migration
# Simulate the pre-plan-47 state: a frontend-only install (API came from core)
row = InstalledPlugin(
name=SLUG, display_name='Cloud Provisioning', slug=SLUG, version='1.0.0',
source_type='builtin', status=InstalledPlugin.STATUS_ACTIVE,
)
row.has_backend = False
row.has_frontend = True
db.session.add(row)
db.session.commit()
extension_migration.run_backend_acquisition()
refreshed = InstalledPlugin.query.filter_by(slug=SLUG).first()
assert refreshed.has_backend is True
rules = [r.rule for r in app.url_map.iter_rules()]
assert any(r.startswith('/api/v1/cloud/') for r in rules)
+76
View File
@@ -0,0 +1,76 @@
"""Prove the FTP extraction (plan 47 Phase 2).
A fresh panel no longer carries the FTP API in core; installing the
serverkit-ftp builtin registers `/api/v1/ftp` and its routes respond (which also
exercises the extension's relative-import rewiring). Uninstall removes it again.
"""
import sys
import pytest
import app as app_pkg
from app.models.plugin import InstalledPlugin
from app.services import plugin_service
SLUG = 'serverkit-ftp'
_PKG = f'app.plugins.{SLUG}'
def test_core_has_no_ftp_routes(app):
rules = [r.rule for r in app.url_map.iter_rules()]
assert [r for r in rules if r.startswith('/api/v1/ftp')] == []
def test_core_import_of_ftp_service_is_gone():
"""The FTP service left core — importing it from app.services must fail."""
import importlib
with pytest.raises(ModuleNotFoundError):
importlib.import_module('app.services.ftp_service')
def test_ftp_in_converted_builtin_slugs():
from app.services.extension_migration import CONVERTED_BUILTIN_SLUGS
assert SLUG in CONVERTED_BUILTIN_SLUGS
@pytest.fixture
def install_dirs(tmp_path, monkeypatch):
backend = tmp_path / 'plugins_backend'
frontend = tmp_path / 'plugins_frontend'
backend.mkdir()
frontend.mkdir()
monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))
monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))
added = str(backend)
import importlib
app_pkg_plugins = importlib.import_module('app.plugins')
if added not in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.append(added)
yield {'backend': backend, 'frontend': frontend}
if added in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.remove(added)
for name in list(sys.modules):
if name == _PKG or name.startswith(_PKG + '.'):
del sys.modules[name]
def test_install_ftp_extension_registers_routes(app, client, auth_headers, install_dirs):
available = {e['slug'] for e in plugin_service.list_builtin_extensions()}
assert SLUG in available, 'serverkit-ftp builtin folder should exist'
plugin = plugin_service.install_builtin_extension(SLUG)
assert plugin.status == InstalledPlugin.STATUS_ACTIVE
assert plugin.has_backend is True
assert plugin.url_prefix == '/api/v1/ftp'
resp = client.get('/api/v1/ftp/status', headers=auth_headers)
assert resp.status_code not in (404, 503), resp.status_code
def test_uninstall_removes_ftp_plugin(app, install_dirs):
plugin = plugin_service.install_builtin_extension(SLUG)
assert plugin_service.uninstall_plugin(plugin.id) is True
assert InstalledPlugin.query.filter_by(slug=SLUG).first() is None
@@ -15,7 +15,9 @@ def test_observability_aliases_registered():
assert any(r.startswith('/api/v1/observability/events') for r in rules)
assert any(r.startswith('/api/v1/observability/uptime') for r in rules)
assert any(r.startswith('/api/v1/observability/fleet') for r in rules)
assert any(r.startswith('/api/v1/observability/status-pages') for r in rules)
# The status-pages observability alias was dropped when status pages moved to
# the serverkit-status extension (plan 47); the public status route now ships
# with that extension rather than core.
def test_original_prefixes_still_present():
@@ -25,8 +27,6 @@ def test_original_prefixes_still_present():
assert any(r.startswith('/api/v1/monitoring') for r in rules)
assert any(r.startswith('/api/v1/telemetry') for r in rules)
assert any(r.startswith('/api/v1/fleet-monitor') for r in rules)
# Public status page route untouched.
assert '/api/v1/status/public/<slug>' in rules
def test_events_alias_matches_telemetry(app, client, auth_headers):
@@ -0,0 +1,154 @@
"""Plan 47 Phase 1 — the setup wizard installs what it recommends.
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.
"""
import pytest
from app import db
from app.models.plugin import InstalledPlugin
from app.models.user import User
from app.services import plugin_service as ps
from app.services.settings_service import SettingsService
from werkzeug.security import generate_password_hash
from flask_jwt_extended import create_access_token
# ── map integrity ────────────────────────────────────────────────────────────
def test_recommendation_map_has_no_dead_slugs(app):
"""Every slug in the use-case map resolves to a builtin or registry entry."""
with app.app_context():
index = ps._recommendation_index()
dead = [
slug
for slugs in ps.RECOMMENDED_EXTENSIONS_BY_USE_CASE.values()
for slug in slugs
if slug not in index
]
assert dead == [], f'recommendation map points at dead slugs: {dead}'
def test_recommend_resolves_and_dedupes(app):
with app.app_context():
recs = ps.recommend_extensions_for_use_cases(['web-apps', 'devops'])
slugs = [r['slug'] for r in recs]
# git appears in both use cases — must be de-duped, first-seen order kept
assert slugs.count('serverkit-git') == 1
assert 'serverkit-status' in slugs
assert 'serverkit-k8s' in slugs
assert 'serverkit-tramo' in slugs
# every entry carries real metadata (not just a display string)
for r in recs:
assert r['display_name']
assert r['source'] in ('builtin', 'registry')
assert 'installed' in r
def test_recommend_empty_use_cases(app):
with app.app_context():
assert ps.recommend_extensions_for_use_cases([]) == []
assert ps.recommend_extensions_for_use_cases(None) == []
# ── endpoint ─────────────────────────────────────────────────────────────────
def test_recommendations_endpoint(client, auth_headers):
resp = client.get('/api/v1/plugins/recommendations?use_cases=wordpress',
headers=auth_headers)
assert resp.status_code == 200
slugs = [r['slug'] for r in resp.get_json()['recommendations']]
assert 'serverkit-wordpress' in slugs
def test_recommendations_endpoint_requires_auth(client):
resp = client.get('/api/v1/plugins/recommendations?use_cases=wordpress')
assert resp.status_code == 401
# ── complete-onboarding persists installed slugs ─────────────────────────────
def test_complete_onboarding_persists_installed_extensions(client, auth_headers):
resp = client.post('/api/v1/auth/complete-onboarding',
json={'use_cases': ['devops'],
'installed_extensions': ['serverkit-k8s', 'serverkit-git']},
headers=auth_headers)
assert resp.status_code == 200
assert SettingsService.get('onboarding_installed_extensions') == [
'serverkit-k8s', 'serverkit-git']
assert SettingsService.get('onboarding_use_cases') == ['devops']
def test_complete_onboarding_rejects_bad_installed_extensions(client, auth_headers):
resp = client.post('/api/v1/auth/complete-onboarding',
json={'use_cases': [], 'installed_extensions': 'nope'},
headers=auth_headers)
assert resp.status_code == 400
def test_complete_onboarding_still_completes_without_installs(client, auth_headers):
"""A wizard run that installs nothing (the lean outcome) still finishes."""
resp = client.post('/api/v1/auth/complete-onboarding',
json={'use_cases': []},
headers=auth_headers)
assert resp.status_code == 200
assert SettingsService.get('setup_completed') is True
# ── wizard-optional flagship gating ──────────────────────────────────────────
def test_finalize_setup_flagships_marks_uninstalled_when_absent(app):
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()
def test_finalize_setup_flagships_keeps_installed(app):
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()
ps.finalize_setup_flagships()
assert 'serverkit-wordpress' 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."""
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)."""
with app.app_context():
InstalledPlugin.query.filter_by(slug='serverkit-wordpress').delete()
db.session.commit()
user = User(email='a@t.local', 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
@@ -107,20 +107,10 @@ def test_dns_legacy_plaintext_migration(app):
# ── cloud providers ─────────────────────────────────────────────────────────
def test_cloud_provider_secret_encrypted_at_rest(app):
from app.models.cloud_server import CloudProvider
from app.services.cloud_provisioning_service import CloudProvisioningService
from app.utils.crypto import is_encrypted, decrypt_secret_safe
p = CloudProvisioningService.create_provider(
{'provider_type': 'digitalocean', 'name': 'do', 'api_key': 'do-token-xyz'})
row = CloudProvider.query.get(p.id)
assert row.api_key_encrypted != 'do-token-xyz'
assert is_encrypted(row.api_key_encrypted) is True
assert decrypt_secret_safe(row.api_key_encrypted) == 'do-token-xyz'
# the auth header uses the decrypted token, not the stored blob
assert CloudProvisioningService._auth_headers(row)['Authorization'] == 'Bearer do-token-xyz'
# CloudProvisioningService moved to the serverkit-cloud-provision extension
# (plan 47); its secret-at-rest coverage now lives in
# tests/test_cloud_provision_extraction.py (installs the extension first). The
# CloudProvider model stays core (G2).
# ── storage (config-file backed) ────────────────────────────────────────────
@@ -0,0 +1,236 @@
"""Prove the Remote Access (WireGuard tunnels) extraction (plan 47 Phase 2).
The tunnels blueprint + broker/publish/netutil services move out of core into
serverkit-remote-access; the Tunnel/ExposedService models stay core (G2). This
also re-homes the former test_tunnel_netutil.py (pure subnet/port helpers) and
test_tunnel_reconcile.py (panel-authoritative reconcile) against the extension.
"""
import importlib
import sys
from types import SimpleNamespace
import pytest
from app import db
from app.models.server import Server
from app.models.tunnel import Tunnel
from app.models.exposed_service import ExposedService
from app.models.plugin import InstalledPlugin
from app.services import agent_registry as ar_mod
from app.services import plugin_service
SLUG = 'serverkit-remote-access'
_PKG = f'app.plugins.{SLUG}'
# ── extraction shape ─────────────────────────────────────────────────────────
def test_core_has_no_tunnel_routes(app):
rules = [r.rule for r in app.url_map.iter_rules()]
assert [r for r in rules if r.startswith('/api/v1/tunnels')] == []
def test_core_import_of_tunnel_services_gone():
for mod in ('tunnel_broker_service', 'tunnel_publish_service', 'tunnel_netutil'):
with pytest.raises(ModuleNotFoundError):
importlib.import_module(f'app.services.{mod}')
def test_remote_access_in_converted_builtin_slugs():
from app.services.extension_migration import CONVERTED_BUILTIN_SLUGS
assert SLUG in CONVERTED_BUILTIN_SLUGS
def test_tunnel_models_stay_core():
from app.models.tunnel import Tunnel # noqa: F401
from app.models.exposed_service import ExposedService # noqa: F401
@pytest.fixture
def install_dirs(tmp_path, monkeypatch):
backend = tmp_path / 'plugins_backend'
frontend = tmp_path / 'plugins_frontend'
backend.mkdir()
frontend.mkdir()
monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))
monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))
added = str(backend)
app_pkg_plugins = importlib.import_module('app.plugins')
if added not in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.append(added)
yield {'backend': backend, 'frontend': frontend}
if added in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.remove(added)
for name in list(sys.modules):
if name == _PKG or name.startswith(_PKG + '.'):
del sys.modules[name]
@pytest.fixture
def ext(app, install_dirs):
plugin_service.install_builtin_extension(SLUG)
tn = importlib.import_module(f'{_PKG}.tunnel_netutil')
broker = importlib.import_module(f'{_PKG}.tunnel_broker_service')
return SimpleNamespace(tn=tn, TunnelBrokerService=broker.TunnelBrokerService)
def test_install_registers_tunnel_routes(app, client, auth_headers, install_dirs):
plugin = plugin_service.install_builtin_extension(SLUG)
assert plugin.status == InstalledPlugin.STATUS_ACTIVE
assert plugin.has_backend is True
assert plugin.url_prefix == '/api/v1/tunnels'
rules = [r.rule for r in app.url_map.iter_rules()]
assert any(r.startswith('/api/v1/tunnels') for r in rules)
# ── re-homed: tunnel_netutil pure helpers ────────────────────────────────────
def test_pick_subnet_first_free(ext):
cidr, edge, priv = ext.tn.pick_subnet([])
assert (cidr, edge, priv) == ('10.88.0.0/24', '10.88.0.1', '10.88.0.2')
def test_pick_subnet_skips_used(ext):
cidr, edge, priv = ext.tn.pick_subnet(['10.88.0.0/24', '10.88.1.0/24'])
assert (cidr, edge, priv) == ('10.88.2.0/24', '10.88.2.1', '10.88.2.2')
def test_pick_subnet_exhausted(ext):
used = ['10.88.%d.0/24' % i for i in range(256)]
with pytest.raises(RuntimeError):
ext.tn.pick_subnet(used)
def test_interface_name_is_stable_and_kernel_valid(ext):
name = ext.tn.interface_name_for('3fa9c2b1-dead-beef-0000-111122223333')
assert name == 'skwg3fa9c2b1'
assert len(name) <= 15
assert name.replace('skwg', '').isalnum()
def test_derive_status(ext):
now = 1_000_000
assert ext.tn.derive_status(now - 10, now) == 'up'
assert ext.tn.derive_status(now - 10_000, now) == 'degraded'
assert ext.tn.derive_status(0, now) == 'pending'
assert ext.tn.derive_status(now, now, interface_up=False) == 'down'
def test_validate_endpoint_host(ext):
assert ext.tn.validate_endpoint_host('203.0.113.5') is True
assert ext.tn.validate_endpoint_host('10.0.0.5') is True
assert ext.tn.validate_endpoint_host('127.0.0.1') is False
assert ext.tn.validate_endpoint_host('0.0.0.0') is False
assert ext.tn.validate_endpoint_host('') is False
assert ext.tn.validate_endpoint_host('not-an-ip') is False
def test_pick_listen_port(ext):
assert ext.tn.pick_listen_port([]) == 51820
assert ext.tn.pick_listen_port([51820]) == 51821
assert ext.tn.pick_listen_port([51820, 51821, 51823]) == 51822
def test_pick_listen_port_exhausted(ext):
used = list(range(ext.tn.DEFAULT_LISTEN_PORT,
ext.tn.DEFAULT_LISTEN_PORT + ext.tn.LISTEN_PORT_RANGE))
with pytest.raises(RuntimeError):
ext.tn.pick_listen_port(used)
def test_diagnose_reachability(ext):
assert ext.tn.diagnose_reachability(0, None, False)['state'] == 'interface_down'
assert ext.tn.diagnose_reachability(1_700_000_000, 999, True)['state'] == 'ok'
assert ext.tn.diagnose_reachability(0, 5, True)['state'] == 'connecting'
d = ext.tn.diagnose_reachability(0, 600, True)
assert d['state'] == 'no_handshake'
assert 'blocked' in d['hint'].lower()
# ── re-homed: panel-authoritative reconcile ──────────────────────────────────
def _server(name, ip=None):
s = Server(name=name, ip_address=ip, status='online')
db.session.add(s)
db.session.commit()
return s
def _record_send(monkeypatch):
calls = []
def fake_send(server_id, action, params=None, user_id=None, timeout=30.0):
calls.append({'server_id': server_id, 'action': action, 'params': params or {}})
return {'success': True, 'data': {}}
monkeypatch.setattr(ar_mod.agent_registry, 'send_command', fake_send)
return calls
def _tunnel(edge, priv, iface, third):
t = Tunnel(
edge_server_id=edge.id, private_server_id=priv.id,
interface_name=iface, subnet='10.88.%d.0/24' % third,
edge_wg_ip='10.88.%d.1' % third, private_wg_ip='10.88.%d.2' % third,
listen_port=51820, edge_pubkey='EDGEPUB', private_pubkey='PRIVPUB',
status='up',
)
db.session.add(t)
db.session.commit()
return t
def test_reconcile_private_side(ext, monkeypatch):
calls = _record_send(monkeypatch)
edge = _server('edge', ip='203.0.113.9')
priv = _server('home')
t = _tunnel(edge, priv, 'skwgrec01', 7)
db.session.add(ExposedService(tunnel_id=t.id, hostname='jelly.example.com',
port=8096, status='published'))
db.session.commit()
res = ext.TunnelBrokerService.reconcile_server(priv.id)
assert res and res[0]['ok']
actions = [c['action'] for c in calls]
assert 'wireguard:interface:up' in actions
assert 'wireguard:peer:set' in actions
assert 'wireguard:forward' in actions
peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')
assert peer['public_key'] == 'EDGEPUB'
assert peer['endpoint'] == '203.0.113.9:51820'
assert peer['persistent_keepalive'] == 25
fwd = next(c['params'] for c in calls if c['action'] == 'wireguard:forward')
assert fwd['listen_port'] == 8096 and fwd['target_port'] == 8096
assert fwd['listen_ip'] == '10.88.7.2'
def test_reconcile_edge_side(ext, monkeypatch):
calls = _record_send(monkeypatch)
edge = _server('edge2', ip='198.51.100.4')
priv = _server('home2')
_tunnel(edge, priv, 'skwgrec02', 8)
ext.TunnelBrokerService.reconcile_server(edge.id)
actions = [c['action'] for c in calls]
assert 'wireguard:interface:up' in actions
assert 'wireguard:peer:set' in actions
assert 'firewall:allow_port' in actions
peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')
assert peer['public_key'] == 'PRIVPUB'
assert 'endpoint' not in peer
def test_reconcile_skips_errored_tunnels(ext, monkeypatch):
calls = _record_send(monkeypatch)
edge = _server('edge3', ip='192.0.2.7')
priv = _server('home3')
t = _tunnel(edge, priv, 'skwgrec03', 9)
t.status = 'error'
db.session.commit()
res = ext.TunnelBrokerService.reconcile_server(priv.id)
assert res == []
assert calls == []
+133
View File
@@ -0,0 +1,133 @@
"""Prove the Status Pages extraction (plan 47 Phase 2).
The status-pages blueprint (public + management routes) and its service move into
serverkit-status; the StatusPage/StatusComponent models stay core (G2). Core's
WordPress health-check job syncs status components only when the extension is
installed (no crash on a lean panel). Re-homes the status-page mutation authz
test from test_api_authz_hardening.py.
"""
import importlib
import sys
import pytest
from werkzeug.security import generate_password_hash
from flask_jwt_extended import create_access_token
from app import db
from app.models.user import User
from app.models.plugin import InstalledPlugin
from app.services import plugin_service
SLUG = 'serverkit-status'
_PKG = f'app.plugins.{SLUG}'
def test_core_has_no_status_page_routes(app):
"""The status-pages management/public routes are gone from core (the
/api/v1/status/apps container-status aggregator is a different blueprint)."""
rules = [r.rule for r in app.url_map.iter_rules()]
assert '/api/v1/status/public/<slug>' not in rules
assert '/api/v1/status/' not in rules
assert not any('observability/status-pages' in r for r in rules)
def test_core_import_of_status_service_gone():
with pytest.raises(ModuleNotFoundError):
importlib.import_module('app.services.status_page_service')
def test_status_in_converted_builtin_slugs():
from app.services.extension_migration import CONVERTED_BUILTIN_SLUGS
assert SLUG in CONVERTED_BUILTIN_SLUGS
def test_status_models_stay_core():
from app.models.status_page import ( # noqa: F401
StatusPage, StatusComponent)
def test_health_check_job_no_ops_without_extension(app):
"""run_health_checks must not crash on a lean panel (no serverkit-status)."""
from app.jobs.builtin_handlers import run_health_checks
run_health_checks() # no production sites, no extension — clean no-op
@pytest.fixture
def install_dirs(tmp_path, monkeypatch):
backend = tmp_path / 'plugins_backend'
frontend = tmp_path / 'plugins_frontend'
backend.mkdir()
frontend.mkdir()
monkeypatch.setattr(plugin_service, 'BACKEND_PLUGINS_DIR', str(backend))
monkeypatch.setattr(plugin_service, 'FRONTEND_PLUGINS_DIR', str(frontend))
added = str(backend)
app_pkg_plugins = importlib.import_module('app.plugins')
if added not in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.append(added)
yield {'backend': backend, 'frontend': frontend}
if added in app_pkg_plugins.__path__:
app_pkg_plugins.__path__.remove(added)
for name in list(sys.modules):
if name == _PKG or name.startswith(_PKG + '.'):
del sys.modules[name]
def _mk_user(username, role):
u = User(email=f'{username}@t.local', username=username, role=role,
is_active=True, password_hash=generate_password_hash('x'))
db.session.add(u)
db.session.commit()
return u
def _token(uid):
return {'Authorization': f'Bearer {create_access_token(identity=uid)}'}
def test_install_registers_status_routes(app, client, auth_headers, install_dirs):
plugin = plugin_service.install_builtin_extension(SLUG)
assert plugin.status == InstalledPlugin.STATUS_ACTIVE
assert plugin.has_backend is True
assert plugin.url_prefix == '/api/v1/status'
rules = [r.rule for r in app.url_map.iter_rules()]
assert '/api/v1/status/public/<slug>' in rules
def test_status_page_mutations_admin_only(app, client, install_dirs):
"""Reads open to any authed user; every mutation is admin-only (relocated
from test_api_authz_hardening.py — now runs against the installed extension)."""
plugin_service.install_builtin_extension(SLUG)
dev = _mk_user('sp_dev', 'developer')
admin = _mk_user('sp_admin', 'admin')
assert client.get('/api/v1/status/', headers=_token(dev.id)).status_code == 200
r = client.post('/api/v1/status/', json={'name': 'Ops', 'slug': 'ops'},
headers=_token(admin.id))
assert r.status_code == 201
page_id = r.get_json()['id']
assert client.post('/api/v1/status/', json={'name': 'X', 'slug': 'x'},
headers=_token(dev.id)).status_code == 403
assert client.put(f'/api/v1/status/{page_id}', json={'name': 'Y'},
headers=_token(dev.id)).status_code == 403
assert client.delete(f'/api/v1/status/{page_id}',
headers=_token(dev.id)).status_code == 403
assert client.post(f'/api/v1/status/{page_id}/components',
json={'name': 'c', 'check_type': 'http'},
headers=_token(dev.id)).status_code == 403
assert client.post(f'/api/v1/status/{page_id}/incidents', json={'title': 't'},
headers=_token(dev.id)).status_code == 403
@pytest.mark.parametrize('persona', ['viewer', 'member', 'foreign'])
def test_status_component_check_admin_only(app, client, scoping_rbac, install_dirs, persona):
"""POST /status/components/<id>/check is a write-ish mutation → admin-only
(relocated from test_api_authz_hardening.py, now against the extension)."""
plugin_service.install_builtin_extension(SLUG)
url = '/api/v1/status/components/999999/check'
assert client.post(url, headers=getattr(scoping_rbac, persona)).status_code == 403, persona
assert client.post(url, headers=scoping_rbac.admin).status_code != 403
-79
View File
@@ -1,79 +0,0 @@
"""Unit tests for the tunnel broker's pure helpers (roadmap #7 / #11).
These import only app.services.tunnel_netutil (stdlib-only) so they prove
the subnet allocator, interface-name derivation and health classification
without needing a DB or connected agents.
"""
from app.services import tunnel_netutil as tn
def test_pick_subnet_first_free():
cidr, edge, priv = tn.pick_subnet([])
assert cidr == '10.88.0.0/24'
assert edge == '10.88.0.1'
assert priv == '10.88.0.2'
def test_pick_subnet_skips_used():
cidr, edge, priv = tn.pick_subnet(['10.88.0.0/24', '10.88.1.0/24'])
assert cidr == '10.88.2.0/24'
assert edge == '10.88.2.1'
assert priv == '10.88.2.2'
def test_pick_subnet_exhausted():
used = ['10.88.%d.0/24' % i for i in range(256)]
try:
tn.pick_subnet(used)
assert False, "expected RuntimeError on exhausted pool"
except RuntimeError:
pass
def test_interface_name_is_stable_and_kernel_valid():
name = tn.interface_name_for('3fa9c2b1-dead-beef-0000-111122223333')
assert name == 'skwg3fa9c2b1'
assert len(name) <= 15
assert name.replace('skwg', '').isalnum()
def test_derive_status():
now = 1_000_000
assert tn.derive_status(now - 10, now) == 'up'
assert tn.derive_status(now - 10_000, now) == 'degraded'
assert tn.derive_status(0, now) == 'pending'
assert tn.derive_status(now, now, interface_up=False) == 'down'
def test_validate_endpoint_host():
assert tn.validate_endpoint_host('203.0.113.5') is True
assert tn.validate_endpoint_host('10.0.0.5') is True # private edge OK
assert tn.validate_endpoint_host('127.0.0.1') is False # loopback
assert tn.validate_endpoint_host('0.0.0.0') is False # unspecified
assert tn.validate_endpoint_host('') is False
assert tn.validate_endpoint_host('not-an-ip') is False
def test_pick_listen_port():
assert tn.pick_listen_port([]) == 51820
assert tn.pick_listen_port([51820]) == 51821
assert tn.pick_listen_port([51820, 51821, 51823]) == 51822 # fills the gap
def test_pick_listen_port_exhausted():
used = list(range(tn.DEFAULT_LISTEN_PORT, tn.DEFAULT_LISTEN_PORT + tn.LISTEN_PORT_RANGE))
try:
tn.pick_listen_port(used)
assert False, "expected RuntimeError on exhausted port pool"
except RuntimeError:
pass
def test_diagnose_reachability():
assert tn.diagnose_reachability(0, None, False)['state'] == 'interface_down'
assert tn.diagnose_reachability(1_700_000_000, 999, True)['state'] == 'ok'
assert tn.diagnose_reachability(0, 5, True)['state'] == 'connecting'
d = tn.diagnose_reachability(0, 600, True)
assert d['state'] == 'no_handshake'
assert 'blocked' in d['hint'].lower()
-101
View File
@@ -1,101 +0,0 @@
"""Phase 3 #19: panel-authoritative tunnel reconcile.
Proves reconcile_server re-issues the right agent commands for each side
of a tunnel, by monkeypatching agent_registry.send_command to record calls
(no live agent needed).
"""
from app import db
from app.models.server import Server
from app.models.tunnel import Tunnel
from app.models.exposed_service import ExposedService
from app.services import agent_registry as ar_mod
from app.services.tunnel_broker_service import TunnelBrokerService
def _server(name, ip=None):
s = Server(name=name, ip_address=ip, status='online')
db.session.add(s)
db.session.commit()
return s
def _record_send(monkeypatch):
calls = []
def fake_send(server_id, action, params=None, user_id=None, timeout=30.0):
calls.append({'server_id': server_id, 'action': action, 'params': params or {}})
return {'success': True, 'data': {}}
monkeypatch.setattr(ar_mod.agent_registry, 'send_command', fake_send)
return calls
def _tunnel(edge, priv, iface, third):
t = Tunnel(
edge_server_id=edge.id, private_server_id=priv.id,
interface_name=iface, subnet='10.88.%d.0/24' % third,
edge_wg_ip='10.88.%d.1' % third, private_wg_ip='10.88.%d.2' % third,
listen_port=51820, edge_pubkey='EDGEPUB', private_pubkey='PRIVPUB',
status='up',
)
db.session.add(t)
db.session.commit()
return t
def test_reconcile_private_side(app, monkeypatch):
calls = _record_send(monkeypatch)
edge = _server('edge', ip='203.0.113.9')
priv = _server('home')
t = _tunnel(edge, priv, 'skwgrec01', 7)
db.session.add(ExposedService(tunnel_id=t.id, hostname='jelly.example.com', port=8096, status='published'))
db.session.commit()
res = TunnelBrokerService.reconcile_server(priv.id)
assert res and res[0]['ok']
actions = [c['action'] for c in calls]
assert 'wireguard:interface:up' in actions
assert 'wireguard:peer:set' in actions
assert 'wireguard:forward' in actions
peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')
assert peer['public_key'] == 'EDGEPUB' # private peers with the edge
assert peer['endpoint'] == '203.0.113.9:51820' # dials the edge endpoint
assert peer['persistent_keepalive'] == 25
fwd = next(c['params'] for c in calls if c['action'] == 'wireguard:forward')
assert fwd['listen_port'] == 8096 and fwd['target_port'] == 8096
assert fwd['listen_ip'] == '10.88.7.2'
def test_reconcile_edge_side(app, monkeypatch):
calls = _record_send(monkeypatch)
edge = _server('edge2', ip='198.51.100.4')
priv = _server('home2')
_tunnel(edge, priv, 'skwgrec02', 8)
TunnelBrokerService.reconcile_server(edge.id)
actions = [c['action'] for c in calls]
assert 'wireguard:interface:up' in actions
assert 'wireguard:peer:set' in actions
assert 'firewall:allow_port' in actions # edge re-opens its UDP port
peer = next(c['params'] for c in calls if c['action'] == 'wireguard:peer:set')
assert peer['public_key'] == 'PRIVPUB' # edge peers with the private host
assert 'endpoint' not in peer # edge has no endpoint for the private peer
def test_reconcile_skips_errored_tunnels(app, monkeypatch):
calls = _record_send(monkeypatch)
edge = _server('edge3', ip='192.0.2.7')
priv = _server('home3')
t = _tunnel(edge, priv, 'skwgrec03', 9)
t.status = 'error'
db.session.commit()
res = TunnelBrokerService.reconcile_server(priv.id)
assert res == []
assert calls == []