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(connect): refetch the JWKS when a command arrives signed with an unknown key

Juan Denisfda418d5fa0c
diff --git a/backend/app/services/connect_client.py b/backend/app/services/connect_client.py
index c27bb784..53bd45a7 100644
--- a/backend/app/services/connect_client.py
+++ b/backend/app/services/connect_client.py
@@ -684,9 +684,10 @@ class RelayClient:
# once an hour, and acted on only when this install can update itself.
self._update = UpdateCheck()
# Signed commands and the Storage Hub's status
- # stream. The JWKS is fetched once per connection: a
- # command is verified against the keys Cloud published, and a key
- # Cloud rotates is picked up on the next reconnect.
+ # stream. The JWKS is fetched once per connection and
+ # refetched when a command arrives signed with a key it
+ # does not know: Cloud mints keys on first use and rotates
+ # them on its own schedule, both between reconnects.
self._jwks = None
self._storage_stream = 0
self._storage_next_at = 0.0
@@ -1031,6 +1032,24 @@ class RelayClient:
self._jwks = None
logger.debug('Connect commands: could not read the JWKS', exc_info=True)
+ def _refresh_jwks_for(self, token, cfg):
+ """ServerKit Cloud mints each signing key the first time it is used and
+ rotates it on its own schedule — both can postdate the JWKS this
+ connection fetched at connect time. One refetch when the kid is
+ unknown; a key still unknown afterwards is refused like any other bad
+ signature.
+ """
+ try:
+ import jwt
+ kid = jwt.get_unverified_header(token).get('kid') if token else None
+ except Exception:
+ return
+ if not kid:
+ return
+ known = {k.get('kid') for k in (self._jwks or {}).get('keys') or []}
+ if kid not in known:
+ self._load_jwks(cfg)
+
def _run_command(self, ws, frame):
"""Verify, acknowledge, run, report.
@@ -1040,6 +1059,7 @@ class RelayClient:
"""
payload = frame.get('p') or {}
cfg = _read_connect_file()
+ self._refresh_jwks_for(payload.get('jwt'), cfg)
try:
claims = connect_commands.verify(
payload.get('jwt'), self._jwks, cfg.get('device_id'),
diff --git a/backend/tests/BASELINE_COUNT b/backend/tests/BASELINE_COUNT
index 05112f24..008e44a8 100644
--- a/backend/tests/BASELINE_COUNT
+++ b/backend/tests/BASELINE_COUNT
@@ -1 +1 @@
-5271
+5275
diff --git a/backend/tests/test_connect_relay.py b/backend/tests/test_connect_relay.py
index 81721d08..873741aa 100644
--- a/backend/tests/test_connect_relay.py
+++ b/backend/tests/test_connect_relay.py
@@ -1,13 +1,19 @@
"""Unit tests for the relay transport helpers (no network)."""
+import base64
import json
import socket
import ssl
+import time
+import types
+import jwt
import pytest
+from cryptography.hazmat.primitives import serialization
+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from websockets.exceptions import ConnectionClosedOK
from websockets.frames import Close
-from app.services import connect_client, connect_keys
+from app.services import connect_client, connect_commands, connect_keys
@pytest.fixture
@@ -283,3 +289,80 @@ def test_flap_logging_fires_after_limit(config_dir, monkeypatch, caplog):
client.start()
client._thread.join(timeout=10)
assert any('flapping' in r.message for r in caplog.records)
+
+
+# ---------- command JWKS refresh ----------
+
+
+def _command_signer():
+ """(sign(claims) -> token, jwks) for a throwaway command key, kid 'k-new'."""
+ key = Ed25519PrivateKey.generate()
+ raw = key.public_key().public_bytes_raw()
+ jwks = {'keys': [{'kty': 'OKP', 'crv': 'Ed25519', 'kid': 'k-new',
+ 'x': base64.urlsafe_b64encode(raw).decode().rstrip('=')}]}
+ private_pem = key.private_bytes(
+ encoding=serialization.Encoding.PEM,
+ format=serialization.PrivateFormat.PKCS8,
+ encryption_algorithm=serialization.NoEncryption(),
+ )
+
+ def sign(**claims):
+ body = {'cmd_id': 'cmd_1', 'device_id': 'dev_abc123',
+ 'action': 'policy.report', 'args': {}, 'scopes': ['policy.report'],
+ 'nonce': f'n{time.time_ns()}', 'iat': int(time.time()),
+ 'exp': int(time.time()) + 600}
+ body.update(claims)
+ return jwt.encode(body, private_pem, algorithm='EdDSA',
+ headers={'kid': 'k-new'})
+
+ return sign, jwks
+
+
+def test_an_unknown_command_key_triggers_one_jwks_refetch(monkeypatch):
+ """ServerKit Cloud mints each signing key on first use, so a command can
+ legitimately arrive signed with a key this connection's JWKS predates."""
+ sign, fresh = _command_signer()
+ client = connect_client.RelayClient()
+ client._jwks = {'keys': [{'kid': 'k-old'}]}
+ calls = []
+ monkeypatch.setattr(client, '_load_jwks',
+ lambda cfg: calls.append(cfg) or setattr(client, '_jwks', fresh))
+ client._refresh_jwks_for(sign(), {'cloud_url': 'https://cloud.test'})
+ assert len(calls) == 1
+ assert client._jwks is fresh
+
+
+def test_a_known_command_key_does_not_refetch(monkeypatch):
+ sign, fresh = _command_signer()
+ client = connect_client.RelayClient()
+ client._jwks = fresh
+ monkeypatch.setattr(client, '_load_jwks',
+ lambda cfg: pytest.fail('refetched a known key'))
+ client._refresh_jwks_for(sign(), {'cloud_url': 'https://cloud.test'})
+
+
+def test_a_garbage_command_token_is_left_to_verification(monkeypatch):
+ client = connect_client.RelayClient()
+ client._jwks = None
+ monkeypatch.setattr(client, '_load_jwks',
+ lambda cfg: pytest.fail('refetched a garbage token'))
+ client._refresh_jwks_for('not-a-jwt', {})
+ client._refresh_jwks_for(None, {})
+
+
+def test_run_command_refreshes_a_stale_jwks_and_acks(config_dir, monkeypatch):
+ """The full path: stale JWKS at connect, command signed with the key
+ ServerKit Cloud minted afterwards — refetch, verify, ack, run."""
+ sign, fresh = _command_signer()
+ connect_commands.NONCES._seen.clear()
+ monkeypatch.setattr(connect_client, '_read_connect_file',
+ lambda: {'device_id': 'dev_abc123',
+ 'cloud_url': 'https://cloud.test'})
+ client = connect_client.RelayClient()
+ client._jwks = {'keys': [{'kid': 'k-old'}]}
+ monkeypatch.setattr(client, '_load_jwks',
+ lambda cfg: setattr(client, '_jwks', fresh))
+ sent = []
+ ws = types.SimpleNamespace(send=lambda raw: sent.append(json.loads(raw)))
+ client._run_command(ws, {'p': {'jwt': sign()}})
+ assert sent and sent[0]['p']['state'] == 'running'