project-pegaprox icon indicating copy to clipboard operation
project-pegaprox copied to clipboard

[Bug] Reverse proxy mode: VM console never connects (wrong PVE port, ticket auth, double 101 handshake, receive timeout, partial sends)

Open lordkill61 opened this issue 2 months ago • 8 comments

PegaProx Version

1.2.0 (build 2026.09.20)

Describe the bug

With Behind Reverse Proxy enabled, the VM console never connects. It loops on "reconnecting" and never shows the screen. Direct access to https://<pegaprox>:5000 works fine, because that uses the standalone VNC server on :5001, which has none of these problems.

The browser → nginx → PegaProx leg is fine: nginx returns 101, and WebSocket upgrade headers and timeouts are set. The failures are all inside the main-port console path (@sock.route .../vncwebsocket → vnc_websocket_proxy, and the same logic in handle_vnc_websocket). I hit five problems one after another and patched each locally. With all five fixed, the console works through the proxy.

1. PVE WebSocket URL uses the VNC port instead of the API port

api/vms.py, vnc_websocket_proxy (~L9245) and handle_vnc_websocket (~L8244):

host, port = manager.host, manager.api_port
...
if pve_port_q and pve_ticket_q and _ppt_ok:
    vnc_ticket = pve_ticket_q
    port = _ppt_port          # <- port is now 5900
...
pve_ws_url = f"wss://{host}:{port}{pve_ws_path}"   # -> wss://pve:5900/... -> ECONNREFUSED

Log: ConnectionRefusedError: [Errno 111] Connection refused right after Got ticket ... port=5900. Fix: pve_ws_url = f"wss://{host}:{manager.api_port}{pve_ws_path}" (port is still correct inside the query string).

2. Reused JS-issued vncproxy ticket + fresh login cookie → 401

Both functions do a fresh /access/ticket login and send Cookie: PVEAuthCookie=<fresh> on the WS upgrade, even when reusing the JS-issued ticket (#352 passthrough). The cluster connects with an API token, so the vncticket is bound to that token and PVE rejects it: Handshake status 401 permission denied - invalid PVEVNC ticket. The standalone handler (start_vnc_websocket_server, ~L8690) already handles this with ws_auth_header (PVEAPIToken= / manager._ticket when reusing). I applied the same logic to the two main-port handlers.

3. Two 101 Switching Protocols responses → browser closes with 1002

app.py wraps the server in geventwebsocket's WebSocketHandler (QuietWebSocketHandler), which upgrades every Upgrade request. The route is a flask-sock @sock.route, and simple_websocket.Server does its own handshake. A packet capture on :5000 shows two identical 101 responses back to back:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: ClpsPACDDqLGFORRjSTjbi1n1Eg=

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
...

Chrome and Firefox parse the second one as a frame and close with 1002 WebSocket Protocol Error (PegaProx logs Client->PVE error: Connection closed: 1002 WebSocket Protocol Error, sent 0, received 0). Local fix: in QuietWebSocketHandler, bypass the gevent upgrade for the flask-sock paths:

def run_application(self):
    _p = self.environ.get("PATH_INFO", "")
    if _p.endswith("/vncwebsocket") or _p.endswith("/shellws"):
        from gevent.pywsgi import WSGIHandler as _PlainWSGIHandler
        return _PlainWSGIHandler.run_application(self)
    return super().run_application()

(/api/ws/updates is probably affected too. I didn't touch it.)

4. ws.receive(timeout=0.1) returning None is treated as disconnect

vnc_websocket_proxy main loop (~L9315):

data = ws.receive(timeout=0.1)
if data is None:
    print("Client disconnected")

simple-websocket's receive() returns None on timeout, not just on close, so the session ends 0.1 s after Step 4: Proxy running... unless the browser happens to send something first. Fix: if data is None and ws.connected: continue before the disconnect branch.

5. Partial socket.send() corrupts large frames (black screen, then 1002)

With 1–4 fixed, the console connects and streams (received 1622214 bytes), then drops with 1002 again after a black screen. simple_websocket/ws.py 1.1.0 writes with self.sock.send(out_data) (L83, 119, 152, 244, 468), which can do a partial write on the gevent socket for large framebuffer updates. The rest of the frame is lost and the stream is corrupt. Changing these to sendall() fixed it. That's an upstream simple-websocket issue, but it's easy to work around in PegaProx (for example, a startup monkey-patch like the existing [ws-patch] for PerMessageDeflate).

Steps to Reproduce

  1. Settings → Server → Reverse Proxy: enable Behind Reverse Proxy, trusted proxy = the nginx IP, bind address 0.0.0.0.
  2. nginx / Nginx Proxy Manager in front with TLS, forwarding http://<pegaprox>:5000, WebSocket upgrade enabled.
  3. Cluster added with an API token.
  4. Open any VM console through https://<proxy-hostname>/.
  5. The console loops on reconnect (errors 1 → 5 above, as each is fixed).

Expected behavior

The console works through the reverse proxy the same way it does on direct access.

Environment

PegaProx version 1.2.0 (build 2026.09.20), LXC install, Python 3.13.5

  • gevent 25.9.1, gevent-websocket 0.10.1, flask-sock 0.7.0, simple-websocket 1.1.0, wsproto 1.3.2, websocket-client 1.9.0
  • Proxmox VE: 9.2.20 (cluster auth via API token)
  • Reverse proxy: Nginx Proxy Manager 2.15.1 (openresty 1.29.2.5), Let's Encrypt, WebSockets on
  • Browsers: Chrome 153 and Firefox (same result)

Additional information

All five local patches together give a working console through the proxy. I can share the diffs or test a build.

lordkill61 avatar Sep 23 '26 11:09 lordkill61

👋 Thanks for reporting a bug!

Unfortunately, it looks like some required information is missing.

Please provide:

  • [ ] PegaProx Version

Why? We are volunteers maintaining PegaProx in our free time. Complete bug reports help us fix issues faster. 🐾

Closing for now — please reopen with the required details or open a new issue.

This is an automated message.

github-actions[bot] avatar Sep 23 '26 11:09 github-actions[bot]

👋 Thanks for reporting a bug!

Unfortunately, it looks like some required information is missing.

Please provide:

  • [ ] PegaProx Version

Why? We are volunteers maintaining PegaProx in our free time. Complete bug reports help us fix issues faster. 🐾

Closing for now — please reopen with the required details or open a new issue.

This is an automated message.

github-actions[bot] avatar Sep 23 '26 11:09 github-actions[bot]

Sorry, guys. I tried to help here, but the bug has been closed twice

lordkill61 avatar Sep 23 '26 12:09 lordkill61

Sorry about the double auto-close, that one's on us. The validator wants the version with a colon after it (PegaProx Version: 1.2.0); your heading form didn't match its regex even though you gave the version twice. Reopened, and I'll get the check loosened.

Went through all five against current code and they all hold:

  1. Yep — both main-port handlers build pve_ws_url from port after it's been reassigned to the vncproxy port. The standalone one uses tunnel_target_port instead, which is exactly why direct access on :5001 works and the proxied path doesn't.
  2. Confirmed. The ws_auth_header block with the PVEAPIToken / _ticket handling only exists in the standalone handler; the two main-port ones send a bare PVEAuthCookie.
  3. Matches — QuietWebSocketHandler upgrades everything and flask-sock then handshakes again.
  4. if data is None: running = False right after a 0.1s receive. Clear.
  5. simple-websocket 1.1.0 here too, same five self.sock.send() call sites you listed.

So this is 1.2.0 as shipped, not something that only bites on Testing. It's the whole console path plus an upstream workaround, so Nico picks it up — assigning him.

If you want to push those diffs as a PR against Testing, very welcome. Otherwise we'll work from what you wrote, it's more than enough to go on.

Marcus

mkellermann97 avatar Sep 23 '26 13:09 mkellermann97

Thanks - this is one of the most useful bug reports we have had. Five separate defects, each isolated with the line number and a packet capture behind the third one. All five are real and all five are now fixed on Testing.

What went in, and where it differs from your patches:

1. PVE API port. Confirmed. port was being reused as both "the port PegaProx talks to PVE on" and "the port that belongs in the vncticket query string", so the second assignment destroyed the first. Rather than pin manager.api_port at the point of use I renamed the second one to vnc_port, so the two can no longer collide, and pulled the URL construction into one helper that all four console handlers share. Same defect turned out to be sitting in the screenshot tile (_screenshot_via_rfb), which is why VM thumbnails were blank on any cluster not on 8006. That one is #956, reported independently the same week.

2. Token-bound vncticket. Confirmed, and your diagnosis of the mechanism is right: the ticket is bound to the auth context that requested it, so presenting a freshly minted cookie alongside it is a mismatch PVE is correct to reject. The standalone handler's ws_auth_header logic is now a shared helper (_pve_console_ws_auth) used by all of them, so the three paths cannot drift apart again. This is the same root cause as #955.

3. Two 101 responses. Confirmed on a capture here as well. The bypass is in, close to your shape but decided by the routing table rather than by a path suffix - it asks werkzeug whether the URL maps to a websocket=True rule, so a new flask-sock route is covered the day it is added instead of the day someone remembers to extend the list. And you were right about /api/ws/updates: it was double-upgrading too.

4. receive() returning None. Confirmed, fixed as you suggested - ws.connected is the thing that tells the two cases apart.

5. Partial send(). Fixed, with one honest caveat about the evidence. The five bare self.sock.send() calls are exactly where you said (ws.py 83, 119, 152, 244, 468 in 1.1.0) and none of them loop, so the mechanism is not in doubt - but we could not make it happen here. A 4 MB raw framebuffer rectangle over loopback arrives whole with the patch and, on this machine, also without it; the kernel simply accepts the whole buffer. So the live reproduction is yours, not ours. What we did verify is the wrapper itself against a deliberately short-writing socket (without it the tail is lost, with it the frame is whole) and that a real console is unchanged with the patch in place. It is applied at startup next to the existing PerMessageDeflate patch and turns send into sendall on the socket the Base class holds, so all five call sites are covered without vendoring the library. Upstream should still hear about it.

It would help a lot if you could check a Testing build before this reaches a release - you are the only person we know of running this exact combination (NPM in front, py3.13, token auth), and the five together are more than we can reproduce end to end here.

mkellermann97 avatar Sep 28 '26 18:09 mkellermann97

All five problems are fixed for 1.3.0. The upgrade now goes to the PVE API port. A reused vncproxy ticket is sent with the cluster's own auth. flask-sock routes get exactly one 101 handshake, a receive timeout no longer counts as a disconnect, and websocket frames are always written in full. Thanks again for such a precise report, and if anything still misbehaves behind your proxy on 1.3.0, feel free to reopen.

(We're donation-funded, https://opencollective.com/pegaprox, in case that's an option for you.)

Marcus

mkellermann97 avatar Oct 07 '26 04:10 mkellermann97

Hi Marcus, sorry for the slow reply. I was away and missed your comments.

Thanks to you and Nico for fixing this so quickly and for the detailed write-up. I've tested 1.3.0 behind Nginx Proxy Manager and everything works:

The VM console connects and stays connected, with no reconnect loop and no black screen. One 101 handshake on the console and on /api/ws/updates (it was two before). Reverse-proxy mode and the bind address survived the upgrade. No console errors in the log. Fix 5 confirmed live: I removed my old local sendall edit and restored the stock simple-websocket 1.1.0 ws.py (hash matches the pip RECORD), so only your wrapper is active. A long console session with heavy screen updates ran cleanly, about 1.2 MB relayed with no drops. I also checked the wrapper against a socket that writes only 1,000 bytes per call: the stock send() delivered 1,000 of 4,000,000 bytes, and with your wrapper all 4,000,000 arrived.

Setup: PegaProx 1.3.0, NPM 2.15.1 (openresty), Python 3.13, cluster auth by API token, PVE 9.2.

Thanks again for the great work on PegaProx!

lordkill61 avatar Oct 07 '26 08:10 lordkill61

No worries about the delay, and thanks for testing it this thoroughly. The 1,000-bytes-per-call socket check is a nice way to prove the wrapper actually does its job instead of just not crashing. Good to know it holds up on NPM 2.15.1 with Python 3.13 as well.

Marcus

mkellermann97 avatar Oct 07 '26 13:10 mkellermann97