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.

refactor(agent): transport-neutral handshake + state ingest doors (plan 77 A2)

Juan Denis745bc2b5d963
diff --git a/backend/app/agent_gateway.py b/backend/app/agent_gateway.py
index e706e572..710fb494 100644
--- a/backend/app/agent_gateway.py
+++ b/backend/app/agent_gateway.py
@@ -9,58 +9,24 @@ import json
import logging
import threading
import time
-from collections import defaultdict
from flask import request
from flask_socketio import Namespace, emit, disconnect
from app.services.agent_registry import agent_registry
from app.models.server import Server
-from app.utils.ip_utils import is_ip_allowed
-from app.services.anomaly_detection_service import anomaly_detection_service
logger = logging.getLogger(__name__)
-# In-memory per-IP auth rate limiter. Guarded by a lock because the gateway
-# runs under async_mode='threading' — on_auth (WS) and the poll /connect
-# endpoint can call this concurrently, and an unlocked read-modify-write of a
-# shared dict races. Buckets are swept periodically so the dict can't grow
-# without bound from one-off IPs on an internet-facing gateway.
-# NOTE: request.remote_addr below is the ProxyFix-corrected real client IP when
-# TRUST_PROXY_HEADERS is on (plan 48). Before that fix, every agent behind nginx
-# shared nginx's address = one global bucket; now the throttle keys per-agent.
-_auth_attempts = defaultdict(list)
-_auth_attempts_lock = threading.Lock()
-_last_auth_sweep = 0.0
-_AUTH_RATE_LIMIT = 10 # max attempts per window
-_AUTH_RATE_WINDOW = 60 # seconds
-
-
-def _check_auth_rate_limit(ip_address: str) -> bool:
- """Record an auth attempt and report whether the IP is still under the
- limit. Returns True when allowed, False when the per-IP window is
- exhausted. Thread-safe."""
- global _last_auth_sweep
- now = time.time()
- with _auth_attempts_lock:
- # Opportunistic sweep: drop buckets whose attempts have all aged out
- # so IPs that connect once and never return don't accumulate forever.
- if now - _last_auth_sweep > _AUTH_RATE_WINDOW:
- for ip in list(_auth_attempts.keys()):
- fresh = [t for t in _auth_attempts[ip] if now - t < _AUTH_RATE_WINDOW]
- if fresh:
- _auth_attempts[ip] = fresh
- else:
- del _auth_attempts[ip]
- _last_auth_sweep = now
-
- recent = [t for t in _auth_attempts[ip_address] if now - t < _AUTH_RATE_WINDOW]
- if len(recent) >= _AUTH_RATE_LIMIT:
- _auth_attempts[ip_address] = recent
- return False
- recent.append(now)
- _auth_attempts[ip_address] = recent
- return True
+# The per-IP auth rate limiter is transport-neutral state and lives with the
+# shared handshake door in agent_registry (plan 77 A2). Re-exported here for
+# callers/tests that historically reached it via the gateway module.
+from app.services.agent_registry import ( # noqa: F401
+ _AUTH_RATE_LIMIT,
+ _AUTH_RATE_WINDOW,
+ _auth_attempts,
+ _check_auth_rate_limit,
+)
class AgentNamespace(Namespace):
@@ -86,6 +52,11 @@ class AgentNamespace(Namespace):
"""
Handle agent authentication.
+ Thin adapter over agent_registry.authenticate_and_register (plan 77
+ A2) — the handshake sequence itself is transport-neutral and shared
+ with the long-poll /connect endpoint; this handler only translates
+ the outcome into socket emits/disconnects.
+
Expected data:
{
"type": "auth",
@@ -98,75 +69,30 @@ class AgentNamespace(Namespace):
"""
sid = request.sid
ip_address = request.remote_addr
- if not _check_auth_rate_limit(ip_address):
- emit('auth_response', {'success': False, 'error': 'Rate limit exceeded'}, room=request.sid, namespace='/agent')
- return
-
- agent_id = data.get('agent_id')
- api_key_prefix = data.get('api_key_prefix')
- signature = data.get('signature')
- timestamp = data.get('timestamp', 0)
- nonce = data.get('nonce') # Optional for backward compatibility
-
- ip_address = request.remote_addr
- logger.info("Auth attempt from agent %s at %s", agent_id, ip_address)
-
- if not all([agent_id, api_key_prefix, signature]):
- emit('auth_fail', {
- 'type': 'auth_fail',
- 'error': 'Missing required fields'
- })
- disconnect()
- return
-
- # Verify authentication (includes signature verification and replay protection)
- server = agent_registry.verify_agent_auth(
- agent_id, api_key_prefix, signature, timestamp,
- nonce=nonce, ip_address=ip_address
- )
-
- if not server:
- emit('auth_fail', {
- 'type': 'auth_fail',
- 'error': 'Authentication failed'
- })
- disconnect()
- return
-
- # Check IP allowlist
- if server.allowed_ips and len(server.allowed_ips) > 0:
- if not is_ip_allowed(ip_address, server.allowed_ips):
- # Log security event
- anomaly_detection_service.track_ip_blocked(
- server.id, ip_address, server.allowed_ips
- )
- emit('auth_fail', {
- 'type': 'auth_fail',
- 'error': 'IP address not allowed'
- })
- logger.warning("IP %s blocked for server %s", ip_address, server.id)
- disconnect()
- return
-
- # Check for new IP and create info alert
- anomaly_detection_service.check_new_ip(server.id, ip_address)
-
- # Register agent
- agent_version = request.headers.get('User-Agent', '').replace('ServerKit-Agent/', '')
-
- session_token = agent_registry.register_agent(
- server_id=server.id,
+ logger.info("Auth attempt from agent %s at %s",
+ (data or {}).get('agent_id'), ip_address)
+
+ session_token, server, error = agent_registry.authenticate_and_register(
+ data or {},
+ ip_address,
+ user_agent=request.headers.get('User-Agent', ''),
+ transport='ws',
socket_id=sid,
- ip_address=ip_address,
- agent_version=agent_version
)
- # register_agent returns None when the DB write failed and it rolled
- # back the in-memory state — don't tell the agent it's authenticated.
- if not session_token:
+ if error == 'rate_limited':
+ emit('auth_response', {'success': False, 'error': 'Rate limit exceeded'}, room=request.sid, namespace='/agent')
+ return
+ if error is not None:
+ messages = {
+ 'missing_fields': 'Missing required fields',
+ 'auth_failed': 'Authentication failed',
+ 'ip_not_allowed': 'IP address not allowed',
+ 'registration_failed': 'Registration failed',
+ }
emit('auth_fail', {
'type': 'auth_fail',
- 'error': 'Registration failed'
+ 'error': messages.get(error, 'Authentication failed')
})
disconnect()
return
@@ -181,8 +107,6 @@ class AgentNamespace(Namespace):
'server_id': server.id
})
- logger.info("Agent %s authenticated successfully from %s", agent_id, ip_address)
-
def on_heartbeat(self, data):
"""
Handle agent heartbeat.
@@ -211,7 +135,7 @@ class AgentNamespace(Namespace):
return
metrics = data.get('metrics', {})
- agent_registry.update_heartbeat(agent.server_id, metrics)
+ agent_registry.ingest_agent_state(agent, metrics=metrics)
emit('heartbeat_ack', {'type': 'heartbeat_ack'})
@@ -266,7 +190,7 @@ class AgentNamespace(Namespace):
return
info = data.get('info', {})
- agent_registry.update_system_info(agent.server_id, info)
+ agent_registry.ingest_agent_state(agent, sysinfo=info)
def on_capabilities(self, data):
"""
@@ -298,9 +222,9 @@ class AgentNamespace(Namespace):
return
# Capability side-effects (incl. the WireGuard tunnel reconcile)
- # happen inside update_capabilities so both transports — this WS
- # handler and the long-poll /poll body — share one ingest path.
- agent_registry.update_capabilities(agent.server_id, data or {})
+ # happen inside the shared ingest so both transports — this WS
+ # handler and the long-poll /poll body — behave identically.
+ agent_registry.ingest_agent_state(agent, capabilities=data or {})
def on_stream(self, data):
"""
diff --git a/backend/app/api/agent_poll.py b/backend/app/api/agent_poll.py
index 26193d29..d0cb82de 100644
--- a/backend/app/api/agent_poll.py
+++ b/backend/app/api/agent_poll.py
@@ -17,13 +17,9 @@ Auth model:
"""
import logging
-from datetime import datetime
from flask import Blueprint, jsonify, request
from app.services.agent_registry import agent_registry
-from app.agent_gateway import _check_auth_rate_limit
-from app.utils.ip_utils import is_ip_allowed
-from app.services.anomaly_detection_service import anomaly_detection_service
logger = logging.getLogger(__name__)
@@ -40,61 +36,30 @@ def _client_ip():
@agent_poll_bp.route('/connect', methods=['POST'])
def connect():
"""Authenticate an agent and return a session_token bound to a
- polling-mode ConnectedAgent. Mirrors the on_auth handler in
- AgentNamespace, minus the socket-room bookkeeping."""
- data = request.get_json(silent=True) or {}
- agent_id = data.get('agent_id')
- api_key_prefix = data.get('api_key_prefix')
- signature = data.get('signature')
- timestamp = data.get('timestamp', 0)
- nonce = data.get('nonce')
-
- if not all([agent_id, api_key_prefix, signature]):
- return jsonify({'success': False, 'error': 'Missing required fields'}), 400
+ polling-mode ConnectedAgent.
+ Thin adapter over agent_registry.authenticate_and_register (plan 77 A2)
+ — the exact sequence the WS on_auth handler runs, minus the socket-room
+ bookkeeping; this endpoint only translates the outcome to HTTP."""
+ data = request.get_json(silent=True) or {}
ip = _client_ip()
- # Apply the SAME per-IP auth throttle that guards the WebSocket auth path
- # (agent_gateway.on_auth). /connect is the REST-transport equivalent of
- # on_auth, so without this it was an unthrottled bypass an attacker could
- # use for credential-stuffing while the WS path stayed rate-limited.
- if not _check_auth_rate_limit(ip):
- logger.warning("Auth rate limit exceeded for IP: %s (poll/connect)", ip)
- return jsonify({'success': False, 'error': 'Rate limit exceeded. Try again later.'}), 429
-
- server = agent_registry.verify_agent_auth(
- agent_id, api_key_prefix, signature, timestamp,
- nonce=nonce, ip_address=ip,
- )
- if not server:
- return jsonify({'success': False, 'error': 'Authentication failed'}), 401
-
- if server.allowed_ips and len(server.allowed_ips) > 0:
- if not is_ip_allowed(ip, server.allowed_ips):
- anomaly_detection_service.track_ip_blocked(server.id, ip, server.allowed_ips)
- return jsonify({'success': False, 'error': 'IP not allowed'}), 403
-
- anomaly_detection_service.check_new_ip(server.id, ip)
-
- agent_version = (request.headers.get('User-Agent') or '').replace('ServerKit-Agent/', '')
- # Synthesize a unique socket_id so the registry's existing storage and
- # heartbeat machinery work unchanged. The "poll-" prefix is what tells
- # WS-only code paths to skip these agents (no socket_id is reachable
- # via socketio.emit).
- import secrets
- socket_id = f'poll-{secrets.token_urlsafe(12)}'
-
- session_token = agent_registry.register_agent(
- server_id=server.id,
- socket_id=socket_id,
- ip_address=ip,
- agent_version=agent_version,
+ session_token, server, error = agent_registry.authenticate_and_register(
+ data,
+ ip,
+ user_agent=request.headers.get('User-Agent') or '',
transport='poll',
)
- # None means the DB write failed and register_agent rolled back the
- # in-memory state — surface a 5xx rather than a session the panel can't back.
- if not session_token:
+ if error == 'rate_limited':
+ return jsonify({'success': False, 'error': 'Rate limit exceeded. Try again later.'}), 429
+ if error == 'missing_fields':
+ return jsonify({'success': False, 'error': 'Missing required fields'}), 400
+ if error == 'auth_failed':
+ return jsonify({'success': False, 'error': 'Authentication failed'}), 401
+ if error == 'ip_not_allowed':
+ return jsonify({'success': False, 'error': 'IP not allowed'}), 403
+ if error is not None:
return jsonify({'success': False, 'error': 'Registration failed'}), 500
return jsonify({
@@ -139,11 +104,10 @@ def poll():
list(caps.keys()) if isinstance(caps, dict) else None,
)
- agent_registry.update_heartbeat(agent.server_id, metrics)
- if sysinfo:
- agent_registry.update_system_info(agent.server_id, sysinfo)
- if caps:
- agent_registry.update_capabilities(agent.server_id, caps)
+ # Shared transport-neutral ingest (plan 77 A1/A2): capability
+ # side-effects (e.g. tunnel reconcile) fire exactly as on the WS path.
+ agent_registry.ingest_agent_state(agent, metrics=metrics, sysinfo=sysinfo,
+ capabilities=caps)
# Long-poll up to 25s for any queued command. Below the typical
# tunnel idle-timeout (Cloudflare ~100s, ngrok ~60s) so we never
diff --git a/backend/app/services/agent_registry.py b/backend/app/services/agent_registry.py
index 5461a855..8b16f141 100644
--- a/backend/app/services/agent_registry.py
+++ b/backend/app/services/agent_registry.py
@@ -18,9 +18,50 @@ from typing import Dict, Optional, Callable, Any
from dataclasses import dataclass, field
from queue import Queue, Empty
+from collections import defaultdict
+
from app import db
from app.models.server import Server, ServerMetrics, ServerCommand, AgentSession
+# ---------------------------------------------------------------------------
+# Per-IP auth rate limiter — transport-neutral state shared by the WS
+# namespace and the long-poll /connect endpoint (moved here from
+# agent_gateway in plan 77 A2 so the handshake door owns its own throttle).
+# Guarded by a lock: async_mode='threading' means both transports can call
+# concurrently. Buckets are swept so one-off IPs don't accumulate forever.
+# request.remote_addr upstream is the ProxyFix-corrected client IP (plan 48).
+# ---------------------------------------------------------------------------
+_auth_attempts = defaultdict(list)
+_auth_attempts_lock = threading.Lock()
+_last_auth_sweep = 0.0
+_AUTH_RATE_LIMIT = 10 # max attempts per window
+_AUTH_RATE_WINDOW = 60 # seconds
+
+
+def _check_auth_rate_limit(ip_address: str) -> bool:
+ """Record an auth attempt and report whether the IP is still under the
+ limit. Returns True when allowed, False when the per-IP window is
+ exhausted. Thread-safe."""
+ global _last_auth_sweep
+ now = time.time()
+ with _auth_attempts_lock:
+ if now - _last_auth_sweep > _AUTH_RATE_WINDOW:
+ for ip in list(_auth_attempts.keys()):
+ fresh = [t for t in _auth_attempts[ip] if now - t < _AUTH_RATE_WINDOW]
+ if fresh:
+ _auth_attempts[ip] = fresh
+ else:
+ del _auth_attempts[ip]
+ _last_auth_sweep = now
+
+ recent = [t for t in _auth_attempts[ip_address] if now - t < _AUTH_RATE_WINDOW]
+ if len(recent) >= _AUTH_RATE_LIMIT:
+ _auth_attempts[ip_address] = recent
+ return False
+ recent.append(now)
+ _auth_attempts[ip_address] = recent
+ return True
+
@dataclass
class ConnectedAgent:
@@ -732,6 +773,95 @@ class AgentRegistry:
# ==================== Authentication ====================
+ # ------------------------------------------------------------------
+ # Transport-neutral handshake + state ingest (plan 77 A2). The WS
+ # namespace (agent_gateway) and the long-poll endpoints (api/agent_poll)
+ # are thin adapters over these two doors; neither may re-implement the
+ # sequence (ratcheted by tests/test_agent_handshake_matrix.py).
+ # ------------------------------------------------------------------
+
+ def authenticate_and_register(self, payload: dict, ip_address: str,
+ user_agent: str = '', transport: str = 'ws',
+ socket_id: str = None):
+ """The ONE agent handshake: rate-limit -> HMAC verify -> allowed-IPs
+ + anomaly tracking -> new-IP check -> version parse -> register.
+
+ Returns ``(session_token, server, error)`` where ``error`` is None on
+ success or one of: 'rate_limited', 'missing_fields', 'auth_failed',
+ 'ip_not_allowed', 'registration_failed'. The transport adapter
+ translates the code into its own wire shape (emit/disconnect vs
+ jsonify/status) and MUST fail closed on any non-None error.
+ """
+ from app.services.anomaly_detection_service import anomaly_detection_service
+ from app.utils.ip_utils import is_ip_allowed
+
+ payload = payload or {}
+ if not _check_auth_rate_limit(ip_address):
+ logger.warning("Auth rate limit exceeded for IP: %s (%s)", ip_address, transport)
+ return None, None, 'rate_limited'
+
+ agent_id = payload.get('agent_id')
+ api_key_prefix = payload.get('api_key_prefix')
+ signature = payload.get('signature')
+ timestamp = payload.get('timestamp', 0)
+ nonce = payload.get('nonce')
+
+ if not all([agent_id, api_key_prefix, signature]):
+ return None, None, 'missing_fields'
+
+ server = self.verify_agent_auth(
+ agent_id, api_key_prefix, signature, timestamp,
+ nonce=nonce, ip_address=ip_address,
+ )
+ if not server:
+ return None, None, 'auth_failed'
+
+ if server.allowed_ips and len(server.allowed_ips) > 0:
+ if not is_ip_allowed(ip_address, server.allowed_ips):
+ anomaly_detection_service.track_ip_blocked(
+ server.id, ip_address, server.allowed_ips)
+ logger.warning("IP %s blocked for server %s", ip_address, server.id)
+ return None, server, 'ip_not_allowed'
+
+ anomaly_detection_service.check_new_ip(server.id, ip_address)
+
+ agent_version = (user_agent or '').replace('ServerKit-Agent/', '')
+ if socket_id is None:
+ # Synthesized id for non-socket transports; the "poll-" prefix
+ # tells WS-only code paths to skip these agents.
+ socket_id = f'poll-{secrets.token_urlsafe(12)}'
+
+ session_token = self.register_agent(
+ server_id=server.id,
+ socket_id=socket_id,
+ ip_address=ip_address,
+ agent_version=agent_version,
+ transport=transport,
+ )
+ # None means the DB write failed and register_agent rolled back the
+ # in-memory state — the adapter must not report success.
+ if not session_token:
+ return None, server, 'registration_failed'
+
+ logger.info("Agent %s authenticated successfully from %s (%s)",
+ agent_id, ip_address, transport)
+ return session_token, server, None
+
+ def ingest_agent_state(self, agent, metrics=None, sysinfo=None,
+ capabilities=None):
+ """One ingest path for agent-reported state on BOTH transports.
+
+ Owns the capability side-effects (the WireGuard tunnel reconcile
+ fires from update_capabilities) so a payload arriving via long-poll
+ behaves exactly like one arriving via WebSocket.
+ """
+ if metrics is not None:
+ self.update_heartbeat(agent.server_id, metrics)
+ if sysinfo:
+ self.update_system_info(agent.server_id, sysinfo)
+ if capabilities:
+ self.update_capabilities(agent.server_id, capabilities)
+
def verify_agent_auth(
self,
agent_id: str,
diff --git a/backend/tests/test_agent_handshake_matrix.py b/backend/tests/test_agent_handshake_matrix.py
new file mode 100644
index 00000000..230f171b
--- /dev/null
+++ b/backend/tests/test_agent_handshake_matrix.py
@@ -0,0 +1,165 @@
+"""Plan 77 A2 gate — ONE agent handshake, exercised for both transports.
+
+agent_registry.authenticate_and_register is the single implementation of
+rate-limit -> HMAC verify -> allowed-IPs + anomaly -> new-IP check ->
+version parse -> register. The WS namespace and the long-poll /connect are
+thin adapters; the ratchet at the bottom asserts neither re-grows its own
+copy of the sequence.
+"""
+import hashlib
+import hmac
+import time
+from pathlib import Path
+
+import pytest
+
+import app.services.agent_registry as reg_mod
+from app import db as _db
+from app.models.server import Server
+from app.services.agent_registry import agent_registry
+
+TRANSPORTS = ['ws', 'poll']
+
+
[email protected](autouse=True)
+def _isolate(app, monkeypatch):
+ reg_mod._auth_attempts.clear()
+ with agent_registry._lock:
+ agent_registry._agents.clear()
+ agent_registry._socket_to_server.clear()
+ import app.services.anomaly_detection_service as ad
+ for name in ("track_auth_attempt", "track_ip_blocked", "track_replay_attack",
+ "check_new_ip"):
+ monkeypatch.setattr(ad.anomaly_detection_service, name,
+ lambda *a, **k: None, raising=False)
+ yield
+ reg_mod._auth_attempts.clear()
+ with agent_registry._lock:
+ agent_registry._agents.clear()
+ agent_registry._socket_to_server.clear()
+
+
+def _mk_agent_server(monkeypatch, allowed_ips=None):
+ api_key, api_secret = Server.generate_api_credentials()
+ server = Server(name='hs-matrix', agent_id='agent-hs')
+ server.set_api_key(api_key)
+ if allowed_ips is not None:
+ server.allowed_ips = allowed_ips
+ _db.session.add(server)
+ _db.session.commit()
+ monkeypatch.setattr(Server, 'get_api_secret', lambda self: api_secret)
+ return server, api_secret
+
+
+def _payload(server, secret, nonce='n-1'):
+ ts = int(time.time() * 1000)
+ msg = f"{server.agent_id}:{ts}:{nonce}"
+ sig = hmac.new(secret.encode(), msg.encode(), hashlib.sha256).hexdigest()
+ return {
+ 'agent_id': server.agent_id,
+ 'api_key_prefix': server.api_key_prefix,
+ 'signature': sig,
+ 'timestamp': ts,
+ 'nonce': nonce,
+ }
+
+
[email protected]('transport', TRANSPORTS)
+def test_good_handshake_registers(app, monkeypatch, transport):
+ server, secret = _mk_agent_server(monkeypatch)
+ token, srv, error = agent_registry.authenticate_and_register(
+ _payload(server, secret), '198.51.100.7',
+ user_agent='ServerKit-Agent/9.9.9', transport=transport,
+ socket_id='sid-1' if transport == 'ws' else None,
+ )
+ assert error is None
+ assert srv.id == server.id
+ agent = agent_registry.get_agent_by_token(token)
+ assert agent is not None and agent.transport == transport
+ assert agent.agent_version == '9.9.9'
+ if transport == 'poll':
+ assert agent.socket_id.startswith('poll-')
+
+
[email protected]('transport', TRANSPORTS)
+def test_bad_hmac_fails_closed(app, monkeypatch, transport):
+ server, secret = _mk_agent_server(monkeypatch)
+ payload = _payload(server, secret)
+ payload['signature'] = 'deadbeef' * 8
+ token, srv, error = agent_registry.authenticate_and_register(
+ payload, '198.51.100.7', transport=transport)
+ assert error == 'auth_failed'
+ assert token is None
+
+
[email protected]('transport', TRANSPORTS)
+def test_missing_fields_fail(app, monkeypatch, transport):
+ token, srv, error = agent_registry.authenticate_and_register(
+ {'agent_id': 'x'}, '198.51.100.7', transport=transport)
+ assert error == 'missing_fields'
+ assert token is None
+
+
[email protected]('transport', TRANSPORTS)
+def test_blocked_ip_tracks_anomaly(app, monkeypatch, transport):
+ server, secret = _mk_agent_server(monkeypatch, allowed_ips=['203.0.113.50'])
+ blocked = []
+ import app.services.anomaly_detection_service as ad
+ monkeypatch.setattr(ad.anomaly_detection_service, 'track_ip_blocked',
+ lambda sid, ip, allowed: blocked.append((sid, ip)))
+ token, srv, error = agent_registry.authenticate_and_register(
+ _payload(server, secret), '198.51.100.7', transport=transport)
+ assert error == 'ip_not_allowed'
+ assert token is None
+ assert blocked == [(server.id, '198.51.100.7')]
+
+
[email protected]('transport', TRANSPORTS)
+def test_new_ip_anomaly_check_runs(app, monkeypatch, transport):
+ server, secret = _mk_agent_server(monkeypatch)
+ seen = []
+ import app.services.anomaly_detection_service as ad
+ monkeypatch.setattr(ad.anomaly_detection_service, 'check_new_ip',
+ lambda sid, ip: seen.append((sid, ip)))
+ token, srv, error = agent_registry.authenticate_and_register(
+ _payload(server, secret), '198.51.100.7', transport=transport)
+ assert error is None
+ assert seen == [(server.id, '198.51.100.7')]
+
+
[email protected]('transport', TRANSPORTS)
+def test_rate_limit_applies_before_auth(app, monkeypatch, transport):
+ server, secret = _mk_agent_server(monkeypatch)
+ for _ in range(reg_mod._AUTH_RATE_LIMIT):
+ assert reg_mod._check_auth_rate_limit('198.51.100.9')
+ token, srv, error = agent_registry.authenticate_and_register(
+ _payload(server, secret), '198.51.100.9', transport=transport)
+ assert error == 'rate_limited'
+ assert token is None
+
+
+# ---------------------------------------------------------------------------
+# Ratchet: the transports stay thin adapters.
+# ---------------------------------------------------------------------------
+
+APP_DIR = Path(__file__).resolve().parents[1] / 'app'
+
+# Word-anchored: 'unregister_agent(' must NOT count as 'register_agent('
+# (substring greps have produced false blockers here before).
+FORBIDDEN = [
+ r'(?<![\w.])verify_agent_auth\(', # HMAC step belongs to the door
+ r'(?<![\w])register_agent\(', # registration step belongs to the door
+ r'(?<![\w.])is_ip_allowed\(', # allowlist step belongs to the door
+ r'(?<![\w.])check_new_ip\(', # anomaly step belongs to the door
+]
+
+
[email protected]('adapter', ['agent_gateway.py', 'api/agent_poll.py'])
+def test_no_second_handshake_implementation(adapter):
+ import re
+ src = (APP_DIR / adapter).read_text(encoding='utf-8')
+ hits = [tok for tok in FORBIDDEN if re.search(tok, src)]
+ assert not hits, (
+ f"{adapter} re-implements handshake steps {hits} — extend "
+ "agent_registry.authenticate_and_register instead (plan 77 A2)."
+ )