Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce241a283d | ||
|
|
91944a0213 |
No files matched your search
@@ -2,8 +2,6 @@
|
|||||||
|
|
||||||
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
||||||
|
|
||||||
> “A comprehensive web-based management dashboard for Dune: Awakening private servers.”
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
@@ -26,26 +24,18 @@ chmod +x start.sh
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
||||||
|
- **In-Game Notifications** — instant broadcasts plus scheduled one-shot/daily/weekly/monthly messages
|
||||||
|
- **Graceful Shutdown / Restart** — in-game countdown warnings with cancel notices, plus scheduled restarts
|
||||||
|
- **Battlegroup Control** — start/stop/restart/update, with update blocked while players are online
|
||||||
- **Chat Logs** with channel filtering and auto-refresh
|
- **Chat Logs** with channel filtering and auto-refresh
|
||||||
- **Director Tools** (battlegroups, world state, transfers)
|
- **Director Tools** (battlegroups, world state, transfers)
|
||||||
- **SSH File Browser** + **in-browser shell**
|
- **SSH File Browser** (jailed to allowed directories) + **in-browser shell**
|
||||||
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
|
- **Pod Management** (list, logs, describe, delete with safe-mode for DB backup pods)
|
||||||
- **Nav Layout** — switch between horizontal and vertical sidebar; persists preference; auto-enables sidebar on mobile
|
- **Backup & Restore** — encrypted full-server snapshots with scheduled backups and retention cleanup
|
||||||
|
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources with verification
|
||||||
- **Firewall Hardening** via iptables
|
- **Firewall Hardening** via iptables
|
||||||
- **Auto‑Update** with safe file replacement
|
- **HTTPS + Remote Access** (self-signed or Let's Encrypt)
|
||||||
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
|
- **Cross-Platform Launchers** (Windows + Linux/macOS, incl. debug mode and SSH key rotation)
|
||||||
- **Cross‑Platform Launchers**
|
|
||||||
- **Organized Logging** with automatic cleanup and redaction
|
|
||||||
- **Debug Mode** with full SSH/K8s tracing
|
|
||||||
- **SSH Key Rotation** — scan all key locations and sync the newest key
|
|
||||||
- **Backup & Restore** — full server snapshots (game DB, K8s resources, RMQ config, dashboard schema) with optional AES-256 encryption and password protection
|
|
||||||
- **Scheduled Backups** — configurable interval or day/time-based scheduling with automatic retention cleanup
|
|
||||||
- **Funcom Service Auth Token Management** — update the `ServiceAuthToken` JWT across files and live K8s resources (secret, YAML, BattleGroup CR) with verification
|
|
||||||
- **Graceful Shutdown / Restart** — in-game countdown warnings, then `battlegroup stop` / `restart`, with cancel notices
|
|
||||||
- **Custom Notifications** — instant in-game broadcasts, plus scheduled one-shot/daily/weekly/monthly messages
|
|
||||||
- **Scheduled Restarts** — daily/weekly/monthly/one-shot with the same countdown, enable/disable/clear without losing settings
|
|
||||||
- **Battlegroup Update Guard** — update refuses while game servers are online
|
|
||||||
- **Jailed File Browser** — restricted to configured directories with symlink-aware checks
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -70,36 +60,12 @@ DuneDashboard/
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Security
|
|
||||||
|
|
||||||
- `settings.yaml` is never committed
|
|
||||||
- SSH keys stored with restricted permissions
|
|
||||||
- All DB queries parameterized
|
|
||||||
- No raw SQL console — the old experimental query/execute endpoints were removed entirely
|
|
||||||
- Shell parameters validated and quoted throughout
|
|
||||||
- File browser jailed to allowed directories
|
|
||||||
- All mutations audited
|
|
||||||
- CSP, HSTS, X‑Frame‑Options enforced in production
|
|
||||||
|
|
||||||
> Because letting users run `DROP TABLE` from a web UI is how horror stories begin — so that UI no longer exists.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Branching Strategy
|
|
||||||
|
|
||||||
- **main** — stable-ish beta
|
|
||||||
- **experimental** — where chaos becomes innovation
|
|
||||||
|
|
||||||
> “This seemed like a great idea at 3am.” — every experimental commit ever
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
Source Available under the **Dune Dashboard Source License (DDSL)**
|
Source Available under the **Dune Dashboard Source License (DDSL)**
|
||||||
|
|||||||
+33
-11
@@ -43,6 +43,27 @@ def fb_within_roots(canonical, roots):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def fb_resolve_canonical(raw, lexical, run_fn, timeout=10):
|
||||||
|
"""Pick a canonical path using the best realpath the target supports.
|
||||||
|
|
||||||
|
- GNU coreutils: ``realpath -m`` works, even for not-yet-existing paths.
|
||||||
|
- BusyBox (e.g. Alpine): no ``-m`` flag, so it is retried as plain
|
||||||
|
``realpath`` (works for existing paths, resolves symlinks).
|
||||||
|
- Otherwise the lexical path is used (``..`` already collapsed, but
|
||||||
|
symlinks stay unresolved).
|
||||||
|
|
||||||
|
``run_fn(command, timeout)`` executes in the target context and returns
|
||||||
|
``(stdout, stderr, returncode)``. Returns the canonical path string.
|
||||||
|
"""
|
||||||
|
out, err, rc = run_fn(f'realpath -m -- {quote_remote(raw)}', timeout)
|
||||||
|
if rc == 0 and (out or '').strip():
|
||||||
|
return (out or '').strip().split('\n')[0].strip()
|
||||||
|
out, err, rc = run_fn(f'realpath -- {quote_remote(raw)}', timeout)
|
||||||
|
if rc == 0 and (out or '').strip():
|
||||||
|
return (out or '').strip().split('\n')[0].strip()
|
||||||
|
return lexical
|
||||||
|
|
||||||
|
|
||||||
def register_api_routes(app, services, settings):
|
def register_api_routes(app, services, settings):
|
||||||
db = services['db']
|
db = services['db']
|
||||||
ssh = services['ssh']
|
ssh = services['ssh']
|
||||||
@@ -1041,14 +1062,15 @@ def register_api_routes(app, services, settings):
|
|||||||
import posixpath
|
import posixpath
|
||||||
roots = _fb_allowed_roots()
|
roots = _fb_allowed_roots()
|
||||||
lexical = posixpath.normpath(raw)
|
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():
|
def _run(command, timeout):
|
||||||
canonical = (out or '').strip().split('\n')[0].strip()
|
# Probe commands are expected to fail on minimal toolchains
|
||||||
else:
|
# (e.g. BusyBox realpath without -m): keep them out of the logs.
|
||||||
# realpath unavailable in this context: fall back to the lexical
|
return _fb_exec(command, pod_name, timeout=timeout, quiet=True)
|
||||||
# path (still blocks '..' escapes; symlinks stay unresolved).
|
|
||||||
logger.warning('File browser: realpath unavailable, using lexical path check')
|
canonical = fb_resolve_canonical(raw, lexical, _run, timeout)
|
||||||
canonical = lexical
|
if canonical == lexical:
|
||||||
|
logger.debug('File browser: using lexical path check (no realpath -m support)')
|
||||||
if not fb_within_roots(canonical, roots):
|
if not fb_within_roots(canonical, roots):
|
||||||
return '', 'Invalid path: outside allowed directories'
|
return '', 'Invalid path: outside allowed directories'
|
||||||
return canonical, ''
|
return canonical, ''
|
||||||
@@ -1083,10 +1105,10 @@ def register_api_routes(app, services, settings):
|
|||||||
return str(e)
|
return str(e)
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
def _fb_exec(command, pod_name=None, timeout=10):
|
def _fb_exec(command, pod_name=None, timeout=10, quiet=False):
|
||||||
"""Execute a command on the VM host or in a K8s pod."""
|
"""Execute a command on the VM host or in a K8s pod."""
|
||||||
if pod_name in _FB_VM_PODS:
|
if pod_name in _FB_VM_PODS:
|
||||||
return k8s.ssh.run(command, timeout=timeout)
|
return k8s.ssh.run(command, timeout=timeout, quiet=quiet)
|
||||||
pod = pod_name or _get_fb_pod()
|
pod = pod_name or _get_fb_pod()
|
||||||
if not pod:
|
if not pod:
|
||||||
return '', 'No pod specified or found', 1
|
return '', 'No pod specified or found', 1
|
||||||
@@ -1094,7 +1116,7 @@ def register_api_routes(app, services, settings):
|
|||||||
if err:
|
if err:
|
||||||
return '', f'Invalid pod name: {err}', 1
|
return '', f'Invalid pod name: {err}', 1
|
||||||
full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}'
|
full_cmd = f'sudo kubectl exec {shlex.quote(pod)} -n {shlex.quote(str(k8s.namespace))} -- {command}'
|
||||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
return k8s.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
|
||||||
|
|
||||||
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
||||||
"""Write a file to the pod filesystem."""
|
"""Write a file to the pod filesystem."""
|
||||||
|
|||||||
@@ -388,7 +388,7 @@ class BackupService:
|
|||||||
with open(meta_path) as f:
|
with open(meta_path) as f:
|
||||||
return json.load(f)
|
return json.load(f)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f'Could not read sidecar meta from {meta_path}: {e}')
|
logger.debug(f'Could not read sidecar meta from {meta_path}: {e}')
|
||||||
try:
|
try:
|
||||||
with tarfile.open(path, 'r:gz') as tar:
|
with tarfile.open(path, 'r:gz') as tar:
|
||||||
for m in tar.getmembers():
|
for m in tar.getmembers():
|
||||||
@@ -396,7 +396,9 @@ class BackupService:
|
|||||||
with tar.extractfile(m) as f:
|
with tar.extractfile(m) as f:
|
||||||
return json.loads(f.read().decode('utf-8'))
|
return json.loads(f.read().decode('utf-8'))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f'Could not read metadata from {path}: {e}')
|
# Expected for encrypted archives (handled by verify with a
|
||||||
|
# password) and pre-sidecar backups; not worth a warning.
|
||||||
|
logger.debug(f'Could not read metadata from {path}: {e}')
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def delete_backup(self, name):
|
def delete_backup(self, name):
|
||||||
|
|||||||
@@ -256,8 +256,15 @@ class DirectorService:
|
|||||||
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||||
name = self._map_to_scale_name(map_name)
|
name = self._map_to_scale_name(map_name)
|
||||||
cm_out, cm_err, cm_rc = self.k8s.run(
|
cm_out, cm_err, cm_rc = self.k8s.run(
|
||||||
f'get serversetscale {name} -o json')
|
f'get serversetscale {name} -o json', quiet=True)
|
||||||
if cm_rc != 0 or not cm_out:
|
if cm_rc != 0 or not cm_out:
|
||||||
|
# A missing ServerSetScale just means the map has none; only
|
||||||
|
# unexpected failures deserve a warning.
|
||||||
|
if cm_rc != 0 and 'not found' not in (cm_err or '').lower():
|
||||||
|
logger.warning("ServerSetScale lookup failed for %s: %s",
|
||||||
|
map_name, (cm_err or '')[:150])
|
||||||
|
else:
|
||||||
|
logger.debug("No ServerSetScale for %s", map_name)
|
||||||
return None
|
return None
|
||||||
return json.loads(cm_out)
|
return json.loads(cm_out)
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -11,10 +11,10 @@ class K8sService:
|
|||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
|
|
||||||
def run(self, kubectl_command, timeout=30):
|
def run(self, kubectl_command, timeout=30, quiet=False):
|
||||||
full_cmd = f'sudo kubectl {kubectl_command} -n {shlex.quote(str(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}")
|
logger.debug(f"K8s executing: kubectl {kubectl_command} -n {self.namespace}")
|
||||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
result = self.ssh.run(full_cmd, timeout=timeout, quiet=quiet)
|
||||||
out, err, rc = result
|
out, err, rc = result
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
logger.debug(f"K8s command failed (rc={rc}): {err[:100] if err else 'no error'}")
|
||||||
|
|||||||
+12
-3
@@ -79,12 +79,15 @@ class SSHService:
|
|||||||
self._client = client
|
self._client = client
|
||||||
return self._client
|
return self._client
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
"""Execute a remote command via SSH.
|
"""Execute a remote command via SSH.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
command: The shell command to execute.
|
command: The shell command to execute.
|
||||||
timeout: Maximum time in seconds to wait for the command.
|
timeout: Maximum time in seconds to wait for the command.
|
||||||
|
quiet: When True, expected non-zero results (e.g. probing for
|
||||||
|
an optional resource) are logged at debug level instead of
|
||||||
|
warning. Return values are unchanged.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Tuple of (stdout, stderr, return_code).
|
Tuple of (stdout, stderr, return_code).
|
||||||
@@ -103,13 +106,19 @@ class SSHService:
|
|||||||
# Debug logging for result
|
# Debug logging for result
|
||||||
logger.debug(f"SSH result: host={self.host}, user={self.user}, rc={rc}, stdout_len={len(out)}, stderr_len={len(err)}")
|
logger.debug(f"SSH result: host={self.host}, user={self.user}, rc={rc}, stdout_len={len(out)}, stderr_len={len(err)}")
|
||||||
if err and rc != 0:
|
if err and rc != 0:
|
||||||
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
if quiet:
|
||||||
|
logger.debug(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"SSH stderr (rc={rc}): {err[:200]}")
|
||||||
if out:
|
if out:
|
||||||
logger.debug(f"SSH stdout preview: {out[:200]}")
|
logger.debug(f"SSH stdout preview: {out[:200]}")
|
||||||
|
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
cmd_short = command[:80] + '...' if len(command) > 80 else command
|
cmd_short = command[:80] + '...' if len(command) > 80 else command
|
||||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
if quiet:
|
||||||
|
logger.debug("SSH command rc=%d (quiet): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||||
|
else:
|
||||||
|
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_short, err[:100] if err else 'none')
|
||||||
return out, err, rc
|
return out, err, rc
|
||||||
except paramiko.SSHException as e:
|
except paramiko.SSHException as e:
|
||||||
logger.error(f"SSH command error ({self.host}): {e}")
|
logger.error(f"SSH command error ({self.host}): {e}")
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""Production HTTP server builder (cheroot) with noise filtering.
|
||||||
|
|
||||||
|
Cheroot writes server-level errors (e.g. scanners dropping TLS handshakes)
|
||||||
|
straight to stderr, bypassing the dashboard's log levels. The filter below
|
||||||
|
sends the known-benign handshake noise to the debug log and lets everything
|
||||||
|
else through untouched.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Fragments identifying a peer that vanished mid-handshake (typically an
|
||||||
|
# internet scanner hitting the public HTTPS port). Never real failures.
|
||||||
|
_HANDSHAKE_NOISE = (
|
||||||
|
'during handshake',
|
||||||
|
'SSLV3_ALERT',
|
||||||
|
'UNEXPECTED_EOF',
|
||||||
|
'TLSV1_ALERT',
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def cheroot_error_filter(original_error_log, msg='', level=20, traceback=False):
|
||||||
|
"""Drop-in replacement for ``server.error_log``.
|
||||||
|
|
||||||
|
Handshake noise -> debug log. Everything else -> original handler.
|
||||||
|
"""
|
||||||
|
text = str(msg)
|
||||||
|
lowered = text.lower()
|
||||||
|
if any(fragment.lower() in lowered for fragment in _HANDSHAKE_NOISE):
|
||||||
|
logger.debug('TLS handshake dropped by peer: %s', text[:200])
|
||||||
|
return
|
||||||
|
original_error_log(msg, level=level, traceback=traceback)
|
||||||
|
|
||||||
|
|
||||||
|
def build_server(host, port, wsgi_app, cert_path=None, key_path=None,
|
||||||
|
numthreads=16, socket_timeout=60):
|
||||||
|
"""Build a cheroot server with timeouts, bounded queues and TLS support."""
|
||||||
|
from cheroot import wsgi as cheroot_wsgi
|
||||||
|
|
||||||
|
server = cheroot_wsgi.Server(
|
||||||
|
(host, port), wsgi_app,
|
||||||
|
numthreads=numthreads,
|
||||||
|
request_queue_size=128,
|
||||||
|
timeout=socket_timeout,
|
||||||
|
accepted_queue_size=128,
|
||||||
|
accepted_queue_timeout=10,
|
||||||
|
)
|
||||||
|
if cert_path and key_path:
|
||||||
|
from cheroot.ssl.builtin import BuiltinSSLAdapter
|
||||||
|
server.ssl_adapter = BuiltinSSLAdapter(cert_path, key_path)
|
||||||
|
original = server.error_log
|
||||||
|
server.error_log = lambda msg='', level=20, traceback=False: \
|
||||||
|
cheroot_error_filter(original, msg, level=level, traceback=traceback)
|
||||||
|
return server
|
||||||
@@ -30,6 +30,23 @@ if __name__ == '__main__':
|
|||||||
cert_path = str(ssl_cert).strip("'\"")
|
cert_path = str(ssl_cert).strip("'\"")
|
||||||
key_path = str(ssl_key).strip("'\"")
|
key_path = str(ssl_key).strip("'\"")
|
||||||
if os.path.exists(cert_path) and os.path.exists(key_path):
|
if os.path.exists(cert_path) and os.path.exists(key_path):
|
||||||
|
try:
|
||||||
|
with open(cert_path, 'rb'):
|
||||||
|
pass
|
||||||
|
with open(key_path, 'rb'):
|
||||||
|
pass
|
||||||
|
except OSError:
|
||||||
|
print(f"\n [ERROR] Cannot read SSL files (permission denied):")
|
||||||
|
print(f" [ERROR] {cert_path}")
|
||||||
|
print(f" [ERROR] {key_path}")
|
||||||
|
print(f" [ERROR] The dashboard runs as '{os.environ.get('USERNAME', 'unknown')}'")
|
||||||
|
print(" [ERROR] but these files are only readable by an Administrator.")
|
||||||
|
print(" [ERROR] Fix with ONE of:")
|
||||||
|
print(" [ERROR] 1. Run the launcher as Administrator (right-click -> Run as administrator)")
|
||||||
|
print(" [ERROR] 2. Grant yourself read access, e.g. in an elevated terminal:")
|
||||||
|
print(f' [ERROR] icacls "{cert_path}" /grant "%USERNAME%:(R)"')
|
||||||
|
print(f' [ERROR] icacls "{key_path}" /grant "%USERNAME%:(R)"\n')
|
||||||
|
sys.exit(1)
|
||||||
ssl_context = (cert_path, key_path)
|
ssl_context = (cert_path, key_path)
|
||||||
protocol = "https"
|
protocol = "https"
|
||||||
else:
|
else:
|
||||||
@@ -147,26 +164,24 @@ if __name__ == '__main__':
|
|||||||
# Socket.IO keeps working (threading mode = HTTP long-polling, which
|
# Socket.IO keeps working (threading mode = HTTP long-polling, which
|
||||||
# runs on any WSGI server).
|
# runs on any WSGI server).
|
||||||
try:
|
try:
|
||||||
from cheroot import wsgi as cheroot_wsgi
|
import cheroot
|
||||||
|
from app.utils.http_server import build_server
|
||||||
except ImportError:
|
except ImportError:
|
||||||
logging.getLogger(__name__).warning(
|
logging.getLogger(__name__).warning(
|
||||||
"cheroot not installed - falling back to dev server "
|
"cheroot not installed - falling back to dev server "
|
||||||
"(no connection timeouts)")
|
"(no connection timeouts)")
|
||||||
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
socketio.run(app, host=host, port=port, debug=debug, log_output=False, ssl_context=ssl_context)
|
||||||
else:
|
else:
|
||||||
server = cheroot_wsgi.Server(
|
try:
|
||||||
(host, port), app,
|
if ssl_context:
|
||||||
numthreads=16,
|
server = build_server(host, port, app, cert_path, key_path)
|
||||||
request_queue_size=128,
|
print(f" Server: cheroot (16 threads, 60s socket timeout, TLS on)")
|
||||||
timeout=60,
|
else:
|
||||||
accepted_queue_size=128,
|
server = build_server(host, port, app)
|
||||||
accepted_queue_timeout=10,
|
print(f" Server: cheroot (16 threads, 60s socket timeout)")
|
||||||
)
|
except OSError as e:
|
||||||
if ssl_context:
|
print(f"\n [ERROR] Could not start TLS server: {e}")
|
||||||
from cheroot.ssl.builtin import BuiltinSSLAdapter
|
print(" [ERROR] If this is a permission error, run the launcher as Administrator once,\n")
|
||||||
server.ssl_adapter = BuiltinSSLAdapter(cert_path, key_path)
|
sys.exit(1)
|
||||||
print(f" Server: cheroot (16 threads, 60s socket timeout, TLS on)")
|
|
||||||
else:
|
|
||||||
print(f" Server: cheroot (16 threads, 60s socket timeout)")
|
|
||||||
print(f" Watchdog: enabled (exit code 42 triggers launcher restart)\n")
|
print(f" Watchdog: enabled (exit code 42 triggers launcher restart)\n")
|
||||||
server.start()
|
server.start()
|
||||||
@@ -116,7 +116,10 @@
|
|||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css">
|
||||||
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/socket.io-client@4.7.2/dist/socket.io.min.js"></script>
|
||||||
<script>
|
<script>
|
||||||
const socket = io();
|
// Polling only: the server runs in threading mode, which has no true
|
||||||
|
// websocket support. Letting the client attempt a websocket upgrade only
|
||||||
|
// produces "Cannot obtain socket from WSGI environment" tracebacks.
|
||||||
|
const socket = io({ transports: ['polling'] });
|
||||||
|
|
||||||
let termVM = null;
|
let termVM = null;
|
||||||
let termPod = null;
|
let termPod = null;
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ class FakeSSH:
|
|||||||
self.rc = rc
|
self.rc = rc
|
||||||
self.commands = []
|
self.commands = []
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
self.commands.append(command)
|
self.commands.append(command)
|
||||||
return self.out, '', self.rc
|
return self.out, '', self.rc
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""Tests for the cheroot server builder + handshake-noise filter."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.utils.http_server import build_server, cheroot_error_filter
|
||||||
|
|
||||||
|
|
||||||
|
class TestHandshakeFilter:
|
||||||
|
def test_handshake_drops_go_to_debug_only(self, caplog):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def orig(msg='', level=20, traceback=False):
|
||||||
|
calls.append((msg, level))
|
||||||
|
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.utils.http_server'):
|
||||||
|
cheroot_error_filter(orig, 'Client (\'1.2.3.4\', 123) lost - peer '
|
||||||
|
'dropped the TLS connection suddenly, during '
|
||||||
|
'handshake: (8, \'[SSL: SSLV3_ALERT_CERTIFICATE_UNKNOWN] \')')
|
||||||
|
assert calls == []
|
||||||
|
assert any('handshake dropped' in r.message for r in caplog.records)
|
||||||
|
assert all(r.levelno == logging.DEBUG for r in caplog.records)
|
||||||
|
|
||||||
|
def test_real_errors_pass_through(self):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def orig(msg='', level=20, traceback=False):
|
||||||
|
calls.append((msg, level, traceback))
|
||||||
|
|
||||||
|
cheroot_error_filter(orig, 'socket.error 104', level=30, traceback=True)
|
||||||
|
assert calls == [('socket.error 104', 30, True)]
|
||||||
|
|
||||||
|
|
||||||
|
def _self_signed_pair(tmp_path):
|
||||||
|
import datetime
|
||||||
|
from cryptography import x509
|
||||||
|
from cryptography.hazmat.primitives import hashes, serialization
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||||
|
from cryptography.x509.oid import NameOID
|
||||||
|
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||||
|
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'localhost')])
|
||||||
|
now = datetime.datetime.now(datetime.timezone.utc)
|
||||||
|
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name)
|
||||||
|
.public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||||
|
.not_valid_before(now).not_valid_after(now + datetime.timedelta(days=1))
|
||||||
|
.sign(key, hashes.SHA256()))
|
||||||
|
cert_path = tmp_path / 'c.pem'
|
||||||
|
key_path = tmp_path / 'k.pem'
|
||||||
|
cert_path.write_bytes(cert.public_bytes(serialization.Encoding.PEM))
|
||||||
|
key_path.write_bytes(key.private_bytes(
|
||||||
|
serialization.Encoding.PEM,
|
||||||
|
serialization.PrivateFormat.TraditionalOpenSSL,
|
||||||
|
serialization.NoEncryption()))
|
||||||
|
return str(cert_path), str(key_path)
|
||||||
|
|
||||||
|
|
||||||
|
class TestBuildServer:
|
||||||
|
def test_timeouts_and_queues(self):
|
||||||
|
server = build_server('127.0.0.1', 0, None)
|
||||||
|
try:
|
||||||
|
assert server.numthreads == 16
|
||||||
|
assert server.timeout == 60
|
||||||
|
assert server.request_queue_size == 128
|
||||||
|
finally:
|
||||||
|
server.stop()
|
||||||
|
|
||||||
|
def test_tls_adapter(self, tmp_path):
|
||||||
|
cert, key = _self_signed_pair(tmp_path)
|
||||||
|
server = build_server('127.0.0.1', 0, None, cert, key)
|
||||||
|
try:
|
||||||
|
assert server.ssl_adapter is not None
|
||||||
|
finally:
|
||||||
|
server.stop()
|
||||||
@@ -16,7 +16,7 @@ class FakeSSH:
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.commands = []
|
self.commands = []
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
def run(self, command, timeout=30, quiet=False):
|
||||||
self.commands.append(command)
|
self.commands.append(command)
|
||||||
return ('ok', '', 0)
|
return ('ok', '', 0)
|
||||||
|
|
||||||
|
|||||||
@@ -2,10 +2,47 @@
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from app.routes.api import fb_within_roots
|
from app.routes.api import fb_resolve_canonical, fb_within_roots
|
||||||
from app.services.backup import is_valid_backup_name
|
from app.services.backup import is_valid_backup_name
|
||||||
|
|
||||||
|
|
||||||
|
class TestCanonicalResolution:
|
||||||
|
def test_gnu_realpath_m(self):
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def run(cmd, timeout):
|
||||||
|
calls.append(cmd)
|
||||||
|
return '/srv/sub/../file.txt\n', '', 0
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/file.txt', '/srv/file.txt', run) == \
|
||||||
|
'/srv/sub/../file.txt'
|
||||||
|
assert calls[0].startswith('realpath -m -- ')
|
||||||
|
|
||||||
|
def test_busybox_falls_back_to_plain_realpath(self):
|
||||||
|
def run(cmd, timeout):
|
||||||
|
if cmd.startswith('realpath -m -- '):
|
||||||
|
return '', 'realpath: -m: No such file or directory', 1
|
||||||
|
assert cmd.startswith('realpath -- ')
|
||||||
|
return '/srv/file.txt\n', '', 0
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/file.txt', '/srv/file.txt', run) == \
|
||||||
|
'/srv/file.txt'
|
||||||
|
|
||||||
|
def test_missing_binary_falls_back_to_lexical(self):
|
||||||
|
def run(cmd, timeout):
|
||||||
|
return '', 'realpath: command not found', 127
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/a/../b', '/srv/b', run) == '/srv/b'
|
||||||
|
|
||||||
|
def test_missing_file_without_m_support(self):
|
||||||
|
# New file on BusyBox: plain realpath fails too, lexical wins.
|
||||||
|
def run(cmd, timeout):
|
||||||
|
return '', 'No such file or directory', 1
|
||||||
|
|
||||||
|
assert fb_resolve_canonical('/srv/new.txt', '/srv/new.txt', run) == \
|
||||||
|
'/srv/new.txt'
|
||||||
|
|
||||||
|
|
||||||
class TestFileBrowserJail:
|
class TestFileBrowserJail:
|
||||||
ROOTS = ['/srv', '/home/dune/.dune']
|
ROOTS = ['/srv', '/home/dune/.dune']
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Tests for SSHService.run(quiet=...) - log level only, same results."""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from app.services.ssh import SSHService
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeChannel:
|
||||||
|
def __init__(self, rc):
|
||||||
|
self._rc = rc
|
||||||
|
|
||||||
|
def settimeout(self, timeout):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def recv_exit_status(self):
|
||||||
|
return self._rc
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeStream:
|
||||||
|
def __init__(self, data, rc):
|
||||||
|
self._data = data
|
||||||
|
self.channel = _FakeChannel(rc)
|
||||||
|
|
||||||
|
def read(self):
|
||||||
|
return self._data
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
def __init__(self, out=b'', err=b'Error from server (NotFound)', rc=1):
|
||||||
|
self._out = _FakeStream(out, rc)
|
||||||
|
self._err = _FakeStream(err, rc)
|
||||||
|
|
||||||
|
def get_transport(self):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def exec_command(self, command, timeout=None):
|
||||||
|
return None, self._out, self._err
|
||||||
|
|
||||||
|
|
||||||
|
def _service_with_fake_client():
|
||||||
|
svc = SSHService.__new__(SSHService)
|
||||||
|
import threading
|
||||||
|
svc.host = 'h'
|
||||||
|
svc.user = 'u'
|
||||||
|
svc.ssh_key = None
|
||||||
|
svc._client = _FakeClient()
|
||||||
|
svc._lock = threading.Lock()
|
||||||
|
# Bypass reconnect logic: _get_client returns the fake directly when
|
||||||
|
# its transport check is skipped. Patch at instance level.
|
||||||
|
svc._get_client = lambda: svc._client
|
||||||
|
return svc
|
||||||
|
|
||||||
|
|
||||||
|
class TestQuietFlag:
|
||||||
|
def test_results_identical_quiet_or_not(self, caplog):
|
||||||
|
svc = _service_with_fake_client()
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
out1, err1, rc1 = svc.run('kubectl get x', quiet=False)
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
out2, err2, rc2 = svc.run('kubectl get x', quiet=True)
|
||||||
|
assert (out1, err1, rc1) == (out2, err2, rc2) == ('', 'Error from server (NotFound)', 1)
|
||||||
|
|
||||||
|
def test_loud_logs_warning_quiet_logs_debug(self, caplog):
|
||||||
|
svc = _service_with_fake_client()
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
caplog.clear()
|
||||||
|
svc.run('kubectl get x', quiet=False)
|
||||||
|
loud_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||||
|
with caplog.at_level(logging.DEBUG, logger='app.services.ssh'):
|
||||||
|
caplog.clear()
|
||||||
|
svc.run('kubectl get x', quiet=True)
|
||||||
|
quiet_levels = {r.levelno for r in caplog.records if 'rc=1' in r.message}
|
||||||
|
assert logging.WARNING in loud_levels
|
||||||
|
assert logging.WARNING not in quiet_levels
|
||||||
Reference in new issue
Block a user