Fix critical and high security issues

- exec_script: relay now enforces admin role before forwarding to agent
- relay CORS: restrict allow_origins via ALLOWED_ORIGINS env var (docker-compose passes app URL)
- session-code: replace Math.random() with crypto.randomInt, add per-key rate limit (10 req/min)
- sessions GET: fix IDOR — users can only read their own sessions (admins see all)
- signal API: validate session ownership on create; enforce ownerUserId on all subsequent actions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
monoadmin
2026-04-10 23:38:03 -07:00
parent e27d4cfa58
commit 27673daa63
5 changed files with 86 additions and 23 deletions

View File

@@ -22,6 +22,8 @@ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(mess
log = logging.getLogger("relay")
DATABASE_URL = os.environ["DATABASE_URL"]
# Comma-separated list of allowed origins for CORS, e.g. "https://app.example.com"
ALLOWED_ORIGINS = [o.strip() for o in os.environ.get("ALLOWED_ORIGINS", "").split(",") if o.strip()]
# ── In-memory connection registry ────────────────────────────────────────────
# machine_id (str) → WebSocket
@@ -30,6 +32,8 @@ agents: dict[str, WebSocket] = {}
viewers: dict[str, WebSocket] = {}
# session_id → machine_id
session_to_machine: dict[str, str] = {}
# session_id → viewer's user role ("admin" | "user")
viewer_roles: dict[str, str] = {}
db_pool: Optional[asyncpg.Pool] = None
@@ -47,7 +51,7 @@ app = FastAPI(lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_origins=ALLOWED_ORIGINS if ALLOWED_ORIGINS else ["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
@@ -68,9 +72,10 @@ async def validate_agent(machine_id: str, access_key: str) -> Optional[dict]:
async def validate_viewer(session_id: str, viewer_token: str) -> Optional[dict]:
async with db_pool.acquire() as conn:
row = await conn.fetchrow(
"""SELECT id, machine_id, machine_name
FROM sessions
WHERE id = $1 AND viewer_token = $2 AND ended_at IS NULL""",
"""SELECT s.id, s.machine_id, s.machine_name, COALESCE(u.role, 'user') AS viewer_role
FROM sessions s
LEFT JOIN users u ON u.id = s.viewer_user_id
WHERE s.id = $1 AND s.viewer_token = $2 AND s.ended_at IS NULL""",
session_id, viewer_token,
)
return dict(row) if row else None
@@ -174,10 +179,13 @@ async def viewer_endpoint(
await websocket.close(code=4002, reason="No machine associated with session")
return
viewer_role = session.get("viewer_role", "user")
await websocket.accept()
viewers[session_id] = websocket
session_to_machine[session_id] = machine_id
log.info(f"Viewer connected to session {session_id} (machine {machine_id})")
viewer_roles[session_id] = viewer_role
log.info(f"Viewer connected to session {session_id} (machine {machine_id}, role {viewer_role})")
if machine_id in agents:
# Tell agent to start streaming for this session
@@ -195,6 +203,14 @@ async def viewer_endpoint(
try:
event = json.loads(text)
event["session_id"] = session_id
# exec_script is restricted to admin viewers only
if event.get("type") == "exec_script":
if viewer_roles.get(session_id) != "admin":
await send_json(websocket, {
"type": "error",
"message": "exec_script requires admin role",
})
continue
# Forward control events to the agent
if machine_id in agents:
await send_json(agents[machine_id], event)
@@ -207,6 +223,7 @@ async def viewer_endpoint(
finally:
viewers.pop(session_id, None)
session_to_machine.pop(session_id, None)
viewer_roles.pop(session_id, None)
if machine_id in agents:
await send_json(agents[machine_id], {"type": "stop_stream", "session_id": session_id})
log.info(f"Viewer disconnected from session {session_id}")