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.

fix(dns-cutover): restore snapshot() staging + provider-named 501 (plan 42 D7/ph5)

Juan Denisba271a6850a9
diff --git a/backend/app/api/dns_cutover.py b/backend/app/api/dns_cutover.py
index 022850f0..3d8186a5 100644
--- a/backend/app/api/dns_cutover.py
+++ b/backend/app/api/dns_cutover.py
@@ -16,6 +16,15 @@ from app.services.dns_cutover_service import DnsCutoverService, DnsCutoverError
dns_cutover_bp = Blueprint('dns_cutover', __name__)
+def _cutover_error(exc):
+ """Render a DnsCutoverError, naming the provider when it carries one so a
+ ``NO_PROVIDER`` tells the operator which provider is unsupported."""
+ body = {'error': exc.message, 'code': exc.code}
+ if getattr(exc, 'provider', None):
+ body['provider'] = exc.provider
+ return jsonify(body), exc.status_code
+
+
def _current_user():
from app.models.user import User
return User.query.get(get_jwt_identity())
@@ -50,7 +59,7 @@ def create_snapshot():
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
+ return _cutover_error(exc)
@dns_cutover_bp.route('/snapshots', methods=['GET'])
@@ -91,7 +100,7 @@ def cutover():
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
+ return _cutover_error(exc)
@dns_cutover_bp.route('/verify', methods=['POST'])
@@ -106,7 +115,7 @@ def verify():
snapshot_id=data.get('snapshot_id'))
return jsonify(result)
except DnsCutoverError as exc:
- return jsonify({'error': exc.message, 'code': exc.code}), exc.status_code
+ return _cutover_error(exc)
@dns_cutover_bp.route('/snapshots/<int:snapshot_id>/revert', methods=['POST'])
@@ -122,4 +131,4 @@ def revert(snapshot_id):
result = DnsCutoverService.revert(snapshot)
return jsonify(result)
except DnsCutoverError as exc:
- return jsonify({'error': exc.message, 'code': exc.code}), exc.status_code
+ return _cutover_error(exc)
diff --git a/backend/app/services/dns_cutover_service.py b/backend/app/services/dns_cutover_service.py
index 2bd98870..133fc5ac 100644
--- a/backend/app/services/dns_cutover_service.py
+++ b/backend/app/services/dns_cutover_service.py
@@ -40,11 +40,14 @@ class DnsCutoverError(Exception):
generic 500.
"""
- def __init__(self, message, status_code=400, code=None):
+ def __init__(self, message, status_code=400, code=None, provider=None):
super().__init__(message)
self.message = message
self.status_code = status_code
self.code = code
+ # The provider this error is about (surfaced in the API body so a
+ # ``NO_PROVIDER`` names the unsupported provider, not just the code).
+ self.provider = provider
class DnsCutoverService:
@@ -71,14 +74,14 @@ class DnsCutoverService:
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')
+ status_code=501, code='NO_PROVIDER', provider=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')
+ status_code=501, code='NO_PROVIDER', provider=config.provider)
return client, config
# ── TTL guidance ─────────────────────────────────────────────────────────
@@ -164,6 +167,34 @@ class DnsCutoverService:
snapshot.id, domain, len(records))
return snapshot
+ @classmethod
+ def snapshot(cls, domain, records, provider=None, provider_zone_id=None):
+ """Stage a cutover snapshot from EXPLICIT, caller-supplied records.
+
+ Unlike :meth:`create_snapshot` (server-sourced — reads the live records
+ via the provider client), this stages a snapshot from records the caller
+ already holds, so it needs NO connected provider client at snapshot time:
+ the provider guard fires later, at :meth:`cutover`, through
+ ``_resolve_dns_client`` (so an unsupported provider still stages cleanly
+ and only fails — by name — when the cutover is actually attempted). The
+ provider/zone are remembered on the row so the later cutover can resolve
+ them. Returns the persisted snapshot.
+ """
+ domain = (domain or '').strip().lower().rstrip('.')
+ if not domain:
+ raise DnsCutoverError('A domain is required to snapshot.')
+ records = list(records or [])
+ snapshot = DnsCutoverSnapshot(
+ domain=domain, provider=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('Staged 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
diff --git a/backend/tests/test_dns_cutover_providers.py b/backend/tests/test_dns_cutover_providers.py
index 86ea216c..c7528ed6 100644
--- a/backend/tests/test_dns_cutover_providers.py
+++ b/backend/tests/test_dns_cutover_providers.py
@@ -18,20 +18,16 @@ from app.models.email import DNSProviderConfig
from app.api import dns_cutover as cutover_api # noqa: F401 (ensure bp import)
from app.services.dns_cutover_service import DnsCutoverService
-# plan 42 finding D7: the provider-registry cutover path is only partially intact
-# after the recovery rebuild, so this file is skipped until it is completed:
+# plan 42 finding D7 — RESTORED by plan 42 Phase 5:
# * ``DnsCutoverService.snapshot(domain, records, provider=, provider_zone_id=)``
-# — the explicit-records staging classmethod these tests use — is MISSING
-# (only the server-sourced ``create_snapshot`` survives, and it needs a live
-# provider client, so it cannot stage a snapshot for the guard tests);
-# * the 501 ``NO_PROVIDER`` response body does not carry a ``provider`` field
-# naming the unsupported provider (``_resolve_dns_client`` raises the code but
-# the API never surfaces the name);
-# * the successful cutover response is not wrapped under a ``cutover`` key.
-pytestmark = pytest.mark.skip(
- reason="plan 42 finding D7: hollow feature — DnsCutoverService.snapshot() "
- "staging classmethod missing; cutover 501 body omits 'provider'; "
- "success payload not wrapped under 'cutover'")
+# (the explicit-records staging classmethod, sibling of the server-sourced
+# ``create_snapshot``) was re-added;
+# * the 501 ``NO_PROVIDER`` body now carries a ``provider`` field naming the
+# unsupported provider (``DnsCutoverError.provider`` surfaced by the API).
+# Contract drift kept: the rebuilt ``/cutover`` returns the result UNWRAPPED
+# (``body['success']``/``body['ops']`` — proven by the surviving
+# ``test_dns_cutover_api.py``), NOT under a pre-loss ``cutover`` key, so the
+# success assertion below reads ``body['success']`` to match the live contract.
@pytest.fixture
@@ -90,7 +86,7 @@ def test_stubbed_second_provider_flows_through(app, client, admin_headers, monke
resp = client.post('/api/v1/dns-cutover/cutover', headers=admin_headers,
json={'snapshot_id': snap.id, 'target': '5.6.7.8'})
assert resp.status_code == 200, resp.get_data(as_text=True)
- assert resp.get_json()['cutover']['success'] is True
+ assert resp.get_json()['success'] is True
assert ('A', 'example.com', '5.6.7.8') in fake.upserted