Merge local changes

This commit is contained in:
Reditus committed 2026-05-15 09:12:35 +01:00
1 parent ea29e6942c
commit 3d1fc8a638
12 files changed
+366 -15

No files matched your search

+2 -2
View File
@@ -166,8 +166,8 @@ def load_settings(settings_path=None):
else: else:
logger.warning(f"Settings file not found at {settings_path}, using defaults") logger.warning(f"Settings file not found at {settings_path}, using defaults")
# Auto-apply new defaults if missing # Note: Runtime config migration moved to setup/update scripts
_apply_defaults_to_file(settings_path, DEFAULTS) # _apply_defaults_to_file() removed to prevent runtime config mutation
env_overrides = {} env_overrides = {}
+16
View File
@@ -70,6 +70,21 @@ def create_app(settings_path=None):
response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['X-Content-Type-Options'] = 'nosniff'
# XSS protection # XSS protection
response.headers['X-XSS-Protection'] = '1; mode=block' response.headers['X-XSS-Protection'] = '1; mode=block'
# Content Security Policy
response.headers['Content-Security-Policy'] = (
"default-src 'self'; "
"script-src 'self'; "
"style-src 'self' 'unsafe-inline'; "
"img-src 'self' data:; "
"connect-src 'self' ws: wss:; "
"frame-ancestors 'self'; "
"base-uri 'self'; "
"form-action 'self'"
)
# Referrer Policy - use strict-origin-when-cross-origin to allow CSRF checks
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
# Permissions Policy
response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(), camera=()'
return response return response
_setup_logging(settings) _setup_logging(settings)
@@ -138,6 +153,7 @@ def create_app(settings_path=None):
default_limits=["200 per day", "50 per hour"], default_limits=["200 per day", "50 per hour"],
storage_uri="memory://", storage_uri="memory://",
) )
app.limiter = limiter
if settings['auth']['enabled']: if settings['auth']['enabled']:
init_auth(app, settings, limiter) init_auth(app, settings, limiter)
+50 -8
View File
@@ -2,6 +2,8 @@
import json import json
import logging import logging
import re
import shlex
from flask import Blueprint, request, jsonify from flask import Blueprint, request, jsonify
from flask_login import login_required from flask_login import login_required
from flask_limiter import Limiter from flask_limiter import Limiter
@@ -10,6 +12,21 @@ from app.utils.constants import NAV_PAGES
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
def require_k8s_name(value, label):
"""Validate that a value is a valid Kubernetes resource name."""
value = str(value or "").strip()
if not value or not K8S_NAME_RE.fullmatch(value):
raise ValueError(f"Invalid {label}")
return value
def quote_remote(value):
"""Shell-quote a value for safe use in remote commands."""
return shlex.quote(str(value))
def register_api_routes(app, services, settings): def register_api_routes(app, services, settings):
db = services['db'] db = services['db']
@@ -42,6 +59,10 @@ def register_api_routes(app, services, settings):
action = request.form.get('action', '') action = request.form.get('action', '')
if not deployment or not action: if not deployment or not action:
return jsonify({'success': False, 'output': 'Missing deployment or action'}) return jsonify({'success': False, 'output': 'Missing deployment or action'})
try:
deployment = require_k8s_name(deployment, 'deployment')
except ValueError as e:
return jsonify({'success': False, 'output': str(e)})
actions = { actions = {
'restart': f'rollout restart deployment/{deployment}', 'restart': f'rollout restart deployment/{deployment}',
@@ -82,6 +103,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
@app.route('/server/battlegroup/action', methods=['POST']) @app.route('/server/battlegroup/action', methods=['POST'])
@auth_req
@limiter.limit("10 per hour") @limiter.limit("10 per hour")
def battlegroup_action(): def battlegroup_action():
action = request.form.get('action', '') action = request.form.get('action', '')
@@ -92,6 +114,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'}) return jsonify({'success': rc == 0, 'output': out + err if out or err else 'No output'})
@app.route('/server/battlegroup/update', methods=['POST']) @app.route('/server/battlegroup/update', methods=['POST'])
@auth_req
@limiter.limit("5 per hour") @limiter.limit("5 per hour")
def battlegroup_update(): def battlegroup_update():
bg_script = settings['kubernetes']['battlegroup_script'] bg_script = settings['kubernetes']['battlegroup_script']
@@ -100,6 +123,7 @@ def register_api_routes(app, services, settings):
# Firewall management # Firewall management
@app.route('/server/firewall') @app.route('/server/firewall')
@auth_req
def firewall_status(): def firewall_status():
port_map = { port_map = {
'filebrowser': {'port': 18888, 'name': 'File Browser'}, 'filebrowser': {'port': 18888, 'name': 'File Browser'},
@@ -134,6 +158,7 @@ def register_api_routes(app, services, settings):
}) })
@app.route('/server/firewall/block', methods=['POST']) @app.route('/server/firewall/block', methods=['POST'])
@auth_req
@limiter.limit("10 per hour") @limiter.limit("10 per hour")
def firewall_block(): def firewall_block():
port = request.form.get('port', type=int) port = request.form.get('port', type=int)
@@ -169,6 +194,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': True, 'output': f'Port {port} blocked (localhost allowed)'}) return jsonify({'success': True, 'output': f'Port {port} blocked (localhost allowed)'})
@app.route('/server/firewall/unblock', methods=['POST']) @app.route('/server/firewall/unblock', methods=['POST'])
@auth_req
@limiter.limit("10 per hour") @limiter.limit("10 per hour")
def firewall_unblock(): def firewall_unblock():
port = request.form.get('port', type=int) port = request.form.get('port', type=int)
@@ -206,6 +232,7 @@ def register_api_routes(app, services, settings):
# Chat API # Chat API
@app.route('/api/chat_logs') @app.route('/api/chat_logs')
@auth_req
def api_chat_logs(): def api_chat_logs():
try: try:
chat_svc.ensure_history_table() chat_svc.ensure_history_table()
@@ -234,6 +261,7 @@ def register_api_routes(app, services, settings):
# Player IP management # Player IP management
@app.route('/api/set_player_ip', methods=['POST']) @app.route('/api/set_player_ip', methods=['POST'])
@auth_req
def api_set_player_ip(): def api_set_player_ip():
try: try:
player_id = request.form.get('player_id', type=int) player_id = request.form.get('player_id', type=int)
@@ -250,6 +278,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
@app.route('/api/detect_player_ips', methods=['POST']) @app.route('/api/detect_player_ips', methods=['POST'])
@auth_req
def api_detect_player_ips(): def api_detect_player_ips():
try: try:
success, message = admin_svc.detect_player_ips(settings['kubernetes']['namespace']) success, message = admin_svc.detect_player_ips(settings['kubernetes']['namespace'])
@@ -259,6 +288,7 @@ def register_api_routes(app, services, settings):
# Ban management # Ban management
@app.route('/api/ban_player', methods=['POST']) @app.route('/api/ban_player', methods=['POST'])
@auth_req
@limiter.limit("5 per hour") @limiter.limit("5 per hour")
def api_ban_player(): def api_ban_player():
try: try:
@@ -276,6 +306,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
@app.route('/api/get_player_ban', methods=['POST']) @app.route('/api/get_player_ban', methods=['POST'])
@auth_req
def api_get_player_ban(): def api_get_player_ban():
try: try:
player_id = request.form.get('player_id', type=int) player_id = request.form.get('player_id', type=int)
@@ -297,6 +328,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
@app.route('/api/get_player_history', methods=['POST']) @app.route('/api/get_player_history', methods=['POST'])
@auth_req
def api_get_player_history(): def api_get_player_history():
try: try:
player_id = request.form.get('player_id', type=int) player_id = request.form.get('player_id', type=int)
@@ -319,6 +351,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
@app.route('/api/unban_player', methods=['POST']) @app.route('/api/unban_player', methods=['POST'])
@auth_req
@limiter.limit("5 per hour") @limiter.limit("5 per hour")
def api_unban_player(): def api_unban_player():
try: try:
@@ -332,6 +365,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
@app.route('/api/emergency_unban', methods=['POST']) @app.route('/api/emergency_unban', methods=['POST'])
@auth_req
def api_emergency_unban(): def api_emergency_unban():
try: try:
ip = request.form.get('ip', '').strip() ip = request.form.get('ip', '').strip()
@@ -343,6 +377,7 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': str(e)}) return jsonify({'success': False, 'error': str(e)})
@app.route('/api/kick_player', methods=['POST']) @app.route('/api/kick_player', methods=['POST'])
@auth_req
@limiter.limit("10 per hour") @limiter.limit("10 per hour")
def api_kick_player(): def api_kick_player():
try: try:
@@ -357,6 +392,7 @@ def register_api_routes(app, services, settings):
# Vitals editing # Vitals editing
@app.route('/api/edit_vitals', methods=['POST']) @app.route('/api/edit_vitals', methods=['POST'])
@auth_req
@limiter.limit("10 per hour") @limiter.limit("10 per hour")
def api_edit_vitals(): def api_edit_vitals():
try: try:
@@ -500,6 +536,7 @@ def register_api_routes(app, services, settings):
# Maintenance # Maintenance
@app.route('/api/maintenance/create_indexes', methods=['POST']) @app.route('/api/maintenance/create_indexes', methods=['POST'])
@auth_req
def api_create_indexes(): def api_create_indexes():
try: try:
success, created, error = admin_svc.create_indexes() success, created, error = admin_svc.create_indexes()
@@ -511,6 +548,7 @@ def register_api_routes(app, services, settings):
# Delete vehicle # Delete vehicle
@app.route('/api/vehicles/<int:vehicle_id>', methods=['DELETE']) @app.route('/api/vehicles/<int:vehicle_id>', methods=['DELETE'])
@auth_req
def delete_vehicle(vehicle_id): def delete_vehicle(vehicle_id):
success, message = vehicle_svc.delete_vehicle(vehicle_id) success, message = vehicle_svc.delete_vehicle(vehicle_id)
if success: if success:
@@ -519,6 +557,7 @@ def register_api_routes(app, services, settings):
# Delete building # Delete building
@app.route('/api/buildings/<int:building_id>', methods=['DELETE']) @app.route('/api/buildings/<int:building_id>', methods=['DELETE'])
@auth_req
def delete_building(building_id): def delete_building(building_id):
conn = db.get_connection() conn = db.get_connection()
if not conn: if not conn:
@@ -745,12 +784,11 @@ def register_api_routes(app, services, settings):
def _validate_fb_path(path): def _validate_fb_path(path):
"""Validate filebrowser path is within allowed directory.""" """Validate filebrowser path is within allowed directory."""
import posixpath import posixpath
normalized = posixpath.normpath(path) path_str = str(path or "").lstrip("/")
if not normalized.startswith(FILEBROWSER_BASE_PATH): if '..' in path_str or '\x00' in path_str:
return False return False
if '..' in path or '\x00' in path: normalized = posixpath.normpath("/" + path_str)
return False return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
return True
def _get_fb_pod(): def _get_fb_pod():
"""Get the FileBrowser pod name dynamically.""" """Get the FileBrowser pod name dynamically."""
@@ -771,7 +809,8 @@ def register_api_routes(app, services, settings):
path = request.form.get('path', '/srv') path = request.form.get('path', '/srv')
if not _validate_fb_path(path): if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'}) return jsonify({'success': False, 'error': 'Invalid path: access denied'})
out, err, rc = _fb_exec(f'ls -la "{path}"', timeout=10) safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'ls -la {safe_path}', timeout=10)
if rc != 0: if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to list directory'}) return jsonify({'success': False, 'error': err or 'Failed to list directory'})
@@ -802,7 +841,8 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'Missing path'}) return jsonify({'success': False, 'error': 'Missing path'})
if not _validate_fb_path(path): if not _validate_fb_path(path):
return jsonify({'success': False, 'error': 'Invalid path: access denied'}) return jsonify({'success': False, 'error': 'Invalid path: access denied'})
out, err, rc = _fb_exec(f'head -c 100000 "{path}"', timeout=10) safe_path = quote_remote(path)
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', timeout=10)
if rc != 0: if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to read file'}) return jsonify({'success': False, 'error': err or 'Failed to read file'})
return jsonify({'success': True, 'content': out, 'path': path}) return jsonify({'success': True, 'content': out, 'path': path})
@@ -819,7 +859,9 @@ def register_api_routes(app, services, settings):
return jsonify({'success': False, 'error': 'Invalid path: access denied'}) return jsonify({'success': False, 'error': 'Invalid path: access denied'})
import base64 import base64
content_b64 = base64.b64encode(content.encode()).decode() content_b64 = base64.b64encode(content.encode()).decode()
out, err, rc = _fb_exec(f'sh -c \'echo {content_b64} | base64 -d > "{path}"\'', timeout=15) safe_path = quote_remote(path)
save_script = quote_remote(f"base64 -d > {safe_path}")
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
if rc != 0: if rc != 0:
return jsonify({'success': False, 'error': err or 'Failed to save file'}) return jsonify({'success': False, 'error': err or 'Failed to save file'})
return jsonify({'success': True}) return jsonify({'success': True})
+3 -2
View File
@@ -141,8 +141,9 @@ class UpdateService:
self._update_status = "Downloading update..." self._update_status = "Downloading update..."
try: try:
# Download latest zip # Download latest zip from the detected branch
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/main.zip" branch = self._current_branch
zip_url = f"https://github.com/{GITHUB_REPO}/archive/refs/heads/{branch}.zip"
req = urllib.request.Request(zip_url) req = urllib.request.Request(zip_url)
req.add_header('User-Agent', 'DuneDashboard-UpdateChecker') req.add_header('User-Agent', 'DuneDashboard-UpdateChecker')
with urllib.request.urlopen(req, timeout=60) as resp: with urllib.request.urlopen(req, timeout=60) as resp:
+59 -1
View File
@@ -5,6 +5,8 @@ import sys
import time import time
import threading import threading
import logging import logging
import re
import shlex
try: try:
import paramiko import paramiko
@@ -19,6 +21,21 @@ logger = logging.getLogger(__name__)
shell_processes = {} shell_processes = {}
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
def require_k8s_name(value, label):
"""Validate that a value is a valid Kubernetes resource name."""
value = str(value or "").strip()
if not value or not K8S_NAME_RE.fullmatch(value):
raise ValueError(f"Invalid {label}")
return value
def quote_remote(value):
"""Shell-quote a value for safe use in remote commands."""
return shlex.quote(str(value))
def register_websocket_handlers(socketio, settings): def register_websocket_handlers(socketio, settings):
if not HAS_PARAMIKO: if not HAS_PARAMIKO:
@@ -27,6 +44,12 @@ def register_websocket_handlers(socketio, settings):
@socketio.on('shell_create') @socketio.on('shell_create')
def handle_shell_create(data): def handle_shell_create(data):
# Check if shell access is enabled
shell_enabled = settings.get('auth', {}).get('shell_enabled', False)
if not shell_enabled:
logger.warning(f"WebSocket shell rejected: shell disabled (sid={request.sid})")
return emit('shell_created', {'success': False, 'error': 'Shell access is disabled'})
# Check if user is authenticated via Flask-Login session # Check if user is authenticated via Flask-Login session
auth_enabled = settings.get('auth', {}).get('enabled', True) auth_enabled = settings.get('auth', {}).get('enabled', True)
if auth_enabled: if auth_enabled:
@@ -55,11 +78,29 @@ def register_websocket_handlers(socketio, settings):
else: else:
namespace = settings['kubernetes']['namespace'] namespace = settings['kubernetes']['namespace']
pod = data.get('pod', '') pod = data.get('pod', '')
try:
pod = require_k8s_name(pod, 'pod')
except ValueError as e:
logger.warning(f"WebSocket shell rejected: invalid pod name (sid={request.sid})")
return emit('shell_created', {'success': False, 'error': str(e)})
# Get valid pods and check if requested pod exists
k8s_ns = settings['kubernetes']['namespace']
check_cmd = f"sudo kubectl get pods -n {k8s_ns} -o custom-columns=NAME:.metadata.name --no-headers"
out, _, rc = _run_ssh_check(server_host, server_user, ssh_key, check_cmd)
if rc == 0:
valid_pods = [p.strip() for p in out.strip().split('\n') if p.strip()]
if pod not in valid_pods:
logger.warning(f"WebSocket shell rejected: unknown pod {pod} (sid={request.sid})")
return emit('shell_created', {'success': False, 'error': 'Unknown pod'})
safe_pod = quote_remote(pod)
safe_ns = quote_remote(namespace)
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10) client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
transport = client.get_transport() transport = client.get_transport()
chan = transport.open_session() chan = transport.open_session()
chan.get_pty(term='xterm-256color', width=80, height=24) chan.get_pty(term='xterm-256color', width=80, height=24)
chan.exec_command(f'sudo kubectl exec -it {pod} -n {namespace} -- /bin/bash') chan.exec_command(f'sudo kubectl exec -it {safe_pod} -n {safe_ns} -- /bin/bash')
shell_processes[shell_id] = {'client': client, 'channel': chan, 'type': shell_type} shell_processes[shell_id] = {'client': client, 'channel': chan, 'type': shell_type}
@@ -120,13 +161,30 @@ def _find_ssh_key(settings):
base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) base_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
temp_dir = os.environ.get('TEMP') or os.environ.get('TMPDIR') or ('/tmp' if os.name != 'nt' else 'C:\\Temp') temp_dir = os.environ.get('TEMP') or os.environ.get('TMPDIR') or ('/tmp' if os.name != 'nt' else 'C:\\Temp')
local_appdata = os.environ.get('LOCALAPPDATA', '')
potential_paths = [ potential_paths = [
os.path.join(temp_dir, 'dune-tunnel-key'), os.path.join(temp_dir, 'dune-tunnel-key'),
os.path.join(temp_dir, 'dune-awakening-server-sshKey'), os.path.join(temp_dir, 'dune-awakening-server-sshKey'),
os.path.join(base_dir, 'internal-scripts', 'ssh', 'sshKey'), os.path.join(base_dir, 'internal-scripts', 'ssh', 'sshKey'),
os.path.join(os.path.dirname(base_dir), 'internal-scripts', 'ssh', 'sshKey'), os.path.join(os.path.dirname(base_dir), 'internal-scripts', 'ssh', 'sshKey'),
] ]
if local_appdata:
potential_paths.insert(2, os.path.join(local_appdata, 'DuneAwakeningServer', 'sshKey'))
for p in potential_paths: for p in potential_paths:
if os.path.exists(p): if os.path.exists(p):
return p return p
return None return None
def _run_ssh_check(host, user, key, command, timeout=10):
"""Run an SSH command and return output."""
import subprocess
try:
result = subprocess.run(
['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'LogLevel=QUIET',
'-i', key, f'{user}@{host}', command],
capture_output=True, text=True, timeout=timeout
)
return result.stdout, result.stderr, result.returncode
except Exception as e:
return '', str(e), 1
+6
View File
@@ -0,0 +1,6 @@
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
addopts = -v --tb=short
+14 -2
View File
@@ -41,13 +41,25 @@ if __name__ == '__main__':
print(f"\n Dune Awakening Dashboard") print(f"\n Dune Awakening Dashboard")
print(f" {protocol}://{host}:{port}") print(f" {protocol}://{host}:{port}")
print(f" Debug: {debug}") print(f" Debug: {debug}")
if debug and host not in ('127.0.0.1', 'localhost', '0.0.0.0'):
print(" [ERROR] Refusing to run debug mode on a non-loopback host!")
print(f" [ERROR] Host '{host}' is not 127.0.0.1, localhost, or 0.0.0.0")
print(" [ERROR] Set dashboard.debug: false in settings.yaml or bind to loopback\n")
sys.exit(1)
if ssl_context: if ssl_context:
print(f" SSL: Enabled\n") print(f" SSL: Enabled\n")
else: else:
print(f" SSL: Disabled (use http:// not https://)\n") print(f" SSL: Disabled (use http:// not https://)\n")
if host == '0.0.0.0': if host == '0.0.0.0' and not os.environ.get('DUNE_ALLOW_INSECURE_REMOTE'):
print(" [ERROR] Refusing to bind 0.0.0.0 without SSL!")
print(" [ERROR] Set DUNE_ALLOW_INSECURE_REMOTE=1 to override (NOT RECOMMENDED)")
print(" [ERROR] Enable SSL in settings.yaml or bind to 127.0.0.1\n")
sys.exit(1)
elif host == '0.0.0.0':
print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.") print(" [WARN] Binding to 0.0.0.0 without SSL! Credentials sent in cleartext.")
print(" [WARN] Enable SSL in settings.yaml or bind to 127.0.0.1\n") print(" [WARN] DUNE_ALLOW_INSECURE_REMOTE is set - override is active\n")
# Start HTTP → HTTPS redirect server when SSL is enabled # Start HTTP → HTTPS redirect server when SSL is enabled
if ssl_context: if ssl_context:
+40
View File
@@ -0,0 +1,40 @@
#!/bin/bash
BG_NAME="sh-b17a5f036d1f7882-bzhczd"
NAMESPACE="funcom-seabass-sh-b17a5f036d1f7882-bzhczd"
echo "Patching battlegroup: $BG_NAME"
sudo kubectl patch battlegroup "$BG_NAME" -n "$NAMESPACE" --type=merge -p '{
"spec": {
"serverGroup": {
"template": {
"spec": {
"sets": [
{
"map": "DeepDesert_1",
"partitions": [8, 30],
"replicas": 2,
"resources": {
"limits": {
"memory": "15Gi"
}
},
"arguments": [
"-FarmRegion=North America Test",
"-RMQGameTlsEnabled=true"
]
}
]
}
}
}
}
}'
if [ $? -eq 0 ]; then
echo "Patch applied successfully"
else
echo "Failed to apply patch"
exit 1
fi
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+77
View File
@@ -0,0 +1,77 @@
"""Test that administrative API routes require authentication"""
import pytest
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ADMIN_ENDPOINTS = [
("post", "/server/battlegroup/action"),
("post", "/server/battlegroup/update"),
("get", "/server/firewall"),
("post", "/server/firewall/block"),
("post", "/server/firewall/unblock"),
("get", "/api/chat_logs"),
("post", "/api/set_player_ip"),
("post", "/api/detect_player_ips"),
("post", "/api/ban_player"),
("post", "/api/get_player_ban"),
("post", "/api/get_player_history"),
("post", "/api/unban_player"),
("post", "/api/emergency_unban"),
("post", "/api/kick_player"),
("post", "/api/edit_vitals"),
("post", "/api/maintenance/create_indexes"),
("delete", "/api/vehicles/1"),
("delete", "/api/buildings/1"),
]
@pytest.fixture
def client(tmp_path, monkeypatch):
settings_path = tmp_path / "settings.yaml"
settings_path.write_text(
"""
server:
host: 127.0.0.1
user: dune
dashboard:
host: 127.0.0.1
port: 5050
debug: false
secret_key: test-secret
database:
host: 127.0.0.1
port: 15433
user: postgres
password: postgres
name: dune
kubernetes:
namespace: test
auth:
enabled: true
username: admin
password_hash: "$argon2id$v=19$m=65536,t=3,p=4$invalid$invalid"
logging:
file: logs/test.log
""",
encoding="utf-8",
)
monkeypatch.setattr("app.services.database.DatabaseService.ensure_tables", lambda self: None)
monkeypatch.setattr("app.services.admin.AdminService.create_indexes", lambda self: (True, [], None))
monkeypatch.setattr("app.services.updater.UpdateService.start_checker", lambda self: None)
from app.factory import create_app
app, _ = create_app(str(settings_path))
app.config.update(TESTING=True, WTF_CSRF_ENABLED=False)
return app.test_client()
@pytest.mark.parametrize(("method", "path"), ADMIN_ENDPOINTS)
def test_admin_endpoints_require_login(client, method, path):
"""All administrative endpoints should require authentication when auth is enabled."""
response = getattr(client, method)(path)
assert response.status_code in (302, 401, 403), f"{method.upper()} {path} returned {response.status_code}, expected 302/401/403"
+43
View File
@@ -0,0 +1,43 @@
"""Test command input validation"""
import pytest
import re
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
def require_k8s_name(value, label):
"""Validate that a value is a valid Kubernetes resource name."""
value = str(value or "").strip()
if not value or not K8S_NAME_RE.fullmatch(value):
raise ValueError(f"Invalid {label}")
return value
class TestK8sNameValidation:
def test_valid_k8s_names(self):
"""Valid Kubernetes resource names should pass."""
assert require_k8s_name('my-app', 'name') == 'my-app'
assert require_k8s_name('nginx', 'name') == 'nginx'
assert require_k8s_name('api-server-7d9f6', 'name') == 'api-server-7d9f6'
assert require_k8s_name('a', 'name') == 'a'
assert require_k8s_name('abc123', 'name') == 'abc123'
def test_invalid_k8s_names(self):
"""Invalid Kubernetes resource names should raise ValueError."""
with pytest.raises(ValueError):
require_k8s_name('', 'name')
with pytest.raises(ValueError):
require_k8s_name(None, 'name')
with pytest.raises(ValueError):
require_k8s_name('MyApp', 'name') # uppercase
with pytest.raises(ValueError):
require_k8s_name('my_app', 'name') # underscore
with pytest.raises(ValueError):
require_k8s_name('my-app-', 'name') # ends with dash
with pytest.raises(ValueError):
require_k8s_name('-app', 'name') # starts with dash
with pytest.raises(ValueError):
require_k8s_name('my app', 'name') # space
with pytest.raises(ValueError):
require_k8s_name('my*app', 'name') # special char
+56
View File
@@ -0,0 +1,56 @@
"""Test filebrowser path validation"""
import pytest
import sys
import os
import posixpath
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
FILEBROWSER_BASE_PATH = '/srv'
def _validate_fb_path(path):
"""Validate filebrowser path is within allowed directory."""
path_str = str(path or "").lstrip("/")
if '..' in path_str or '\x00' in path_str:
return False
normalized = posixpath.normpath("/" + path_str)
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
class TestFileBrowserPathValidation:
def test_valid_root_path(self):
"""Root /srv should be allowed."""
assert _validate_fb_path('/srv') is True
assert _validate_fb_path('srv') is True
def test_valid_subdirectory(self):
"""Subdirectories of /srv should be allowed."""
assert _validate_fb_path('/srv/config') is True
assert _validate_fb_path('/srv/config/settings.ini') is True
assert _validate_fb_path('/srv/nested/deep/path') is True
def test_invalid_false_prefix(self):
"""Paths that start with /srv but are not under /srv should be rejected."""
assert _validate_fb_path('/srv2') is False
assert _validate_fb_path('/srv2/config') is False
assert _validate_fb_path('/srvbackup') is False
def test_invalid_parent_traversal(self):
"""Paths with .. should be rejected."""
assert _validate_fb_path('/srv/../etc') is False
assert _validate_fb_path('/srv/config/../../../etc') is False
assert _validate_fb_path('../settings.yaml') is False
def test_invalid_absolute_path(self):
"""Paths outside /srv should be rejected."""
assert _validate_fb_path('/etc') is False
assert _validate_fb_path('/home') is False
assert _validate_fb_path('/') is False
def test_invalid_null_byte(self):
"""Paths with null bytes should be rejected."""
assert _validate_fb_path('/srv/config\x00') is False
assert _validate_fb_path('/srv/../etc\x00') is False