Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

fix(dashboard): avoid content blockers on metrics history requests (#133)

Rebertt Rodriguesa092ba1afe56
diff --git a/backend/app/api/metrics.py b/backend/app/api/metrics.py
index f25b74fa..5500e970 100644
--- a/backend/app/api/metrics.py
+++ b/backend/app/api/metrics.py
@@ -8,6 +8,19 @@ from app.services.metrics_history_service import MetricsHistoryService
metrics_bp = Blueprint('metrics', __name__)
+def metrics_history_response():
+ """Return validated local metrics history for either API route."""
+ period = request.args.get('period', '1h')
+ valid_periods = ['1h', '6h', '24h', '7d', '30d']
+ if period not in valid_periods:
+ return jsonify({
+ 'error': f"Invalid period. Must be one of: {', '.join(valid_periods)}"
+ }), 400
+
+ data = MetricsHistoryService.get_history(period)
+ return jsonify(data), 200
+
+
@metrics_bp.route('/history', methods=['GET'])
@viewer_required
def get_metrics_history():
@@ -19,17 +32,7 @@ def get_metrics_history():
Returns:
JSON with time-series data points and summary statistics
"""
- period = request.args.get('period', '1h')
-
- # Validate period
- valid_periods = ['1h', '6h', '24h', '7d', '30d']
- if period not in valid_periods:
- return jsonify({
- 'error': f"Invalid period. Must be one of: {', '.join(valid_periods)}"
- }), 400
-
- data = MetricsHistoryService.get_history(period)
- return jsonify(data), 200
+ return metrics_history_response()
@metrics_bp.route('/stats', methods=['GET'])
diff --git a/backend/app/api/system.py b/backend/app/api/system.py
index 45244a8f..196e096e 100644
--- a/backend/app/api/system.py
+++ b/backend/app/api/system.py
@@ -7,7 +7,8 @@ from flask_jwt_extended import jwt_required, get_jwt_identity
from app.error_reporting import unexpected_response
from app.exceptions import ValidationError
from app.models import User
-from app.middleware.rbac import admin_required, get_current_user
+from app.middleware.rbac import admin_required, get_current_user, viewer_required
+from app.api.metrics import metrics_history_response
from app.services.system_service import SystemService
from app.services.resource_tier_service import ResourceTierService
from app.services import install_profile_service
@@ -149,6 +150,13 @@ def get_metrics():
return jsonify(metrics), 200
+@system_bp.route('/performance-history', methods=['GET'])
+@viewer_required
+def get_performance_history():
+ """Get local metrics history through a content-blocker-safe route."""
+ return metrics_history_response()
+
+
@system_bp.route('/info', methods=['GET'])
@jwt_required()
def get_system_info():
diff --git a/backend/tests/test_metrics_history_routes.py b/backend/tests/test_metrics_history_routes.py
new file mode 100644
index 00000000..fb90c2f9
--- /dev/null
+++ b/backend/tests/test_metrics_history_routes.py
@@ -0,0 +1,65 @@
+"""Compatibility tests for the local metrics-history routes."""
+
+import pytest
+
+from app.services.metrics_history_service import MetricsHistoryService
+
+
+HISTORY_PATHS = (
+ '/api/v1/metrics/history',
+ '/api/v1/system/performance-history',
+)
+VALID_PERIODS = ('1h', '6h', '24h', '7d', '30d')
+
+
[email protected]('period', VALID_PERIODS)
+def test_history_routes_return_the_same_payload(
+ client, viewer_headers, monkeypatch, period):
+ calls = []
+ payload = {
+ 'period': period,
+ 'points': 1,
+ 'data': [{'timestamp': '2026-09-03T12:00:00Z'}],
+ 'summary': {'cpu': {'average': 12.5}},
+ }
+
+ def fake_get_history(_cls, requested_period):
+ calls.append(requested_period)
+ return payload
+
+ monkeypatch.setattr(
+ MetricsHistoryService, 'get_history', classmethod(fake_get_history))
+
+ old_response = client.get(
+ f'{HISTORY_PATHS[0]}?period={period}', headers=viewer_headers)
+ new_response = client.get(
+ f'{HISTORY_PATHS[1]}?period={period}', headers=viewer_headers)
+
+ assert old_response.status_code == 200
+ assert new_response.status_code == 200
+ assert old_response.get_json() == new_response.get_json() == payload
+ assert calls == [period, period]
+
+
[email protected]('path', HISTORY_PATHS)
+def test_history_routes_require_authentication(client, path):
+ response = client.get(f'{path}?period=1h')
+
+ assert response.status_code == 401
+
+
[email protected]('path', HISTORY_PATHS)
+def test_history_routes_reject_invalid_periods(
+ client, viewer_headers, monkeypatch, path):
+ def fail_if_called(_cls, _period):
+ raise AssertionError('invalid periods must not reach the service')
+
+ monkeypatch.setattr(
+ MetricsHistoryService, 'get_history', classmethod(fail_if_called))
+
+ response = client.get(f'{path}?period=2h', headers=viewer_headers)
+
+ assert response.status_code == 400
+ assert response.get_json() == {
+ 'error': 'Invalid period. Must be one of: 1h, 6h, 24h, 7d, 30d'
+ }
diff --git a/docs/API_SURFACE.md b/docs/API_SURFACE.md
index a9e9a896..cb893a85 100644
--- a/docs/API_SURFACE.md
+++ b/docs/API_SURFACE.md
@@ -664,6 +664,7 @@ Regenerate (backend/):
- `GET /system/metrics`
- `GET /system/network`
- `GET /system/notices`
+- `GET /system/performance-history`
- `GET /system/processes`
- `GET /system/resource-tier`
- `GET /system/services`
diff --git a/frontend/src/components/dashboard/widgets/metrics.js b/frontend/src/components/dashboard/widgets/metrics.js
index bf5ef1e6..30691081 100644
--- a/frontend/src/components/dashboard/widgets/metrics.js
+++ b/frontend/src/components/dashboard/widgets/metrics.js
@@ -6,7 +6,7 @@
* they are shaped differently, so each metric carries the candidate paths for
* both:
*
- * local host GET /api/v1/metrics/history?period=…
+ * local host GET /api/v1/system/performance-history?period=…
* → MetricsHistory.to_dict() (backend/app/models/metrics_history.py)
* { timestamp, level, cpu:{percent,min,max},
* memory:{percent,used_bytes,total_bytes,…},
diff --git a/frontend/src/components/dashboard/widgets/useWidgetData.js b/frontend/src/components/dashboard/widgets/useWidgetData.js
index e86972bf..98179fb4 100644
--- a/frontend/src/components/dashboard/widgets/useWidgetData.js
+++ b/frontend/src/components/dashboard/widgets/useWidgetData.js
@@ -115,7 +115,7 @@ function safeRange(range) {
/**
* Raw history payload for one resource + range.
- * local -> GET /api/v1/metrics/history?period=…
+ * local -> GET /api/v1/system/performance-history?period=…
* agent server -> GET /api/v1/servers/<id>/metrics/history?period=…
* Both answer `{ period, points, data: [...], summary }`.
*/
diff --git a/frontend/src/services/api/__tests__/system.test.mjs b/frontend/src/services/api/__tests__/system.test.mjs
new file mode 100644
index 00000000..f48b78ed
--- /dev/null
+++ b/frontend/src/services/api/__tests__/system.test.mjs
@@ -0,0 +1,20 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { getMetricsHistory } from '../system.js';
+
+
+test('getMetricsHistory uses the content-blocker-safe route', async () => {
+ const calls = [];
+ const context = {
+ request(path) {
+ calls.push(path);
+ return Promise.resolve({ period: '6h' });
+ },
+ };
+
+ const result = await getMetricsHistory.call(context, '6h');
+
+ assert.deepEqual(calls, ['/system/performance-history?period=6h']);
+ assert.deepEqual(result, { period: '6h' });
+});
diff --git a/frontend/src/services/api/system.js b/frontend/src/services/api/system.js
index 11df5c1a..406631a0 100644
--- a/frontend/src/services/api/system.js
+++ b/frontend/src/services/api/system.js
@@ -724,7 +724,7 @@ export async function getUptimeTrackingStatus() {
// Metrics History endpoints
export async function getMetricsHistory(period = '1h') {
- return this.request(`/metrics/history?period=${period}`);
+ return this.request(`/system/performance-history?period=${period}`);
}
export async function getMetricsStats() {