From 54d9d5db251a236e0e05b0fba40d5e61d95359e1 Mon Sep 17 00:00:00 2001 From: Reditus <33814724+ReditusDraco@users.noreply.github.com> Date: Mon, 21 Sep 2026 14:51:37 +0100 Subject: [PATCH] v7.3: graceful shutdown/restart with countdown, custom/scheduled notifications, update guard, file jail, security hardening, experimental tab removed --- README.md | 1 - app/config.py | 2 + app/factory.py | 35 + app/routes/api.py | 1050 ++++++---------- app/routes/main.py | 6 - app/services/admin.py | 9 +- app/services/backup.py | 78 +- app/services/director.py | 26 +- app/services/k8s.py | 29 +- app/services/lifecycle.py | 497 ++++++++ app/services/schedule_util.py | 136 +++ app/services/scheduled_broadcast.py | 251 ++++ app/utils/constants.py | 4 - settings.yaml.example | 3 + templates/account_detail.html | 4 +- templates/accounts.html | 4 +- templates/admin_experimental.html | 1535 ------------------------ templates/backup.html | 8 +- templates/events.html | 2 +- templates/files.html | 34 +- templates/guilds.html | 2 +- templates/map.html | 2 +- templates/player_detail.html | 14 +- templates/players.html | 10 +- templates/server.html | 871 +++++++++++++- templates/shell.html | 6 +- templates/vehicles.html | 4 +- tests/test_battlegroup_update_guard.py | 50 + tests/test_lifecycle.py | 240 ++++ tests/test_scheduled_broadcast.py | 138 +++ tests/test_security_validations.py | 76 ++ 31 files changed, 2764 insertions(+), 2363 deletions(-) create mode 100644 app/services/lifecycle.py create mode 100644 app/services/schedule_util.py create mode 100644 app/services/scheduled_broadcast.py delete mode 100644 templates/admin_experimental.html create mode 100644 tests/test_battlegroup_update_guard.py create mode 100644 tests/test_lifecycle.py create mode 100644 tests/test_scheduled_broadcast.py create mode 100644 tests/test_security_validations.py diff --git a/README.md b/README.md index d897f80..d95cdbe 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,6 @@ Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SS ## Branching Strategy - **main** — stable-ish beta -- **nightly** — latest features - **experimental** — where chaos becomes innovation > “This seemed like a great idea at 3am.” — every experimental commit ever diff --git a/app/config.py b/app/config.py index d9561dd..a7d6de0 100644 --- a/app/config.py +++ b/app/config.py @@ -51,6 +51,8 @@ DEFAULTS = { }, 'filebrowser': { 'port': 18888, + # Empty = built-in defaults (/srv, /home/dune/.dune). + 'allowed_roots': [], }, 'firewall': { 'block_filebrowser': True, diff --git a/app/factory.py b/app/factory.py index e84fe24..9fd96e7 100644 --- a/app/factory.py +++ b/app/factory.py @@ -27,6 +27,8 @@ from app.services.updater import UpdateService from app.services.director import DirectorService from app.services.rmq import RmqService from app.services.backup import BackupService +from app.services.lifecycle import LifecycleService +from app.services.scheduled_broadcast import ScheduledBroadcastService from app.utils.cache import MultiCache from app.routes.main import register_routes from app.routes.api import register_api_routes @@ -277,6 +279,12 @@ def create_app(settings_path=None): backup_svc = BackupService(ssh_service, k8s_service, rmq_svc, settings) logging.debug("BackupService initialized") + lifecycle_svc = LifecycleService(ssh_service, admin_svc, settings) + logging.debug("LifecycleService initialized") + + sched_broadcast_svc = ScheduledBroadcastService(admin_svc) + logging.debug("ScheduledBroadcastService initialized") + services = { 'db': db_service, 'dash_db': dash_db_service, @@ -291,6 +299,8 @@ def create_app(settings_path=None): 'director': director_svc, 'rmq': rmq_svc, 'backup': backup_svc, + 'lifecycle': lifecycle_svc, + 'broadcasts': sched_broadcast_svc, } logging.debug(f"All services registered: {list(services.keys())}") @@ -538,6 +548,31 @@ def create_app(settings_path=None): except Exception as e: logging.debug(f'Could not start backup scheduler: {e}') + # ── Lifecycle Scheduler (scheduled restarts + notifications) ──────── + try: + lifecycle_svc = services.get('lifecycle') + broadcasts_svc = services.get('broadcasts') + if lifecycle_svc or broadcasts_svc: + def _lifecycle_scheduler(): + while True: + time.sleep(30) + try: + if lifecycle_svc: + lifecycle_svc.check_and_fire() + except Exception as e: + logging.error(f'Lifecycle scheduler: {e}') + try: + if broadcasts_svc: + broadcasts_svc.check_and_fire() + except Exception as e: + logging.error(f'Broadcast scheduler: {e}') + + lifecycle_thread = threading.Thread(target=_lifecycle_scheduler, daemon=True) + lifecycle_thread.start() + logging.info('Lifecycle scheduler: Background thread started') + except Exception as e: + logging.debug(f'Could not start lifecycle scheduler: {e}') + app.dune_settings = settings app.dune_services = services diff --git a/app/routes/api.py b/app/routes/api.py index 8680abd..f2d6750 100644 --- a/app/routes/api.py +++ b/app/routes/api.py @@ -31,6 +31,18 @@ def quote_remote(value): return shlex.quote(str(value)) +def fb_within_roots(canonical, roots): + """True when a canonical absolute path is inside one of the roots.""" + canonical = '/' + str(canonical or '').strip().lstrip('/') + canonical = canonical.rstrip('/') or '/' + for root in roots or []: + root = str(root).strip().rstrip('/') or '/' + root = '/' + root.lstrip('/') + if canonical == root or canonical.startswith(root + '/'): + return True + return False + + def register_api_routes(app, services, settings): db = services['db'] ssh = services['ssh'] @@ -39,6 +51,8 @@ def register_api_routes(app, services, settings): admin_svc = services['admin'] vehicle_svc = services['vehicle'] backup_svc = services.get('backup') + lifecycle_svc = services.get('lifecycle') + broadcasts_svc = services.get('broadcasts') audit_svc = services.get('audit') # Get or create rate limiter - use existing one from factory if available @@ -128,10 +142,207 @@ def register_api_routes(app, services, settings): @auth_req def battlegroup_update(): + # Safety guard: refuse to update while game servers are online. + running = k8s.get_running_game_pods() + if running is None: + return jsonify({'success': False, + 'output': 'Update blocked: could not verify pod status. ' + 'Stop the server first, then try again.'}) + if running: + shown = ', '.join(running[:5]) + if len(running) > 5: + shown += f', ... ({len(running)} total)' + return jsonify({'success': False, + 'output': f'Update blocked: server is online ' + f'({len(running)} game pod(s) Running: {shown}). ' + f'Stop/shutdown the server first.'}) bg_script = settings['kubernetes']['battlegroup_script'] out, err, rc = ssh.run(f'{bg_script} update', timeout=600) return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) + # Lifecycle: graceful shutdown/start/restart + scheduled restarts + @app.route('/server/lifecycle/status') + @auth_req + def lifecycle_status(): + if not lifecycle_svc: + return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) + status = lifecycle_svc.status() + status['success'] = True + return jsonify(status) + + @app.route('/server/lifecycle/start', methods=['POST']) + @auth_req + def lifecycle_start(): + if not lifecycle_svc: + return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) + if lifecycle_svc.status().get('active'): + return jsonify({'success': False, 'output': 'A countdown is already running'}) + bg_script = settings['kubernetes']['battlegroup_script'] + out, err, rc = ssh.run(f'{bg_script} start', timeout=300) + if audit_svc: + audit_svc.log('server_start', {'result': rc}, user='admin', + severity='warning' if rc != 0 else 'info') + return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) + + @app.route('/server/lifecycle/shutdown', methods=['POST']) + @auth_req + def lifecycle_shutdown(): + if not lifecycle_svc: + return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) + result = lifecycle_svc.start_shutdown(reason='manual') + if audit_svc and result.get('success'): + audit_svc.log('server_shutdown_countdown', {'action_at': result.get('action_at')}, + user='admin', severity='warning') + return jsonify(result) + + @app.route('/server/lifecycle/restart', methods=['POST']) + @auth_req + def lifecycle_restart(): + if not lifecycle_svc: + return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) + result = lifecycle_svc.start_restart(reason='manual') + if audit_svc and result.get('success'): + audit_svc.log('server_restart_countdown', {'action_at': result.get('action_at')}, + user='admin', severity='warning') + return jsonify(result) + + @app.route('/server/lifecycle/cancel', methods=['POST']) + @auth_req + def lifecycle_cancel(): + if not lifecycle_svc: + return jsonify({'success': False, 'output': 'Lifecycle service unavailable'}) + result = lifecycle_svc.cancel() + if audit_svc and result.get('success'): + audit_svc.log('server_lifecycle_cancel', {'kind': result.get('kind')}, + user='admin', severity='info') + return jsonify(result) + + @app.route('/server/lifecycle/schedule') + @auth_req + def lifecycle_schedule_get(): + if not lifecycle_svc: + return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) + cfg = lifecycle_svc.get_schedule() + return jsonify({'success': True, 'schedule': cfg}) + + @app.route('/server/lifecycle/schedule', methods=['POST']) + @auth_req + def lifecycle_schedule_set(): + if not lifecycle_svc: + return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) + data = request.get_json() or {} + try: + cfg = lifecycle_svc.update_schedule(data) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) + except Exception as e: + logger.error(f'Lifecycle schedule save failed: {e}') + return jsonify({'success': False, 'error': 'Could not save schedule'}) + if audit_svc: + audit_svc.log('server_restart_schedule', + {'enabled': cfg.get('enabled'), 'mode': cfg.get('mode'), + 'next_run': cfg.get('next_run')}, + user='admin', severity='info') + return jsonify({'success': True, 'schedule': cfg}) + + @app.route('/server/lifecycle/schedule/enabled', methods=['POST']) + @auth_req + def lifecycle_schedule_enabled(): + if not lifecycle_svc: + return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) + data = request.get_json() or {} + cfg = lifecycle_svc.set_enabled(data.get('enabled', True)) + if audit_svc: + audit_svc.log('server_restart_schedule', + {'enabled': cfg.get('enabled'), 'mode': cfg.get('mode'), + 'next_run': cfg.get('next_run')}, + user='admin', severity='info') + return jsonify({'success': True, 'schedule': cfg}) + + @app.route('/server/lifecycle/schedule/clear', methods=['POST']) + @auth_req + def lifecycle_schedule_clear(): + if not lifecycle_svc: + return jsonify({'success': False, 'error': 'Lifecycle service unavailable'}) + cfg = lifecycle_svc.clear_schedule() + if audit_svc: + audit_svc.log('server_restart_schedule', + {'cleared': True, 'mode': cfg.get('mode')}, + user='admin', severity='info') + return jsonify({'success': True, 'schedule': cfg}) + + # Custom notifications (moved here from Experimental - confirmed working) + @app.route('/server/broadcast', methods=['POST']) + @auth_req + def server_broadcast(): + data = request.get_json() or {} + title = (data.get('title') or '').strip() + message = (data.get('message') or '').strip() + try: + duration = int(data.get('duration', 30)) + except (ValueError, TypeError): + duration = 30 + duration = max(5, min(300, duration)) + if not title or not message: + return jsonify({'success': False, 'error': 'Title and message are required'}) + success, result = admin_svc.send_global_broadcast(title, message, duration) + if audit_svc and success: + audit_svc.log('server_broadcast', {'title': title, 'duration': duration}, + user='admin', severity='info') + return jsonify({'success': success, 'output': result}) + + @app.route('/server/broadcasts/schedule') + @auth_req + def broadcasts_schedule_list(): + if not broadcasts_svc: + return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) + return jsonify({'success': True, 'entries': broadcasts_svc.list_entries()}) + + @app.route('/server/broadcasts/schedule', methods=['POST']) + @auth_req + def broadcasts_schedule_save(): + if not broadcasts_svc: + return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) + data = request.get_json() or {} + try: + entry = broadcasts_svc.save_entry(data) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) + except Exception as e: + logger.error(f'Broadcast schedule save failed: {e}') + return jsonify({'success': False, 'error': 'Could not save scheduled notification'}) + if audit_svc: + audit_svc.log('server_broadcast_schedule', + {'id': entry.get('id'), 'enabled': entry.get('enabled'), + 'mode': entry.get('mode'), 'next_run': entry.get('next_run')}, + user='admin', severity='info') + return jsonify({'success': True, 'entry': entry}) + + @app.route('/server/broadcasts/schedule/enabled', methods=['POST']) + @auth_req + def broadcasts_schedule_enabled(): + if not broadcasts_svc: + return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) + data = request.get_json() or {} + try: + entry = broadcasts_svc.set_enabled(data.get('id'), data.get('enabled', True)) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) + return jsonify({'success': True, 'entry': entry}) + + @app.route('/server/broadcasts/schedule/delete', methods=['POST']) + @auth_req + def broadcasts_schedule_delete(): + if not broadcasts_svc: + return jsonify({'success': False, 'error': 'Broadcast service unavailable'}) + data = request.get_json() or {} + ok = broadcasts_svc.delete_entry(str(data.get('id') or '')) + if audit_svc and ok: + audit_svc.log('server_broadcast_schedule', + {'deleted': str(data.get('id') or '')}, + user='admin', severity='info') + return jsonify({'success': ok}) + # Firewall management def _get_bgd_nodeport(): """Resolve the current BGD service NodePort from K8s.""" @@ -800,12 +1011,47 @@ def register_api_routes(app, services, settings): # File browser FILEBROWSER_BASE_PATH = '/srv' - def _validate_fb_path(path): - """Validate filebrowser path — allow any path, block traversal.""" - path_str = str(path or "").lstrip("/") - if '..' in path_str or '\x00' in path_str: - return False - return True + # Built-in file-browser jail roots (used when settings has none). + _FB_DEFAULT_ROOTS = ('/srv', '/home/dune/.dune') + + def _fb_allowed_roots(): + """Allowed file-browser roots from settings, else built-in defaults.""" + roots = (settings.get('filebrowser', {}) or {}).get('allowed_roots') + if isinstance(roots, str): + roots = [roots] + cleaned = [] + for root in roots or []: + root = '/' + str(root or '').strip().lstrip('/') + root = root.rstrip('/') or '/' + if root and root not in cleaned: + cleaned.append(root) + return cleaned or list(_FB_DEFAULT_ROOTS) + + def _fb_resolve_path(path, pod_name=None, timeout=10): + """Canonicalize a path in the target context and enforce the jail. + + Returns (canonical_path, error). error is '' on success, in which + case canonical_path is safe to use in remote commands. + """ + raw = str(path or '') + if '\x00' in raw: + return '', 'Invalid path: access denied' + if not raw.startswith('/'): + return '', 'Invalid path: must be absolute' + import posixpath + roots = _fb_allowed_roots() + lexical = posixpath.normpath(raw) + out, err, rc = _fb_exec(f'realpath -m -- {quote_remote(raw)}', pod_name, timeout=timeout) + if rc == 0 and (out or '').strip(): + canonical = (out or '').strip().split('\n')[0].strip() + else: + # realpath unavailable in this context: fall back to the lexical + # path (still blocks '..' escapes; symlinks stay unresolved). + logger.warning('File browser: realpath unavailable, using lexical path check') + canonical = lexical + if not fb_within_roots(canonical, roots): + return '', 'Invalid path: outside allowed directories' + return canonical, '' def _get_fb_pod(): """Get the default FileBrowser pod name dynamically.""" @@ -821,20 +1067,39 @@ def register_api_routes(app, services, settings): available.append(p) return available + # Pod names the file browser accepts: the VM host entries shown in the + # pod selector, or real Kubernetes pod names (RFC 1123). + _FB_VM_PODS = ('__VM__', '__VM__ (Host OS)') + + def _fb_check_pod(pod_name): + """Validate a file-browser pod value. Returns an error string or ''.""" + if not pod_name: + return '' + if pod_name in _FB_VM_PODS: + return '' + try: + require_k8s_name(pod_name, 'pod') + except ValueError as e: + return str(e) + return '' + def _fb_exec(command, pod_name=None, timeout=10): """Execute a command on the VM host or in a K8s pod.""" - if pod_name == '__VM__' or (pod_name and pod_name.startswith('__VM__')): + if pod_name in _FB_VM_PODS: return k8s.ssh.run(command, timeout=timeout) pod = pod_name or _get_fb_pod() if not pod: return '', 'No pod specified or found', 1 - full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}' + err = _fb_check_pod(pod) + if err: + return '', f'Invalid pod name: {err}', 1 + full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}' return k8s.ssh.run(full_cmd, timeout=timeout) def _fb_write_file(content_b64, path, pod_name=None, timeout=30): """Write a file to the pod filesystem.""" import base64 - cmd = f"echo '{content_b64}' | base64 -d > '{path}'" + cmd = f"echo '{content_b64}' | base64 -d > {quote_remote(path)}" return _fb_exec(f"sh -c {quote_remote(cmd)}", pod_name, timeout) def _get_pod_from_request(): @@ -857,9 +1122,10 @@ def register_api_routes(app, services, settings): def api_files_list(): path = request.form.get('path', '/srv') pod_name = _get_pod_from_request() - if not _validate_fb_path(path): - return jsonify({'success': False, 'error': 'Invalid path: access denied'}) - safe_path = quote_remote(path) + canonical, err = _fb_resolve_path(path, pod_name) + if err: + return jsonify({'success': False, 'error': err}) + safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'ls -la {safe_path}', pod_name, timeout=10) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to list directory'}) @@ -890,9 +1156,10 @@ def register_api_routes(app, services, settings): pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) - if not _validate_fb_path(path): - return jsonify({'success': False, 'error': 'Invalid path: access denied'}) - safe_path = quote_remote(path) + canonical, err = _fb_resolve_path(path, pod_name) + if err: + return jsonify({'success': False, 'error': err}) + safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', pod_name, timeout=10) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to read file'}) @@ -907,11 +1174,12 @@ def register_api_routes(app, services, settings): pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) - if not _validate_fb_path(path): - return jsonify({'success': False, 'error': 'Invalid path: access denied'}) + canonical, err = _fb_resolve_path(path, pod_name) + if err: + return jsonify({'success': False, 'error': err}) import base64 content_b64 = base64.b64encode(content.encode()).decode() - out, err, rc = _fb_write_file(content_b64, path, pod_name) + out, err, rc = _fb_write_file(content_b64, canonical, pod_name) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to save file'}) return jsonify({'success': True}) @@ -923,10 +1191,11 @@ def register_api_routes(app, services, settings): pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) - if not _validate_fb_path(path): - return jsonify({'success': False, 'error': 'Invalid path: access denied'}) + canonical, err = _fb_resolve_path(path, pod_name) + if err: + return jsonify({'success': False, 'error': err}) import base64 - safe_path = quote_remote(path) + safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'base64 {safe_path}', pod_name, timeout=30) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to read file'}) @@ -942,16 +1211,15 @@ def register_api_routes(app, services, settings): pod_name = _get_pod_from_request() if not uploaded: return jsonify({'success': False, 'error': 'No file provided'}) - if not _validate_fb_path(target_path): - return jsonify({'success': False, 'error': 'Invalid path: access denied'}) import base64 filename = uploaded.filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1] if uploaded.filename else 'uploaded_file' dest = target_path.rstrip('/') + '/' + filename - if not _validate_fb_path(dest): + canonical, err = _fb_resolve_path(dest, pod_name) + if err: return jsonify({'success': False, 'error': 'Invalid destination path'}) content = uploaded.read() content_b64 = base64.b64encode(content).decode() - out, err, rc = _fb_write_file(content_b64, dest, pod_name) + out, err, rc = _fb_write_file(content_b64, canonical, pod_name) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to upload file'}) return jsonify({'success': True, 'filename': filename}) @@ -963,9 +1231,10 @@ def register_api_routes(app, services, settings): pod_name = _get_pod_from_request() if not path: return jsonify({'success': False, 'error': 'Missing path'}) - if not _validate_fb_path(path): - return jsonify({'success': False, 'error': 'Invalid path: access denied'}) - safe_path = quote_remote(path) + canonical, err = _fb_resolve_path(path, pod_name) + if err: + return jsonify({'success': False, 'error': err}) + safe_path = quote_remote(canonical) out, err, rc = _fb_exec(f'rm -rf {safe_path}', pod_name, timeout=10) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to delete'}) @@ -1080,10 +1349,23 @@ def register_api_routes(app, services, settings): return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503 return jsonify({'success': False, 'error': str(e)}), 500 + _MAP_NAME_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") + + def _require_map_name(map_name): + """Validate a director map name (used in kubectl resource names).""" + map_name = str(map_name or '').strip() + if not _MAP_NAME_RE.fullmatch(map_name): + raise ValueError('Invalid map name') + return map_name + @app.route('/api/director/server_set_scale/') @auth_req def director_server_set_scale_get(map_name): try: + try: + map_name = _require_map_name(map_name) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}), 400 if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 scale = director_svc.get_server_set_scale(map_name) @@ -1101,6 +1383,10 @@ def register_api_routes(app, services, settings): @auth_req def director_server_set_scale_patch(map_name): try: + try: + map_name = _require_map_name(map_name) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}), 400 if not director_svc: return jsonify({'success': False, 'error': 'Director service not available'}), 503 config = request.get_json() @@ -1138,17 +1424,25 @@ def register_api_routes(app, services, settings): except Exception as e: return jsonify({'success': False, 'error': str(e)}), 500 + def _require_pod(data): + """Extract + validate a pod name from a JSON body. Raises ValueError.""" + pod = (data.get('pod', '') or '').strip() + if not pod: + raise ValueError('pod name required') + return require_k8s_name(pod, 'pod') + @app.route('/api/pod/logs', methods=['POST']) @auth_req def api_pod_logs(): try: data = request.get_json(force=True) or {} - pod = data.get('pod', '').strip() - if not pod: - return jsonify({'success': False, 'error': 'pod name required'}) + try: + pod = _require_pod(data) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) ns = settings['kubernetes']['namespace'] out, err, rc = ssh.run( - f'sudo kubectl logs -n {ns} {pod} --tail=300 2>/dev/null || echo "NO_LOGS"', timeout=15) + f'sudo kubectl logs -n {shlex.quote(str(ns))} {shlex.quote(pod)} --tail=300 2>/dev/null || echo "NO_LOGS"', timeout=15) if rc != 0 and 'NO_LOGS' not in (out or ''): return jsonify({'success': False, 'error': err or 'Failed to get logs'}) logs = (out or '').replace('NO_LOGS\n', '').replace('NO_LOGS', '') @@ -1161,11 +1455,12 @@ def register_api_routes(app, services, settings): def api_pod_delete(): try: data = request.get_json(force=True) or {} - pod = data.get('pod', '').strip() - if not pod: - return jsonify({'success': False, 'error': 'pod name required'}) + try: + pod = _require_pod(data) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) ns = settings['kubernetes']['namespace'] - out, err, rc = ssh.run(f'sudo kubectl delete pod -n {ns} {pod} --wait=false', timeout=30) + out, err, rc = ssh.run(f'sudo kubectl delete pod -n {shlex.quote(str(ns))} {shlex.quote(pod)} --wait=false', timeout=30) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to delete pod'}) return jsonify({'success': True, 'message': f'Pod {pod} deleted (will be recreated by its controller)'}) @@ -1177,11 +1472,12 @@ def register_api_routes(app, services, settings): def api_pod_describe(): try: data = request.get_json(force=True) or {} - pod = data.get('pod', '').strip() - if not pod: - return jsonify({'success': False, 'error': 'pod name required'}) + try: + pod = _require_pod(data) + except ValueError as e: + return jsonify({'success': False, 'error': str(e)}) ns = settings['kubernetes']['namespace'] - out, err, rc = ssh.run(f'sudo kubectl describe pod -n {ns} {pod}', timeout=30) + out, err, rc = ssh.run(f'sudo kubectl describe pod -n {shlex.quote(str(ns))} {shlex.quote(pod)}', timeout=30) if rc != 0: return jsonify({'success': False, 'error': err or 'Failed to describe pod'}) return jsonify({'success': True, 'describe': out or '', 'pod': pod}) @@ -1412,650 +1708,6 @@ def register_api_routes(app, services, settings): logger.error(f"Failed to toggle debug: {e}") return jsonify({'success': False, 'error': str(e)}), 500 - # ── Admin Experimental: Broadcast ───────────────────────────────── - @app.route('/api/admin-experimental/broadcast', methods=['POST']) - @auth_req - - def admin_broadcast(): - data = request.get_json() or {} - title = (data.get('title') or '').strip() - message = (data.get('message') or '').strip() - try: - duration = int(data.get('duration', 30)) - except (ValueError, TypeError): - duration = 30 - if not title or not message: - return jsonify({'success': False, 'error': 'Title and message are required'}) - success, result = admin_svc.send_global_broadcast(title, message, duration) - return jsonify({'success': success, 'output': result}) - - # ── Admin Experimental: Query Database ──────────────────────────── - @app.route('/api/admin-experimental/query', methods=['POST']) - @auth_req - - def admin_query(): - data = request.get_json() or {} - sql = (data.get('sql') or '').strip() - if not sql: - return jsonify({'success': False, 'error': 'SQL is required'}) - lower = sql.strip().lower() - if not any(lower.startswith(w) for w in ('select', 'with', 'show', 'explain')): - return jsonify({'success': False, 'error': 'Only SELECT/WITH queries allowed'}) - result = admin_svc.admin_db_query(sql) - return jsonify({'success': True, 'rows': result or []}) - - # ── Admin Experimental: Search Players ──────────────────────────── - @app.route('/api/admin-experimental/search-players', methods=['POST']) - @auth_req - def admin_search_players(): - data = request.get_json() or {} - term = (data.get('term') or '').strip() - if not term: - return jsonify({'success': False, 'error': 'Search term required'}) - try: - results = admin_svc.search_players(term) - return jsonify({'success': True, 'players': results}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Online Players ───────────────────────────── - @app.route('/api/admin-experimental/online-players', methods=['GET']) - @auth_req - def admin_online_players(): - try: - players = admin_svc.get_online_players() - return jsonify({'success': True, 'players': players}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Adjust Currency ─────────────────────────── - @app.route('/api/admin-experimental/adjust-currency', methods=['POST']) - @auth_req - - def admin_adjust_currency(): - data = request.get_json() or {} - pid = data.get('player_controller_id') - cid = data.get('currency_id') - delta = data.get('delta') - if pid is None or cid is None or delta is None: - return jsonify({'success': False, 'error': 'player_controller_id, currency_id, and delta required'}) - success, result = admin_svc.adjust_currency(pid, int(cid), int(delta)) - return jsonify({'success': success, 'output': result}) - - # ── Admin Experimental: Change Faction ──────────────────────────── - @app.route('/api/admin-experimental/change-faction', methods=['POST']) - @auth_req - - def admin_change_faction(): - data = request.get_json() or {} - pid = data.get('player_id') - fid = data.get('faction_id') - if pid is None or fid is None: - return jsonify({'success': False, 'error': 'player_id and faction_id required'}) - success, result = admin_svc.change_faction(pid, int(fid)) - return jsonify({'success': success, 'output': result}) - - # ── Admin Experimental: Battlegroup Info ────────────────────────── - @app.route('/api/admin-experimental/battlegroup', methods=['GET']) - @auth_req - def admin_battlegroup(): - try: - out, err, rc = ssh.run("wget -qO- http://10.43.135.0:11717/v0/battlegroup", timeout=15) - if rc != 0 or not out: - return jsonify({'success': False, 'error': f'BGD unreachable: {err}'}) - parsed = json.loads(out) - return jsonify({'success': True, 'data': parsed}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: View Currency Balances ──────────────────── - @app.route('/api/admin-experimental/currency-balances', methods=['POST']) - @auth_req - def admin_currency_balances(): - data = request.get_json() or {} - pcid = data.get('player_controller_id') - if not pcid: - return jsonify({'success': False, 'error': 'player_controller_id required'}) - try: - result = admin_svc.get_currency_balances(pcid) - return jsonify({'success': True, 'balances': result}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Teleport Player ─────────────────────────── - @app.route('/api/admin-experimental/teleport', methods=['POST']) - @auth_req - - def admin_teleport(): - data = request.get_json() or {} - fls_id = data.get('fls_id') - partition_id = data.get('partition_id') - x = data.get('x', 0) - y = data.get('y', 0) - z = data.get('z', 0) - if not fls_id or not partition_id: - return jsonify({'success': False, 'error': 'fls_id and partition_id required'}) - try: - success, msg = admin_svc.teleport_player(fls_id, int(partition_id), float(x), float(y), float(z)) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/partitions', methods=['GET']) - @auth_req - def admin_partitions(): - try: - partitions = admin_svc.get_partitions() - return jsonify({'success': True, 'partitions': partitions}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Faction Reputation ──────────────────────── - @app.route('/api/admin-experimental/faction-reputation', methods=['POST']) - @auth_req - def admin_faction_reputation(): - data = request.get_json() or {} - actor_id = data.get('actor_id') - if not actor_id: - return jsonify({'success': False, 'error': 'actor_id required'}) - try: - # GET mode - if 'set' not in data: - result = admin_svc.get_faction_reputation(actor_id) - return jsonify({'success': True, 'reputation': result}) - else: - success, msg = admin_svc.set_faction_reputation(actor_id, int(data['faction_id']), int(data['amount'])) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Inventory Lookup ────────────────────────── - @app.route('/api/admin-experimental/inventory', methods=['POST']) - @auth_req - def admin_inventory(): - data = request.get_json() or {} - account_id = data.get('account_id') - if not account_id: - return jsonify({'success': False, 'error': 'account_id required'}) - try: - inv = admin_svc.get_inventory(account_id) - pawn = admin_svc.get_player_pawn(account_id) - return jsonify({'success': True, 'inventory': inv, 'pawn': pawn}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Guild Tools ──────────────────────────────── - @app.route('/api/admin-experimental/guilds', methods=['GET']) - @auth_req - def admin_guilds(): - try: - guilds = admin_svc.get_all_guilds() - return jsonify({'success': True, 'guilds': guilds}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/guild-data', methods=['POST']) - @auth_req - def admin_guild_data(): - data = request.get_json() or {} - guild_id = data.get('guild_id') - if not guild_id: - return jsonify({'success': False, 'error': 'guild_id required'}) - try: - guild = admin_svc.get_guild_data(guild_id) - return jsonify({'success': True, 'guild': guild}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/disband-guild', methods=['POST']) - @auth_req - - def admin_disband_guild(): - data = request.get_json() or {} - guild_id = data.get('guild_id') - if not guild_id: - return jsonify({'success': False, 'error': 'guild_id required'}) - try: - success, msg = admin_svc.disband_guild(guild_id) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/remove-guild-member', methods=['POST']) - @auth_req - - def admin_remove_guild_member(): - data = request.get_json() or {} - guild_id = data.get('guild_id') - player_id = data.get('player_id') - if not guild_id or not player_id: - return jsonify({'success': False, 'error': 'guild_id and player_id required'}) - try: - success, msg = admin_svc.remove_guild_member(guild_id, player_id) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Player Tags ──────────────────────────────── - @app.route('/api/admin-experimental/player-tags', methods=['POST']) - @auth_req - def admin_player_tags(): - data = request.get_json() or {} - account_id = data.get('account_id') - if not account_id: - return jsonify({'success': False, 'error': 'account_id required'}) - try: - if 'tags_to_add' in data or 'tags_to_remove' in data: - success, msg = admin_svc.update_player_tags(account_id, data.get('tags_to_add', []), data.get('tags_to_remove', [])) - return jsonify({'success': success, 'output': msg}) - else: - tags = admin_svc.get_player_tags(account_id) - return jsonify({'success': True, 'tags': tags}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/flag-cheater', methods=['POST']) - @auth_req - - def admin_flag_cheater(): - data = request.get_json() or {} - account_id = data.get('account_id') - cheat_type = data.get('cheat_type', 'manual') - if not account_id: - return jsonify({'success': False, 'error': 'account_id required'}) - try: - success, msg = admin_svc.flag_cheater(account_id, cheat_type) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Player Vehicles ─────────────────────────── - @app.route('/api/admin-experimental/player-vehicles', methods=['POST']) - @auth_req - def admin_player_vehicles(): - data = request.get_json() or {} - player_id = data.get('player_id') - account_id = data.get('account_id') - if not player_id or not account_id: - return jsonify({'success': False, 'error': 'player_id and account_id required'}) - try: - vehicles = admin_svc.get_player_vehicles(player_id, account_id) - return jsonify({'success': True, 'vehicles': vehicles}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Player Stats ────────────────────────────── - @app.route('/api/admin-experimental/player-stats', methods=['POST']) - @auth_req - def admin_player_stats(): - data = request.get_json() or {} - pcid = data.get('player_controller_id') - if not pcid: - return jsonify({'success': False, 'error': 'player_controller_id required'}) - try: - stats = admin_svc.get_player_stats(pcid) - return jsonify({'success': True, 'stats': stats}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Character Management ────────────────────── - @app.route('/api/admin-experimental/set-character-name', methods=['POST']) - @auth_req - def admin_set_character_name(): - data = request.get_json() or {} - account_id = data.get('account_id') - name = data.get('name', '').strip() - if not account_id or not name: - return jsonify({'success': False, 'error': 'account_id and name required'}) - try: - success, msg = admin_svc.set_character_name(account_id, name) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/delete-character', methods=['POST']) - @auth_req - - def admin_delete_character(): - data = request.get_json() or {} - actor_id = data.get('actor_id') - if not actor_id: - return jsonify({'success': False, 'error': 'actor_id required'}) - try: - success, msg = admin_svc.delete_character(actor_id) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/delete-account', methods=['POST']) - @auth_req - - def admin_delete_account(): - data = request.get_json() or {} - user_id = data.get('user_id') - reason = data.get('reason', 'admin') - if not user_id: - return jsonify({'success': False, 'error': 'user_id required'}) - try: - success, msg = admin_svc.delete_account(user_id, reason) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/set-demo-state', methods=['POST']) - @auth_req - def admin_set_demo_state(): - data = request.get_json() or {} - user_id = data.get('user_id') - demo_state = data.get('demo_state', 'none') - if not user_id: - return jsonify({'success': False, 'error': 'user_id required'}) - try: - success, msg = admin_svc.set_demo_state(user_id, demo_state) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Journey / Progression ───────────────────── - @app.route('/api/admin-experimental/journey', methods=['POST']) - @auth_req - def admin_journey(): - data = request.get_json() or {} - account_id = data.get('account_id') - node_ids = data.get('node_ids', []) - action = data.get('action', 'complete') - if not account_id or not node_ids: - return jsonify({'success': False, 'error': 'account_id and node_ids required'}) - try: - if action == 'complete': - success, msg = admin_svc.complete_journey_nodes(account_id, node_ids) - elif action == 'reveal': - success, msg = admin_svc.reveal_journey_nodes(account_id, node_ids) - elif action == 'reset': - success, msg = admin_svc.reset_journey_nodes(account_id, node_ids) - else: - return jsonify({'success': False, 'error': 'Invalid action'}) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/specialization', methods=['POST']) - @auth_req - def admin_specialization(): - data = request.get_json() or {} - player_id = data.get('player_id') - if not player_id: - return jsonify({'success': False, 'error': 'player_id required'}) - try: - if 'reset' in data: - success, msg = admin_svc.reset_specialization(player_id) - else: - track = data.get('track_type', 'combat') - xp = data.get('xp', 0) - level = data.get('level', 1) - success, msg = admin_svc.set_specialization(player_id, track, xp, level) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Guild Roster ────────────────────────────── - @app.route('/api/admin-experimental/guild-members', methods=['POST']) - @auth_req - def admin_guild_members(): - data = request.get_json() or {} - guild_id = data.get('guild_id') - if not guild_id: - return jsonify({'success': False, 'error': 'guild_id required'}) - try: - if 'promote' in data: - success, msg = admin_svc.promote_guild_member(guild_id, data['player_id'], data['new_role']) - return jsonify({'success': success, 'output': msg}) - else: - members = admin_svc.get_guild_members(guild_id) - return jsonify({'success': True, 'members': members}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Economy ─────────────────────────────────── - @app.route('/api/admin-experimental/clean-vendor-stock', methods=['POST']) - @auth_req - def admin_clean_vendor_stock(): - data = request.get_json() or {} - player_id = data.get('player_id') - if not player_id: - return jsonify({'success': False, 'error': 'player_id required'}) - try: - success, msg = admin_svc.clean_player_vendor_stock(player_id) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/tax-invoices', methods=['POST']) - @auth_req - def admin_tax_invoices(): - data = request.get_json() or {} - player_id = data.get('player_id') - if not player_id: - return jsonify({'success': False, 'error': 'player_id required'}) - try: - invoices = admin_svc.get_player_tax_invoices(player_id) - return jsonify({'success': True, 'invoices': invoices}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Spice Fields ────────────────────────────── - @app.route('/api/admin-experimental/spice', methods=['POST']) - @auth_req - - def admin_spice(): - data = request.get_json() or {} - try: - if data.get('action') == 'reset': - success, msg = admin_svc.reset_spice_state(data['map_name'], data.get('dimension_index', 0)) - else: - success, msg = admin_svc.force_spice_spawn(data['server_id'], data['spicefield_type_id']) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Server Tools ────────────────────────────── - @app.route('/api/admin-experimental/server-tools', methods=['POST']) - @auth_req - - def admin_server_tools(): - data = request.get_json() or {} - try: - if data.get('action') == 'set_offline': - success, msg = admin_svc.set_players_offline(data.get('server_ids', [])) - elif data.get('action') == 'cleanup_orphans': - success, msg = admin_svc.cleanup_orphaned() - else: - return jsonify({'success': False, 'error': 'Invalid action'}) - return jsonify({'success': success, 'output': msg}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Permissions ────────────────────────────── - @app.route('/api/admin-experimental/permissions', methods=['POST']) - @auth_req - def admin_permissions(): - data = request.get_json() or {} - try: - if 'set_rank' in data: - success, msg = admin_svc.set_player_rank(data['actor_id'], data['player_id'], data['rank'], data.get('map_id', '')) - return jsonify({'success': success, 'output': msg}) - elif data.get('actor_id'): - perms = admin_svc.get_actor_permissions(data['actor_id']) - return jsonify({'success': True, 'permissions': perms}) - else: - return jsonify({'success': False, 'error': 'actor_id required'}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: RMQ Explorer ───────────────────────────── - @app.route('/api/admin-experimental/rmq/overview') - @auth_req - def admin_rmq_overview(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - data = rmq.combined_overview() - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/queues') - @auth_req - def admin_rmq_queues(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - data = rmq.combined_queues() - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/exchanges') - @auth_req - def admin_rmq_exchanges(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - data = rmq.combined_exchanges() - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/bindings') - @auth_req - def admin_rmq_bindings(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - data = rmq.bindings() - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/consumers') - @auth_req - def admin_rmq_consumers(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - data = rmq.consumers() - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/peek', methods=['POST']) - @auth_req - def admin_rmq_peek(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - cfg = request.get_json() or {} - queue_name = cfg.get('queue', '') - count = int(cfg.get('count', 5)) - if not queue_name: - return jsonify({'success': False, 'error': 'queue name required'}), 400 - data = rmq.peek_messages(queue_name, count=count) - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/publish', methods=['POST']) - @auth_req - def admin_rmq_publish(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - cfg = request.get_json() or {} - exchange = cfg.get('exchange', '') - routing_key = cfg.get('routing_key', '') - message = cfg.get('message', '') - side = cfg.get('side', 'admin') - if not exchange: - return jsonify({'success': False, 'error': 'exchange name required'}), 400 - if side == 'game': - result = rmq.game_publish(exchange, routing_key, message) - else: - result = rmq.publish(exchange, routing_key, message) - return jsonify({'success': True, 'data': result}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/rmq/health') - @auth_req - def admin_rmq_health(): - try: - rmq = services.get('rmq') - if not rmq: - return jsonify({'success': False, 'error': 'RMQ service not available'}), 503 - data = rmq.health() - return jsonify({'success': True, 'data': data}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: Function Explorer ───────────────────────── - @app.route('/api/admin-experimental/functions', methods=['GET']) - @auth_req - def admin_list_functions(): - try: - funcs = admin_svc.list_all_functions() - return jsonify({'success': True, 'functions': funcs}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/functions/', methods=['GET']) - @auth_req - def admin_function_details(name): - try: - detail = admin_svc.get_function_details(name) - if not detail: - return jsonify({'success': False, 'error': 'Function not found'}) - return jsonify({'success': True, 'function': detail}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - @app.route('/api/admin-experimental/functions//execute', methods=['POST']) - @auth_req - - def admin_execute_function(name): - data = request.get_json() or {} - params = data.get('params', []) - try: - success, result, error = admin_svc.execute_function(name, params) - if success: - return jsonify({'success': True, 'result': result}) - else: - return jsonify({'success': False, 'error': error}) - except Exception as e: - return jsonify({'success': False, 'error': str(e)}) - - # ── Admin Experimental: SQL Execute (admin functions) ───────────── - @app.route('/api/admin-experimental/execute', methods=['POST']) - @auth_req - - def admin_execute(): - data = request.get_json() or {} - sql = (data.get('sql') or '').strip() - if not sql: - return jsonify({'success': False, 'error': 'SQL is required'}) - lower = sql.strip().lower() - allowed_prefixes = ('select', 'with', 'insert', 'update', 'delete', 'call', 'show', 'explain') - if not any(lower.startswith(w) for w in allowed_prefixes): - return jsonify({'success': False, 'error': 'SQL prefix not allowed'}) - success, result = admin_svc.admin_db_execute(sql) - return jsonify({'success': success, 'result': result if success else str(result)}) - # ── Backup Endpoints ────────────────────────────────────────────── if backup_svc: @@ -2155,6 +1807,7 @@ def register_api_routes(app, services, settings): def api_backup_schedule_set(): data = request.get_json() or {} result = backup_svc.update_schedule(data) + result.pop('password', None) # never send password to client return jsonify({'success': True, 'schedule': result}) @app.route('/api/backup/run-scheduled', methods=['POST']) @@ -2196,7 +1849,7 @@ def register_api_routes(app, services, settings): # ── Step 1: Read & update secret YAML (small file, keep current approach) ── t0 = time.time() - out, err, rc = ssh.run(f'cat {secret_yaml}', timeout=10) + out, err, rc = ssh.run(f'cat {shlex.quote(secret_yaml)}', timeout=10) t1 = time.time() logger.info(f'[token] read secret YAML: {t1-t0:.2f}s rc={rc}') if rc != 0: @@ -2205,7 +1858,8 @@ def register_api_routes(app, services, settings): fls_prefix = 'FuncomLiveServices__ServiceAuthToken: "' idx = out.find(fls_prefix) if idx == -1: - logger.error(f'Secret YAML lines: {[l for l in out.splitlines() if "ServiceAuthToken" in l]}') + # Never log matching lines: they contain the token itself. + logger.error('Secret YAML has no FuncomLiveServices__ServiceAuthToken line') return jsonify({'success': False, 'error': 'Could not find FuncomLiveServices__ServiceAuthToken line in secret file'}) start = idx + len(fls_prefix) end = out.find('"', start) @@ -2224,7 +1878,7 @@ def register_api_routes(app, services, settings): # ── Step 2: Update main battlegroup YAML via read-modify-write ── # Extract old token from the main YAML (may differ from secret YAML) t4 = time.time() - out, err, rc = ssh.run(f'cat {main_yaml}', timeout=10) + out, err, rc = ssh.run(f'cat {shlex.quote(main_yaml)}', timeout=10) t5 = time.time() logger.info(f'[token] read main YAML: {t5-t4:.2f}s rc={rc}') if rc != 0: @@ -2233,7 +1887,8 @@ def register_api_routes(app, services, settings): ini_prefix = '-ini:engine:[FuncomLiveServices]:ServiceAuthToken=' idx = out.find(ini_prefix) if idx == -1: - logger.error(f'Main YAML lines: {[l for l in out.splitlines() if "ServiceAuthToken" in l]}') + # Never log matching lines: they contain the token itself. + logger.error('Main YAML has no ServiceAuthToken line') return jsonify({'success': False, 'error': 'Could not find ServiceAuthToken in battlegroup file'}) old_start = idx + len(ini_prefix) old_end = out.find('\n', old_start) @@ -2251,9 +1906,9 @@ def register_api_routes(app, services, settings): return jsonify({'success': False, 'error': f'Failed to write battlegroup file: {err}'}) # Verify: count total ServiceAuthToken lines vs new-token lines - out, err, rc = ssh.run(f"grep -c 'ServiceAuthToken' {main_yaml} || true", timeout=5) + out, err, rc = ssh.run(f"grep -c 'ServiceAuthToken' {shlex.quote(main_yaml)} || true", timeout=5) total_lines = int(out.strip() or 0) - out, err, rc = ssh.run(f"grep -cF '{token}' {main_yaml} || true", timeout=5) + out, err, rc = ssh.run(f"grep -cF {shlex.quote(token)} {shlex.quote(main_yaml)} || true", timeout=5) new_count = int(out.strip() or 0) logger.info(f'[token] main YAML verify: {new_count}/{total_lines} tokens replaced') @@ -2261,7 +1916,7 @@ def register_api_routes(app, services, settings): bg_name = resource_prefix t8 = time.time() out, err, rc = ssh.run( - f'sudo kubectl get battlegroup {bg_name} -n {ns} -o yaml', timeout=10 + f'sudo kubectl get battlegroup {shlex.quote(bg_name)} -n {shlex.quote(str(ns))} -o yaml', timeout=10 ) t9 = time.time() logger.info(f'[token] read BG CR: {t9-t8:.2f}s rc={rc}') @@ -2270,7 +1925,8 @@ def register_api_routes(app, services, settings): old_start = out.find(ini_prefix) if old_start == -1: - logger.error(f'BG CR lines: {[l for l in out.splitlines() if "ServiceAuthToken" in l]}') + # Never log matching lines: they contain the token itself. + logger.error('BattleGroup CR has no ServiceAuthToken line') return jsonify({'success': False, 'error': 'Could not find ServiceAuthToken in BattleGroup CR'}) old_start += len(ini_prefix) old_end = out.find('\n', old_start) @@ -2289,7 +1945,7 @@ def register_api_routes(app, services, settings): return jsonify({'success': False, 'error': f'Failed to write BG CR temp file: {err}'}) out, err, rc = ssh.run( - f'sudo kubectl apply -f {cr_temp}', timeout=15 + f'sudo kubectl apply -f {shlex.quote(cr_temp)}', timeout=15 ) t12 = time.time() logger.info(f'[token] apply BG CR: {t12-t11:.2f}s rc={rc}') @@ -2298,22 +1954,22 @@ def register_api_routes(app, services, settings): # Verify new token count in live CR out, err, rc = ssh.run( - f"sudo kubectl get battlegroup {bg_name} -n {ns} -o yaml | grep -cF '{token}' || true", + f"sudo kubectl get battlegroup {shlex.quote(bg_name)} -n {shlex.quote(str(ns))} -o yaml | grep -cF {shlex.quote(token)} || true", timeout=5 ) live_count = int(out.strip() or 0) logger.info(f'[token] BG CR verify: {live_count}/{cr_count} tokens replaced') # Clean up temp file - ssh.run(f'rm -f {cr_temp}', timeout=3) + ssh.run(f'rm -f {shlex.quote(cr_temp)}', timeout=3) # ── Step 4: Update K8s secret via kubectl patch ── patch = json.dumps({'stringData': {'FuncomLiveServices__ServiceAuthToken': token}}) patch_encoded = base64.b64encode(patch.encode()).decode() t13 = time.time() out, err, rc = ssh.run( - f"printf '%s' '{patch_encoded}' | base64 -d > /tmp/service-auth-token-patch.json; " - f"sudo kubectl patch secret server-gateway-secret -n {ns} --patch-file /tmp/service-auth-token-patch.json", + f"printf '%s' {shlex.quote(patch_encoded)} | base64 -d > /tmp/service-auth-token-patch.json; " + f"sudo kubectl patch secret server-gateway-secret -n {shlex.quote(str(ns))} --patch-file /tmp/service-auth-token-patch.json", timeout=15 ) t14 = time.time() diff --git a/app/routes/main.py b/app/routes/main.py index f0b220f..058eb43 100644 --- a/app/routes/main.py +++ b/app/routes/main.py @@ -530,12 +530,6 @@ def register_routes(app, services, settings): logger.exception("Error in server_status route") return render_template('server.html', db_error=f"{type(e).__name__}: {e}") - # Admin Experimental - @app.route('/admin-experimental') - @login_required - def admin_experimental(): - return render_template('admin_experimental.html') - # Backup / Restore @app.route('/backup') @login_required diff --git a/app/services/admin.py b/app/services/admin.py index 3b94fac..9458a13 100644 --- a/app/services/admin.py +++ b/app/services/admin.py @@ -802,6 +802,13 @@ class AdminService: token = os.environ.get('DUNE_BROADCAST_TOKEN', getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr') + # Duration is interpolated into Erlang code: force an int in range. + try: + duration = max(5, min(300, int(duration))) + except (TypeError, ValueError): + duration = 30 + # Escape the token for the Erlang double-quoted binary literal. + token_esc = str(token).replace('\\', '\\\\').replace('"', '\\"') title_b64 = base64.b64encode(title.encode('utf-8')).decode() message_b64 = base64.b64encode(message.encode('utf-8')).decode() @@ -809,7 +816,7 @@ class AdminService: f'Title = base64:decode(<<"{title_b64}">>), ' f'Body = base64:decode(<<"{message_b64}">>), ' f'Duration = {duration}, ' - f'Token = <<"{token}">>, ' + f'Token = <<"{token_esc}">>, ' 'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, ' 'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, ' 'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), ' diff --git a/app/services/backup.py b/app/services/backup.py index 42a503d..f2bb295 100644 --- a/app/services/backup.py +++ b/app/services/backup.py @@ -1,9 +1,11 @@ """Backup service - backup creation, restore orchestration, backup management""" import base64 +import ipaddress import json import logging import os +import re import shlex import shutil import subprocess @@ -24,6 +26,16 @@ class BackupError(Exception): pass +# Backup names are always created as backup-DD-MM-YYYY_HHMMSS. Anything else +# (e.g. '../../...') is rejected so names can never escape the backup dir +# or break out of remote shell commands. +BACKUP_NAME_RE = re.compile(r"^backup-\d{2}-\d{2}-\d{4}_\d{6}$") + + +def is_valid_backup_name(name): + return bool(name and BACKUP_NAME_RE.fullmatch(str(name))) + + class BackupService: BACKUP_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups') @@ -388,6 +400,9 @@ class BackupService: return {} def delete_backup(self, name): + if not is_valid_backup_name(name): + logger.warning(f'Backup: rejected invalid backup name: {name!r}') + return False path = self._backup_path(f'{name}.tar.gz') if os.path.exists(path): os.remove(path) @@ -397,6 +412,8 @@ class BackupService: return True def verify_backup(self, name, password=''): + if not is_valid_backup_name(name): + return {'success': False, 'error': 'Invalid backup name'} path = self._backup_path(f'{name}.tar.gz') if not os.path.exists(path): return {'success': False, 'error': 'Backup not found'} @@ -444,6 +461,8 @@ class BackupService: # ── Restore Orchestration ───────────────────────────────────────── def restore_preview(self, name): + if not is_valid_backup_name(name): + return {'success': False, 'error': 'Invalid backup name'} path = self._backup_path(f'{name}.tar.gz') if not os.path.exists(path): return {'success': False, 'error': 'Backup not found'} @@ -493,6 +512,8 @@ class BackupService: return {'success': False, 'error': str(e)} def start_restore(self, backup_name, options): + if not is_valid_backup_name(backup_name): + return {'success': False, 'error': 'Invalid backup name'} ssh_user = self.settings.get('server', {}).get('user', 'dune') ssh_key = self.settings.get('server', {}).get('ssh_key', '') vm_ip = self.settings.get('server', {}).get('host', '') @@ -589,7 +610,8 @@ class BackupService: try: with open(upload_path, 'rb') as f: b64_data = base64.b64encode(f.read()).decode() - r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > /tmp/restore-{backup_name}.tar.gz', timeout=300) + remote_archive = f'/tmp/restore-{backup_name}.tar.gz' + r = ssh_cmd(f'echo {shlex.quote(b64_data)} | base64 -d > {shlex.quote(remote_archive)}', timeout=300) if r.returncode != 0: raise BackupError(f'Upload failed: {r.stderr}') complete_step('Uploading backup archive to new VM', True) @@ -607,10 +629,11 @@ class BackupService: # Step 2: Extract archive on VM add_step('Extracting backup archive on VM') try: + restore_dir = f'/tmp/restore-{backup_name}' r = ssh_cmd( - f'mkdir -p /tmp/restore-{backup_name} && ' - f'cd /tmp/restore-{backup_name} && ' - f'tar xzf /tmp/restore-{backup_name}.tar.gz --strip-components=1', + f'mkdir -p {shlex.quote(restore_dir)} && ' + f'cd {shlex.quote(restore_dir)} && ' + f'tar xzf {shlex.quote(remote_archive)} --strip-components=1', timeout=60) if r.returncode != 0: raise BackupError(f'Extract failed: {r.stderr}') @@ -624,8 +647,9 @@ class BackupService: try: d = f'/tmp/restore-{backup_name}' for fname in ['secrets.yaml', 'configmaps.yaml']: + manifest = f'{d}/k8s-manifests/{fname}' r = ssh_cmd( - f'sudo kubectl apply -n {ns} -f {d}/k8s-manifests/{fname} 2>/dev/null || true', + f'sudo kubectl apply -n {shlex.quote(str(ns))} -f {shlex.quote(manifest)} 2>/dev/null || true', timeout=30) if r.returncode != 0: logger.warning(f'Could not apply {fname}: {r.stderr}') @@ -638,8 +662,9 @@ class BackupService: add_step('Applying battlegroup CRD') try: d = f'/tmp/restore-{backup_name}' + crd = f'{d}/k8s-manifests/battlegroup-crd.yaml' r = ssh_cmd( - f'sudo kubectl apply -f {d}/k8s-manifests/battlegroup-crd.yaml', timeout=60) + f'sudo kubectl apply -f {shlex.quote(crd)}', timeout=60) if r.returncode != 0: raise BackupError(r.stderr) complete_step('Applying battlegroup CRD', True) @@ -650,7 +675,7 @@ class BackupService: try: for i in range(30): r = ssh_cmd( - f'sudo kubectl get pods -n {ns} --no-headers 2>/dev/null | ' + f'sudo kubectl get pods -n {shlex.quote(str(ns))} --no-headers 2>/dev/null | ' f'grep -c -E "(dbdepl|mq-.*-sts)" || true', timeout=15) if r.returncode == 0 and r.stdout.strip(): count = int(r.stdout.strip()) @@ -667,7 +692,7 @@ class BackupService: try: for i in range(30): r = ssh_cmd( - f'sudo kubectl get pods -n {ns} -l role=db --no-headers ' + f'sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db --no-headers ' f'-o custom-columns=STATUS:.status.phase 2>/dev/null | head -1', timeout=15) if 'Running' in r.stdout: @@ -684,7 +709,7 @@ class BackupService: add_step('Importing game database') try: r = ssh_cmd( - f'cd /tmp/restore-{backup_name} && ' + f'cd {shlex.quote(restore_dir)} && ' f'/home/dune/.dune/bin/battlegroup import', timeout=600) if r.returncode != 0: @@ -708,9 +733,9 @@ class BackupService: if dash_sql_content: b64_sql = base64.b64encode(dash_sql_content).decode() r = ssh_cmd( - f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && ' + f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && ' f'echo {shlex.quote(b64_sql)} | base64 -d | ' - f'sudo kubectl exec -n {ns} -i $dbpod -- psql -U postgres -d dune', + f'sudo kubectl exec -n {shlex.quote(str(ns))} -i $dbpod -- psql -U postgres -d dune', timeout=120) if r.returncode != 0: logger.warning(f'Dashboard DB restore warning: {r.stderr}') @@ -728,8 +753,8 @@ class BackupService: "GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA dashboard TO dune;" "GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA dashboard TO dune;") r = ssh_cmd( - f'dbpod=$(sudo kubectl get pods -n {ns} -l role=db -o name | head -1) && ' - f'sudo kubectl exec -n {ns} $dbpod -- psql -U postgres -d dune ' + f'dbpod=$(sudo kubectl get pods -n {shlex.quote(str(ns))} -l role=db -o name | head -1) && ' + f'sudo kubectl exec -n {shlex.quote(str(ns))} $dbpod -- psql -U postgres -d dune ' f'-c {shlex.quote(sql)}', timeout=30) if r.returncode != 0: logger.warning(f'Dashboard schema ownership warning: {r.stderr}') @@ -741,15 +766,20 @@ class BackupService: if opts.get('restore_ping_fix', True) and opts.get('new_ip'): add_step('Applying HOST_DATACENTER ping fix') try: + try: + new_ip = str(ipaddress.ip_address(str(opts['new_ip']).strip())) + except ValueError: + raise BackupError(f'Invalid IP address: {opts.get("new_ip")!r}') r = ssh_cmd('hostname', timeout=10) hostname = r.stdout.strip() - new_ip = opts['new_ip'] + if not re.fullmatch(r'[A-Za-z0-9_.-]{1,253}', hostname): + raise BackupError(f'Unexpected hostname: {hostname!r}') for deploy_suffix in ['bgd-deploy', 'sgw-deploy', 'tr-deploy']: full_name = f'{ns}-{deploy_suffix}' ssh_cmd( - f'sudo kubectl set env deploy/{full_name} -n {ns} ' - f'HOST_DATACENTER_ID={hostname} ' - f'HOST_DATACENTER_IP_ADDRESS={new_ip}', + f'sudo kubectl set env deploy/{shlex.quote(full_name)} -n {shlex.quote(str(ns))} ' + f'HOST_DATACENTER_ID={shlex.quote(hostname)} ' + f'HOST_DATACENTER_IP_ADDRESS={shlex.quote(new_ip)}', timeout=30) complete_step('Applying HOST_DATACENTER ping fix', True) except Exception as e: @@ -762,21 +792,24 @@ class BackupService: pw = self.settings.get('rabbitmq', {}).get('password', '') for side in ['admin', 'game']: pod_r = ssh_cmd( - f'sudo kubectl get pods -n {ns} -o name | grep mq-{side}-sts | head -1', + f'sudo kubectl get pods -n {shlex.quote(str(ns))} -o name | grep mq-{side}-sts | head -1', timeout=15) if pod_r.returncode != 0 or not pod_r.stdout.strip(): logger.warning(f'No mq-{side} pod found') continue pod = pod_r.stdout.strip() + if not re.fullmatch(r'[a-z0-9]([-a-z0-9]*[a-z0-9])?', pod): + logger.warning(f'Skipping unexpected pod name: {pod!r}') + continue for cmd in [ - f'rabbitmqctl add_user dashboard_admin {pw}', + f'rabbitmqctl add_user dashboard_admin {shlex.quote(str(pw))}', f'rabbitmqctl set_user_tags dashboard_admin administrator', f'rabbitmqctl set_permissions -p / dashboard_admin ".*" ".*" ".*"', f'rabbitmqctl eval ' f'\'application:set_env(rabbit, auth_backends, ' f'[rabbit_auth_backend_cache, rabbit_auth_backend_internal]).\'', ]: - ssh_cmd(f'sudo kubectl exec -n {ns} {pod} -- {cmd}', timeout=15) + ssh_cmd(f'sudo kubectl exec -n {shlex.quote(str(ns))} {shlex.quote(pod)} -- {cmd}', timeout=15) complete_step('Re-creating RMQ dashboard_admin user on both instances', True) except Exception as e: complete_step('Re-creating RMQ dashboard_admin user on both instances', False, str(e)) @@ -786,7 +819,8 @@ class BackupService: add_step('Restoring dashboard settings.yaml locally') try: d = f'/tmp/restore-{backup_name}' - r = ssh_cmd(f'cat {d}/settings.yaml', timeout=15) + settings_file = f'{d}/settings.yaml' + r = ssh_cmd(f'cat {shlex.quote(settings_file)}', timeout=15) if r.returncode == 0 and r.stdout.strip(): local_settings = os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))), @@ -802,7 +836,7 @@ class BackupService: # Step 10: Cleanup add_step('Cleaning up temporary files on VM') try: - ssh_cmd(f'rm -rf /tmp/restore-{backup_name} /tmp/restore-{backup_name}.tar.gz', + ssh_cmd(f'rm -rf {shlex.quote(restore_dir)} {shlex.quote(remote_archive)}', timeout=15) complete_step('Cleaning up temporary files on VM', True) except Exception as e: diff --git a/app/services/director.py b/app/services/director.py index 45302d8..dd64f86 100644 --- a/app/services/director.py +++ b/app/services/director.py @@ -1,12 +1,16 @@ """Director service - battlegroup director API and ConfigMap management.""" +import ipaddress import json import logging +import shlex +import time import urllib.error import urllib.request import configparser import io import base64 +import re from typing import Any, Dict, Optional logger = logging.getLogger(__name__) @@ -48,11 +52,19 @@ class DirectorService: for line in (out or '').split('\n'): line = line.strip() if 'bgd-svc' in line: - svc_name = line.split('/')[-1] + svc_name = line.split('/')[-1].strip() + if not re.fullmatch(r'[a-z0-9]([-a-z0-9]*[a-z0-9])?', svc_name or ''): + logger.warning("Director: unexpected svc name %r", svc_name) + continue ip_out, ip_err, ip_rc = self.k8s.run( - f'get svc {svc_name} -o jsonpath={{.spec.clusterIP}}', timeout=10) + f'get svc {shlex.quote(svc_name)} -o jsonpath={{.spec.clusterIP}}', timeout=10) if ip_rc == 0 and ip_out: ip = ip_out.strip() + try: + ipaddress.ip_address(ip) + except ValueError: + logger.warning("Director: unexpected cluster IP %r", ip) + continue logger.info("Director: resolved BGD svc cluster IP %s", ip) return f'http://{ip}:{_BGD_CONTAINER_PORT}' logger.warning("Director: no BGD service found in namespace %s", self.namespace) @@ -108,7 +120,7 @@ class DirectorService: svc_url = f"{self._bgd_svc_url}{path}" logger.debug("Director SSH fallback: %s %s", method, svc_url) if method == 'GET': - out, err, rc = self.ssh.run(f'wget -qO- {svc_url}', timeout=timeout) + out, err, rc = self.ssh.run(f'wget -qO- {shlex.quote(svc_url)}', timeout=timeout) else: body_bytes = None if raw_data and isinstance(data, str): @@ -117,14 +129,14 @@ class DirectorService: body_bytes = json.dumps(data).encode() body_b64 = base64.b64encode(body_bytes).decode() if body_bytes else '' tmp = f'/tmp/director_{int(time.time())}_{id(self)}' - self.ssh.run(f'echo {body_b64} | base64 -d > {tmp}', timeout=5) + self.ssh.run(f'echo {shlex.quote(body_b64)} | base64 -d > {shlex.quote(tmp)}', timeout=5) try: out, err, rc = self.ssh.run( - f'wget -qO- --post-file={tmp} ' - f'--header="Content-Type: application/json" {svc_url}', + f'wget -qO- --post-file={shlex.quote(tmp)} ' + f'--header="Content-Type: application/json" {shlex.quote(svc_url)}', timeout=timeout) finally: - self.ssh.run(f'rm -f {tmp}', timeout=5) + self.ssh.run(f'rm -f {shlex.quote(tmp)}', timeout=5) if rc == 0 and out: return out logger.warning("Director SSH fallback failed (rc=%d): %s", diff --git a/app/services/k8s.py b/app/services/k8s.py index 294b84f..4165f28 100644 --- a/app/services/k8s.py +++ b/app/services/k8s.py @@ -1,6 +1,7 @@ """Kubernetes service - kubectl operations via SSH""" import logging +import shlex logger = logging.getLogger(__name__) @@ -11,7 +12,7 @@ class K8sService: self.namespace = namespace def run(self, kubectl_command, timeout=30): - full_cmd = f'sudo kubectl {kubectl_command} -n {self.namespace}' + full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(self.namespace))}' logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}") result = self.ssh.run(full_cmd, timeout=timeout) out, err, rc = result @@ -30,6 +31,32 @@ class K8sService: logger.debug(f"Found {len(pods)} pods in namespace {self.namespace}") return pods + def get_running_game_pods(self): + """List game server pods (sg-*-pod-*) currently in Running phase. + + Used as the "server is online" signal, e.g. to block battlegroup + updates while players could be connected. + + Returns: + List of running game pod names, [] when none running, + or None when pod status could not be determined. + """ + out, err, rc = self.run( + 'get pods --no-headers -o custom-columns=NAME:.metadata.name,STATUS:.status.phase') + if rc != 0: + logger.warning(f"Could not get pod statuses: {err[:100] if err else 'no error'}") + return None + running = [] + for line in (out or '').strip().split('\n'): + parts = line.strip().split() + if len(parts) < 2: + continue + name, phase = parts[0], parts[1] + if phase == 'Running' and '-sg-' in name and '-pod-' in name: + running.append(name) + logger.debug(f"Found {len(running)} running game pods in namespace {self.namespace}") + return running + def find_pod_by_pattern(self, pattern): pods = self.get_pods() for pod in pods: diff --git a/app/services/lifecycle.py b/app/services/lifecycle.py new file mode 100644 index 0000000..d2db0c3 --- /dev/null +++ b/app/services/lifecycle.py @@ -0,0 +1,497 @@ +"""Lifecycle service - graceful shutdown/start/restart with in-game countdown. + +Notification path reuses the Experimental In-Game Broadcast +(AdminService.send_global_broadcast) - no duplicate RMQ code. + +Countdown (seconds before action -> spoken label -> broadcast duration): + 15m, 10m, 5m, 3m, 2m, 1m, 30s -> duration 10 + 10s -> duration 5 (so it does not overlap the final 1s notice) + 1s -> final "now" notice, duration 10 + +Scheduled restarts use the same marks but say "Scheduled restart in X ...". +""" + +import copy +import json +import logging +import os +import threading +import time +from datetime import datetime, timedelta + +from app.services.schedule_util import ( + SCHEDULE_MODES, + clean_days, + clean_times, + compute_next_run as util_compute_next_run, + parse_hhmm, + parse_when, +) + +logger = logging.getLogger(__name__) + + +# (seconds_before_action, spoken label, broadcast duration seconds) +COUNTDOWN_MARKS = [ + (900, '15 minutes', 10), + (600, '10 minutes', 10), + (300, '5 minutes', 10), + (180, '3 minutes', 10), + (120, '2 minutes', 10), + (60, '1 minute', 10), + (30, '30 seconds', 10), + (10, '10 seconds', 5), +] + +FINAL_MARK_SECONDS = 1 +FINAL_DURATION = 10 +FULL_COUNTDOWN_SECONDS = 900 +# A mark that became due within the last N seconds is sent immediately +# (covers thread startup delay, e.g. the first 15-minute notice at job start). +# Marks older than this were missed while the dashboard was down: skipped. +MARK_GRACE_SECONDS = 60 + + +def _default_state_dir(): + return os.path.join( + os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups') + + +def default_schedule(): + return { + 'enabled': False, + 'mode': 'daily', + 'daily_times': ['05:00'], + 'weekly_days': [6], + 'weekly_times': ['05:00'], + 'monthly_days': [1], + 'monthly_time': '05:00', + 'once_at': '', + 'next_run': '', + 'last_started_for': '', + } + + +class LifecycleService: + """Owns one active countdown at a time + the restart schedule file.""" + + def __init__(self, ssh_service, admin_service, settings, state_dir=None): + self.ssh = ssh_service + self.admin = admin_service + self.settings = settings or {} + self.state_dir = state_dir or _default_state_dir() + os.makedirs(self.state_dir, exist_ok=True) + self._lock = threading.Lock() + self._active = None + self._cancel_event = threading.Event() + self._thread = None + + # ── schedule persistence ────────────────────────────────────────── + + def _schedule_path(self): + return os.path.join(self.state_dir, 'lifecycle-schedule.json') + + def get_schedule(self): + cfg = default_schedule() + try: + with open(self._schedule_path()) as f: + stored = json.load(f) or {} + for key in cfg: + if key in stored: + cfg[key] = stored[key] + except FileNotFoundError: + pass + except Exception as e: + logger.warning(f'Lifecycle: could not read schedule: {e}') + return cfg + + def _save_schedule(self, cfg): + with open(self._schedule_path(), 'w') as f: + json.dump(cfg, f, indent=2) + + def update_schedule(self, data): + """Validate + store schedule, recompute next_run. Returns stored cfg.""" + cfg = self.get_schedule() + data = dict(data or {}) + + if 'enabled' in data: + cfg['enabled'] = bool(data['enabled']) + if 'mode' in data: + mode = str(data['mode']).strip().lower() + if mode not in SCHEDULE_MODES: + raise ValueError(f'Invalid mode: {mode!r}') + cfg['mode'] = mode + if 'daily_times' in data: + cfg['daily_times'] = self._clean_times(data['daily_times']) + if 'weekly_times' in data: + cfg['weekly_times'] = self._clean_times(data['weekly_times']) + if 'weekly_days' in data: + cfg['weekly_days'] = self._clean_days(data['weekly_days'], 0, 6) + if 'monthly_days' in data: + cfg['monthly_days'] = self._clean_days(data['monthly_days'], 1, 31) + if 'monthly_time' in data: + parse_hhmm(data['monthly_time']) + cfg['monthly_time'] = str(data['monthly_time']).strip() + if 'once_at' in data: + cfg['once_at'] = str(data['once_at'] or '').strip() + if cfg['once_at']: + try: + parse_when(cfg['once_at']) + except ValueError: + raise ValueError('One-shot date/time is not valid.') + + # Mode-specific sanity so a bad form cannot arm a silent never-fire job. + if cfg['mode'] == 'daily' and not cfg['daily_times']: + raise ValueError('Daily mode needs at least one time (HH:MM).') + if cfg['mode'] == 'weekly' and (not cfg['weekly_days'] or not cfg['weekly_times']): + raise ValueError('Weekly mode needs days and at least one time.') + if cfg['mode'] == 'monthly' and (not cfg['monthly_days'] or not cfg['monthly_time']): + raise ValueError('Monthly mode needs days of month and a time.') + if cfg['mode'] == 'once' and not cfg['once_at']: + raise ValueError('One-shot mode needs a date/time.') + + cfg['next_run'] = self.compute_next_run(cfg) + # Arming a new schedule must not replay an old occurrence marker. + if 'next_run' in cfg and cfg.get('last_started_for') == cfg['next_run']: + cfg['last_started_for'] = '' + self._save_schedule(cfg) + return cfg + + @staticmethod + def _clean_times(values): + return clean_times(values) + + @staticmethod + def _clean_days(values, low, high): + return clean_days(values, low, high) + + def compute_next_run(self, cfg=None, now=None): + """Next action time as ISO string, or '' when nothing upcoming.""" + return util_compute_next_run(cfg or self.get_schedule(), now) + + def set_enabled(self, enabled): + """Flip the enabled flag only; all schedule settings are preserved.""" + cfg = self.get_schedule() + cfg['enabled'] = bool(enabled) + cfg['next_run'] = self.compute_next_run(cfg) + if cfg.get('last_started_for') == cfg['next_run']: + cfg['last_started_for'] = '' + self._save_schedule(cfg) + return cfg + + def clear_schedule(self): + """Disarm the schedule but keep mode/times/days settings. + + Clears the armed one-shot date, any pending next_run and the + last-fired marker; the configured mode, times and days are kept + so the schedule can be re-enabled without re-typing everything. + """ + cfg = self.get_schedule() + cfg['enabled'] = False + cfg['once_at'] = '' + cfg['next_run'] = '' + cfg['last_started_for'] = '' + self._save_schedule(cfg) + return cfg + + # ── active countdown ────────────────────────────────────────────── + + def status(self): + with self._lock: + if not self._active: + return {'active': False} + active = copy.deepcopy(self._active) + active['active'] = True + active['now'] = time.time() + return active + + def start_shutdown(self, reason='manual', context=''): + return self._start('shutdown', time.time() + FULL_COUNTDOWN_SECONDS, + reason, context) + + def start_restart(self, reason='manual', context=''): + return self._start('restart', time.time() + FULL_COUNTDOWN_SECONDS, + reason, context) + + def start_restart_at(self, action_at, reason='scheduled', context=''): + return self._start('restart', float(action_at), reason, context) + + def _start(self, kind, action_at, reason, context): + if kind not in ('shutdown', 'restart'): + return {'success': False, 'error': f'Unknown action: {kind}'} + with self._lock: + if self._active: + return {'success': False, + 'error': f"A {self._active['kind']} countdown is already running"} + self._cancel_event.clear() + self._active = { + 'kind': kind, + 'reason': reason, + 'context': context or '', + 'started_at': time.time(), + 'action_at': float(action_at), + 'status': 'countdown', + 'sent': [], + 'log': [], + 'error': '', + } + thread = threading.Thread(target=self._run_countdown, daemon=True) + self._thread = thread + thread.start() + action_iso = datetime.fromtimestamp(float(action_at)).isoformat() + logger.info(f'Lifecycle: {kind} countdown started ({reason}) -> {action_iso}') + return {'success': True, 'kind': kind, + 'action_at': datetime.fromtimestamp(float(action_at)).isoformat()} + + def cancel(self): + with self._lock: + if not self._active: + return {'success': False, 'error': 'No active countdown'} + if self._active.get('status') in ('executing', 'completed', 'failed'): + return {'success': False, + 'error': 'Countdown already finished executing and cannot be cancelled'} + kind = self._active['kind'] + reason = self._active.get('reason', 'manual') + context = self._active.get('context', '') + self._active['status'] = 'cancelling' + self._cancel_event.set() + thread = self._thread + if thread and thread.is_alive(): + thread.join(timeout=30) + with self._lock: + self._active = None + self._thread = None + self._cancel_event.clear() + logger.info(f'Lifecycle: {kind} countdown cancelled') + # Tell players in-game so they know the shutdown/restart is off. + # The countdown thread itself stays silent on cancel: this is the + # single place the cancellation notice is sent (no duplicates). + notice_ok, notice_detail = self._cancellation_notice(kind, reason, context) + result = {'success': True, 'kind': kind, + 'notice_sent': bool(notice_ok), 'notice': str(notice_detail)[:300]} + if not notice_ok: + logger.warning(f'Lifecycle: cancellation notice failed: {notice_detail}') + return result + + def _cancellation_notice(self, kind, reason, context): + """In-game broadcast announcing the countdown was cancelled.""" + if kind == 'shutdown': + title = 'Server Shutdown' + message = 'Shutdown called off - the server is staying online.' + elif reason == 'scheduled': + context_suffix = f' ({context})' if context else '' + title = 'Scheduled Server Restart' + message = (f'Scheduled restart{context_suffix} called off - ' + f'staying online.') + else: + title = 'Server Restart' + message = 'Restart called off - the server is staying online.' + try: + return self.admin.send_global_broadcast(title, message, 10) + except Exception as e: + logger.error(f'Lifecycle cancellation-notice error: {e}') + return False, str(e) + + def _wait_until(self, target_ts): + """Sleep until target_ts, waking early on cancel (1s slices).""" + while True: + if self._cancel_event.is_set(): + return False + remaining = float(target_ts) - time.time() + if remaining <= 0: + return True + self._cancel_event.wait(timeout=min(1.0, remaining)) + if self._cancel_event.is_set(): + return False + + def _run_countdown(self): + with self._lock: + active = self._active + if not active: + return + kind = active['kind'] + reason = active.get('reason', 'manual') + context = active.get('context', '') + action_at = float(active['action_at']) + scheduled = (reason == 'scheduled') + + for seconds_before, label, duration in COUNTDOWN_MARKS: + mark_at = action_at - seconds_before + now = time.time() + if now >= mark_at: + if now - mark_at <= MARK_GRACE_SECONDS: + # Due right now (e.g. the first notice at job start): + # send immediately instead of waiting. + pass + else: + # Missed while the dashboard was down: skip the stale mark. + self._record_sent(label, True, 'skipped (past due)') + continue + elif not self._wait_until(mark_at): + self._finish_cancelled() + return + title, message = self._message_for(kind, label, duration, scheduled, context, + final=False) + ok, detail = self._broadcast(title, message, duration) + self._record_sent(label, ok, detail) + if not ok: + # Keep counting down: a missed notice must not strand players + # without the final warning, but the miss is visible in status. + logger.warning(f'Lifecycle: broadcast failed at {label}: {detail}') + + if not self._wait_until(action_at - FINAL_MARK_SECONDS): + self._finish_cancelled() + return + final_label = 'shutting down now' if kind == 'shutdown' else 'restarting now' + if scheduled and kind == 'restart': + final_label = 'scheduled restart starting now' + title, message = self._message_for(kind, final_label, FINAL_DURATION, + scheduled, context, final=True) + ok, detail = self._broadcast(title, message, FINAL_DURATION) + self._record_sent('now', ok, detail) + + # Small buffer so the final notice is visible before the stop/restart. + time.sleep(2) + if self._cancel_event.is_set(): + self._finish_cancelled() + return + + self._set_status('executing') + ok, detail = self._execute(kind) + with self._lock: + if self._active: + self._active['status'] = 'completed' if ok else 'failed' + self._active['error'] = '' if ok else detail + self._active['completed_at'] = time.time() + self._active['log'].append(f'action: {detail}') + finished = copy.deepcopy(self._active) + # Leave the finished record briefly for the UI poll, then clear. + self._active = None + self._thread = None + logger.info(f"Lifecycle: {kind} finished ok={ok}: {detail}") + return finished + + def _finish_cancelled(self): + with self._lock: + if self._active: + self._active['status'] = 'cancelled' + self._active = None + self._thread = None + self._cancel_event.clear() + logger.info('Lifecycle: countdown cancelled during wait') + + def _set_status(self, status): + with self._lock: + if self._active: + self._active['status'] = status + + def _record_sent(self, label, ok, detail): + with self._lock: + if self._active is not None: + self._active['sent'].append( + {'mark': label, 'ok': bool(ok), 'detail': str(detail)[:200], + 'at': time.time()}) + + @staticmethod + def _message_for(kind, label, duration, scheduled, context, final=False): + context_suffix = f' ({context})' if scheduled and context else '' + if kind == 'shutdown': + if final: + return ('Server Shutdown', 'Shutting down now - see you soon!') + return ('Server Shutdown', + f'Heads up - the server is shutting down in {label}. ' + f'Get somewhere safe!') + # restart + if final: + if scheduled: + return ('Scheduled Server Restart', + f'Scheduled restart starting now{context_suffix} - back shortly!') + return ('Server Restart', 'Restarting now - back shortly!') + if scheduled: + return ('Scheduled Server Restart', + f'Heads up - scheduled restart in {label}{context_suffix}. ' + f'Get somewhere safe!') + return ('Server Restart', + f'Heads up - server restart in {label}. Get somewhere safe!') + + def _broadcast(self, title, message, duration): + try: + return self.admin.send_global_broadcast(title, message, int(duration)) + except Exception as e: + logger.error(f'Lifecycle broadcast error: {e}') + return False, str(e) + + def _execute(self, kind): + script = (self.settings.get('kubernetes', {}) or {}).get( + 'battlegroup_script', '/home/dune/.dune/bin/battlegroup') + action = 'stop' if kind == 'shutdown' else 'restart' + try: + out, err, rc = self.ssh.run(f'{script} {action}', timeout=300) + detail = (out or '') + (err or '') + detail = detail.strip() or f'{action} completed' + if rc != 0: + return False, f'{action} failed (rc={rc}): {detail[:500]}' + return True, detail[:1000] + except Exception as e: + return False, str(e) + + # ── scheduler tick (called from factory background thread) ───────── + + def describe_context(self, cfg=None): + cfg = cfg or self.get_schedule() + mode = cfg.get('mode', 'daily') + if mode == 'once': + return 'one-time' + if mode == 'daily': + return 'daily ' + ', '.join(cfg.get('daily_times') or []) + if mode == 'weekly': + day_names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + days = ', '.join(day_names[d] for d in (cfg.get('weekly_days') or [])) + return f"weekly {days} {', '.join(cfg.get('weekly_times') or [])}" + if mode == 'monthly': + return (f"monthly day {', '.join(str(d) for d in (cfg.get('monthly_days') or []))} " + f"{cfg.get('monthly_time', '')}") + return mode + + def check_and_fire(self, now=None): + """Start the countdown when inside the 15-minute window before next_run.""" + cfg = self.get_schedule() + if not cfg.get('enabled'): + return None + next_run = cfg.get('next_run') or self.compute_next_run(cfg, now) + if not next_run: + return None + # Keep next_run fresh if the mode changed underneath us. + if cfg.get('next_run') != next_run: + cfg['next_run'] = next_run + self._save_schedule(cfg) + try: + action_at = parse_when(next_run).timestamp() + except ValueError: + return None + now_ts = time.time() if now is None else now.timestamp() + if cfg.get('last_started_for') == next_run: + return None + with self._lock: + if self._active: + return None + if now_ts < action_at - FULL_COUNTDOWN_SECONDS: + return None + if now_ts > action_at + 120: + # Missed window (dashboard was down): roll forward, do not fire late. + cfg['last_started_for'] = next_run + cfg['next_run'] = self.compute_next_run(cfg, datetime.now()) + self._save_schedule(cfg) + logger.warning(f'Lifecycle: missed scheduled restart for {next_run}, rolled forward') + return None + context = self.describe_context(cfg) + result = self.start_restart_at(action_at, reason='scheduled', context=context) + if result.get('success'): + cfg['last_started_for'] = next_run + # Advance to the occurrence *after* this one, not after now. + anchor = datetime.fromtimestamp(action_at) + timedelta(seconds=1) + cfg['next_run'] = self.compute_next_run(cfg, anchor) + self._save_schedule(cfg) + logger.info(f'Lifecycle: scheduled restart countdown started for {next_run}') + return result + return None diff --git a/app/services/schedule_util.py b/app/services/schedule_util.py new file mode 100644 index 0000000..ff12874 --- /dev/null +++ b/app/services/schedule_util.py @@ -0,0 +1,136 @@ +"""Shared schedule helpers: validation + next-run computation. + +Used by the restart lifecycle scheduler and the custom-notification +scheduler. All times are server-local naive datetimes. ISO strings from +`` ("YYYY-MM-DDTHH:MM") and UTC ("...Z") +strings are both accepted. +""" + +import logging +from datetime import datetime, timedelta + +logger = logging.getLogger(__name__) + +SCHEDULE_MODES = ('once', 'daily', 'weekly', 'monthly') + + +def parse_hhmm(value): + """Parse 'HH:MM' -> (hour, minute), raising ValueError when invalid.""" + parts = str(value or '').strip().split(':') + if len(parts) != 2: + raise ValueError(f'Invalid time: {value!r} (expected HH:MM)') + hour, minute = int(parts[0]), int(parts[1]) + if not (0 <= hour <= 23 and 0 <= minute <= 59): + raise ValueError(f'Invalid time: {value!r}') + return hour, minute + + +def clean_times(values): + """Validate a list of 'HH:MM' strings; returns sorted unique list.""" + if isinstance(values, str): + values = [values] + cleaned = [] + for value in values or []: + value = str(value).strip() + if not value: + continue + parse_hhmm(value) + if value not in cleaned: + cleaned.append(value) + return sorted(cleaned) + + +def clean_days(values, low, high): + """Validate a list of integer days in [low, high]; sorted unique list.""" + if isinstance(values, (int, str)): + values = [values] + cleaned = [] + for value in values or []: + try: + day = int(value) + except (TypeError, ValueError): + raise ValueError(f'Invalid day: {value!r}') + if not (low <= day <= high): + raise ValueError(f'Day out of range: {value!r}') + if day not in cleaned: + cleaned.append(day) + return sorted(cleaned) + + +def parse_when(raw): + """Parse an ISO datetime string -> naive server-local datetime.""" + dt = datetime.fromisoformat(str(raw).strip()) + if dt.tzinfo is not None: + dt = dt.astimezone().replace(tzinfo=None) + return dt + + +def next_once(cfg, now): + raw = str(cfg.get('once_at') or '').strip() + if not raw: + return '' + candidate = parse_when(raw) + return candidate.isoformat() if candidate > now else '' + + +def next_daily_weekly(now, days, times): + cleaned_times = [] + for value in times or []: + try: + cleaned_times.append(parse_hhmm(value)) + except ValueError: + continue + if not cleaned_times: + return '' + best = None + for offset in range(8): + base = datetime(now.year, now.month, now.day) + timedelta(days=offset) + if days is not None and base.weekday() not in days: + continue + for hour, minute in cleaned_times: + candidate = base.replace(hour=hour, minute=minute, second=0, microsecond=0) + if candidate <= now: + continue + if best is None or candidate < best: + best = candidate + return best.isoformat() if best else '' + + +def next_monthly(now, cfg, time_key='monthly_time', days_key='monthly_days'): + try: + hour, minute = parse_hhmm(cfg.get(time_key, '05:00')) + except ValueError: + return '' + month_days = set(cfg.get(days_key) or []) + if not month_days: + return '' + # Scan day-by-day (covers varying month lengths without dateutil). + base = datetime(now.year, now.month, now.day) + for offset in range(1, 370): + day = base + timedelta(days=offset) + if day.day not in month_days: + continue + candidate = day.replace(hour=hour, minute=minute, second=0, microsecond=0) + if candidate > now: + return candidate.isoformat() + return '' + + +def compute_next_run(cfg, now=None): + """Next action time as ISO string, or '' when nothing upcoming.""" + cfg = cfg or {} + now = now or datetime.now() + mode = cfg.get('mode', 'daily') + try: + if mode == 'once': + return next_once(cfg, now) + if mode == 'daily': + return next_daily_weekly(now, days=None, times=cfg.get('daily_times') or []) + if mode == 'weekly': + return next_daily_weekly(now, days=set(cfg.get('weekly_days') or []), + times=cfg.get('weekly_times') or []) + if mode == 'monthly': + return next_monthly(now, cfg) + except Exception as e: + logger.warning(f'Schedule: next-run calc failed: {e}') + return '' diff --git a/app/services/scheduled_broadcast.py b/app/services/scheduled_broadcast.py new file mode 100644 index 0000000..d4aba09 --- /dev/null +++ b/app/services/scheduled_broadcast.py @@ -0,0 +1,251 @@ +"""Scheduled custom notifications - one-off/recurring in-game broadcasts. + +Shares schedule validation + next-run computation with the restart +lifecycle scheduler (app/services/schedule_util.py). Delivery reuses the +confirmed In-Game Broadcast path (AdminService.send_global_broadcast). +""" + +import json +import logging +import os +import threading +import uuid +from datetime import datetime, timedelta + +from app.services.schedule_util import ( + SCHEDULE_MODES, + clean_days, + clean_times, + compute_next_run, + parse_hhmm, + parse_when, +) + +logger = logging.getLogger(__name__) + +MIN_DURATION = 5 +MAX_DURATION = 300 +DEFAULT_DURATION = 30 +# A missed occurrence older than this is rolled forward, never fired late. +MISSED_WINDOW_SECONDS = 3600 + + +def _default_state_dir(): + return os.path.join( + os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'backups') + + +def default_entry(): + return { + 'id': uuid.uuid4().hex[:8], + 'enabled': True, + 'title': '', + 'message': '', + 'duration': DEFAULT_DURATION, + 'mode': 'daily', + 'daily_times': ['12:00'], + 'weekly_days': [6], + 'weekly_times': ['12:00'], + 'monthly_days': [1], + 'monthly_time': '12:00', + 'once_at': '', + 'next_run': '', + 'last_fired_for': '', + } + + +class ScheduledBroadcastService: + """Stores + fires scheduled custom notification entries.""" + + def __init__(self, admin_service, state_dir=None): + self.admin = admin_service + self.state_dir = state_dir or _default_state_dir() + os.makedirs(self.state_dir, exist_ok=True) + self._lock = threading.Lock() + + # ── persistence ─────────────────────────────────────────────────── + + def _path(self): + return os.path.join(self.state_dir, 'broadcast-schedule.json') + + def list_entries(self): + try: + with open(self._path()) as f: + stored = json.load(f) or {} + entries = stored.get('entries') or [] + return [e for e in entries if isinstance(e, dict)] + except FileNotFoundError: + return [] + except Exception as e: + logger.warning(f'ScheduledBroadcast: could not read schedule: {e}') + return [] + + def _save(self, entries): + with open(self._path(), 'w') as f: + json.dump({'entries': entries}, f, indent=2) + + def _find(self, entries, entry_id): + for entry in entries: + if entry.get('id') == entry_id: + return entry + return None + + # ── CRUD ────────────────────────────────────────────────────────── + + def save_entry(self, data): + """Create or update an entry; validates, recomputes next_run.""" + data = dict(data or {}) + with self._lock: + entries = self.list_entries() + entry_id = str(data.get('id') or '').strip() + if entry_id: + entry = self._find(entries, entry_id) + if entry is None: + raise ValueError(f'Unknown scheduled notification: {entry_id!r}') + else: + entry = default_entry() + entries.append(entry) + + if 'enabled' in data: + entry['enabled'] = bool(data['enabled']) + for field in ('title', 'message'): + if field in data: + entry[field] = str(data[field] or '').strip() + if 'duration' in data: + try: + duration = int(data['duration']) + except (TypeError, ValueError): + raise ValueError('Duration must be a number of seconds.') + entry['duration'] = max(MIN_DURATION, min(MAX_DURATION, duration)) + if 'mode' in data: + mode = str(data['mode']).strip().lower() + if mode not in SCHEDULE_MODES: + raise ValueError(f'Invalid mode: {mode!r}') + entry['mode'] = mode + if 'daily_times' in data: + entry['daily_times'] = clean_times(data['daily_times']) + if 'weekly_times' in data: + entry['weekly_times'] = clean_times(data['weekly_times']) + if 'weekly_days' in data: + entry['weekly_days'] = clean_days(data['weekly_days'], 0, 6) + if 'monthly_days' in data: + entry['monthly_days'] = clean_days(data['monthly_days'], 1, 31) + if 'monthly_time' in data: + parse_hhmm(data['monthly_time']) + entry['monthly_time'] = str(data['monthly_time']).strip() + if 'once_at' in data: + entry['once_at'] = str(data['once_at'] or '').strip() + if entry['once_at']: + try: + parse_when(entry['once_at']) + except ValueError: + raise ValueError('One-shot date/time is not valid.') + + if not entry['title'] or not entry['message']: + raise ValueError('Title and message are required.') + mode = entry['mode'] + if mode == 'daily' and not entry['daily_times']: + raise ValueError('Daily mode needs at least one time (HH:MM).') + if mode == 'weekly' and (not entry['weekly_days'] or not entry['weekly_times']): + raise ValueError('Weekly mode needs days and at least one time.') + if mode == 'monthly' and (not entry['monthly_days'] or not entry['monthly_time']): + raise ValueError('Monthly mode needs days of month and a time.') + if mode == 'once' and not entry['once_at']: + raise ValueError('One-shot mode needs a date/time.') + + entry['next_run'] = compute_next_run(entry) + if entry.get('last_fired_for') == entry['next_run']: + entry['last_fired_for'] = '' + self._save(entries) + logger.info(f"ScheduledBroadcast: saved entry {entry['id']} " + f"enabled={entry['enabled']} next={entry['next_run']}") + return dict(entry) + + def delete_entry(self, entry_id): + with self._lock: + entries = self.list_entries() + kept = [e for e in entries if e.get('id') != entry_id] + if len(kept) == len(entries): + return False + self._save(kept) + logger.info(f'ScheduledBroadcast: deleted entry {entry_id}') + return True + + def set_enabled(self, entry_id, enabled): + """Flip enabled only; message + schedule settings are preserved.""" + with self._lock: + entries = self.list_entries() + entry = self._find(entries, entry_id) + if entry is None: + raise ValueError(f'Unknown scheduled notification: {entry_id!r}') + entry['enabled'] = bool(enabled) + entry['next_run'] = compute_next_run(entry) + if entry.get('last_fired_for') == entry['next_run']: + entry['last_fired_for'] = '' + self._save(entries) + return dict(entry) + + # ── scheduler tick (called from factory background thread) ───────── + + def check_and_fire(self, now=None): + """Send every due entry once. Returns list of fired entry summaries.""" + now_dt = now or datetime.now() + now_ts = now_dt.timestamp() + fired = [] + with self._lock: + entries = self.list_entries() + changed = False + for entry in entries: + if not entry.get('enabled'): + continue + next_run = entry.get('next_run') or compute_next_run(entry, now_dt) + if not next_run: + continue + if entry.get('next_run') != next_run: + entry['next_run'] = next_run + changed = True + if entry.get('last_fired_for') == next_run: + continue + try: + action_ts = parse_when(next_run).timestamp() + except ValueError: + continue + if now_ts < action_ts: + continue + if now_ts > action_ts + MISSED_WINDOW_SECONDS: + # Dashboard was down: roll forward, never fire late. + entry['last_fired_for'] = next_run + if entry['mode'] == 'once': + entry['enabled'] = False + entry['next_run'] = '' + else: + entry['next_run'] = compute_next_run(entry, now_dt) + changed = True + logger.warning( + f"ScheduledBroadcast: missed {entry['id']} for {next_run}, rolled forward") + continue + ok, detail = self._send(entry) + entry['last_fired_for'] = next_run + if entry['mode'] == 'once': + # One-shot fires exactly once, settings are kept for reuse. + entry['enabled'] = False + entry['next_run'] = '' + else: + anchor = datetime.fromtimestamp(action_ts) + timedelta(seconds=1) + entry['next_run'] = compute_next_run(entry, anchor) + changed = True + fired.append({'id': entry['id'], 'success': bool(ok), + 'detail': str(detail)[:300]}) + logger.info(f"ScheduledBroadcast: fired {entry['id']} " + f"for {next_run} ok={ok}") + if changed: + self._save(entries) + return fired + + def _send(self, entry): + try: + return self.admin.send_global_broadcast( + entry['title'], entry['message'], int(entry.get('duration') or 30)) + except Exception as e: + logger.error(f'ScheduledBroadcast send error: {e}') + return False, str(e) \ No newline at end of file diff --git a/app/utils/constants.py b/app/utils/constants.py index 9888c27..c225825 100644 --- a/app/utils/constants.py +++ b/app/utils/constants.py @@ -82,7 +82,6 @@ NAV_PAGES = [ ('/guilds', 'Guilds'), ('/buildings', 'Buildings'), ('/map', 'Map'), - ('/admin-experimental', 'Experimental'), ] NAV_GROUPS = [ @@ -105,7 +104,4 @@ NAV_GROUPS = [ ('/chat', 'Chat'), ('/map', 'Map'), ]), - ('System', [ - ('/admin-experimental', 'Experimental'), - ]), ] diff --git a/settings.yaml.example b/settings.yaml.example index 1857290..d4e81ce 100644 --- a/settings.yaml.example +++ b/settings.yaml.example @@ -52,6 +52,9 @@ director: # File Browser filebrowser: port: 18888 # File Browser service port + #allowed_roots: # Directories the file browser may access. + # - /srv # Empty/missing = defaults (/srv, /home/dune/.dune). + # - /home/dune/.dune # Firewall Security # Block external internet access to game server services that have no authentication. diff --git a/templates/account_detail.html b/templates/account_detail.html index dde089e..b848c00 100644 --- a/templates/account_detail.html +++ b/templates/account_detail.html @@ -57,10 +57,10 @@ {% for c in characters %} {{ c.player_name or 'Unknown' }} - {% if c.online_status %}{{ c.online_status }}{% else %}—{% endif %} + {% if c.online_status %}{{ c.online_status }}{% else %}-{% endif %} {{ c.id }} {{ c.map or 'N/A' }} - {% if c.faction_name %}{{ c.faction_name }}{% else %}—{% endif %} + {% if c.faction_name %}{{ c.faction_name }}{% else %}-{% endif %} {{ c.last_login_time.strftime('%Y-%m-%d %H:%M') if c.last_login_time else 'N/A' }} {{ c.transform_text or '' }} diff --git a/templates/accounts.html b/templates/accounts.html index 24d4d51..cc836a0 100644 --- a/templates/accounts.html +++ b/templates/accounts.html @@ -33,8 +33,8 @@ {% for a in accounts %} {{ a.funcom_id or a.platform_name or 'Unknown' }} - {{ a.character_name or '—'|safe }} - {% if a.online_status %}{{ a.online_status }}{% else %}—{% endif %} + {{ a.character_name or '-' }} + {% if a.online_status %}{{ a.online_status }}{% else %}-{% endif %} {{ a.user }} {{ a.platform_id or 'N/A' }} {{ a.player_count }} diff --git a/templates/admin_experimental.html b/templates/admin_experimental.html deleted file mode 100644 index 0b4e091..0000000 --- a/templates/admin_experimental.html +++ /dev/null @@ -1,1535 +0,0 @@ -{% extends "base.html" %} -{% block title %}Experimental - Dune Awakening Dashboard{% endblock %} -{% block content %} - -
-
-
⚠
-

Experimental Features — Proceed with Caution

-

This area contains untested, experimental tools that interact directly with your game server's internal systems (RabbitMQ, PostgreSQL, Battlegroup Director).

-

These tools can corrupt data, crash servers, or delete characters. Do not report bugs about this page. Always snapshot or backup your server first.

-
- - -
-
-
- - - - - - - -{% endblock %} diff --git a/templates/backup.html b/templates/backup.html index 846250a..5f87e2a 100644 --- a/templates/backup.html +++ b/templates/backup.html @@ -10,7 +10,7 @@
-
⚠ WIP — Use with caution
+
⚠ WIP - Use with caution
This feature is still experimental. Test on a non-production environment first. Keep offline backups of anything critical before using restore. @@ -23,7 +23,7 @@ Backups contain sensitive information including database contents, K8s secrets, and server configuration. Store backup files in a secure, offline location. Use a password to encrypt backups containing private data. Do not share backup files or expose them in insecure storage. - ⚠ If you set a password, never forget it — lost passwords cannot be recovered and the backup will be permanently unrecoverable. + ⚠ If you set a password, don't forget it - there's no way to recover it, and the backup will be locked for good.
@@ -299,7 +299,7 @@ {% if is_online %} -
Player is online — editing disabled. Log out first.
+
Player is online - editing is disabled. Log out first.
{% else %} {% endif %} -
Read-only. Balances reflect last game save — game server writes deltas on top of DB value.
+
Read-only. Balances are from the last game save - the game server applies its own changes on top of these values.
@@ -186,7 +186,7 @@ {{ s.track_type }}{{ s.xp_amount | format_number }}{{ s.level }} {% endfor %} {% if tech_knowledge is not none %} - Tech Knowledge Points{{ tech_knowledge | format_number }}— + Tech Knowledge Points{{ tech_knowledge | format_number }}- {% endif %} @@ -289,11 +289,11 @@

Inventory

{% if is_online %} -
Player is online — editing disabled. Log out first.
+
Player is online - editing is disabled. Log out first.
{% endif %}
- +
@@ -642,7 +642,7 @@
-
+
+
+
+ Custom Notification + +
+
+
+ Send a custom in-game broadcast to all connected players right now. + Uses the confirmed In-Game Broadcast (RabbitMQ heartbeats exchange). +
+
+ + +
+
+ + +
+
+ + + +
+
+
+ +
+
+ Scheduled Notifications + Loading... +
+
+
+ Schedule a custom message to display in-game at specific dates, times and intervals. + One-shot entries fire once, then switch off automatically (settings are kept). +
+
+
+

New scheduled notification

+ +
+ + +
+
+ + +
+
+ + + +
+
+
Times - pick a time, then Add:
+
+ + +
+
+
+ + + +
+ + + +
+
+
+ +
+ +
+
+
+ Graceful Shutdown / Restart + No active countdown +
+
+
+ Graceful actions warn players in-game first via the In-Game Broadcast, then run + battlegroup stop / restart. + Notices at 15m, 10m, 5m, 3m, 2m, 1m, 30s (10s each), 10s (5s), then a final notice at 1s. +
+
+ + + + + +
+
+
No active countdown.
+
+
+
+ +
+
+ Scheduled Restarts + Loading... +
+
+
+ Same in-game countdown as above, but the notices say e.g. + "Scheduled restart in 5 minutes (daily 05:00)." + The countdown starts 15 minutes before the restart time. +
+
+ + +
+
+
Times - pick a time, then Add:
+
+ + +
+
+
+ + + +
+ + + + + +
+
Enable / Disable / Clear keep your saved days and times.
+
Next restart: -
+
+
+ +
+ +
+
+
+ Battlegroup Control + Click "Refresh Status" to load +
+
+
+ + + + + +
+
+
Click "Refresh Status" to load battlegroup status...
+
+
+
+
Active Server IDs
@@ -126,6 +368,8 @@
+
+
World Partitions
@@ -165,10 +409,10 @@ {% if deploys_ok %}
Button Guide: - Restart — rolling restart of pods - Status — rollout status - Scale to 0 — stop all pods - Scale to 1 — start a pod + Restart - rolling restart of pods + Status - rollout status + Scale to 0 - stop all pods + Scale to 1 - start a pod
@@ -204,25 +448,6 @@ -
-
- Battlegroup Control - Click "Refresh Status" to load -
-
-
- - - - - -
-
-
Click "Refresh Status" to load battlegroup status...
-
-
-
-
Pod Status
@@ -233,6 +458,25 @@
+
+
+ Firewall Security + Loading... +
+
+
+ Security Recommendation: The following services are exposed to the internet without authentication. + Block them so only localhost (the dashboard via SSH tunnel) can reach them. +
+
+ + +
+
+ +
Funcom Service Auth Token [WIP] @@ -240,11 +484,11 @@
- ⚠ WIP — Use with caution. This feature is still experimental. + ⚠ WIP - Use with caution. This feature is still experimental. Only use if you understand the risks. Backup your *.yaml files first.
- ServiceAuthToken — Used by the game server to authenticate with Funcom's live services. + ServiceAuthToken - Used by the game server to authenticate with Funcom's live services. If this token is regenerated by Funcom, paste the new JWT below and save. All consuming pods must be restarted afterward.
@@ -263,12 +507,12 @@
- 🐛 Debug Logging + Debug Logging Loading...
- 📝 Verbose Logging: Enable to log detailed information about SSH commands, API requests, database queries, and service connections. + Verbose Logging: Enable to log detailed information about SSH commands, API requests, database queries, and service connections. Logs are written to logs/debug.log. Sanitizes sensitive data (passwords, tokens) automatically.
@@ -281,9 +525,11 @@
+
+
- 📋 Audit Log Viewer + Audit Log Viewer Loading...
@@ -324,24 +570,6 @@
-
-
- Firewall Security - Loading... -
-
-
- Security Recommendation: The following services are exposed to the internet without authentication. - Block them so only localhost (the dashboard via SSH tunnel) can reach them. -
-
- - -
-
- {% endif %} {% endblock %} @@ -558,7 +786,7 @@ async function bgAction(action, btn) { const confirmMsgs = { 'stop': 'Stop the battlegroup? This will disconnect all players.', 'restart': 'Restart the battlegroup? This will disconnect all players.', - 'update': 'Update the battlegroup? This will download new images and restart. This may take several minutes.' + 'update': 'Update the battlegroup? This will download new images and restart. This may take several minutes. The server must be stopped first - update is blocked while game pods are running.' }; if (confirmMsgs[action] && !confirm(confirmMsgs[action])) return; if ((action === 'stop' || action === 'restart') && !confirm('Are you sure? This will affect live players.')) return; @@ -611,6 +839,539 @@ document.getElementById('bg-btn-restart')?.addEventListener('click', function() document.getElementById('bg-btn-update')?.addEventListener('click', function() { bgAction('update', this); }); document.getElementById('bg-btn-refresh')?.addEventListener('click', bgRefreshStatus); +// Graceful lifecycle (countdown + scheduled restarts) +function lcSetBusy(busy) { + for (const id of ['lc-btn-start', 'lc-btn-shutdown', 'lc-btn-restart']) { + const btn = document.getElementById(id); + if (btn) btn.disabled = busy; + } +} + +function lcRenderStatus(data) { + const pre = document.getElementById('lc-status-text'); + const indicator = document.getElementById('lc-status-indicator'); + const cancelBtn = document.getElementById('lc-btn-cancel'); + if (!data.active) { + pre.textContent = 'No active countdown.'; + indicator.textContent = 'No active countdown'; + indicator.style.color = 'var(--text-muted)'; + if (cancelBtn) cancelBtn.disabled = true; + return; + } + const actionAt = data.action_at ? new Date(data.action_at * 1000).toLocaleString() : 'unknown'; + const lines = [ + `Active: ${data.kind} (${data.reason || 'manual'}${data.context ? ' - ' + data.context : ''})`, + `Status: ${data.status}`, + `Action at: ${actionAt}`, + '', + 'Notices sent:', + ]; + for (const s of (data.sent || [])) { + lines.push(` - ${s.mark}: ${s.ok ? 'sent' : 'FAILED - ' + (s.detail || 'error')}`); + } + if (data.error) lines.push('', 'Error: ' + data.error); + pre.textContent = lines.join('\n'); + indicator.textContent = `${data.kind} countdown: ${data.status}`; + indicator.style.color = 'var(--warn)'; + if (cancelBtn) cancelBtn.disabled = (data.status === 'executing'); +} + +async function lcRefresh() { + try { + const resp = await fetch('/server/lifecycle/status'); + const data = await resp.json(); + if (data.success === false && data.error) { + document.getElementById('lc-status-text').textContent = 'Error: ' + data.error; + return; + } + lcRenderStatus(data); + } catch (e) { + document.getElementById('lc-status-text').textContent = 'Error: ' + e.message; + } +} + +async function lcAction(kind) { + const msgs = { + 'start': 'Start the battlegroup now? This is immediate (no countdown).', + 'shutdown': 'Graceful shutdown? Players get in-game warnings at 15m, 10m, 5m, 3m, 2m, 1m, 30s, 10s, then shutdown.', + 'restart': 'Graceful restart? Players get in-game warnings at 15m, 10m, 5m, 3m, 2m, 1m, 30s, 10s, then restart.' + }; + if (msgs[kind] && !confirm(msgs[kind])) return; + if ((kind === 'shutdown' || kind === 'restart') && !confirm('Are you sure? This will affect live players.')) return; + lcSetBusy(true); + try { + const url = kind === 'start' ? '/server/lifecycle/start' : `/server/lifecycle/${kind}`; + const resp = await csrfFetch(url, { method: 'POST' }); + const data = await resp.json(); + if (!data.success) { + document.getElementById('lc-status-text').textContent = 'Failed: ' + (data.output || data.error || 'unknown error'); + } + await lcRefresh(); + } catch (e) { + document.getElementById('lc-status-text').textContent = 'Error: ' + e.message; + } + lcSetBusy(false); +} + +async function lcCancel() { + if (!confirm('Cancel the active countdown? No further warnings will be sent.')) return; + try { + const resp = await csrfFetch('/server/lifecycle/cancel', { method: 'POST' }); + const data = await resp.json(); + if (!data.success) alert('Cancel failed: ' + (data.error || data.output || 'unknown')); + await lcRefresh(); + } catch (e) { alert('Cancel error: ' + e.message); } +} + +// ── Shared picker helpers (no typing: wheels, calendars, click-to-select) ── +function escapeHtml(s) { + return String(s == null ? '' : s) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function renderTimeChips(containerId, times, onRemove) { + const c = document.getElementById(containerId); + c.innerHTML = ''; + if (!times.length) { + c.innerHTML = 'No times yet - pick one above and hit Add.'; + return; + } + times.forEach(t => { + const s = document.createElement('span'); + s.textContent = t + ' ×'; + s.title = 'Click to remove'; + s.style.cssText = 'padding:4px 10px;background:var(--primary);color:#fff;border-radius:12px;font-size:12px;cursor:pointer;'; + s.onclick = () => onRemove(t); + c.appendChild(s); + }); +} + +function addPickedTime(inputId, arr, rerender) { + const raw = document.getElementById(inputId).value; + if (!raw) return; + const t = raw.slice(0, 5); + if (!/^\d{2}:\d{2}$/.test(t)) return; + if (!arr.includes(t)) { arr.push(t); arr.sort(); } + rerender(); +} + +function renderDayGrid(containerId, selected, onToggle) { + const g = document.getElementById(containerId); + g.innerHTML = ''; + for (let d = 1; d <= 31; d++) { + const b = document.createElement('button'); + b.textContent = d; + b.type = 'button'; + const on = selected.includes(d); + b.style.cssText = 'padding:6px 0;border-radius:6px;cursor:pointer;font-size:12px;' + + (on ? 'background:var(--primary);color:#fff;border:1px solid var(--primary);font-weight:700;' + : 'background:var(--bg);color:var(--text);border:1px solid var(--border);'); + b.onclick = () => onToggle(d); + g.appendChild(b); + } +} + +// ── Custom notification (send now) ── +async function bcSend() { + const btn = document.getElementById('bc-send-btn'); + const msg = document.getElementById('bc-msg'); + const status = document.getElementById('bc-status'); + const title = document.getElementById('bc-title').value.trim(); + const message = document.getElementById('bc-message').value.trim(); + const duration = parseInt(document.getElementById('bc-duration').value) || 30; + if (!title || !message) { + msg.textContent = 'Title and message are required.'; + msg.style.color = 'var(--danger)'; + return; + } + btn.disabled = true; + btn.textContent = 'Sending...'; + msg.textContent = 'Sending...'; + msg.style.color = 'var(--text-muted)'; + try { + const resp = await csrfFetch('/server/broadcast', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title, message, duration }) + }); + const data = await resp.json(); + if (data.success) { + msg.textContent = 'Broadcast sent!'; + msg.style.color = 'var(--success)'; + status.textContent = 'Last sent just now'; + } else { + msg.textContent = 'Error: ' + (data.output || data.error || 'unknown'); + msg.style.color = 'var(--danger)'; + } + } catch (e) { + msg.textContent = 'Error: ' + e.message; + msg.style.color = 'var(--danger)'; + } + btn.disabled = false; + btn.textContent = 'Send Broadcast'; +} + +// ── Restart schedule (picker-driven) ── +const lcSched = { enabled: false, mode: 'daily', daily_times: [], weekly_days: [], + weekly_times: [], monthly_days: [], monthly_time: '05:00', once_at: '', next_run: '' }; + +function lcSchedModeChanged() { + const mode = document.getElementById('lc-sched-mode').value; + lcSched.mode = mode; + for (const m of ['daily', 'weekly', 'monthly', 'once']) { + document.getElementById('lc-sched-' + m).style.display = (m === mode) ? '' : 'none'; + } +} + +function lcRenderPickers() { + renderTimeChips('lc-daily-chips', lcSched.daily_times, + (t) => { lcSched.daily_times = lcSched.daily_times.filter(x => x !== t); lcRenderPickers(); }); + renderTimeChips('lc-weekly-chips', lcSched.weekly_times, + (t) => { lcSched.weekly_times = lcSched.weekly_times.filter(x => x !== t); lcRenderPickers(); }); + renderDayGrid('lc-monthly-grid', lcSched.monthly_days, + (d) => { + const i = lcSched.monthly_days.indexOf(d); + if (i >= 0) lcSched.monthly_days.splice(i, 1); + else { lcSched.monthly_days.push(d); lcSched.monthly_days.sort((a, b) => a - b); } + lcRenderPickers(); + }); +} + +function lcApplyToForm(s) { + Object.assign(lcSched, { + enabled: !!s.enabled, mode: s.mode || 'daily', + daily_times: [...(s.daily_times || [])], weekly_days: [...(s.weekly_days || [])], + weekly_times: [...(s.weekly_times || [])], monthly_days: [...(s.monthly_days || [])], + monthly_time: s.monthly_time || '05:00', once_at: s.once_at || '', next_run: s.next_run || '', + }); + document.getElementById('lc-sched-enabled').checked = lcSched.enabled; + document.getElementById('lc-sched-mode').value = lcSched.mode; + document.getElementById('lc-monthly-time').value = lcSched.monthly_time; + if (lcSched.once_at) { + try { document.getElementById('lc-once-at').value = lcSched.once_at.slice(0, 16); } catch (e) { /* ignore */ } + } else { + document.getElementById('lc-once-at').value = ''; + } + const weekdays = new Set(lcSched.weekly_days.map(String)); + document.querySelectorAll('.lc-weekday').forEach(cb => { cb.checked = weekdays.has(cb.value); }); + document.getElementById('lc-sched-next').textContent = lcSched.next_run ? new Date(lcSched.next_run).toLocaleString() : '-'; + document.getElementById('lc-sched-indicator').textContent = lcSched.enabled ? `Enabled (${lcSched.mode})` : 'Disabled'; + lcSchedModeChanged(); + lcRenderPickers(); +} + +function lcCollectFromForm() { + lcSched.enabled = document.getElementById('lc-sched-enabled').checked; + lcSched.mode = document.getElementById('lc-sched-mode').value; + lcSched.weekly_days = Array.from(document.querySelectorAll('.lc-weekday:checked')).map(cb => Number(cb.value)); + lcSched.monthly_time = document.getElementById('lc-monthly-time').value || '05:00'; + // Send the local calendar value as-is (no UTC conversion) so the + // server schedules it in server-local time. + lcSched.once_at = document.getElementById('lc-once-at').value || ''; + return { ...lcSched }; +} + +async function lcLoadSchedule() { + const msg = document.getElementById('lc-sched-message'); + try { + const resp = await fetch('/server/lifecycle/schedule'); + const data = await resp.json(); + if (!data.success) { msg.textContent = 'Failed to load schedule.'; return; } + lcApplyToForm(data.schedule || {}); + } catch (e) { msg.textContent = 'Error: ' + e.message; } +} + +async function lcSaveSchedule() { + const msg = document.getElementById('lc-sched-message'); + msg.textContent = 'Saving...'; + msg.style.color = 'var(--text-muted)'; + try { + const resp = await csrfFetch('/server/lifecycle/schedule', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(lcCollectFromForm()) + }); + const data = await resp.json(); + if (data.success) { + lcApplyToForm(data.schedule); + msg.textContent = 'Schedule saved.'; + msg.style.color = 'var(--success)'; + } else { + msg.textContent = 'Error: ' + (data.error || 'unknown'); + msg.style.color = 'var(--danger)'; + } + } catch (e) { + msg.textContent = 'Error: ' + e.message; + msg.style.color = 'var(--danger)'; + } +} + +async function lcSetEnabled(on) { + const msg = document.getElementById('lc-sched-message'); + try { + const resp = await csrfFetch('/server/lifecycle/schedule/enabled', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ enabled: on }) + }); + const data = await resp.json(); + if (data.success) { + lcApplyToForm(data.schedule); + msg.textContent = on ? 'Schedule enabled.' : 'Schedule disabled - settings kept.'; + msg.style.color = 'var(--success)'; + } else { + msg.textContent = 'Error: ' + (data.error || 'unknown'); + msg.style.color = 'var(--danger)'; + } + } catch (e) { + msg.textContent = 'Error: ' + e.message; + msg.style.color = 'var(--danger)'; + } +} + +async function lcClearSchedule() { + if (!confirm('Clear the restart schedule? Days and times are kept, but the armed date and pending run are removed and the schedule is disabled.')) return; + const msg = document.getElementById('lc-sched-message'); + try { + const resp = await csrfFetch('/server/lifecycle/schedule/clear', { method: 'POST' }); + const data = await resp.json(); + if (data.success) { + lcApplyToForm(data.schedule); + msg.textContent = 'Schedule cleared - days and times kept.'; + msg.style.color = 'var(--success)'; + } else { + msg.textContent = 'Error: ' + (data.error || 'unknown'); + msg.style.color = 'var(--danger)'; + } + } catch (e) { + msg.textContent = 'Error: ' + e.message; + msg.style.color = 'var(--danger)'; + } +} + +// ── Scheduled notifications ── +let bnEntries = []; +const bnForm = { id: '', daily_times: [], weekly_times: [], monthly_days: [] }; +const BN_DAY_NAMES = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; + +function bnModeChanged() { + const mode = document.getElementById('bn-mode').value; + for (const m of ['daily', 'weekly', 'monthly', 'once']) { + document.getElementById('bn-sched-' + m).style.display = (m === mode) ? '' : 'none'; + } +} + +function bnRenderPickers() { + renderTimeChips('bn-daily-chips', bnForm.daily_times, + (t) => { bnForm.daily_times = bnForm.daily_times.filter(x => x !== t); bnRenderPickers(); }); + renderTimeChips('bn-weekly-chips', bnForm.weekly_times, + (t) => { bnForm.weekly_times = bnForm.weekly_times.filter(x => x !== t); bnRenderPickers(); }); + renderDayGrid('bn-monthly-grid', bnForm.monthly_days, + (d) => { + const i = bnForm.monthly_days.indexOf(d); + if (i >= 0) bnForm.monthly_days.splice(i, 1); + else { bnForm.monthly_days.push(d); bnForm.monthly_days.sort((a, b) => a - b); } + bnRenderPickers(); + }); +} + +function bnDescribe(e) { + if (e.mode === 'once') return 'one-shot ' + (e.once_at ? new Date(e.once_at).toLocaleString() : '(unscheduled)'); + if (e.mode === 'daily') return 'daily ' + (e.daily_times || []).join(', '); + if (e.mode === 'weekly') { + const days = (e.weekly_days || []).map(d => BN_DAY_NAMES[d] || d).join(', '); + return `weekly ${days} ${(e.weekly_times || []).join(', ')}`; + } + if (e.mode === 'monthly') return `monthly day ${(e.monthly_days || []).join(', ')} ${e.monthly_time || ''}`; + return e.mode; +} + +function bnRenderList() { + const list = document.getElementById('bn-list'); + const indicator = document.getElementById('bn-indicator'); + const active = bnEntries.filter(e => e.enabled).length; + indicator.textContent = bnEntries.length ? `${active}/${bnEntries.length} enabled` : 'None yet'; + if (!bnEntries.length) { + list.innerHTML = '

No scheduled notifications yet - use the form below.

'; + return; + } + list.innerHTML = ''; + bnEntries.forEach(e => { + const row = document.createElement('div'); + row.style.cssText = 'display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:8px 10px;margin-bottom:6px;background:var(--bg);border:1px solid var(--border);border-radius:6px;'; + const next = e.next_run ? new Date(e.next_run).toLocaleString() : '-'; + row.innerHTML = + `${escapeHtml(e.title)}` + + `${escapeHtml(bnDescribe(e))}` + + `next: ${next}` + + `${e.enabled ? 'ON' : 'OFF'}`; + const mkBtn = (label, bg, fn) => { + const b = document.createElement('button'); + b.textContent = label; + b.style.cssText = `padding:4px 12px;background:${bg};color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;`; + b.onclick = fn; + return b; + }; + row.appendChild(mkBtn('Edit', 'var(--primary)', () => bnEdit(e.id))); + row.appendChild(mkBtn(e.enabled ? 'Disable' : 'Enable', e.enabled ? '#e67e22' : '#27ae60', () => bnToggle(e.id, !e.enabled))); + row.appendChild(mkBtn('Delete', '#e74c3c', () => bnDelete(e.id))); + list.appendChild(row); + }); +} + +async function bnLoad() { + const msg = document.getElementById('bn-msg'); + try { + const resp = await fetch('/server/broadcasts/schedule'); + const data = await resp.json(); + if (!data.success) { msg.textContent = 'Failed to load.'; return; } + bnEntries = data.entries || []; + bnRenderList(); + } catch (e) { msg.textContent = 'Error: ' + e.message; } +} + +function bnResetForm() { + document.getElementById('bn-id').value = ''; + document.getElementById('bn-form-title').textContent = 'New scheduled notification'; + document.getElementById('bn-title').value = 'Server Notice'; + document.getElementById('bn-message').value = ''; + document.getElementById('bn-duration').value = 30; + document.getElementById('bn-enabled').checked = true; + document.getElementById('bn-mode').value = 'daily'; + document.getElementById('bn-once-at').value = ''; + document.getElementById('bn-monthly-time').value = '12:00'; + bnForm.id = ''; + bnForm.daily_times = ['12:00']; + bnForm.weekly_times = ['12:00']; + bnForm.monthly_days = [1]; + const weekdays = new Set(['6']); + document.querySelectorAll('.bn-weekday').forEach(cb => { cb.checked = weekdays.has(cb.value); }); + bnModeChanged(); + bnRenderPickers(); +} + +function bnEdit(id) { + const e = bnEntries.find(x => x.id === id); + if (!e) return; + document.getElementById('bn-id').value = e.id; + document.getElementById('bn-form-title').textContent = 'Edit scheduled notification'; + document.getElementById('bn-title').value = e.title || ''; + document.getElementById('bn-message').value = e.message || ''; + document.getElementById('bn-duration').value = e.duration || 30; + document.getElementById('bn-enabled').checked = !!e.enabled; + document.getElementById('bn-mode').value = e.mode || 'daily'; + document.getElementById('bn-monthly-time').value = e.monthly_time || '12:00'; + try { document.getElementById('bn-once-at').value = (e.once_at || '').slice(0, 16); } + catch (err) { document.getElementById('bn-once-at').value = ''; } + bnForm.id = e.id; + bnForm.daily_times = [...(e.daily_times || [])]; + bnForm.weekly_times = [...(e.weekly_times || [])]; + bnForm.monthly_days = [...(e.monthly_days || [])]; + const weekdays = new Set((e.weekly_days || []).map(String)); + document.querySelectorAll('.bn-weekday').forEach(cb => { cb.checked = weekdays.has(cb.value); }); + bnModeChanged(); + bnRenderPickers(); + document.getElementById('bn-form-title').scrollIntoView({ block: 'nearest' }); +} + +function bnCollect() { + return { + id: document.getElementById('bn-id').value || undefined, + title: document.getElementById('bn-title').value.trim(), + message: document.getElementById('bn-message').value.trim(), + duration: parseInt(document.getElementById('bn-duration').value) || 30, + enabled: document.getElementById('bn-enabled').checked, + mode: document.getElementById('bn-mode').value, + daily_times: [...bnForm.daily_times], + weekly_times: [...bnForm.weekly_times], + weekly_days: Array.from(document.querySelectorAll('.bn-weekday:checked')).map(cb => Number(cb.value)), + monthly_days: [...bnForm.monthly_days], + monthly_time: document.getElementById('bn-monthly-time').value || '12:00', + once_at: document.getElementById('bn-once-at').value || '', + }; +} + +async function bnSave() { + const msg = document.getElementById('bn-msg'); + const body = bnCollect(); + if (!body.title || !body.message) { + msg.textContent = 'Title and message are required.'; + msg.style.color = 'var(--danger)'; + return; + } + msg.textContent = 'Saving...'; + msg.style.color = 'var(--text-muted)'; + try { + const resp = await csrfFetch('/server/broadcasts/schedule', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }); + const data = await resp.json(); + if (data.success) { + msg.textContent = 'Saved.'; + msg.style.color = 'var(--success)'; + await bnLoad(); + bnResetForm(); + } else { + msg.textContent = 'Error: ' + (data.error || 'unknown'); + msg.style.color = 'var(--danger)'; + } + } catch (e) { + msg.textContent = 'Error: ' + e.message; + msg.style.color = 'var(--danger)'; + } +} + +async function bnToggle(id, on) { + try { + const resp = await csrfFetch('/server/broadcasts/schedule/enabled', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ id, enabled: on }) + }); + const data = await resp.json(); + if (!data.success) alert('Failed: ' + (data.error || 'unknown')); + await bnLoad(); + } catch (e) { alert('Error: ' + e.message); } +} + +async function bnDelete(id) { + if (!confirm('Delete this scheduled notification?')) return; + try { + const resp = await csrfFetch('/server/broadcasts/schedule/delete', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ id }) + }); + const data = await resp.json(); + if (!data.success) alert('Delete failed.'); + await bnLoad(); + } catch (e) { alert('Error: ' + e.message); } +} + +document.getElementById('lc-btn-start')?.addEventListener('click', () => lcAction('start')); +document.getElementById('lc-btn-shutdown')?.addEventListener('click', () => lcAction('shutdown')); +document.getElementById('lc-btn-restart')?.addEventListener('click', () => lcAction('restart')); +document.getElementById('lc-btn-cancel')?.addEventListener('click', lcCancel); +document.getElementById('lc-btn-refresh')?.addEventListener('click', lcRefresh); +document.getElementById('bc-send-btn')?.addEventListener('click', bcSend); +document.getElementById('lc-sched-mode')?.addEventListener('change', lcSchedModeChanged); +document.getElementById('lc-sched-save')?.addEventListener('click', lcSaveSchedule); +document.getElementById('lc-sched-enable')?.addEventListener('click', () => lcSetEnabled(true)); +document.getElementById('lc-sched-disable')?.addEventListener('click', () => lcSetEnabled(false)); +document.getElementById('lc-sched-clear')?.addEventListener('click', lcClearSchedule); +document.getElementById('lc-daily-add')?.addEventListener('click', () => addPickedTime('lc-daily-time-pick', lcSched.daily_times, lcRenderPickers)); +document.getElementById('lc-weekly-add')?.addEventListener('click', () => addPickedTime('lc-weekly-time-pick', lcSched.weekly_times, lcRenderPickers)); +document.getElementById('bn-mode')?.addEventListener('change', bnModeChanged); +document.getElementById('bn-save')?.addEventListener('click', bnSave); +document.getElementById('bn-reset')?.addEventListener('click', bnResetForm); +document.getElementById('bn-daily-add')?.addEventListener('click', () => addPickedTime('bn-daily-time-pick', bnForm.daily_times, bnRenderPickers)); +document.getElementById('bn-weekly-add')?.addEventListener('click', () => addPickedTime('bn-weekly-time-pick', bnForm.weekly_times, bnRenderPickers)); +lcRefresh(); +lcLoadSchedule(); +bnResetForm(); +bnLoad(); +setInterval(lcRefresh, 15000); + // Firewall Security async function loadFwStatus() { const indicator = document.getElementById('fw-status-indicator'); @@ -706,7 +1467,7 @@ async function loadAuditLogs(action = '', user = '', severity = '', limit = 100, const data = await resp.json(); if (!data.success) { - tbody.innerHTML = '
'; + tbody.innerHTML = ''; return; } @@ -726,22 +1487,22 @@ async function loadAuditLogs(action = '', user = '', severity = '', limit = 100, document.getElementById('audit-warning-count').textContent = warningCount; document.getElementById('audit-error-count').textContent = errorCount; - // Render table + // Render table (all server data escaped - never raw innerHTML) tbody.innerHTML = logs.map(log => { const details = log.details ? JSON.stringify(log.details) : '-'; const severityColor = log.severity === 'error' ? 'color:#e74c3c;' : (log.severity === 'warning' ? 'color:#f39c12;' : 'color:#3498db;'); const timestamp = log.timestamp ? log.timestamp.replace('T', ' ').substring(0, 19) : '-'; return '' + - '' + - '' + - '' + - '' + - '' + + '' + + '' + + '' + + '' + + '' + ''; }).join(''); } catch (e) { - tbody.innerHTML = ''; + tbody.innerHTML = ''; } } diff --git a/templates/shell.html b/templates/shell.html index 414625b..227f4a1 100644 --- a/templates/shell.html +++ b/templates/shell.html @@ -72,7 +72,7 @@ - - + + diff --git a/tests/test_battlegroup_update_guard.py b/tests/test_battlegroup_update_guard.py new file mode 100644 index 0000000..e2c0291 --- /dev/null +++ b/tests/test_battlegroup_update_guard.py @@ -0,0 +1,50 @@ +"""Tests for the battlegroup update guard (block while game pods run).""" + +from app.services.k8s import K8sService + +NS = 'funcom-seabass-sh-b17a5f036d1f7882-ccdijf' + + +class FakeSSH: + def __init__(self, out='', rc=0): + self.out = out + self.rc = rc + self.commands = [] + + def run(self, command, timeout=30): + self.commands.append(command) + return self.out, '', self.rc + + +def make_k8s(out='', rc=0): + return K8sService(ssh_service=FakeSSH(out, rc), namespace=NS) + + +class TestRunningGamePods: + def test_detects_running_game_pods(self): + out = ( + f'sh-b17a5f036d1f7882-ccdijf-sg-overmap-pod-2 Running\n' + f'sh-b17a5f036d1f7882-ccdijf-sg-survival-1-pod-1 Running\n' + f'sh-b17a5f036d1f7882-ccdijf-bgd-deploy-xxx Running\n' + f'sh-b17a5f036d1f7882-ccdijf-mq-game-sts-0 Running\n' + ) + running = make_k8s(out).get_running_game_pods() + # Only sg-*-pod-* count as game servers; infra pods do not block. + assert running == [ + 'sh-b17a5f036d1f7882-ccdijf-sg-overmap-pod-2', + 'sh-b17a5f036d1f7882-ccdijf-sg-survival-1-pod-1', + ] + + def test_empty_when_no_game_pods_running(self): + out = ( + f'sh-b17a5f036d1f7882-ccdijf-bgd-deploy-xxx Running\n' + f'sh-b17a5f036d1f7882-ccdijf-sg-overmap-pod-2 Completed\n' + f'sh-b17a5f036d1f7882-ccdijf-mq-game-sts-0 Running\n' + ) + assert make_k8s(out).get_running_game_pods() == [] + + def test_empty_when_no_pods(self): + assert make_k8s('').get_running_game_pods() == [] + + def test_none_when_status_unknown(self): + assert make_k8s('', rc=1).get_running_game_pods() is None diff --git a/tests/test_lifecycle.py b/tests/test_lifecycle.py new file mode 100644 index 0000000..a5b3950 --- /dev/null +++ b/tests/test_lifecycle.py @@ -0,0 +1,240 @@ +"""Tests for graceful shutdown/restart lifecycle service.""" + +import time +from datetime import datetime, timedelta + +import pytest + +from app.services.lifecycle import ( + COUNTDOWN_MARKS, + FINAL_DURATION, + LifecycleService, +) + + +class FakeSSH: + def __init__(self): + self.commands = [] + + def run(self, command, timeout=30): + self.commands.append(command) + return ('ok', '', 0) + + +class FakeAdmin: + def __init__(self): + self.broadcasts = [] + + def send_global_broadcast(self, title, message, duration=30): + self.broadcasts.append((title, message, duration)) + return True, 'sent' + + +def make_service(tmp_path): + ssh = FakeSSH() + admin = FakeAdmin() + svc = LifecycleService( + ssh, admin, + {'kubernetes': {'battlegroup_script': '/home/dune/.dune/bin/battlegroup'}}, + state_dir=str(tmp_path), + ) + return svc, ssh, admin + + +class TestCountdownTable: + def test_marks_match_spec(self): + """15m..30s last 10s, 10s lasts 5s, final lasts 10s.""" + assert [(s, d) for s, _, d in COUNTDOWN_MARKS] == [ + (900, 10), (600, 10), (300, 10), (180, 10), + (120, 10), (60, 10), (30, 10), (10, 5), + ] + assert FINAL_DURATION == 10 + + def test_manual_messages(self): + title, msg = LifecycleService._message_for( + 'restart', '5 minutes', 10, False, '', final=False) + assert 'restart' in title.lower() + assert '5 minutes' in msg + title, msg = LifecycleService._message_for( + 'shutdown', '30 seconds', 10, False, '', final=False) + assert 'shut' in msg.lower() + + def test_scheduled_messages_mention_schedule(self): + title, msg = LifecycleService._message_for( + 'restart', '5 minutes', 10, True, 'daily 05:00', final=False) + assert 'Scheduled' in title + assert 'daily 05:00' in msg + + +class TestActiveJob: + def test_start_and_cancel(self, tmp_path): + svc, _, _ = make_service(tmp_path) + try: + result = svc.start_restart(reason='manual') + assert result['success'] + assert svc.status()['active'] is True + assert svc.status()['kind'] == 'restart' + # Second job must be rejected while one is active. + again = svc.start_shutdown() + assert not again['success'] + finally: + cancelled = svc.cancel() + assert cancelled['success'] + assert svc.status()['active'] is False + + def test_cancel_without_active(self, tmp_path): + svc, _, _ = make_service(tmp_path) + assert not svc.cancel()['success'] + + def test_first_notice_sent_immediately(self, tmp_path): + """The 15-minute notice is due at job start: it must be sent, not skipped.""" + svc, _, admin = make_service(tmp_path) + try: + assert svc.start_restart(reason='manual')['success'] + deadline = time.time() + 10 + while time.time() < deadline and not admin.broadcasts: + time.sleep(0.2) + assert admin.broadcasts, 'expected the 15-minute notice right after start' + title, message, duration = admin.broadcasts[0] + assert '15 minutes' in message and duration == 10 + finally: + svc.cancel() + + def test_cancel_sends_ingame_notice(self, tmp_path): + svc, _, admin = make_service(tmp_path) + assert svc.start_shutdown(reason='manual')['success'] + deadline = time.time() + 10 + while time.time() < deadline and not admin.broadcasts: + time.sleep(0.2) + result = svc.cancel() + assert result['success'] + assert result['notice_sent'] is True + assert any('called off' in msg.lower() for _, msg, _ in admin.broadcasts) + + def test_short_countdown_runs_to_execute(self, tmp_path): + """12s countdown: stale marks skipped, late marks sent, action executed.""" + import time as _time + svc, ssh, admin = make_service(tmp_path) + action_at = _time.time() + 12 + assert svc.start_restart_at(action_at, reason='manual')['success'] + deadline = _time.time() + 40 + while _time.time() < deadline and svc.status().get('active', False): + _time.sleep(0.5) + assert not svc.status().get('active', False) + assert any('battlegroup' in cmd and 'restart' in cmd for cmd in ssh.commands) + assert any('restarting now' in msg.lower() for _, msg, _ in admin.broadcasts) + + +class TestScheduleCalc: + def test_daily_next_run(self, tmp_path): + svc, _, _ = make_service(tmp_path) + now = datetime(2026, 9, 21, 4, 0, 0) # Monday + cfg = {'mode': 'daily', 'daily_times': ['05:00']} + assert svc.compute_next_run(cfg, now) == '2026-09-21T05:00:00' + + def test_daily_rolls_to_tomorrow(self, tmp_path): + svc, _, _ = make_service(tmp_path) + now = datetime(2026, 9, 21, 6, 0, 0) + cfg = {'mode': 'daily', 'daily_times': ['05:00']} + assert svc.compute_next_run(cfg, now) == '2026-09-22T05:00:00' + + def test_weekly_next_run(self, tmp_path): + svc, _, _ = make_service(tmp_path) + now = datetime(2026, 9, 21, 4, 0, 0) # Monday (weekday 0) + cfg = {'mode': 'weekly', 'weekly_days': [6], 'weekly_times': ['05:00']} + nxt = datetime.fromisoformat(svc.compute_next_run(cfg, now)) + assert nxt.weekday() == 6 + assert (nxt.hour, nxt.minute) == (5, 0) + + def test_monthly_next_run(self, tmp_path): + svc, _, _ = make_service(tmp_path) + now = datetime(2026, 9, 21, 6, 0, 0) + cfg = {'mode': 'monthly', 'monthly_days': [1], 'monthly_time': '05:00'} + nxt = datetime.fromisoformat(svc.compute_next_run(cfg, now)) + assert (nxt.month, nxt.day, nxt.hour) == (10, 1, 5) + + def test_once_future_and_past(self, tmp_path): + svc, _, _ = make_service(tmp_path) + now = datetime(2026, 9, 21, 4, 0, 0) + future = (now + timedelta(hours=2)).isoformat() + assert svc.compute_next_run({'mode': 'once', 'once_at': future}, now) == future + past = (now - timedelta(hours=1)).isoformat() + assert svc.compute_next_run({'mode': 'once', 'once_at': past}, now) == '' + + def test_update_schedule_rejects_bad_mode(self, tmp_path): + svc, _, _ = make_service(tmp_path) + with pytest.raises(ValueError): + svc.update_schedule({'mode': 'yearly'}) + + def test_disable_preserves_settings(self, tmp_path): + svc, _, _ = make_service(tmp_path) + svc.update_schedule({'enabled': True, 'mode': 'daily', + 'daily_times': ['06:00']}) + cfg = svc.set_enabled(False) + assert cfg['enabled'] is False + assert cfg['daily_times'] == ['06:00'] + assert cfg['mode'] == 'daily' + cfg = svc.set_enabled(True) + assert cfg['enabled'] is True + assert cfg['daily_times'] == ['06:00'] + + def test_clear_disarms_but_keeps_settings(self, tmp_path): + svc, _, _ = make_service(tmp_path) + svc.update_schedule({'enabled': True, 'mode': 'weekly', + 'weekly_days': [1, 3], + 'weekly_times': ['07:00']}) + cfg = svc.clear_schedule() + assert cfg['enabled'] is False + assert cfg['next_run'] == '' + assert cfg['mode'] == 'weekly' + assert cfg['weekly_days'] == [1, 3] + assert cfg['weekly_times'] == ['07:00'] + + def test_once_accepts_utc_and_local_strings(self, tmp_path): + svc, _, _ = make_service(tmp_path) + now = datetime.now().replace(second=0, microsecond=0) + future_local = (now + timedelta(hours=2)).replace(microsecond=0) + assert svc.compute_next_run( + {'mode': 'once', 'once_at': future_local.isoformat()}, now) != '' + future_utc = future_local.strftime('%Y-%m-%dT%H:%M:%SZ') + assert svc.compute_next_run( + {'mode': 'once', 'once_at': future_utc}, now) != '' + + +class TestSchedulerFire: + def test_fire_inside_window_starts_countdown(self, tmp_path): + svc, _, _ = make_service(tmp_path) + try: + action_at = (datetime.now() + timedelta(minutes=10)).replace( + second=0, microsecond=0) + svc.update_schedule({ + 'enabled': True, 'mode': 'once', + 'once_at': action_at.isoformat(), + }) + result = svc.check_and_fire() + assert result and result['success'] + assert svc.status()['active'] is True + assert svc.status()['reason'] == 'scheduled' + # Second tick must not double-fire the same occurrence. + assert svc.check_and_fire() is None + finally: + svc.cancel() + + def test_no_fire_outside_window(self, tmp_path): + svc, _, _ = make_service(tmp_path) + action_at = datetime.now() + timedelta(hours=5) + svc.update_schedule({ + 'enabled': True, 'mode': 'once', + 'once_at': action_at.replace(second=0, microsecond=0).isoformat(), + }) + assert svc.check_and_fire() is None + assert svc.status()['active'] is False + + def test_disabled_schedule_never_fires(self, tmp_path): + svc, _, _ = make_service(tmp_path) + action_at = datetime.now() + timedelta(minutes=5) + svc.update_schedule({ + 'enabled': False, 'mode': 'once', + 'once_at': action_at.replace(second=0, microsecond=0).isoformat(), + }) + assert svc.check_and_fire() is None diff --git a/tests/test_scheduled_broadcast.py b/tests/test_scheduled_broadcast.py new file mode 100644 index 0000000..07380d6 --- /dev/null +++ b/tests/test_scheduled_broadcast.py @@ -0,0 +1,138 @@ +"""Tests for scheduled custom notifications.""" + +from datetime import datetime, timedelta + +import pytest + +from app.services.scheduled_broadcast import ScheduledBroadcastService + + +class FakeAdmin: + def __init__(self): + self.broadcasts = [] + + def send_global_broadcast(self, title, message, duration=30): + self.broadcasts.append((title, message, duration)) + return True, 'sent' + + +def make_service(tmp_path): + admin = FakeAdmin() + svc = ScheduledBroadcastService(admin, state_dir=str(tmp_path)) + return svc, admin + + +def base_entry(**overrides): + entry = { + 'title': 'Notice', + 'message': 'Hello players', + 'duration': 30, + 'mode': 'daily', + 'daily_times': ['12:00'], + } + entry.update(overrides) + return entry + + +class TestEntryCrud: + def test_save_and_list(self, tmp_path): + svc, _ = make_service(tmp_path) + entry = svc.save_entry(base_entry()) + assert entry['id'] + assert entry['next_run'] + assert [e['id'] for e in svc.list_entries()] == [entry['id']] + + def test_requires_title_and_message(self, tmp_path): + svc, _ = make_service(tmp_path) + with pytest.raises(ValueError): + svc.save_entry(base_entry(title='')) + with pytest.raises(ValueError): + svc.save_entry(base_entry(message='')) + + def test_duration_clamped(self, tmp_path): + svc, _ = make_service(tmp_path) + assert svc.save_entry(base_entry(duration=999))['duration'] == 300 + assert svc.save_entry(base_entry(duration=1))['duration'] == 5 + + def test_rejects_bad_mode(self, tmp_path): + svc, _ = make_service(tmp_path) + with pytest.raises(ValueError): + svc.save_entry(base_entry(mode='yearly')) + + def test_delete(self, tmp_path): + svc, _ = make_service(tmp_path) + entry = svc.save_entry(base_entry()) + assert svc.delete_entry(entry['id']) is True + assert svc.list_entries() == [] + assert svc.delete_entry(entry['id']) is False + + def test_enable_disable_preserves_settings(self, tmp_path): + svc, _ = make_service(tmp_path) + entry = svc.save_entry(base_entry(daily_times=['06:00', '18:00'])) + disabled = svc.set_enabled(entry['id'], False) + assert disabled['enabled'] is False + assert disabled['daily_times'] == ['06:00', '18:00'] + assert disabled['title'] == 'Notice' + assert disabled['message'] == 'Hello players' + enabled = svc.set_enabled(entry['id'], True) + assert enabled['enabled'] is True + assert enabled['daily_times'] == ['06:00', '18:00'] + + +class TestFiring: + def test_daily_fires_at_time(self, tmp_path): + svc, admin = make_service(tmp_path) + target = (datetime.now() + timedelta(minutes=1)).replace(second=0, microsecond=0) + entry = svc.save_entry(base_entry( + daily_times=[target.strftime('%H:%M')])) + assert entry['next_run'] != '' + fired = svc.check_and_fire(target + timedelta(seconds=5)) + assert len(fired) == 1 + assert admin.broadcasts and admin.broadcasts[0][:2] == ('Notice', 'Hello players') + # Must not fire twice for the same occurrence. + assert svc.check_and_fire(target + timedelta(seconds=10)) == [] + # ... but the next occurrence is armed. + updated = svc.list_entries()[0] + assert updated['next_run'] and updated['next_run'] != entry['next_run'] + + def test_once_past_never_arms(self, tmp_path): + svc, _ = make_service(tmp_path) + now = datetime.now().replace(second=0, microsecond=0) + entry = svc.save_entry(base_entry( + mode='once', once_at=(now - timedelta(minutes=1)).isoformat())) + assert entry['next_run'] == '' + + def test_once_fires_then_disables_keeping_settings(self, tmp_path): + svc, admin = make_service(tmp_path) + now = datetime.now().replace(second=0, microsecond=0) + entry = svc.save_entry(base_entry( + mode='once', once_at=(now + timedelta(minutes=1)).isoformat())) + assert entry['next_run'] != '' + fired = svc.check_and_fire(now + timedelta(minutes=2)) + assert len(fired) == 1 + updated = [e for e in svc.list_entries() if e['id'] == entry['id']][0] + assert updated['enabled'] is False + assert updated['title'] == 'Notice' # settings kept for reuse + assert updated['once_at'] != '' + + def test_disabled_entry_never_fires(self, tmp_path): + svc, admin = make_service(tmp_path) + target = (datetime.now() + timedelta(minutes=1)).replace(second=0, microsecond=0) + svc.save_entry(base_entry( + enabled=False, daily_times=[target.strftime('%H:%M')])) + assert svc.check_and_fire(target + timedelta(seconds=5)) == [] + assert admin.broadcasts == [] + + def test_missed_window_rolls_forward_without_firing(self, tmp_path): + svc, admin = make_service(tmp_path) + now = datetime.now().replace(second=0, microsecond=0) + svc.save_entry(base_entry( + daily_times=[(now - timedelta(hours=3)).strftime('%H:%M')])) + # Force the stored next_run into the past to simulate downtime. + entries = svc.list_entries() + past = (now - timedelta(hours=2)).isoformat() + entries[0]['next_run'] = past + entries[0]['last_fired_for'] = '' + svc._save(entries) + assert svc.check_and_fire(now) == [] + assert admin.broadcasts == [] diff --git a/tests/test_security_validations.py b/tests/test_security_validations.py new file mode 100644 index 0000000..64b8d86 --- /dev/null +++ b/tests/test_security_validations.py @@ -0,0 +1,76 @@ +"""Tests for no-behavior-change security validations.""" + +import pytest + +from app.routes.api import fb_within_roots +from app.services.backup import is_valid_backup_name + + +class TestFileBrowserJail: + ROOTS = ['/srv', '/home/dune/.dune'] + + def test_inside_roots(self): + assert fb_within_roots('/srv', self.ROOTS) + assert fb_within_roots('/srv/', self.ROOTS) + assert fb_within_roots('/srv/sub/dir/file.txt', self.ROOTS) + assert fb_within_roots('/home/dune/.dune/settings.conf', self.ROOTS) + + def test_outside_roots(self): + assert not fb_within_roots('/', self.ROOTS) + assert not fb_within_roots('/etc/passwd', self.ROOTS) + assert not fb_within_roots('/etc/shadow', self.ROOTS) + assert not fb_within_roots('/home/dune/.ssh/id_rsa', self.ROOTS) + assert not fb_within_roots('/home/dune/.dune-evil/x', self.ROOTS) + assert not fb_within_roots('/srv-evil/x', self.ROOTS) + assert not fb_within_roots('', self.ROOTS) + + def test_prefix_trick_rejected(self): + # '/srv-evil' must not match root '/srv' + assert not fb_within_roots('/srv-evil', ['/srv']) + assert fb_within_roots('/srv/a', ['/srv']) + + +class TestBackupNameWhitelist: + def test_valid_names(self): + assert is_valid_backup_name('backup-21-09-2026_103000') + assert is_valid_backup_name('backup-01-01-2000_000000') + + def test_rejects_traversal_and_shell(self): + assert not is_valid_backup_name('../../settings') + assert not is_valid_backup_name('backup-21-09-2026_103000; id') + assert not is_valid_backup_name('x; id>/tmp/pwn; echo ') + assert not is_valid_backup_name('') + assert not is_valid_backup_name(None) + assert not is_valid_backup_name('backup-21-09-2026_103000.tar.gz') + assert not is_valid_backup_name('something-else') + + +class TestOnceAtValidation: + def test_lifecycle_rejects_garbage(self, tmp_path): + from app.services.lifecycle import LifecycleService + + class FakeSSH: + def run(self, *a, **k): + return '', '', 0 + + class FakeAdmin: + def send_global_broadcast(self, *a, **k): + return True, 'sent' + + svc = LifecycleService(FakeSSH(), FakeAdmin(), {}, state_dir=str(tmp_path)) + with pytest.raises(ValueError): + svc.update_schedule({'mode': 'once', 'once_at': 'not-a-date'}) + + def test_broadcast_rejects_garbage(self, tmp_path): + from app.services.scheduled_broadcast import ScheduledBroadcastService + + class FakeAdmin: + def send_global_broadcast(self, *a, **k): + return True, 'sent' + + svc = ScheduledBroadcastService(FakeAdmin(), state_dir=str(tmp_path)) + with pytest.raises(ValueError): + svc.save_entry({ + 'title': 't', 'message': 'm', 'mode': 'once', + 'once_at': 'not-a-date', + })
Error: ' + data.error + '
Error: ' + escapeHtml(data.error || 'unknown') + '
' + timestamp + '' + (log.action || '-') + '' + (log.user || '-') + '' + (log.severity || 'info') + '' + details + '' + escapeHtml(timestamp) + '' + escapeHtml(log.action || '-') + '' + escapeHtml(log.user || '-') + '' + escapeHtml(log.severity || 'info') + '' + escapeHtml(details) + '
Error: ' + e.message + '
Error: ' + escapeHtml(e.message) + '
{{ v.id }} {{ v.class | class_name }} {{ v.actor_name or 'N/A' }}{% if v.owner_name %}{{ v.owner_name }}{% else %}—{% endif %}{% if v.pilot_name %}Active {{ v.pilot_name }}{% else %}—{% endif %}{% if v.owner_name %}{{ v.owner_name }}{% else %}-{% endif %}{% if v.pilot_name %}Active {{ v.pilot_name }}{% else %}-{% endif %} {{ v.map or 'N/A' }} {{ v.transform_text or '' }}