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.

Harden the Cloud tunnel per review

Juan Denis4c70658f9067
diff --git a/backend/app/services/connect_session.py b/backend/app/services/connect_session.py
index 750294d8..32131f24 100644
--- a/backend/app/services/connect_session.py
+++ b/backend/app/services/connect_session.py
@@ -79,8 +79,8 @@ def verify_grant(token: str, device_id: str, jwks: dict, now: float = None) -> d
raise ConnectSessionRefused('bad_grant', 'The grant is not readable.')
key = next((k for k in jwks['keys'] if k.get('kid') == kid), None)
# Keys carry their purpose; one published for anything else (signed
- # commands) is not accepted as a sign-in.
- if key is None or key.get('crv') != 'Ed25519' or key.get('purpose', 'session') != 'session':
+ # commands), or with none at all, is not accepted as a sign-in.
+ if key is None or key.get('crv') != 'Ed25519' or key.get('purpose') != 'session':
raise ConnectSessionRefused('unknown_key', 'The grant was signed with a key this panel does not trust.')
try:
raw = base64.urlsafe_b64decode(key['x'] + '=' * (-len(key['x']) % 4))
diff --git a/backend/app/services/connect_tunnel.py b/backend/app/services/connect_tunnel.py
index 31b8c5ec..6c075d59 100644
--- a/backend/app/services/connect_tunnel.py
+++ b/backend/app/services/connect_tunnel.py
@@ -162,8 +162,12 @@ class Tunnel:
return
prefix = payload.get('prefix') or ''
prefix = prefix if PREFIX.match(prefix) else ''
+ # Straight to loopback: environment proxies (HTTP_PROXY and friends)
+ # would otherwise receive the grant, the bearer token and the body.
+ session = requests.Session()
+ session.trust_env = False
try:
- resp = requests.request(
+ resp = session.request(
payload.get('method') or 'GET',
f'http://127.0.0.1:{self._port}{path}',
headers=loopback_headers(payload),
@@ -238,7 +242,8 @@ class SioStream:
headers = {k: v for k, v in loopback_headers(self._payload).items()
if k.lower() not in HANDSHAKE}
self._ws = connect(f'ws://127.0.0.1:{self._port}{path}', origin=origin,
- additional_headers=headers, open_timeout=10)
+ additional_headers=headers, open_timeout=10,
+ proxy=None)
except Exception as exc:
logger.warning('Connect tunnel: Socket.IO did not open on the panel: %s', exc)
self.stop()
diff --git a/backend/tests/test_connect_tunnel.py b/backend/tests/test_connect_tunnel.py
index 7f54605e..552361de 100644
--- a/backend/tests/test_connect_tunnel.py
+++ b/backend/tests/test_connect_tunnel.py
@@ -61,8 +61,9 @@ def test_the_socket_io_leg_makes_its_own_handshake(monkeypatch):
# client's own made the panel answer 400 and every socket close at once.
seen = {}
- def fake_connect(url, origin=None, additional_headers=None, open_timeout=None):
- seen.update(url=url, origin=origin, headers=additional_headers)
+ def fake_connect(url, origin=None, additional_headers=None, open_timeout=None,
+ proxy=True):
+ seen.update(url=url, origin=origin, headers=additional_headers, proxy=proxy)
raise OSError('stop here')
import websockets.sync.client
@@ -80,6 +81,9 @@ def test_the_socket_io_leg_makes_its_own_handshake(monkeypatch):
assert seen['headers']['User-Agent'] == 'Chrome'
assert seen['headers']['X-ServerKit-Connect-Grant'] == 'g'
assert seen['origin'] == 'http://127.0.0.1:5000'
+ # websockets 15 reads HTTPS_PROXY/ALL_PROXY by default; the loopback leg
+ # carries the grant and must never take a detour through one.
+ assert seen['proxy'] is None
assert sent[-1] == {'s': 's1', 't': 'close'}
@@ -157,6 +161,18 @@ def test_a_redirect_stays_under_the_prefix(local_panel):
assert frames[-1]['p']['headers']['Location'] == f'{PREFIX}/new'
+def test_the_loopback_replay_ignores_environment_proxies(local_panel, monkeypatch):
+ # requests honours HTTP_PROXY by default, which would hand the grant and
+ # the bearer token to whatever proxy the host has configured.
+ for name in ('HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy'):
+ monkeypatch.setenv(name, 'http://127.0.0.1:1')
+ for name in ('NO_PROXY', 'no_proxy'):
+ monkeypatch.delenv(name, raising=False)
+ frames = _run_http(local_panel, {'method': 'GET', 'path': '/assets/app.js',
+ 'headers': {}, 'grant': 'g'})
+ assert frames[-1]['p']['status'] == 200
+
+
def test_a_panel_that_does_not_answer_is_a_refusal_not_a_blank_page():
frames = _run_http(1, {'method': 'GET', 'path': '/', 'headers': {}})
assert frames[-1]['reason'] == 'panel_unreachable'
@@ -208,6 +224,16 @@ def test_a_command_key_cannot_sign_somebody_in():
assert exc.value.code == 'unknown_key'
+def test_a_key_that_does_not_name_its_purpose_cannot_sign_somebody_in():
+ # Cloud publishes a purpose on every key; one without it is not
+ # presumed to be a session key.
+ sign, jwks = _signer()
+ del jwks['keys'][0]['purpose']
+ with pytest.raises(connect_session.ConnectSessionRefused) as exc:
+ connect_session.verify_grant(sign(), DEVICE, jwks)
+ assert exc.value.code == 'unknown_key'
+
+
# ---------- signing in ----------
@pytest.fixture
diff --git a/frontend/src/components/backups/BackupDetailDrawer.jsx b/frontend/src/components/backups/BackupDetailDrawer.jsx
index 2e47eb66..895b67cd 100644
--- a/frontend/src/components/backups/BackupDetailDrawer.jsx
+++ b/frontend/src/components/backups/BackupDetailDrawer.jsx
@@ -4,6 +4,7 @@
// so its open/close slide animation plays even when there's no run selected.
import { Drawer, Pill } from '@/components/ds';
import { Button } from '@/components/ui/button';
+import { Link } from 'react-router-dom';
import { Archive, RotateCcw, ShieldCheck, Download, Trash2, ExternalLink } from 'lucide-react';
import { humanSize, formatMoney, formatDateTime, statusKind, storageLabel } from './format';
import { useTranslation } from 'react-i18next';
@@ -79,9 +80,9 @@ export default function BackupDetailDrawer({ run, open, onClose, onRestore, onVe
</div>
{run.job_id && (
- <a className="backup-detail-drawer__joblink" href="/monitoring/jobs">
+ <Link className="backup-detail-drawer__joblink" to="/monitoring/jobs">
<ExternalLink size={13} /> {t('app.backupDetailDrawer.viewJob', 'View job')}
- </a>
+ </Link>
)}
</div>
</Drawer>
diff --git a/frontend/src/components/setup/SetupStepSummary.jsx b/frontend/src/components/setup/SetupStepSummary.jsx
index 0f19ff5f..6ec06c92 100644
--- a/frontend/src/components/setup/SetupStepSummary.jsx
+++ b/frontend/src/components/setup/SetupStepSummary.jsx
@@ -1,4 +1,5 @@
import { useState, useEffect } from 'react';
+import { Link } from 'react-router-dom';
import { useResourceTier } from '../../contexts/useResourceTier.js';
import { Sparkles, Check, Loader, AlertTriangle } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
@@ -346,7 +347,7 @@ const SetupStepSummary = ({ accountInfo, useCases, twoFactorEnabled, onFinish })
</div>
{anyError && (
<p className="recommendation-error">
- {t('app.setupStepSummary.someExtensionsCouldnTBeInstalled', 'Some extensions couldn\'t be installed. You can retry from the')} <a href="/extensions">{t('common.labels.extensions', 'Extensions')}</a> page.
+ {t('app.setupStepSummary.someExtensionsCouldnTBeInstalled', 'Some extensions couldn\'t be installed. You can retry from the')} <Link to="/extensions">{t('common.labels.extensions', 'Extensions')}</Link> page.
</p>
)}
</>
diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.js
index 13584224..155351bc 100644
--- a/frontend/src/services/api/client.js
+++ b/frontend/src/services/api/client.js
@@ -36,10 +36,11 @@ const viteEnv = import.meta.env || {};
const configuredBase = (viteEnv.DEV && viteEnv.VITE_API_PROXY === 'true')
? '/api/v1'
: normalizeApiBaseUrl(viteEnv.VITE_API_URL);
-// Opened through ServerKit Cloud's relay, a root-relative API path has to
-// carry the panel's prefix (services/tunnelBase.js).
-const API_BASE_URL = (TUNNEL_BASE && configuredBase.startsWith('/'))
- ? `${TUNNEL_BASE}${configuredBase}`
+// Opened through ServerKit Cloud's relay, every API call goes through the
+// relay under the panel's prefix (services/tunnelBase.js) — even in a build
+// with an absolute VITE_API_URL, since only the relay attaches Cloud's grant.
+const API_BASE_URL = TUNNEL_BASE
+ ? `${TUNNEL_BASE}${configuredBase.startsWith('/') ? configuredBase : '/api/v1'}`
: configuredBase;
// Requests that are safe to share with a concurrent identical caller: a plain