Files
SimpleRemoter/server/go/hub/register_session_test.go
T
yuanyuanxianganddeepseek-flash 808747f9d2 Feature(Go): terminal_close, idle sweep and legacy-client guard
Add the terminal_close tool so a caller can release a shell session
explicitly instead of waiting for it to age out. The tool is idempotent
for the session it names, rejects a session_id that does not match the
live session with -32002, and runs without the per-device lock so it can
interrupt a terminal_exec call that is still polling on the same device.

Give hub leases a generation counter: the generation is bumped when a
pending lease is created and carried across a device re-login. MCP-side
closes pass the generation, so a stale session can no longer tear down a
shell a human operator opened after the device reconnected. The reaper
runs on a 30 s ticker (shortened when TermIdle is smaller), skips
sessions that are still opening, and reclaims idle sessions as well as
commands overdue past the one-hour busy cap.

The pre-bind terminal-close path in cmd no longer closes
unconditionally; it touches only a pending lease, because an unbound
sub-connection carries no lease identity and may be a stale orphan.

Covered by unit tests for close semantics, lock exemption, reaper
lifecycle and lease-generation ownership, plus a live run against a
Debug ghost: close before and during a command, reopen, idle reap and
mismatched-id rejection all behave as specified.

Co-Authored-By: deepseek-flash
2026-11-12 21:53:54 +01:00

226 lines
8.5 KiB
Go

package hub
import (
"bytes"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/connection"
)
// A reconnecting client logs in with a fresh Device struct. Its screen / shell
// sub-conns ride their own TCP connections and survive the main-conn reconnect,
// so Register must carry the session state over — otherwise a web terminal goes
// dead on every reconnect: SendToTerminal returns ErrDeviceOffline for every
// keystroke (handleTermInput drops the error silently) while shell output keeps
// streaming, so the browser looks connected but typing does nothing, and the
// shell can no longer be torn down (orphan shells + leaked sockets).
func TestRegisterKeepsTerminalSession(t *testing.T) {
h := New()
var sent []*connection.Context
h.SetSender(func(ctx *connection.Context, data []byte) error {
sent = append(sent, ctx)
return nil
})
mainConn := &connection.Context{RemoteAddr: "10.0.0.1:1000"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, mainConn)
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
term := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindTerminalConn("dev", term, true) {
t.Fatal("BindTerminalConn rejected the pending session")
}
// Main conn drops and the client logs in again (fresh Device struct).
reconnected := &connection.Context{RemoteAddr: "10.0.0.1:1002"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, reconnected)
if got := h.MainConn("dev"); got != reconnected {
t.Fatalf("MainConn = %p, want the reconnected ctx %p", got, reconnected)
}
sent = nil
if err := h.SendToTerminal("dev", []byte("ls\r")); err != nil {
t.Fatalf("SendToTerminal after re-register: %v (terminal binding was dropped)", err)
}
if len(sent) != 1 || sent[0] != term {
t.Fatalf("keystroke went to %v, want the bound shell sub-conn", sent)
}
if !h.TerminalIsPTY("dev") {
t.Fatal("terminalIsPTY lost across re-register (resize would be silently ignored)")
}
if got := h.TerminalDeviceID(term); got != "dev" {
t.Fatalf("TerminalDeviceID(shell) = %q, want dev (output would be parsed as commands)", got)
}
}
// Same failure mode for the screen path: losing the cached geometry and last
// IDR leaves a viewer that joins right after the reconnect with nothing to
// decode until the device happens to emit the next IDR.
func TestRegisterKeepsScreenCache(t *testing.T) {
h := New()
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
screen := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindScreenConn("dev", screen) {
t.Fatal("BindScreenConn failed")
}
h.PublishResolution("dev", 1920, 1080)
keyframe := []byte{0xde, 0xad, 0xbe, 0xef}
h.PublishScreenFrame("dev", keyframe, true)
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
st := h.ScreenState("dev")
if !st.Active {
t.Fatal("screen session marked inactive after re-register")
}
if st.Width != 1920 || st.Height != 1080 {
t.Fatalf("cached geometry = %dx%d, want 1920x1080", st.Width, st.Height)
}
if !bytes.Equal(st.Keyframe, keyframe) {
t.Fatalf("cached IDR = %x, want %x (late joiners would wait for the next IDR)", st.Keyframe, keyframe)
}
}
// Once a sub-conn really goes away, its unbind must still clear the session so
// a later re-register cannot resurrect a stale binding.
func TestRegisterDoesNotReviveClosedSessions(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
term := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindTerminalConn("dev", term, true) {
t.Fatal("BindTerminalConn rejected the pending session")
}
h.UnbindTerminalConn(term) // shell sub-conn dropped
h.UnbindScreenConn(&connection.Context{RemoteAddr: "10.0.0.1:1003"}) // no-op, not bound
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
if err := h.SendToTerminal("dev", []byte("ls\r")); err != ErrDeviceOffline {
t.Fatalf("SendToTerminal = %v, want ErrDeviceOffline (no session)", err)
}
}
// The old main conn's OnDisconnect runs concurrently with a re-login. Its
// cleanup must be scoped to the connection it is about, otherwise the stale
// callback strips the sessions Register just carried over — and deleting by
// ID alone hides a live client until its next reconnect.
func TestStaleDisconnectCannotTearDownNewRegistration(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
oldConn := &connection.Context{RemoteAddr: "10.0.0.1:1000"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, oldConn)
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
term := &connection.Context{RemoteAddr: "10.0.0.1:1001"}
if !h.BindTerminalConn("dev", term, true) {
t.Fatal("BindTerminalConn failed")
}
if !h.BindScreenConn("dev", &connection.Context{RemoteAddr: "10.0.0.1:1003"}) {
t.Fatal("BindScreenConn failed")
}
// Re-login lands first; the old conn's teardown runs afterwards.
newConn := &connection.Context{RemoteAddr: "10.0.0.1:1002"}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"}, newConn)
if h.CloseScreenPinned("dev", oldConn) {
t.Fatal("stale disconnect closed the screen session of the new registration")
}
if h.CloseTerminalSessionPinned("dev", oldConn) {
t.Fatal("stale disconnect closed the terminal session of the new registration")
}
if h.UnregisterPinned("dev", oldConn) {
t.Fatal("stale disconnect removed the re-registered device")
}
if got := h.MainConn("dev"); got != newConn {
t.Fatalf("MainConn = %p, want the new conn %p", got, newConn)
}
if !h.ScreenState("dev").Active {
t.Fatal("screen session lost to the stale disconnect")
}
if err := h.SendToTerminal("dev", []byte("ls\r")); err != nil {
t.Fatalf("SendToTerminal after stale disconnect: %v", err)
}
// The real owner can still clean up.
if !h.UnregisterPinned("dev", newConn) {
t.Fatal("UnregisterPinned rejected the owning main conn")
}
if h.MainConn("dev") != nil {
t.Fatal("device still registered after the owner's disconnect")
}
}
// Only a *bound* session rides across a reconnect: a terminal request that
// never produced a shell sub-conn is re-issued by the browser instead of
// pinning the device "busy" forever.
func TestRegisterDoesNotCarryPendingTerminal(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("OpenTerminalSession: %v", err)
}
if !h.IsTerminalPending("dev") {
t.Fatal("session should be pending after OpenTerminalSession")
}
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
if h.IsTerminalPending("dev") {
t.Fatal("pending request carried across re-register; device would stay 'busy' forever")
}
if err := h.OpenTerminalSession("dev"); err != nil {
t.Fatalf("retry after re-register: %v, want nil", err)
}
}
// A lease generation is an ownership proof: a stale opener whose pending
// request a re-login dropped cannot close the lease someone else acquired
// afterwards, while the current owner can still close its own.
func TestCloseTerminalSessionLeaseIgnoresRenewedLease(t *testing.T) {
h := New()
h.SetSender(func(ctx *connection.Context, data []byte) error { return nil })
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1000"})
stale, err := h.OpenTerminalSessionLease("dev")
if err != nil {
t.Fatalf("first open: %v", err)
}
// Re-login drops the pending request without an OnTerminalClosed event.
h.Register(&Device{ID: "dev", PeerIP: "10.0.0.1"},
&connection.Context{RemoteAddr: "10.0.0.1:1002"})
current, err := h.OpenTerminalSessionLease("dev")
if err != nil {
t.Fatalf("second open: %v", err)
}
if h.CloseTerminalSessionLease("dev", stale) {
t.Fatal("a stale generation closed the renewed lease")
}
if !h.HasTerminalSession("dev") {
t.Fatal("renewed lease was torn down by the stale close")
}
if !h.CloseTerminalSessionLease("dev", current) {
t.Fatal("the owning generation could not close its lease")
}
if h.HasTerminalSession("dev") {
t.Fatal("lease still held after the owner closed it")
}
}