ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
fix(recovery): rebuild DNS cutover service+API and SSH site importer
Juan Denisa131cf5e0fa7
diff --git a/backend/app/api/dns_cutover.py b/backend/app/api/dns_cutover.pynew file mode 100644index 00000000..022850f0--- /dev/null+++ b/backend/app/api/dns_cutover.py@@ -0,0 +1,125 @@+"""Reversible DNS cutover endpoints (``/api/v1/dns-cutover``).++Snapshot a domain's live provider records, perform (or dry-run) a cutover that+repoints them at the imported site's new address, verify propagation across+public resolvers, and revert — restoring the pre-cutover world byte-for-byte.++Read verbs (ttl-guidance, list/get snapshots, verify) are open to any+authenticated user; the mutating verbs (snapshot, cutover, revert) are+admin-only (plan 31 #1/#2/#3).+"""+from flask import Blueprint, request, jsonify+from flask_jwt_extended import jwt_required, get_jwt_identity++from app.services.dns_cutover_service import DnsCutoverService, DnsCutoverError++dns_cutover_bp = Blueprint('dns_cutover', __name__)+++def _current_user():+ from app.models.user import User+ return User.query.get(get_jwt_identity())+++def _require_admin():+ user = _current_user()+ if not user or not user.is_admin:+ return jsonify({'error': 'Admin access required'}), 403+ return None+++@dns_cutover_bp.route('/ttl-guidance', methods=['POST'])+@jwt_required()+def ttl_guidance():+ data = request.get_json(silent=True) or {}+ return jsonify(DnsCutoverService.ttl_guidance(data.get('records') or []))+++@dns_cutover_bp.route('/snapshot', methods=['POST'])+@jwt_required()+def create_snapshot():+ guard = _require_admin()+ if guard:+ return guard+ data = request.get_json(silent=True) or {}+ try:+ snapshot = DnsCutoverService.create_snapshot(+ domain=data.get('domain'),+ provider_zone_id=data.get('provider_zone_id'),+ provider=data.get('provider'),+ names=data.get('names'))+ return jsonify(snapshot.to_dict()), 201+ except DnsCutoverError as exc:+ return jsonify({'error': exc.message, 'code': exc.code}), exc.status_code+++@dns_cutover_bp.route('/snapshots', methods=['GET'])+@jwt_required()+def list_snapshots():+ domain = request.args.get('domain')+ snapshots = DnsCutoverService.list_snapshots(domain)+ return jsonify({'snapshots': [s.to_dict() for s in snapshots]})+++@dns_cutover_bp.route('/snapshots/<int:snapshot_id>', methods=['GET'])+@jwt_required()+def get_snapshot(snapshot_id):+ snapshot = DnsCutoverService.get_snapshot(snapshot_id)+ if not snapshot:+ return jsonify({'error': 'Snapshot not found'}), 404+ return jsonify(snapshot.to_dict())+++@dns_cutover_bp.route('/cutover', methods=['POST'])+@jwt_required()+def cutover():+ guard = _require_admin()+ if guard:+ return guard+ data = request.get_json(silent=True) or {}+ snapshot_id = data.get('snapshot_id')+ if not snapshot_id:+ return jsonify({'error': 'snapshot_id is required — a cutover needs a '+ 'snapshot so it can be reverted'}), 400+ snapshot = DnsCutoverService.get_snapshot(snapshot_id)+ if not snapshot:+ return jsonify({'error': 'Snapshot not found'}), 404+ try:+ result = DnsCutoverService.cutover(+ snapshot, target=data.get('target'),+ record_types=data.get('record_types') or ['A'],+ dry_run=bool(data.get('dry_run')))+ return jsonify(result)+ except DnsCutoverError as exc:+ return jsonify({'error': exc.message, 'code': exc.code}), exc.status_code+++@dns_cutover_bp.route('/verify', methods=['POST'])+@jwt_required()+def verify():+ data = request.get_json(silent=True) or {}+ try:+ result = DnsCutoverService.verify(+ domain=data.get('domain'),+ record_type=data.get('record_type') or 'A',+ expected=data.get('expected'),+ snapshot_id=data.get('snapshot_id'))+ return jsonify(result)+ except DnsCutoverError as exc:+ return jsonify({'error': exc.message, 'code': exc.code}), exc.status_code+++@dns_cutover_bp.route('/snapshots/<int:snapshot_id>/revert', methods=['POST'])+@jwt_required()+def revert(snapshot_id):+ guard = _require_admin()+ if guard:+ return guard+ snapshot = DnsCutoverService.get_snapshot(snapshot_id)+ if not snapshot:+ return jsonify({'error': 'Snapshot not found'}), 404+ try:+ result = DnsCutoverService.revert(snapshot)+ return jsonify(result)+ except DnsCutoverError as exc:+ return jsonify({'error': exc.message, 'code': exc.code}), exc.status_codediff --git a/backend/app/models/site_import.py b/backend/app/models/site_import.pyindex d245959a..0e8c91ab 100644--- a/backend/app/models/site_import.py+++ b/backend/app/models/site_import.py@@ -13,7 +13,8 @@ from app import db# Formats the importer registry may grow to support. 'cpanel' ships first;# the others plug into the same pipeline (see app/services/site_importers/).-VALID_SOURCE_TYPES = ('auto', 'cpanel', 'directadmin', 'hestia', 'wordpress_ssh')+VALID_SOURCE_TYPES = ('auto', 'cpanel', 'directadmin', 'hestia', 'ssh',+ 'wordpress_ssh')VALID_STATUSES = ('created', 'uploading', 'analyzing', 'analyzed',diff --git a/backend/app/services/dns_cutover_service.py b/backend/app/services/dns_cutover_service.pynew file mode 100644index 00000000..2bd98870--- /dev/null+++ b/backend/app/services/dns_cutover_service.py@@ -0,0 +1,360 @@+"""Reversible DNS cutover — snapshot a domain's live records, flip them at the new+box, verify propagation, and (if needed) revert to the pre-cutover WORLD.++A migration cutover repoints a domain's records at the freshly-imported site.+ServerKit's DNS activity ledger only records the *after* value of each write, so+it cannot power a revert on its own. This service therefore:++* **snapshots** the domain's existing provider records (server-sourced — the+ panel reads them itself; the client may only filter which *names* to include,+ never supply record data — plan 31 #2);+* performs the **cutover** (with a dry-run that returns the exact provider ops+ without writing — plan 31 #1), tracking the records it *creates* so the revert+ can undo them;+* **verifies** post-cutover resolution across public resolvers (plan 31 #1);+* **reverts** by DELETING the records the cutover created (reverse order) and+ re-applying every captured record, restoring the world byte-for-byte+ (plan 31 #3, Decision 3).++The provider client is resolved through the registered ``DNSProviderConfig``+providers (Decision 4); providers without a shared client stay a clean 501+``NO_PROVIDER`` naming the provider.+"""+import logging++from app import db+from app.models.dns_cutover_snapshot import DnsCutoverSnapshot+from app.services.dns_ownership_service import DnsOwnershipService++logger = logging.getLogger(__name__)++# Recommended TTL to lower records to before a cutover (5 minutes).+RECOMMENDED_CUTOVER_TTL = 300+++class DnsCutoverError(Exception):+ """A cutover operation that maps to an HTTP error.++ ``status_code`` (default 400) and ``code`` are surfaced by the API layer so+ an unsupported provider becomes a clean ``501 NO_PROVIDER`` rather than a+ generic 500.+ """++ def __init__(self, message, status_code=400, code=None):+ super().__init__(message)+ self.message = message+ self.status_code = status_code+ self.code = code+++class DnsCutoverService:+ """Snapshot / cutover / verify / revert for a reversible DNS migration."""++ # ── provider resolution (Decision 4) ─────────────────────────────────────+ @classmethod+ def _resolve_dns_client(cls, provider=None, provider_zone_id=None):+ """Resolve a shared DNS client + its provider config, routing through the+ registered providers rather than hardcoding Cloudflare.++ Returns ``(client, config)``. Raises :class:`DnsCutoverError` (501+ ``NO_PROVIDER``, provider named) when nothing is connected or the+ provider has no shared client yet.+ """+ from app.models.email import DNSProviderConfig+ from app.services.dns import DnsCredential, get_client++ query = DNSProviderConfig.query+ if provider:+ query = query.filter_by(provider=provider)+ config = query.filter_by(is_default=True).first() or query.first()+ if not config:+ named = f' for provider {provider!r}' if provider else ''+ raise DnsCutoverError(+ f'No connected DNS provider{named} to perform this cutover.',+ status_code=501, code='NO_PROVIDER')+ try:+ client = get_client(DnsCredential.from_provider_config(config))+ except ValueError:+ raise DnsCutoverError(+ f'DNS cutover is not supported for provider {config.provider!r} '+ 'yet — connect Cloudflare or perform this change manually.',+ status_code=501, code='NO_PROVIDER')+ return client, config++ # ── TTL guidance ─────────────────────────────────────────────────────────+ @classmethod+ def ttl_guidance(cls, records):+ """Advise lowering TTLs before a cutover so the switch propagates fast.++ Returns the recommended pre-cutover TTL, the current max TTL across the+ supplied records (the worst-case propagation wait), and a per-record+ breakdown flagging records that still need lowering.+ """+ records = records or []+ ttls = []+ for rec in records:+ try:+ ttl = int(rec.get('ttl'))+ except (TypeError, ValueError):+ continue+ if ttl > 0:+ ttls.append(ttl)+ current_max = max(ttls) if ttls else None+ breakdown = []+ for rec in records:+ try:+ ttl = int(rec.get('ttl'))+ except (TypeError, ValueError):+ ttl = None+ breakdown.append({+ 'name': rec.get('name'),+ 'type': rec.get('type') or rec.get('record_type'),+ 'ttl': ttl,+ 'needs_lowering': bool(ttl and ttl > RECOMMENDED_CUTOVER_TTL),+ })+ return {+ 'recommended_ttl': RECOMMENDED_CUTOVER_TTL,+ 'current_max_ttl': current_max,+ # Worst-case seconds a stale answer may linger after the flip.+ 'propagation_wait_seconds': current_max if current_max else 3600,+ 'advice': (+ 'Lower the TTL of the records you will cut over to '+ f'{RECOMMENDED_CUTOVER_TTL}s and wait for the previous (higher) '+ 'TTL to elapse before flipping — resolvers then pick up the new '+ 'target within minutes, and a revert is just as fast.'),+ 'records': breakdown,+ }++ # ── snapshots (server-sourced, Decision 2) ───────────────────────────────+ @classmethod+ def create_snapshot(cls, domain, provider_zone_id, provider=None, names=None):+ """Snapshot the domain's live provider records before a cutover.++ The panel reads the records itself from the provider (server-sourced);+ ``names`` may only FILTER which record names to include — the client+ never supplies record data. Returns the persisted snapshot row.+ """+ domain = (domain or '').strip().lower().rstrip('.')+ if not domain:+ raise DnsCutoverError('A domain is required to snapshot.')+ if not provider_zone_id:+ raise DnsCutoverError('A provider_zone_id is required to snapshot.')++ client, config = cls._resolve_dns_client(provider, provider_zone_id)+ res = client.list_records(provider_zone_id)+ if not res.get('success'):+ raise DnsCutoverError(+ f"Could not read live records for the zone: {res.get('error')}",+ status_code=502)+ records = res.get('records', []) or []++ if names:+ wanted = {(n or '').strip().lower().rstrip('.') for n in names}+ records = [r for r in records+ if (r.get('name') or '').strip().lower().rstrip('.') in wanted]++ snapshot = DnsCutoverSnapshot(+ domain=domain, provider=config.provider,+ provider_zone_id=provider_zone_id, status='captured')+ snapshot.set_records(records)+ snapshot.set_created_records([])+ db.session.add(snapshot)+ db.session.commit()+ logger.info('Captured DNS cutover snapshot %s for %s (%d record(s))',+ snapshot.id, domain, len(records))+ return snapshot++ @classmethod+ def list_snapshots(cls, domain=None):+ query = DnsCutoverSnapshot.query+ if domain:+ query = query.filter_by(domain=(domain or '').strip().lower().rstrip('.'))+ return query.order_by(DnsCutoverSnapshot.created_at.desc(),+ DnsCutoverSnapshot.id.desc()).all()++ @classmethod+ def get_snapshot(cls, snapshot_id):+ return DnsCutoverSnapshot.query.get(snapshot_id)++ # ── cutover (Decision 1) ─────────────────────────────────────────────────+ @classmethod+ def _plan_ops(cls, snapshot, target, record_types):+ """Compute the exact provider ops a cutover would perform: for each+ record type, repoint ``snapshot.domain`` at ``target``. An op is a+ ``create`` when the snapshot has no matching (type, name) predecessor,+ else an ``update`` carrying the old value.+ """+ domain = snapshot.domain+ captured = snapshot.get_records()+ ops = []+ for record_type in record_types:+ record_type = (record_type or '').strip().upper()+ if not record_type:+ continue+ predecessor = next(+ (r for r in captured+ if (r.get('type') or '').upper() == record_type+ and (r.get('name') or '').strip().lower().rstrip('.') == domain),+ None)+ ops.append({+ 'action': 'update' if predecessor else 'create',+ 'type': record_type,+ 'name': domain,+ 'old': predecessor.get('content') if predecessor else None,+ 'new': target,+ })+ return ops++ @classmethod+ def cutover(cls, snapshot, target, record_types=('A',), dry_run=False):+ """Repoint the snapshotted domain's records at ``target``.++ A cutover structurally requires a snapshot row (so a revert is always+ possible). ``dry_run`` returns the exact provider ops WITHOUT writing and+ needs no connected provider. A real cutover applies each op via the+ ownership-guarded upsert (``allow_foreign=True`` — the operator is+ deliberately taking over their own record), records the ids of records it+ CREATED for the revert, and flips the snapshot to ``cutover``.+ """+ from datetime import datetime++ from app.services.dns import DnsRecordSpec++ if snapshot is None:+ raise DnsCutoverError('A snapshot is required to cut over.')+ target = (target or '').strip()+ if not target:+ raise DnsCutoverError('A cutover target (the new address) is required.')+ record_types = list(record_types or ['A'])++ ops = cls._plan_ops(snapshot, target, record_types)+ if dry_run:+ return {'success': True, 'dry_run': True,+ 'snapshot_id': snapshot.id, 'domain': snapshot.domain,+ 'target': target, 'ops': ops}++ client, config = cls._resolve_dns_client(snapshot.provider,+ snapshot.provider_zone_id)+ results = []+ created = list(snapshot.get_created_records())+ for op in ops:+ spec = DnsRecordSpec(record_type=op['type'], name=op['name'],+ content=target)+ res = DnsOwnershipService.guarded_upsert(+ client, provider=config.provider,+ provider_zone_id=snapshot.provider_zone_id, spec=spec,+ source='cutover', config_id=config.id, allow_foreign=True)+ ok = bool(res.get('success'))+ results.append({'type': op['type'], 'name': op['name'],+ 'action': op['action'], 'success': ok,+ 'error': res.get('error')})+ # A record with no snapshot predecessor is one the cutover CREATED;+ # remember its provider id so revert can delete it (Decision 3).+ if ok and op['action'] == 'create':+ created.append({'id': res.get('record_id'), 'type': op['type'],+ 'name': op['name'], 'content': target})++ snapshot.set_created_records(created)+ snapshot.status = 'cutover'+ snapshot.applied_at = datetime.utcnow()+ db.session.commit()++ all_ok = all(r['success'] for r in results)+ return {'success': all_ok, 'dry_run': False, 'snapshot_id': snapshot.id,+ 'domain': snapshot.domain, 'target': target, 'ops': ops,+ 'results': results, 'snapshot': snapshot.to_dict()}++ # ── verify (plan 31 #1) ──────────────────────────────────────────────────+ @classmethod+ def verify(cls, domain, record_type='A', expected=None, snapshot_id=None):+ """Check post-cutover resolution across public resolvers.++ Thin wrapper over the multi-resolver propagation check. When+ ``expected`` (the address the cutover pointed at) is given, annotate the+ result with whether every resolver already returns it (plan 31 #1).+ """+ from app.services.dns_zone_service import DNSZoneService++ domain = (domain or '').strip().lower().rstrip('.')+ if not domain:+ raise DnsCutoverError('A domain is required to verify.')+ record_type = (record_type or 'A').strip().upper()++ resolvers = DNSZoneService.check_propagation(domain, record_type)+ answered = [r for r in resolvers if r.get('propagated')]+ result = {+ 'domain': domain,+ 'record_type': record_type,+ 'snapshot_id': snapshot_id,+ 'resolvers': resolvers,+ 'propagated': bool(resolvers) and all(r.get('propagated') for r in resolvers),+ 'answered_count': len(answered),+ 'resolver_count': len(resolvers),+ }+ if expected is not None:+ result['expected'] = expected+ result['matches_expected'] = bool(answered) and all(+ expected in (r.get('result') or []) for r in answered)+ return result++ # ── revert (Decision 3) ──────────────────────────────────────────────────+ @classmethod+ def revert(cls, snapshot):+ """Restore the pre-cutover WORLD, not just the captured values.++ First DELETE (in reverse creation order) the records the cutover created,+ so a create-only cutover reverts to *empty*, not to a stale target. Then+ re-apply every captured record with ``allow_foreign=True`` (the record+ now points at the new box — our own cutover write — and we deliberately+ restore the operator's original value). (plan 31 #3, Decision 3.)+ """+ from app.services.dns import DnsRecordSpec++ if snapshot is None:+ raise DnsCutoverError('A snapshot is required to revert.')++ client, config = cls._resolve_dns_client(snapshot.provider,+ snapshot.provider_zone_id)++ # 1) Delete cutover-created records, newest first.+ deletions = []+ for rec in reversed(snapshot.get_created_records()):+ res = DnsOwnershipService.guarded_delete(+ client, provider_zone_id=snapshot.provider_zone_id,+ record_type=rec.get('type'), name=rec.get('name'),+ provider_record_id=rec.get('id'), provider=config.provider,+ source='cutover-revert', config_id=config.id)+ deletions.append({'type': rec.get('type'), 'name': rec.get('name'),+ 'deleted': bool(res.get('success')),+ 'error': res.get('error')})++ # 2) Re-apply every captured record, restoring the operator's values.+ restorations = []+ for rec in snapshot.get_records():+ spec = DnsRecordSpec(+ record_type=rec.get('type'), name=rec.get('name'),+ content=rec.get('content', ''), ttl=rec.get('ttl') or 3600,+ priority=rec.get('priority'), proxied=bool(rec.get('proxied')))+ res = DnsOwnershipService.guarded_upsert(+ client, provider=config.provider,+ provider_zone_id=snapshot.provider_zone_id, spec=spec,+ source='cutover-revert', config_id=config.id, allow_foreign=True)+ restorations.append({'type': rec.get('type'), 'name': rec.get('name'),+ 'restored': bool(res.get('success')),+ 'error': res.get('error')})++ deleted_count = sum(1 for d in deletions if d.get('deleted'))+ snapshot.status = 'reverted_with_deletions' if deletions else 'reverted'+ db.session.commit()++ restored_ok = all(r.get('restored') for r in restorations)+ return {+ 'success': restored_ok,+ 'snapshot_id': snapshot.id,+ 'domain': snapshot.domain,+ 'status': snapshot.status,+ 'deletions': deletions,+ 'deleted_count': deleted_count,+ 'restorations': restorations,+ 'snapshot': snapshot.to_dict(),+ }diff --git a/backend/app/services/site_import_service.py b/backend/app/services/site_import_service.pyindex 3057c98d..bd6990c1 100644--- a/backend/app/services/site_import_service.py+++ b/backend/app/services/site_import_service.py@@ -77,11 +77,20 @@ class SiteImportService:raise SiteImportError(f'source_type must be one of {VALID_SOURCE_TYPES}')source = source or {}- if not source.get('upload_path') and not source.get('url'):- raise SiteImportError(- "source must contain 'upload_path' or 'url'")- if source.get('url'):- cls._validate_url(source['url']) # fail fast at creation time+ if source_type == 'ssh':+ # SSH sources carry connection facts (host/user/docroot), not an+ # archive; validate + normalise (keyfile-only, no password field).+ from app.services.site_importers.ssh import parse_ssh_source+ try:+ source = parse_ssh_source(source)+ except ValueError as exc:+ raise SiteImportError(str(exc))+ else:+ if not source.get('upload_path') and not source.get('url'):+ raise SiteImportError(+ "source must contain 'upload_path' or 'url'")+ if source.get('url'):+ cls._validate_url(source['url']) # fail fast at creation timeimp = SiteImport(source_type=source_type, status='created',created_by=user_id)imp.set_source(source)@@ -253,6 +262,8 @@ class SiteImportService:@classmethoddef analyze(cls, imp):"""Fetch + extract + analyse; sets status analyzed/failed."""+ if imp.source_type == 'ssh':+ return cls._analyze_ssh(imp)imp.status = 'analyzing'imp.error = Noneimp.current_step = 'analyze'@@ -307,6 +318,54 @@ class SiteImportService:db.session.commit()raise+ @classmethod+ def _analyze_ssh(cls, imp):+ """Stage a live site over SSH, then build the analyse report from the+ source + pull result. Credentials never persist: the DB password is+ scrubbed from the durable source once the pull has consumed it, and the+ staging manifest records no secrets (plan 31 #7/#9, Decision 5)."""+ from app.services.site_importers.ssh import GenericSshImporter++ imp.status = 'analyzing'+ imp.error = None+ imp.current_step = 'analyze'+ db.session.commit()+ try:+ source = imp.get_source()+ staging = cls.extracted_dir(imp)+ if os.path.isdir(staging):+ shutil.rmtree(staging, ignore_errors=True)+ os.makedirs(staging, exist_ok=True)++ importer = GenericSshImporter()+ cls._log(imp, "Staging site over SSH from "+ f"{source.get('user')}@{source.get('host')} ...")+ pull = importer.pull(source, staging)++ analysis = GenericSshImporter.analyze_source(source, pull)+ imp.set_analysis(analysis)++ # Scrub the DB password from the durable record now the pull is done.+ scrubbed = {k: v for k, v in source.items() if k != 'db_password'}+ imp.set_source(scrubbed)++ imp.status = 'analyzed'+ imp.current_step = None+ cls._log(imp, 'Analysis complete (SSH source): '+ f"{len(analysis.get('domains', []))} domain(s), "+ f"{len(analysis.get('databases', []))} database(s).")+ for warning in analysis.get('warnings', []):+ cls._log(imp, f'Warning: {warning}')+ db.session.commit()+ return analysis+ except Exception as exc:+ db.session.rollback()+ imp.status = 'failed'+ imp.error = str(exc)+ cls._log(imp, f'Analysis failed: {exc}')+ db.session.commit()+ raise+# ── run ──@classmethoddef run(cls, imp, from_step=None):@@ -460,6 +519,19 @@ class SiteImportService:def _step_copy_files(cls, imp, ctx):application = cls._get_app(imp, ctx)analysis = ctx['analysis']+ # SSH imports stage the docroot directly (no homedir layout to walk).+ staged = analysis.get('staged_docroot')+ if staged:+ src = os.path.join(ctx['extracted'], staged)+ if not os.path.isdir(src):+ raise SiteImportError(+ f'Staged docroot not found: {src}')+ shutil.copytree(src, application.root_path, dirs_exist_ok=True)+ copied = sum(len(files) for _b, _d, files+ in os.walk(application.root_path))+ cls._log(imp, f'Copied staged site files ({copied} file(s) now in '+ 'docroot).')+ returnif not analysis.get('homedir_present'):ctx['result']['warnings'].append('Backup has no homedir — no site files copied.')diff --git a/backend/app/services/site_importers/__init__.py b/backend/app/services/site_importers/__init__.pyindex b37609f4..fae302a7 100644--- a/backend/app/services/site_importers/__init__.py+++ b/backend/app/services/site_importers/__init__.py@@ -48,7 +48,11 @@ def detect_format(extracted_dir):from .cpanel import CpanelImporter # noqa: E402from .directadmin import DirectadminImporter # noqa: E402from .hestia import HestiaImporter # noqa: E402+from .ssh import GenericSshImporter # noqa: E402register_importer(CpanelImporter)register_importer(DirectadminImporter)register_importer(HestiaImporter)+# Live SSH pull importer (never auto-detected — detect() is a no-op; reached+# only when the operator picks the 'ssh' source type).+register_importer(GenericSshImporter)diff --git a/backend/app/services/site_importers/ssh.py b/backend/app/services/site_importers/ssh.pynew file mode 100644index 00000000..0d19e808--- /dev/null+++ b/backend/app/services/site_importers/ssh.py@@ -0,0 +1,276 @@+"""Generic SSH site importer — pull a live site off a reachable box over SSH.++Unlike the archive importers (cPanel/DirectAdmin/Hestia) which unpack a backup+tarball, this importer connects to a running server and STAGES the site: it+rsyncs the docroot and (optionally) dumps the site database into the import+run's work directory, then hands the standard pipeline a ready-to-copy+``docroot/`` directory via the analysis' ``staged_docroot`` key.++Security posture (plan 31 Decision 5):++* **Keyfile-only auth.** Authentication is by an SSH *key file on the panel+ host* (``ssh -i``) under ``BatchMode=yes`` — no interactive password, no+ ``sshpass`` dependency. ``parse_ssh_source`` deliberately has NO ``password``+ field.+* **No secrets persist.** The keyfile stays a path reference; the DB password is+ piped to the remote over stdin (never on the argv, never in the env of the+ local process) and is scrubbed from the durable import record after the pull.+ The staging manifest records only non-secret facts.+* **Linux-gated.** The live pull shells out to ``ssh``/``rsync``/``mysqldump``+ and runs on a Linux panel host only; the wizard says so on Windows dev.+"""+import json+import os+import shlex+import subprocess++from .base import BaseSiteImporter+++class SshImportError(ValueError):+ """Invalid SSH source spec or a failed remote step (maps to HTTP 400)."""+++def parse_ssh_source(source):+ """Validate + normalise an SSH import source into the durable spec.++ Required: ``host``, ``user``, ``docroot``. Auth is keyfile-only — any+ ``password`` field is dropped (plan 31 #8). DB fields are carried through+ only when present (they drive an optional remote dump). Raises+ :class:`ValueError` when a required field is missing.+ """+ source = source or {}+ host = (source.get('host') or '').strip()+ user = (source.get('user') or source.get('username') or '').strip()+ docroot = (source.get('docroot') or '').strip()++ missing = [name for name, value in+ (('host', host), ('user', user), ('docroot', docroot)) if not value]+ if missing:+ raise SshImportError('SSH source requires: ' + ', '.join(missing))++ try:+ port = int(source.get('port') or 22)+ except (TypeError, ValueError):+ raise SshImportError('SSH port must be a number')++ parsed = {+ 'host': host,+ 'port': port,+ 'user': user,+ 'docroot': docroot,+ 'domain': (source.get('domain') or '').strip() or host,+ # Keyfile path on the panel host (never the key material itself).+ 'ssh_key': (source.get('ssh_key') or source.get('keyfile') or '').strip() or None,+ }+ # Optional DB facts for a remote dump — carried through, never required.+ for key in ('db_name', 'db_user', 'db_password', 'db_host'):+ value = source.get(key)+ if value:+ parsed[key] = value+ return parsed+++class GenericSshImporter(BaseSiteImporter):+ """Pull a site off a reachable box over SSH and stage it for the pipeline."""++ format = 'ssh'++ #: Non-secret staging manifest written next to the pulled artifacts.+ MANIFEST_NAME = 'ssh-import-manifest.json'++ # Timeouts (seconds) for the remote steps.+ _CONNECT_TIMEOUT = 15+ _RSYNC_TIMEOUT = 3600+ _DUMP_TIMEOUT = 3600++ # ── the archive-importer interface (this format is never auto-detected) ──+ def detect(self, extracted_dir):+ return False++ def analyze(self, extracted_dir):+ # SSH analysis is built from the source + pull result, not from a+ # extracted archive dir — see ``analyze_source`` / SiteImportService.+ return self._empty_report('ssh')++ # ── SSH options (keyfile-only, batch mode) ──+ @classmethod+ def _ssh_opts(cls, port, ssh_key):+ opts = ['-p', str(port),+ '-o', 'BatchMode=yes',+ '-o', 'StrictHostKeyChecking=accept-new',+ '-o', f'ConnectTimeout={cls._CONNECT_TIMEOUT}']+ if ssh_key:+ opts += ['-i', ssh_key]+ return opts++ # ── the pull ──+ def pull(self, source, staging_dir):+ """Stage the remote site under ``staging_dir``: rsync the docroot into+ ``docroot/`` and, when DB facts are present, dump the database.++ Returns ``{'staging_dir', 'docroot_dir': 'docroot', 'db_dump': <name|None>}``.+ Linux-only; raises :class:`SshImportError` elsewhere.+ """+ if os.name == 'nt':+ raise SshImportError(+ 'SSH site import runs on a Linux panel host only.')++ source = parse_ssh_source(source)+ os.makedirs(staging_dir, exist_ok=True)+ docroot_dst = os.path.join(staging_dir, 'docroot')+ os.makedirs(docroot_dst, exist_ok=True)++ ssh_opts = self._ssh_opts(source['port'], source.get('ssh_key'))+ remote = f"{source['user']}@{source['host']}"++ self._rsync_docroot(remote, source['docroot'], docroot_dst, ssh_opts)++ db_dump = None+ if source.get('db_name'):+ db_dump = 'database.sql'+ self._dump_database(remote, source, ssh_opts,+ os.path.join(staging_dir, db_dump))++ self._write_manifest(staging_dir, source, db_dump)+ return {'staging_dir': staging_dir, 'docroot_dir': 'docroot',+ 'db_dump': db_dump}++ @classmethod+ def _rsync_docroot(cls, remote, docroot, dest, ssh_opts):+ ssh_cmd = 'ssh ' + ' '.join(shlex.quote(o) for o in ssh_opts)+ src = f"{remote}:{docroot.rstrip('/')}/"+ cmd = ['rsync', '-az', '--delete', '-e', ssh_cmd, src, dest + os.sep]+ try:+ subprocess.run(cmd, check=True, capture_output=True,+ timeout=cls._RSYNC_TIMEOUT)+ except subprocess.CalledProcessError as exc:+ stderr = (exc.stderr or b'').decode('utf-8', 'replace').strip()+ raise SshImportError(f'Failed to pull docroot over SSH: {stderr}')+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise SshImportError(f'Failed to pull docroot over SSH: {exc}')++ @classmethod+ def _dump_database(cls, remote, source, ssh_opts, out_path):+ """Dump the remote database to ``out_path``. The DB password is piped to+ the remote over stdin (``MYSQL_PWD=$(cat)``) so it never appears on the+ command line or in the local process environment."""+ db_user = source.get('db_user') or source['user']+ db_name = source['db_name']+ db_host = source.get('db_host') or 'localhost'+ password = source.get('db_password') or ''+ # Read the password from stdin into MYSQL_PWD, then run mysqldump.+ remote_cmd = (+ 'MYSQL_PWD="$(cat)" mysqldump '+ f'-h {shlex.quote(db_host)} -u {shlex.quote(db_user)} '+ f'{shlex.quote(db_name)}')+ cmd = ['ssh'] + ssh_opts + [remote, remote_cmd]+ try:+ with open(out_path, 'wb') as fh:+ proc = subprocess.run(+ cmd, input=(password + '\n').encode(), stdout=fh,+ stderr=subprocess.PIPE, timeout=cls._DUMP_TIMEOUT)+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise SshImportError(f'Failed to dump remote database: {exc}')+ if proc.returncode != 0:+ stderr = (proc.stderr or b'').decode('utf-8', 'replace').strip()+ raise SshImportError(f'Remote mysqldump failed: {stderr}')++ # ── analysis (built from the source + pull result) ──+ @staticmethod+ def analyze_source(source, pull_result):+ """Build the neutral analyse report from the SSH source + pull result.++ The pipeline copies the staged ``docroot/`` directly (``staged_docroot``)+ instead of walking a homedir layout.+ """+ source = parse_ssh_source(source)+ report = BaseSiteImporter._empty_report('ssh')+ report['homedir_present'] = True+ report['staged_docroot'] = (pull_result or {}).get('docroot_dir', 'docroot')+ report['domains'] = [{+ 'domain': source.get('domain') or source.get('host'),+ 'docroot': source.get('docroot'),+ 'type': 'php',+ }]+ if source.get('db_name'):+ report['databases'] = [{+ 'name': source['db_name'],+ 'engine': 'mysql',+ 'dump_path': (pull_result or {}).get('db_dump'),+ 'size': 0,+ }]+ if source.get('db_user'):+ report['db_users'] = [{+ 'user': source['db_user'],+ 'hash': '',+ 'hash_format': None,+ 'grants': [],+ }]+ return report++ # ── manifest (no secrets) ──+ @staticmethod+ def _write_manifest(staging_dir, source, db_dump):+ """Write a staging manifest recording ONLY non-secret facts — never the+ DB password or the key material/path (plan 31 #9)."""+ source = source or {}+ manifest = {+ 'source_type': 'ssh',+ 'host': source.get('host'),+ 'port': source.get('port', 22),+ 'user': source.get('user'),+ 'docroot': source.get('docroot'),+ 'domain': source.get('domain') or source.get('host'),+ 'db_name': source.get('db_name'),+ 'db_user': source.get('db_user'),+ 'db_dump': db_dump,+ 'auth': 'keyfile' if source.get('ssh_key') else 'agent',+ # Presence flags only — the secrets themselves never land here.+ 'db_password_present': bool(source.get('db_password')),+ }+ os.makedirs(staging_dir, exist_ok=True)+ path = os.path.join(staging_dir, GenericSshImporter.MANIFEST_NAME)+ with open(path, 'w', encoding='utf-8') as fh:+ json.dump(manifest, fh, indent=2)+ return path++ # ── optional preflight probe (wizard "test connection") ──+ @classmethod+ def probe(cls, source):+ """Preflight: verify the box is reachable and inspect the docroot.++ Returns ``{'reachable': bool, 'files': [...], 'has_wp_config': bool,+ 'error': str|None}``. Linux-only; never raises — the wizard renders the+ result. Keyfile-only, BatchMode (so an un-set-up key fails fast rather+ than hanging on a password prompt)."""+ if os.name == 'nt':+ return {'reachable': False,+ 'error': 'SSH import preflight runs on a Linux panel host only.'}+ try:+ source = parse_ssh_source(source)+ except ValueError as exc:+ return {'reachable': False, 'error': str(exc)}++ ssh_opts = cls._ssh_opts(source['port'], source.get('ssh_key'))+ remote = f"{source['user']}@{source['host']}"+ docroot = source['docroot']+ remote_cmd = (+ f'ls -1a {shlex.quote(docroot)} 2>/dev/null | head -50; '+ f'test -f {shlex.quote(docroot.rstrip("/") + "/wp-config.php")} '+ '&& echo __HAS_WP_CONFIG__')+ cmd = ['ssh'] + ssh_opts + [remote, remote_cmd]+ try:+ proc = subprocess.run(cmd, capture_output=True,+ timeout=cls._CONNECT_TIMEOUT + 10)+ except (OSError, subprocess.TimeoutExpired) as exc:+ return {'reachable': False, 'error': str(exc)}+ if proc.returncode != 0:+ stderr = (proc.stderr or b'').decode('utf-8', 'replace').strip()+ return {'reachable': False, 'error': stderr or 'SSH connection failed'}+ lines = (proc.stdout or b'').decode('utf-8', 'replace').splitlines()+ has_wp = '__HAS_WP_CONFIG__' in lines+ files = [ln for ln in lines+ if ln and ln != '__HAS_WP_CONFIG__' and ln not in ('.', '..')]+ return {'reachable': True, 'files': files, 'has_wp_config': has_wp,+ 'error': None}diff --git a/backend/tests/test_dns_cutover.py b/backend/tests/test_dns_cutover.pynew file mode 100644index 00000000..6167b966--- /dev/null+++ b/backend/tests/test_dns_cutover.py@@ -0,0 +1,237 @@+"""Proving tests for the reversible DNS cutover SERVICE (plan 31 #1/#2/#3/#4).++Covers: TTL guidance, server-sourced snapshots with name filtering, dry-run vs+real cutover, created-record tracking, world-restoring revert (delete created ++re-apply captured), verify annotation, and the provider-registry 501.++The provider client is stubbed (a fake Cloudflare-shaped client) so nothing+touches the network; the ownership ledger writes go through the real+``DnsOwnershipService`` against the in-memory test DB.+"""+import pytest++from app import db+from app.models.dns_cutover_snapshot import DnsCutoverSnapshot+from app.services.dns_cutover_service import DnsCutoverService, DnsCutoverError+++class FakeConfig:+ id = 1+ provider = 'cloudflare'+ name = 'test-cf'+++class FakeClient:+ """A minimal Cloudflare-shaped client backed by an in-memory record list."""++ def __init__(self, records=None):+ self.records = [dict(r) for r in (records or [])]+ self.upserts = []+ self.deletes = []+ self._seq = 100++ def list_records(self, zone_id):+ return {'success': True, 'records': [dict(r) for r in self.records]}++ def find_record_id(self, zone_id, record_type, name, caa=None):+ for r in self.records:+ if r['type'] == record_type and r['name'] == name:+ return r['id']+ return None++ def upsert(self, zone_id, spec, record_id=None):+ self._seq += 1+ rid = record_id or f'rec{self._seq}'+ self.upserts.append({'type': spec.record_type, 'name': spec.name,+ 'content': spec.content, 'record_id': record_id})+ self.records = [r for r in self.records+ if not (r['type'] == spec.record_type and r['name'] == spec.name)]+ self.records.append({'id': rid, 'type': spec.record_type, 'name': spec.name,+ 'content': spec.content, 'ttl': spec.ttl,+ 'proxied': spec.proxied, 'priority': spec.priority})+ return {'success': True, 'record_id': rid}++ def delete(self, zone_id, record_id=None, record_type=None, name=None):+ self.deletes.append({'record_id': record_id, 'type': record_type, 'name': name})+ self.records = [r for r in self.records if r['id'] != record_id]+ return {'success': True}+++def _install_client(monkeypatch, client, config=None):+ config = config or FakeConfig()+ monkeypatch.setattr(+ DnsCutoverService, '_resolve_dns_client',+ lambda provider=None, provider_zone_id=None: (client, config))+ return config+++DOMAIN = 'site.example.com'+ZONE = 'zone123'+++# --------------------------------------------------------------------------- #+# TTL guidance+# --------------------------------------------------------------------------- #++def test_ttl_guidance_flags_records_needing_lowering(app):+ guidance = DnsCutoverService.ttl_guidance([+ {'name': DOMAIN, 'type': 'A', 'ttl': 3600},+ {'name': DOMAIN, 'type': 'MX', 'ttl': 120},+ ])+ assert guidance['recommended_ttl'] == 300+ assert guidance['current_max_ttl'] == 3600+ assert guidance['propagation_wait_seconds'] == 3600+ flags = {r['type']: r['needs_lowering'] for r in guidance['records']}+ assert flags['A'] is True and flags['MX'] is False+++# --------------------------------------------------------------------------- #+# server-sourced snapshots (Decision 2)+# --------------------------------------------------------------------------- #++def test_snapshot_reads_live_records_and_filters_by_name(app, monkeypatch):+ client = FakeClient([+ {'id': 'a1', 'type': 'A', 'name': DOMAIN, 'content': '203.0.113.1',+ 'ttl': 3600, 'proxied': False, 'priority': None},+ {'id': 'w1', 'type': 'A', 'name': f'www.{DOMAIN}', 'content': '203.0.113.1',+ 'ttl': 3600, 'proxied': False, 'priority': None},+ ])+ _install_client(monkeypatch, client)++ snap = DnsCutoverService.create_snapshot(DOMAIN, ZONE, provider='cloudflare',+ names=[DOMAIN])+ assert snap.status == 'captured'+ assert snap.provider == 'cloudflare'+ records = snap.get_records()+ assert len(records) == 1 and records[0]['name'] == DOMAIN # www filtered out+++def test_snapshot_requires_zone(app, monkeypatch):+ _install_client(monkeypatch, FakeClient())+ with pytest.raises(DnsCutoverError):+ DnsCutoverService.create_snapshot(DOMAIN, None)+++# --------------------------------------------------------------------------- #+# cutover (Decision 1) — dry-run vs real, created-record tracking+# --------------------------------------------------------------------------- #++def test_cutover_dry_run_returns_ops_without_writing(app, monkeypatch):+ client = FakeClient()+ _install_client(monkeypatch, client)+ snap = DnsCutoverSnapshot(domain=DOMAIN, provider='cloudflare',+ provider_zone_id=ZONE, status='captured')+ snap.set_records([])+ db.session.add(snap)+ db.session.commit()++ result = DnsCutoverService.cutover(snap, target='198.51.100.9', dry_run=True)+ assert result['dry_run'] is True+ assert result['ops'][0] == {'action': 'create', 'type': 'A', 'name': DOMAIN,+ 'old': None, 'new': '198.51.100.9'}+ assert client.upserts == [] # nothing written+ assert snap.status == 'captured' # snapshot untouched+++def test_cutover_creates_and_tracks_created_records(app, monkeypatch):+ client = FakeClient() # zone has no A record yet+ _install_client(monkeypatch, client)+ snap = DnsCutoverSnapshot(domain=DOMAIN, provider='cloudflare',+ provider_zone_id=ZONE, status='captured')+ snap.set_records([])+ db.session.add(snap)+ db.session.commit()++ result = DnsCutoverService.cutover(snap, target='198.51.100.9')+ assert result['success'] is True+ assert snap.status == 'cutover'+ created = snap.get_created_records()+ assert len(created) == 1 and created[0]['type'] == 'A'+ assert created[0]['content'] == '198.51.100.9'+ assert len(client.upserts) == 1+++# --------------------------------------------------------------------------- #+# revert (Decision 3) — world-restoring+# --------------------------------------------------------------------------- #++def test_revert_of_create_only_cutover_deletes_and_reverts_to_empty(app, monkeypatch):+ client = FakeClient()+ _install_client(monkeypatch, client)+ snap = DnsCutoverSnapshot(domain=DOMAIN, provider='cloudflare',+ provider_zone_id=ZONE, status='captured')+ snap.set_records([])+ db.session.add(snap)+ db.session.commit()++ DnsCutoverService.cutover(snap, target='198.51.100.9')+ assert client.records # the created A exists on the provider++ result = DnsCutoverService.revert(snap)+ assert result['deleted_count'] == 1+ assert snap.status == 'reverted_with_deletions'+ assert result['deletions'][0]['deleted'] is True+ assert client.records == [] # world restored to empty+++def test_revert_reapplies_captured_values_byte_for_byte(app, monkeypatch):+ # Zone already has the operator's A record → cutover UPDATES it (no create).+ original = {'id': 'a1', 'type': 'A', 'name': DOMAIN, 'content': '203.0.113.1',+ 'ttl': 3600, 'proxied': False, 'priority': None}+ client = FakeClient([dict(original)])+ _install_client(monkeypatch, client)+ snap = DnsCutoverSnapshot(domain=DOMAIN, provider='cloudflare',+ provider_zone_id=ZONE, status='captured')+ snap.set_records([dict(original)])+ db.session.add(snap)+ db.session.commit()++ DnsCutoverService.cutover(snap, target='198.51.100.9')+ assert client.records[0]['content'] == '198.51.100.9' # flipped+ assert snap.get_created_records() == [] # nothing created++ result = DnsCutoverService.revert(snap)+ assert result['deleted_count'] == 0+ assert snap.status == 'reverted'+ assert client.records[0]['content'] == '203.0.113.1' # old value restored+++# --------------------------------------------------------------------------- #+# verify (plan 31 #1)+# --------------------------------------------------------------------------- #++def test_verify_annotates_matches_expected(app, monkeypatch):+ from app.services.dns_zone_service import DNSZoneService+ monkeypatch.setattr(DNSZoneService, 'check_propagation', staticmethod(+ lambda domain, record_type='A': [+ {'nameserver': 'Google', 'result': ['198.51.100.9'], 'propagated': True},+ {'nameserver': 'Cloudflare', 'result': ['198.51.100.9'], 'propagated': True},+ ]))+ res = DnsCutoverService.verify(DOMAIN, record_type='A', expected='198.51.100.9')+ assert res['propagated'] is True+ assert res['matches_expected'] is True+ assert res['answered_count'] == 2++ res2 = DnsCutoverService.verify(DOMAIN, record_type='A', expected='203.0.113.1')+ assert res2['matches_expected'] is False+++# --------------------------------------------------------------------------- #+# provider registry resolution (Decision 4)+# --------------------------------------------------------------------------- #++def test_resolve_client_no_provider_is_clean_501(app):+ with pytest.raises(DnsCutoverError) as ei:+ DnsCutoverService._resolve_dns_client('cloudflare', ZONE)+ assert ei.value.status_code == 501 and ei.value.code == 'NO_PROVIDER'+++def test_resolve_client_unsupported_provider_is_clean_501(app):+ from app.models.email import DNSProviderConfig+ db.session.add(DNSProviderConfig(name='r53', provider='route53',+ api_key='x', is_default=True))+ db.session.commit()+ with pytest.raises(DnsCutoverError) as ei:+ DnsCutoverService._resolve_dns_client('route53', ZONE)+ assert ei.value.status_code == 501 and ei.value.code == 'NO_PROVIDER'+ assert 'route53' in ei.value.messagediff --git a/backend/tests/test_dns_cutover_api.py b/backend/tests/test_dns_cutover_api.pynew file mode 100644index 00000000..18371270--- /dev/null+++ b/backend/tests/test_dns_cutover_api.py@@ -0,0 +1,188 @@+"""Proving tests for the DNS cutover API (``/api/v1/dns-cutover``, plan 31 #1).++Covers: auth + admin gating, TTL guidance, the dry-run cutover (no provider+needed), the snapshot-required contract, verify, and revert — with the provider+client stubbed so nothing touches the network.+"""+import pytest++from app import db+from app.models.dns_cutover_snapshot import DnsCutoverSnapshot+from app.services.dns_cutover_service import DnsCutoverService+++DOMAIN = 'site.example.com'+ZONE = 'zone123'+++class _FakeConfig:+ id = 1+ provider = 'cloudflare'+ name = 'test-cf'+++class _FakeClient:+ """Minimal Cloudflare-shaped client backed by an in-memory record list."""++ def __init__(self, records=None):+ self.records = [dict(r) for r in (records or [])]+ self._seq = 100++ def list_records(self, zone_id):+ return {'success': True, 'records': [dict(r) for r in self.records]}++ def find_record_id(self, zone_id, record_type, name, caa=None):+ for r in self.records:+ if r['type'] == record_type and r['name'] == name:+ return r['id']+ return None++ def upsert(self, zone_id, spec, record_id=None):+ self._seq += 1+ rid = record_id or f'rec{self._seq}'+ self.records = [r for r in self.records+ if not (r['type'] == spec.record_type and r['name'] == spec.name)]+ self.records.append({'id': rid, 'type': spec.record_type, 'name': spec.name,+ 'content': spec.content, 'ttl': spec.ttl,+ 'proxied': spec.proxied, 'priority': spec.priority})+ return {'success': True, 'record_id': rid}++ def delete(self, zone_id, record_id=None, record_type=None, name=None):+ self.records = [r for r in self.records if r['id'] != record_id]+ return {'success': True}+++def _install_client(monkeypatch, client, config=None):+ config = config or _FakeConfig()+ monkeypatch.setattr(+ DnsCutoverService, '_resolve_dns_client',+ lambda provider=None, provider_zone_id=None: (client, config))+++def member_headers(app):+ from app.models import User+ from flask_jwt_extended import create_access_token+ from werkzeug.security import generate_password_hash+ user = User(email='[email protected]', username='member_cutover',+ password_hash=generate_password_hash('x'),+ role=User.ROLE_VIEWER, is_active=True)+ db.session.add(user)+ db.session.commit()+ return {'Authorization': f'Bearer {create_access_token(identity=user.id)}'}+++def _snapshot(records=None):+ snap = DnsCutoverSnapshot(domain=DOMAIN, provider='cloudflare',+ provider_zone_id=ZONE, status='captured')+ snap.set_records(records or [])+ db.session.add(snap)+ db.session.commit()+ return snap+++# --------------------------------------------------------------------------- #+# auth+# --------------------------------------------------------------------------- #++def test_endpoints_require_auth(client):+ assert client.post('/api/v1/dns-cutover/ttl-guidance', json={}).status_code == 401+ assert client.get('/api/v1/dns-cutover/snapshots').status_code == 401+++def test_snapshot_requires_admin(client, member_headers):+ r = client.post('/api/v1/dns-cutover/snapshot', headers=member_headers,+ json={'domain': DOMAIN, 'provider_zone_id': ZONE})+ assert r.status_code == 403+++# --------------------------------------------------------------------------- #+# ttl guidance (read verb, any authed user)+# --------------------------------------------------------------------------- #++def test_ttl_guidance_endpoint(client, auth_headers):+ r = client.post('/api/v1/dns-cutover/ttl-guidance', headers=auth_headers,+ json={'records': [{'name': DOMAIN, 'type': 'A', 'ttl': 3600}]})+ assert r.status_code == 200+ assert r.get_json()['recommended_ttl'] == 300+++# --------------------------------------------------------------------------- #+# cutover: snapshot required + dry-run+# --------------------------------------------------------------------------- #++def test_cutover_requires_snapshot_id(client, auth_headers):+ r = client.post('/api/v1/dns-cutover/cutover', headers=auth_headers,+ json={'target': '198.51.100.9'})+ assert r.status_code == 400+ assert 'snapshot_id' in r.get_json()['error']+++def test_cutover_dry_run_needs_no_provider(client, auth_headers):+ snap = _snapshot([])+ r = client.post('/api/v1/dns-cutover/cutover', headers=auth_headers,+ json={'snapshot_id': snap.id, 'target': '198.51.100.9',+ 'dry_run': True})+ assert r.status_code == 200+ body = r.get_json()+ assert body['dry_run'] is True+ assert body['ops'][0]['new'] == '198.51.100.9'+++def test_cutover_missing_snapshot_404(client, auth_headers):+ r = client.post('/api/v1/dns-cutover/cutover', headers=auth_headers,+ json={'snapshot_id': 999999, 'target': '198.51.100.9'})+ assert r.status_code == 404+++# --------------------------------------------------------------------------- #+# snapshot / verify / revert (provider stubbed)+# --------------------------------------------------------------------------- #++def test_snapshot_endpoint_creates_row(client, auth_headers, monkeypatch):+ _install_client(monkeypatch, _FakeClient([+ {'id': 'a1', 'type': 'A', 'name': DOMAIN, 'content': '203.0.113.1',+ 'ttl': 3600, 'proxied': False, 'priority': None}]))+ r = client.post('/api/v1/dns-cutover/snapshot', headers=auth_headers,+ json={'domain': DOMAIN, 'provider_zone_id': ZONE,+ 'provider': 'cloudflare'})+ assert r.status_code == 201+ body = r.get_json()+ assert body['status'] == 'captured' and body['record_count'] == 1+++def test_verify_endpoint(client, auth_headers, monkeypatch):+ from app.services.dns_zone_service import DNSZoneService+ monkeypatch.setattr(DNSZoneService, 'check_propagation', staticmethod(+ lambda domain, record_type='A': [+ {'nameserver': 'Google', 'result': ['198.51.100.9'], 'propagated': True}]))+ r = client.post('/api/v1/dns-cutover/verify', headers=auth_headers,+ json={'domain': DOMAIN, 'expected': '198.51.100.9'})+ assert r.status_code == 200+ assert r.get_json()['matches_expected'] is True+++def test_revert_endpoint_round_trip(client, auth_headers, monkeypatch):+ _install_client(monkeypatch, _FakeClient())+ snap = _snapshot([])+ DnsCutoverService.cutover(snap, target='198.51.100.9') # create-only++ r = client.post(f'/api/v1/dns-cutover/snapshots/{snap.id}/revert',+ headers=auth_headers)+ assert r.status_code == 200+ body = r.get_json()+ assert body['deleted_count'] == 1+ assert body['status'] == 'reverted_with_deletions'+++def test_list_and_get_snapshots(client, auth_headers):+ snap = _snapshot([])+ r = client.get('/api/v1/dns-cutover/snapshots', headers=auth_headers)+ assert r.status_code == 200+ assert any(s['id'] == snap.id for s in r.get_json()['snapshots'])++ r2 = client.get(f'/api/v1/dns-cutover/snapshots/{snap.id}', headers=auth_headers)+ assert r2.status_code == 200 and r2.get_json()['id'] == snap.id++ assert client.get('/api/v1/dns-cutover/snapshots/999999',+ headers=auth_headers).status_code == 404