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.

Keep corrupt configs and serialize config writes

Juan Denise2ba3a347686
diff --git a/backend/app/utils/config_store.py b/backend/app/utils/config_store.py
index de5fa43d..cd75f6de 100644
--- a/backend/app/utils/config_store.py
+++ b/backend/app/utils/config_store.py
@@ -22,26 +22,54 @@ the pattern followed here.
"""
import copy
import json
+import logging
import os
+import tempfile
+import threading
+import time
+
+logger = logging.getLogger(__name__)
+
+# One writer per file at a time within the (single) panel process.
+_write_locks = {}
+_write_locks_guard = threading.Lock()
+
+
+def _lock_for(path):
+ key = os.path.abspath(path)
+ with _write_locks_guard:
+ return _write_locks.setdefault(key, threading.Lock())
def load_json_config(path, default):
"""JSON file → dict; *default* on missing or corrupt.
A corrupt config reads as the default, never raises — the same contract
- the hand-rolled copies had, and the one callers rely on at boot. The
- fallback is a deep copy: callers mutate what they get back, and a shared
- default object would leak those mutations into every later call.
+ the hand-rolled copies had, and the one callers rely on at boot. It is
+ moved aside first: callers save what they loaded, so the next save would
+ otherwise overwrite the only copy of the operator's settings with the
+ defaults. The fallback is a deep copy: callers mutate what they get back,
+ and a shared default object would leak those mutations into every later
+ call.
"""
if os.path.exists(path):
try:
with open(path, 'r') as f:
return json.load(f)
except Exception: # noqa: BLE001
- pass
+ _quarantine(path)
return copy.deepcopy(default)
+def _quarantine(path):
+ aside = f'{path}.corrupt-{time.strftime("%Y%m%d%H%M%S")}'
+ try:
+ os.replace(path, aside)
+ logger.error('Unreadable config %s moved to %s; using defaults', path, aside)
+ except OSError:
+ logger.exception('Unreadable config %s could not be moved aside', path)
+
+
def save_json_config(path, config):
"""dict → JSON file (indented), creating the parent dir. Returns the
service-dict shape every caller already returns.
@@ -50,19 +78,34 @@ def save_json_config(path, config):
reader never sees a half-written config and a failed write leaves the
previous one intact. ``os.replace`` is atomic on POSIX and on Windows.
"""
+ with _lock_for(path):
+ return _save(path, config)
+
+
+def _save(path, config):
directory = os.path.dirname(path) or '.'
- tmp = f'{path}.tmp'
+ tmp = None
try:
os.makedirs(directory, exist_ok=True)
- with open(tmp, 'w') as f:
+ # A unique temp per write: with one fixed name, two concurrent saves
+ # wrote into the same file and could rename a half-written config
+ # into place.
+ fd, tmp = tempfile.mkstemp(dir=directory, prefix=os.path.basename(path) + '.',
+ suffix='.tmp')
+ with os.fdopen(fd, 'w') as f:
json.dump(config, f, indent=2)
+ if os.name != 'nt':
+ # mkstemp creates 0600; keep the mode the file had (or the
+ # 0644 a plain open() gave it) so other readers are unaffected.
+ os.chmod(tmp, os.stat(path).st_mode & 0o777 if os.path.exists(path) else 0o644)
os.replace(tmp, path)
return {'success': True, 'message': 'Configuration saved'}
except Exception as e: # noqa: BLE001
# The old file is still whole; drop the partial temp so a later write
# is not confused by it. Cleanup failure must not mask the real error.
- try:
- os.remove(tmp)
- except OSError:
- pass
+ if tmp:
+ try:
+ os.remove(tmp)
+ except OSError:
+ pass
return {'success': False, 'error': str(e)}
diff --git a/backend/tests/test_config_store.py b/backend/tests/test_config_store.py
index 7049159d..364e78bd 100644
--- a/backend/tests/test_config_store.py
+++ b/backend/tests/test_config_store.py
@@ -146,3 +146,42 @@ def test_uptime_history_reports_a_failed_save(tmp_path, monkeypatch):
monkeypatch.setattr(json, 'dump', lambda *a, **k: (_ for _ in ()).throw(OSError('disk full')))
assert UptimeService._save_history({'checks': [1]}) is False
+
+
+def test_corrupt_file_is_kept_aside_so_the_next_save_cannot_destroy_it(tmp_path):
+ """Callers save what they loaded: with the corrupt file left in place,
+ the next save replaced the operator's only copy with the defaults."""
+ path = tmp_path / 'cfg.json'
+ path.write_text('{"smtp_host": "mail.example.com", "trunc')
+ loaded = load_json_config(str(path), {'smtp_host': ''})
+ save_json_config(str(path), loaded)
+
+ aside = list(tmp_path.glob('cfg.json.corrupt-*'))
+ assert len(aside) == 1
+ assert 'mail.example.com' in aside[0].read_text()
+
+
+def test_concurrent_saves_never_leave_a_torn_file(tmp_path):
+ """One fixed temp name let two writers share it and rename a
+ half-written config into place."""
+ import threading
+ path = str(tmp_path / 'cfg.json')
+ big = {'rows': [{'n': i, 'pad': 'x' * 200} for i in range(300)]}
+ errors = []
+
+ def writer(tag):
+ for _ in range(20):
+ result = save_json_config(path, {**big, 'tag': tag})
+ if not result['success']:
+ errors.append(result['error'])
+
+ threads = [threading.Thread(target=writer, args=(t,)) for t in range(6)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert errors == []
+ with open(path) as f:
+ assert json.load(f)['rows'] == big['rows']
+ assert list(tmp_path.glob('*.tmp')) == []