From 43c87cd5eb9fbed0e06971d544406062602b1f2a Mon Sep 17 00:00:00 2001 From: Juan Denis Date: Sun, 22 Nov 2026 01:44:59 -0500 Subject: [PATCH] Scope fleet-wide server reads to the workspace GHSA-qcjj-hf95-6rgw: the workspace check landed on every route, but the routes that list, search or export across the fleet take no id in the path, so they kept answering from unfiltered Server and ServerMetrics queries. Any account, down to a viewer in no workspace, could enumerate other workspaces' servers and read their metric history. The fleet-monitor reads (heatmap, comparison, alerts, thresholds, anomalies, search, both exports) and the mobile summary and offline cache now take the caller and apply the rule GET /servers uses. A sweep over every parameterless GET route found three more of the same shape, fixed here too: the proxy overview, the metrics retention stats, and server-group membership. --- backend/app/api/fleet_monitor.py | 24 +- backend/app/api/mobile.py | 9 +- backend/app/api/proxy.py | 5 +- backend/app/api/servers.py | 23 +- backend/app/services/fleet_monitor_service.py | 83 +++++-- backend/app/services/proxy_stack_service.py | 10 +- .../app/services/server_metrics_service.py | 32 ++- backend/tests/test_fleet_metrics_batching.py | 6 +- backend/tests/test_fleet_proxy.py | 17 +- .../tests/test_fleet_read_workspace_access.py | 206 ++++++++++++++++++ backend/tests/test_ingress_plane.py | 5 +- 11 files changed, 360 insertions(+), 60 deletions(-) create mode 100644 backend/tests/test_fleet_read_workspace_access.py diff --git a/backend/app/api/fleet_monitor.py b/backend/app/api/fleet_monitor.py index 8802ba18..6e041b53 100644 --- a/backend/app/api/fleet_monitor.py +++ b/backend/app/api/fleet_monitor.py @@ -4,6 +4,10 @@ Fleet Monitor API Endpoints for fleet-wide monitoring: heatmaps, comparisons, alert thresholds, anomaly detection, capacity forecasting, fleet search, and metrics export. + +Every read passes the caller to the service, which answers only for servers +that caller can access — the workspace rule GET /servers applies. These routes +carry no server id in the path, so nothing else enforces it for them. """ from flask import Blueprint, request, jsonify, Response @@ -24,7 +28,7 @@ fleet_monitor_bp = Blueprint('fleet_monitor', __name__) def get_fleet_heatmap(): """Get latest metrics for all servers in heatmap format.""" group_id = request.args.get('group_id') - return jsonify(fleet_monitor_service.get_fleet_heatmap(group_id)) + return jsonify(fleet_monitor_service.get_fleet_heatmap(get_current_user(), group_id)) # ==================== Comparison ==================== @@ -41,7 +45,8 @@ def get_comparison(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - return jsonify(fleet_monitor_service.get_comparison_timeseries(server_ids, metric, period)) + return jsonify(fleet_monitor_service.get_comparison_timeseries( + get_current_user(), server_ids, metric, period)) # ==================== Alerts ==================== @@ -55,7 +60,8 @@ def get_alerts(): server_id = request.args.get('server_id') limit = request.args.get('limit', 50, type=int) - return jsonify(fleet_monitor_service.get_alerts(status, severity, server_id, limit)) + return jsonify(fleet_monitor_service.get_alerts( + get_current_user(), status, severity, server_id, limit)) @fleet_monitor_bp.route('/alerts//acknowledge', methods=['POST']) @@ -89,7 +95,7 @@ def resolve_alert(alert_id): def get_thresholds(): """Get alert thresholds.""" server_id = request.args.get('server_id') - return jsonify(fleet_monitor_service.get_thresholds(server_id)) + return jsonify(fleet_monitor_service.get_thresholds(get_current_user(), server_id)) @fleet_monitor_bp.route('/thresholds', methods=['POST']) @@ -120,7 +126,7 @@ def delete_threshold(threshold_id): def get_anomalies(): """Get anomaly detection results.""" server_id = request.args.get('server_id') - return jsonify(fleet_monitor_service.detect_anomalies(server_id)) + return jsonify(fleet_monitor_service.detect_anomalies(get_current_user(), server_id)) # ==================== Capacity Forecast ==================== @@ -146,7 +152,7 @@ def search_fleet(): if not query or len(query) < 2: return jsonify({'error': 'Query must be at least 2 characters'}), 400 - return jsonify(fleet_monitor_service.search_fleet(query, search_type)) + return jsonify(fleet_monitor_service.search_fleet(get_current_user(), query, search_type)) # ==================== Export ==================== @@ -163,7 +169,8 @@ def export_csv(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - csv_data = fleet_monitor_service.export_metrics_csv(server_ids, metric, period) + csv_data = fleet_monitor_service.export_metrics_csv( + get_current_user(), server_ids, metric, period) return Response( csv_data, mimetype='text/csv', @@ -183,7 +190,8 @@ def export_json(): if not server_ids: return jsonify({'error': 'ids parameter is required'}), 400 - return jsonify(fleet_monitor_service.get_comparison_timeseries(server_ids, metric, period)) + return jsonify(fleet_monitor_service.get_comparison_timeseries( + get_current_user(), server_ids, metric, period)) # ==================== Prometheus ==================== diff --git a/backend/app/api/mobile.py b/backend/app/api/mobile.py index 5b2a6e78..74ec231f 100644 --- a/backend/app/api/mobile.py +++ b/backend/app/api/mobile.py @@ -4,6 +4,8 @@ from app.models.user import User from app import db from app.exceptions import not_found from app.api._request import json_object +from app.middleware.rbac import get_current_user +from app.services.workspace_service import WorkspaceService mobile_bp = Blueprint('mobile', __name__) @@ -100,7 +102,9 @@ def get_mobile_summary(): from app.models.server import Server from app.models.security_alert import SecurityAlert - server_count = Server.query.count() + # Only the servers this caller can reach — the workspace rule /servers applies. + server_count = WorkspaceService.filter_accessible_servers( + Server.query, get_current_user()).count() active_alerts = SecurityAlert.query.filter_by(resolved=False).count() if hasattr(SecurityAlert, 'resolved') else 0 # MonitoringService returns nested sections; a section that could not be @@ -122,7 +126,8 @@ def get_offline_data(): """Get data for offline caching.""" from app.models.server import Server - servers = Server.query.limit(50).all() + servers = WorkspaceService.filter_accessible_servers( + Server.query, get_current_user()).limit(50).all() return jsonify({ 'servers': [{'id': s.id, 'name': s.name, 'hostname': s.hostname, 'status': s.status} for s in servers], 'cached_at': __import__('datetime').datetime.utcnow().isoformat(), diff --git a/backend/app/api/proxy.py b/backend/app/api/proxy.py index 1fe8e648..d1dee8dd 100644 --- a/backend/app/api/proxy.py +++ b/backend/app/api/proxy.py @@ -33,14 +33,15 @@ def _require_server(server_id): @proxy_bp.route('/proxy/overview', methods=['GET']) @jwt_required() def proxy_overview(): - """Fleet-wide proxy posture: one row per server. + """Fleet-wide proxy posture: one row per server the caller can access. Mounted under ``/api/v1/servers`` → full path ``/api/v1/servers/proxy/ overview``. The static ``proxy`` segment can't match the ```` converter on ``//proxy``, and Werkzeug prefers static rules over dynamic ones, so the two never collide. Best-effort; always returns JSON. """ - return jsonify({'servers': ProxyStackService.fleet_overview()}) + from app.middleware.rbac import get_current_user + return jsonify({'servers': ProxyStackService.fleet_overview(get_current_user())}) @proxy_bp.route('//proxy', methods=['GET']) diff --git a/backend/app/api/servers.py b/backend/app/api/servers.py index ff51cb0c..fa821e1d 100644 --- a/backend/app/api/servers.py +++ b/backend/app/api/servers.py @@ -100,6 +100,20 @@ def _get_operable_server(server_id): return server +def _group_dict(group, include_servers=False): + """A server group as the current user sees it: a group is a fleet-wide + label, but its members and their count stop at the servers the caller + can access, so a group never lists a foreign workspace's servers.""" + from app.services.workspace_service import WorkspaceService + user = get_current_user() + servers = [s for s in group.servers if WorkspaceService.can_access_server(user, s)] + result = group.to_dict() + result['server_count'] = len(servers) + if include_servers: + result['servers'] = [s.to_dict() for s in servers] + return result + + def _ip_pattern_errors(allowed_ips): """One message per invalid allow-list entry; empty when all are valid.""" if not isinstance(allowed_ips, list): @@ -217,9 +231,10 @@ PERMISSION_PROFILES = { @servers_bp.route('/groups', methods=['GET']) @jwt_required() def list_groups(): - """List all server groups""" + """List all server groups. Groups are fleet-wide labels; the member + count is of the servers the caller can access.""" groups = ServerGroup.query.all() - return jsonify([g.to_dict() for g in groups]) + return jsonify([_group_dict(g) for g in groups]) @servers_bp.route('/groups', methods=['POST']) @@ -253,7 +268,7 @@ def get_group(group_id): if not group: return jsonify({'error': 'Group not found'}), 404 - return jsonify(group.to_dict(include_servers=True)) + return jsonify(_group_dict(group, include_servers=True)) @servers_bp.route('/groups/', methods=['PUT']) @@ -1300,7 +1315,7 @@ def get_server_metrics_aggregated(server_id): @developer_required def get_metrics_retention_stats(): """Get metrics retention statistics.""" - result = ServerMetricsService.get_retention_stats() + result = ServerMetricsService.get_retention_stats(get_current_user()) return jsonify(result) diff --git a/backend/app/services/fleet_monitor_service.py b/backend/app/services/fleet_monitor_service.py index 8f2b8d74..9e5185e0 100644 --- a/backend/app/services/fleet_monitor_service.py +++ b/backend/app/services/fleet_monitor_service.py @@ -20,6 +20,7 @@ from app.models.server import Server, ServerMetrics, ServerGroup from app.models.metric_alert import ServerAlertThreshold, MetricAlert from app.services.agent_registry import agent_registry from app.services.server_metrics_service import latest_metrics_by_server +from app.services.workspace_service import WorkspaceService logger = logging.getLogger(__name__) @@ -32,15 +33,40 @@ METRIC_COLUMNS = { } +def _visible_servers(user, query=None): + """A Server query narrowed to what *user* may see — the same workspace + rule as GET /servers. Every read below goes through this or + `_visible_server`; the unscoped `Server.query` is for the system-level + passes only (threshold checks, the token-gated Prometheus scrape).""" + return WorkspaceService.filter_accessible_servers( + Server.query if query is None else query, user) + + +def _visible_server(user, server_id): + """The server if *user* may see it, else None — a foreign id reads + exactly like an unknown one.""" + return WorkspaceService.get_accessible_server(user, server_id) + + +def _visible_server_ids(user): + """Subquery of the server ids *user* may see, for filtering child rows.""" + return WorkspaceService.filter_accessible_servers( + db.session.query(Server.id), user) + + class FleetMonitorService: - """Service for fleet-wide monitoring and alerting.""" + """Service for fleet-wide monitoring and alerting. + + The read methods take the calling ``user`` and answer only for servers that + user can access (GHSA-qcjj-hf95-6rgw). + """ # ==================== Fleet Heatmap ==================== @staticmethod - def get_fleet_heatmap(group_id: str = None) -> List[Dict]: - """Get latest metrics for all servers, shaped for heatmap display.""" - query = Server.query + def get_fleet_heatmap(user, group_id: str = None) -> List[Dict]: + """Latest metrics for the servers *user* can access, shaped for heatmap display.""" + query = _visible_servers(user) if group_id: query = query.filter_by(group_id=group_id) @@ -70,9 +96,11 @@ class FleetMonitorService: @staticmethod def get_comparison_timeseries( - server_ids: List[str], metric: str = 'cpu', period: str = '24h' + user, server_ids: List[str], metric: str = 'cpu', period: str = '24h' ) -> Dict: - """Get time-series data for multiple servers for overlay charting.""" + """Get time-series data for multiple servers for overlay charting. + + Ids *user* cannot access are skipped, like ids that do not exist.""" hours_back = {'1h': 1, '6h': 6, '24h': 24, '7d': 168, '30d': 720}.get(period, 24) interval = {'1h': 1, '6h': 5, '24h': 15, '7d': 60, '30d': 360}.get(period, 15) cutoff = datetime.utcnow() - timedelta(hours=hours_back) @@ -80,7 +108,7 @@ class FleetMonitorService: series = [] for server_id in server_ids: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue @@ -113,9 +141,17 @@ class FleetMonitorService: # ==================== Alert Thresholds ==================== @staticmethod - def get_thresholds(server_id: str = None) -> List[Dict]: - """Get alert thresholds, optionally filtered by server.""" + def get_thresholds(user, server_id: str = None) -> List[Dict]: + """Get alert thresholds, optionally filtered by server. + + Global defaults (no server) are fleet policy and visible to everyone; + per-server overrides only for servers *user* can access.""" query = ServerAlertThreshold.query + if not user.is_admin: + query = query.filter( + (ServerAlertThreshold.server_id == None) | # noqa: E711 + ServerAlertThreshold.server_id.in_(_visible_server_ids(user)) + ) if server_id: query = query.filter( (ServerAlertThreshold.server_id == server_id) | @@ -286,11 +322,13 @@ class FleetMonitorService: @staticmethod def get_alerts( - status: str = None, severity: str = None, + user, status: str = None, severity: str = None, server_id: str = None, limit: int = 50 ) -> List[Dict]: - """Get metric alerts with filters.""" + """Get metric alerts for the servers *user* can access, with filters.""" query = MetricAlert.query.order_by(MetricAlert.created_at.desc()) + if not user.is_admin: + query = query.filter(MetricAlert.server_id.in_(_visible_server_ids(user))) if status: query = query.filter_by(status=status) if severity: @@ -322,9 +360,12 @@ class FleetMonitorService: # ==================== Anomaly Detection ==================== @staticmethod - def detect_anomalies(server_id: str = None) -> List[Dict]: + def detect_anomalies(user, server_id: str = None) -> List[Dict]: """Simple z-score anomaly detection on 7-day hourly averages.""" - servers = [Server.query.get(server_id)] if server_id else Server.query.filter_by(status='online').all() + if server_id: + servers = [_visible_server(user, server_id)] + else: + servers = _visible_servers(user).filter_by(status='online').all() cutoff = datetime.utcnow() - timedelta(days=7) anomalies = [] @@ -484,14 +525,14 @@ class FleetMonitorService: # ==================== Fleet Search ==================== @staticmethod - def search_fleet(query: str, search_type: str = 'any') -> List[Dict]: - """Search across all servers for containers, services, or ports.""" + def search_fleet(user, query: str, search_type: str = 'any') -> List[Dict]: + """Search the servers *user* can access for containers, services, or ports.""" query_lower = query.lower() results = [] # Search server names and hostnames if search_type in ('any', 'server'): - servers = Server.query.filter( + servers = _visible_servers(user).filter( (Server.name.ilike(f'%{query}%')) | (Server.hostname.ilike(f'%{query}%')) | (Server.ip_address.ilike(f'%{query}%')) @@ -510,7 +551,7 @@ class FleetMonitorService: if search_type in ('any', 'container'): connected = agent_registry.get_connected_servers() for server_id in connected: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue @@ -536,7 +577,7 @@ class FleetMonitorService: # Search tags if search_type in ('any', 'tag'): - all_servers = Server.query.all() + all_servers = _visible_servers(user).all() for s in all_servers: if s.tags: for tag in s.tags: @@ -608,8 +649,8 @@ class FleetMonitorService: # ==================== CSV Export ==================== @staticmethod - def export_metrics_csv(server_ids: List[str], metric: str = 'cpu', period: str = '24h') -> str: - """Export metrics as CSV string.""" + def export_metrics_csv(user, server_ids: List[str], metric: str = 'cpu', period: str = '24h') -> str: + """Export metrics as CSV string, for the ids *user* can access.""" hours_back = {'1h': 1, '6h': 6, '24h': 24, '7d': 168, '30d': 720}.get(period, 24) cutoff = datetime.utcnow() - timedelta(hours=hours_back) col_name = METRIC_COLUMNS.get(metric, 'cpu_percent') @@ -619,7 +660,7 @@ class FleetMonitorService: writer.writerow(['timestamp', 'server_id', 'server_name', metric]) for server_id in server_ids: - server = Server.query.get(server_id) + server = _visible_server(user, server_id) if not server: continue diff --git a/backend/app/services/proxy_stack_service.py b/backend/app/services/proxy_stack_service.py index 7056ae29..0abd502d 100644 --- a/backend/app/services/proxy_stack_service.py +++ b/backend/app/services/proxy_stack_service.py @@ -478,10 +478,10 @@ class ProxyStackService: return None @staticmethod - def fleet_overview(): - """Fleet-wide proxy posture: one row per server. + def fleet_overview(user): + """Fleet-wide proxy posture: one row per server *user* can access. - Best-effort and guarded — never raises. Joins every ``Server`` with its + Best-effort and guarded — never raises. Joins each such ``Server`` with its ``ProxyStack`` (if one exists). Servers that never opted into a managed stack report the host-nginx default (``proxy_type='nginx'``, ``status='host'``) rather than being omitted, so the dashboard shows the @@ -499,7 +499,9 @@ class ProxyStackService: return [] try: - servers = Server.query.order_by(Server.name).all() + from app.services.workspace_service import WorkspaceService + servers = WorkspaceService.filter_accessible_servers( + Server.query, user).order_by(Server.name).all() except Exception as e: # pragma: no cover - DB guard logger.warning(f"fleet_overview server query failed: {e}") return [] diff --git a/backend/app/services/server_metrics_service.py b/backend/app/services/server_metrics_service.py index 12356b7f..e9919e87 100644 --- a/backend/app/services/server_metrics_service.py +++ b/backend/app/services/server_metrics_service.py @@ -13,7 +13,7 @@ from typing import Dict, List, Optional, Any from sqlalchemy import func, and_ from app import db -from app.models.server import ServerMetrics +from app.models.server import Server, ServerMetrics logger = logging.getLogger(__name__) @@ -284,28 +284,38 @@ class ServerMetricsService: return deleted @classmethod - def get_retention_stats(cls) -> Dict[str, Any]: - """Get statistics about metrics retention. + def get_retention_stats(cls, user) -> Dict[str, Any]: + """Get statistics about metrics retention, over the servers *user* + can access (admins: all of them). Returns: Dict with record counts, date ranges, and storage info """ try: - # Total count - total_count = ServerMetrics.query.count() - - # Count per server - server_counts = db.session.query( + from app.services.workspace_service import WorkspaceService + metrics = ServerMetrics.query + counts = db.session.query( ServerMetrics.server_id, func.count().label('count') - ).group_by(ServerMetrics.server_id).all() + ) + if not user.is_admin: + visible = WorkspaceService.filter_accessible_servers( + db.session.query(Server.id), user) + metrics = metrics.filter(ServerMetrics.server_id.in_(visible)) + counts = counts.filter(ServerMetrics.server_id.in_(visible)) + + # Total count + total_count = metrics.count() + + # Count per server + server_counts = counts.group_by(ServerMetrics.server_id).all() # Date range - oldest = ServerMetrics.query.order_by( + oldest = metrics.order_by( ServerMetrics.timestamp.asc() ).first() - newest = ServerMetrics.query.order_by( + newest = metrics.order_by( ServerMetrics.timestamp.desc() ).first() diff --git a/backend/tests/test_fleet_metrics_batching.py b/backend/tests/test_fleet_metrics_batching.py index 7d7b07d3..55b9e994 100644 --- a/backend/tests/test_fleet_metrics_batching.py +++ b/backend/tests/test_fleet_metrics_batching.py @@ -8,6 +8,7 @@ from sqlalchemy import event from app import db from app.models.server import Server, ServerMetrics +from factories import make_user from app.services.fleet_monitor_service import FleetMonitorService from app.services.server_metrics_service import latest_metrics_by_server @@ -79,10 +80,11 @@ def test_each_fleet_reader_uses_one_metrics_query( # Arrives later, but describes an older observation. seed_sample(server, now - timedelta(hours=1), 20) db.session.commit() + admin = make_user(db, role='admin') with metric_queries() as queries: if reader == 'heatmap': - result = FleetMonitorService.get_fleet_heatmap() + result = FleetMonitorService.get_fleet_heatmap(admin) assert len(result) == size assert all(row['cpu'] == 10 for row in result) elif reader == 'prometheus': @@ -115,7 +117,7 @@ def test_heatmap_keeps_group_scope_and_missing_metrics(app, db_session): included.group_id = group.id seed_server('excluded') db.session.commit() - result = FleetMonitorService.get_fleet_heatmap(group.id) + result = FleetMonitorService.get_fleet_heatmap(make_user(db, role='admin'), group.id) assert len(result) == 1 assert result[0]['id'] == included.id assert result[0]['group_name'] == 'selected' diff --git a/backend/tests/test_fleet_proxy.py b/backend/tests/test_fleet_proxy.py index 7e5fbe0a..b39450cb 100644 --- a/backend/tests/test_fleet_proxy.py +++ b/backend/tests/test_fleet_proxy.py @@ -13,6 +13,13 @@ from app.services.proxy_stack_service import ProxyStackService as PS from app.models.proxy_stack import ProxyStack # noqa: F401 +def _admin(): + """The overview is scoped to its caller; an admin sees the whole fleet.""" + from app import db + from factories import make_user + return make_user(db, role='admin') + + def _make_server(name, agent_id): from app import db from app.models.server import Server @@ -28,7 +35,7 @@ def _make_server(name, agent_id): def test_fleet_overview_empty_when_no_servers(app): with app.app_context(): - assert PS.fleet_overview() == [] + assert PS.fleet_overview(_admin()) == [] def test_fleet_overview_one_row_per_server(app): @@ -37,7 +44,7 @@ def test_fleet_overview_one_row_per_server(app): sid_b = _make_server('bravo', 'agent-fp-b') sid_c = _make_server('charlie', 'agent-fp-c') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) # A row for every server, even ones that never opted into a stack. assert len(overview) == 3 ids = {row['server_id'] for row in overview} @@ -61,7 +68,7 @@ def test_fleet_overview_one_row_per_server(app): def test_fleet_overview_host_default_for_unconfigured(app): with app.app_context(): sid = _make_server('hostonly', 'agent-fp-host') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) assert len(overview) == 1 row = overview[0] # No managed stack → host nginx, status 'host'. @@ -80,7 +87,7 @@ def test_fleet_overview_reflects_configured_stack(app): # Configure one server onto a managed Traefik stack. PS.configure(sid_traefik, proxy_type='traefik') - overview = PS.fleet_overview() + overview = PS.fleet_overview(_admin()) by_id = {row['server_id']: row for row in overview} # Configured server reflects its stack type; not the host default. @@ -120,7 +127,7 @@ def test_fleet_overview_recommendation_levels(app): # info: a stack server running with no apps yet. PS.switch(sid_idle_stack, 'caddy') - rows = {r['server_id']: r for r in PS.fleet_overview()} + rows = {r['server_id']: r for r in PS.fleet_overview(_admin())} warn = rows[sid_warn]['recommendation'] assert warn['level'] == 'warn' diff --git a/backend/tests/test_fleet_read_workspace_access.py b/backend/tests/test_fleet_read_workspace_access.py new file mode 100644 index 00000000..788a0d8a --- /dev/null +++ b/backend/tests/test_fleet_read_workspace_access.py @@ -0,0 +1,206 @@ +"""Fleet-wide READ routes obey the same workspace rule as /servers +(GHSA-qcjj-hf95-6rgw). + +`test_server_workspace_access.py` sweeps every `` route. The +routes here take no id in the path — they list, search or export across the +fleet, or take ids in the query string — so that sweep never reached them and +they answered from unfiltered `Server` / `ServerMetrics` queries. +""" +import re +from datetime import datetime, timedelta + +import pytest + +from factories import headers_for, make_server, make_user + +NAME = 'frw-tenantb-billing-db' +HOST = 'frw-billing.internal' +IP = '10.99.77.5' +CONTAINER = 'frw-ledger-postgres' +TAG = 'frw-pci-scope' + + +@pytest.fixture +def setup(app): + from app import db + from app.models.metric_alert import MetricAlert, ServerAlertThreshold + from app.models.server import ServerGroup, ServerMetrics + from app.services.workspace_service import WorkspaceService + + admin = make_user(db, 'frw_admin', 'admin') + member = make_user(db, 'frw_member', 'developer') + outsider = make_user(db, 'frw_outsider', 'developer') + viewer = make_user(db, 'frw_viewer', 'viewer') + ws = WorkspaceService.create_workspace({'name': 'FRW'}, admin.id) + WorkspaceService.add_member(ws.id, member.id) + WorkspaceService.create_workspace({'name': 'FRW-out'}, outsider.id) + + # Groups are fleet-wide labels, so a foreign server can sit in one. + group = ServerGroup(name='frw-group') + db.session.add(group) + db.session.commit() + server = make_server(db, name=NAME, hostname=HOST, ip_address=IP, + status='online', tags=[TAG], workspace_id=ws.id, + group_id=group.id) + # A flat week with a spike at the end: enough samples for the comparison + # and export routes, and an outlier for the anomaly detector. + now = datetime.utcnow() + for i in range(30): + last = i == 29 + db.session.add(ServerMetrics( + server_id=server.id, + timestamp=now - timedelta(minutes=(29 - i) * 20), + cpu_percent=99.0 if last else 10.0 + (i % 2), + memory_percent=88.2, disk_percent=91.4, + extra={'containers': [{'name': CONTAINER, 'image': 'postgres:16', + 'status': 'running'}]})) + db.session.add(MetricAlert(server_id=server.id, metric='cpu', + severity='critical', value=99.0, threshold=95.0)) + db.session.add(ServerAlertThreshold(server_id=server.id, metric='cpu')) + db.session.add(ServerAlertThreshold(server_id=None, metric='disk')) + db.session.commit() + return {'server': server.id, 'group': group.id, 'admin': admin.id, + 'member': member.id, 'outsider': outsider.id, 'viewer': viewer.id} + + +def _leaks(setup, text): + return [needle for needle in (setup['server'], NAME, HOST, IP, CONTAINER, TAG) + if needle in text] + + +def _fleet_reads(sid, gid): + return [ + f'/api/v1/servers/groups/{gid}', + '/api/v1/servers/proxy/overview', + '/api/v1/fleet-monitor/heatmap', + f'/api/v1/fleet-monitor/comparison?ids={sid}&metric=cpu&period=24h', + '/api/v1/fleet-monitor/alerts', + f'/api/v1/fleet-monitor/alerts?server_id={sid}', + '/api/v1/fleet-monitor/thresholds', + f'/api/v1/fleet-monitor/thresholds?server_id={sid}', + '/api/v1/fleet-monitor/anomalies', + f'/api/v1/fleet-monitor/anomalies?server_id={sid}', + '/api/v1/fleet-monitor/search?q=frw-', + '/api/v1/fleet-monitor/search?q=10.99', + '/api/v1/fleet-monitor/search?q=frw-ledger&type=container', + '/api/v1/fleet-monitor/search?q=frw-pci&type=tag', + f'/api/v1/fleet-monitor/export/csv?ids={sid}&metric=memory', + f'/api/v1/fleet-monitor/export/json?ids={sid}&metric=cpu', + '/api/v1/mobile/offline-cache', + ] + + +# Developer-only reads: a viewer is refused outright, before any scoping. +_DEVELOPER_READS = ['/api/v1/servers/metrics/retention'] + + +@pytest.mark.parametrize('who', ['outsider', 'viewer']) +def test_non_member_reads_nothing_about_a_foreign_server(client, setup, who): + leaked = {} + with _connected(setup['server']): + for url in _fleet_reads(setup['server'], setup['group']) + _DEVELOPER_READS: + resp = client.get(url, headers=headers_for(setup[who])) + if who == 'viewer' and url in _DEVELOPER_READS: + assert resp.status_code == 403, (url, resp.status_code) + else: + assert resp.status_code == 200, (url, resp.status_code) + found = _leaks(setup, resp.get_data(as_text=True)) + if found: + leaked[url] = found + assert not leaked, leaked + + +@pytest.mark.parametrize('who', ['member', 'admin']) +def test_member_and_admin_still_read_their_server(client, setup, who): + """The fix narrows, it must not blank the page for people who belong.""" + missing = [] + with _connected(setup['server']): + for url in _fleet_reads(setup['server'], setup['group']) + _DEVELOPER_READS: + resp = client.get(url, headers=headers_for(setup[who])) + assert resp.status_code == 200, (url, resp.status_code) + if not _leaks(setup, resp.get_data(as_text=True)): + missing.append(url) + assert not missing, missing + + +def test_global_thresholds_stay_visible_to_everyone(client, setup): + """A threshold with no server is fleet policy, not a tenant's data.""" + rows = client.get('/api/v1/fleet-monitor/thresholds', + headers=headers_for(setup['outsider'])).get_json() + assert [r['metric'] for r in rows] == ['disk'] + assert rows[0]['server_id'] is None + + +def test_mobile_summary_counts_only_accessible_servers(client, setup): + def count(who): + return client.get('/api/v1/mobile/summary', + headers=headers_for(setup[who])).get_json()['servers'] + assert count('member') == count('outsider') + 1 + assert count('admin') == count('member') + + +def test_comparison_keeps_accessible_ids_and_drops_foreign_ones(client, setup, app): + """A mixed id list answers for the caller's own servers only — the foreign + id is dropped silently, exactly as an unknown id already was.""" + from app import db + from app.models.server import ServerMetrics + own = make_server(db, name='frw-shared-box') + db.session.add(ServerMetrics(server_id=own.id, cpu_percent=5.0)) + db.session.commit() + body = client.get( + f"/api/v1/fleet-monitor/comparison?ids={setup['server']},{own.id}", + headers=headers_for(setup['outsider'])).get_json() + assert [s['server_id'] for s in body['series']] == [own.id] + + +def _connected(server_id): + from unittest.mock import patch + return patch('app.services.agent_registry.agent_registry.get_connected_servers', + return_value=[server_id]) + + +def test_group_member_count_stops_at_accessible_servers(client, setup): + def count(who): + rows = client.get('/api/v1/servers/groups', + headers=headers_for(setup[who])).get_json() + return next(r['server_count'] for r in rows if r['id'] == setup['group']) + assert (count('outsider'), count('member'), count('admin')) == (0, 1, 1) + + +def _fleet_get_rules(app, setup): + """Every GET route with no path parameter, plus the ones keyed by a server + group. `` routes have their own sweep in + test_server_workspace_access.py.""" + for rule in app.url_map.iter_rules(): + if not rule.rule.startswith('/api/v1/') or 'GET' not in rule.methods: + continue + url = rule.rule.replace('', setup['group']) + if '<' in url: + continue + yield url + + +def test_no_fleet_read_route_leaks_a_foreign_server(app, client, setup): + """Sweep: whatever list/search/export/summary route exists — including one + added after this test — a developer outside the workspace never gets the + foreign server's id, name, hostname, IP, tag or container back. The + member test above proves those needles are reachable through the same + routes, so an empty answer here is the filter and not a blank fixture.""" + sid = setup['server'] + # Ask for the foreign server every way a route might accept: an id-taking + # route answers for it, a search route matches it, the rest ignore it. + query = f'?ids={sid}&server_id={sid}&q=frw-&query=frw-&search=frw-' + leaks = [] + with _connected(sid): + for rule in sorted(set(_fleet_get_rules(app, setup))): + url = rule + query + try: + resp = client.get(url, headers=headers_for(setup['outsider'])) + except Exception as exc: # a route that crashes is not a leak + if re.search('frw-', str(exc)): + leaks.append(f'GET {url} raised with the server in it') + continue + found = _leaks(setup, resp.get_data(as_text=True)) + if found: + leaks.append(f'GET {url} -> {resp.status_code} {found}') + assert not leaks, '\n'.join(leaks) diff --git a/backend/tests/test_ingress_plane.py b/backend/tests/test_ingress_plane.py index bb0e529d..c830dce1 100644 --- a/backend/tests/test_ingress_plane.py +++ b/backend/tests/test_ingress_plane.py @@ -104,7 +104,10 @@ def test_fleet_overview_reports_mismatch_counts(app): s = _make_server(app, 'fleet-srv') ProxyStackService.switch(s.id, 'caddy') _make_app(s.id, 'php', name='php-site') # nginx plane on a caddy server -> mismatch - rows = {r['server_id']: r for r in ProxyStackService.fleet_overview()} + from app import db + from factories import make_user + admin = make_user(db, role='admin') + rows = {r['server_id']: r for r in ProxyStackService.fleet_overview(admin)} row = rows[s.id] assert row['proxy_type'] == 'caddy' assert row['app_count'] == 1