vcom/internal/ssh/conn/conn_test.go
vrubelroman c328fff867 feat(ssh): add refcounted connection Pool and Lease (2B.4)
Panels, jobs and previews hold Leases; only the pool closes a
connection, after IdleClose without leases or on Close, so concurrent
use and release cannot race (N-P0-8) and a mirror keeps its connection
when the other panel leaves (N-P1-12). Concurrent Acquires of one
user@host:port share a single dial (N-P2-8); Reconnect retries with
backoff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 03:51:51 +03:00

297 lines
8.5 KiB
Go

package conn
import (
"context"
"errors"
"strings"
"sync"
"testing"
"time"
"vcom/internal/testutil/sshtest"
)
// events collects Conn events.
type events struct {
mu sync.Mutex
ev []Event
}
func (e *events) add(ev Event) {
e.mu.Lock()
e.ev = append(e.ev, ev)
e.mu.Unlock()
}
func (e *events) has(s State) bool {
e.mu.Lock()
defer e.mu.Unlock()
for _, ev := range e.ev {
if ev.State == s {
return true
}
}
return false
}
func (e *events) snapshot() []Event {
e.mu.Lock()
defer e.mu.Unlock()
return append([]Event(nil), e.ev...)
}
func (e *events) last() Event {
e.mu.Lock()
defer e.mu.Unlock()
if len(e.ev) == 0 {
return Event{}
}
return e.ev[len(e.ev)-1]
}
// fastKeepalive makes liveness tests take well under a second.
var fastKeepalive = ConnOptions{
KeepaliveInterval: 100 * time.Millisecond,
KeepaliveTimeout: 100 * time.Millisecond,
KeepaliveMaxMiss: 2,
}
func (e *env) connect(addr, password string, o ConnOptions) *Conn {
e.t.Helper()
c, err := e.dialer(DialOptions{}).connect(context.Background(), endpointFor(addr, password), o)
if err != nil {
e.t.Fatalf("connect: %v", err)
}
e.t.Cleanup(c.close)
return c
}
// Ported from the testbed (B6, TestFreezeHangs), N-P1-2: a frozen link was
// never noticed and calls hung forever. Now keepalive marks it Lost within
// interval*(miss+1)+timeout and the hung ReadDir returns ErrConnLost.
func TestFreezeDetectedAsLost(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
var ev events
o := fastKeepalive
o.OnEvent = ev.add
c := e.connect(px.Addr, srv.Password, o)
sc, err := c.Client()
if err != nil {
t.Fatal(err)
}
dir := t.TempDir()
if _, err := sc.ReadDir(dir); err != nil {
t.Fatal(err)
}
px.Freeze(true)
defer px.Freeze(false)
start := time.Now()
res := make(chan error, 1)
go func() {
_, err := sc.ReadDir(dir)
res <- c.MapErr(err)
}()
bound := o.KeepaliveInterval*time.Duration(o.KeepaliveMaxMiss+1) + o.KeepaliveTimeout
waitFor(t, bound+500*time.Millisecond, "state Lost", func() bool { return c.State() == Lost })
t.Logf("lost after %v (bound %v)", time.Since(start), bound)
select {
case err := <-res:
if !errors.Is(err, ErrConnLost) {
t.Errorf("hung ReadDir: err = %v, want ErrConnLost", err)
}
case <-time.After(time.Second):
t.Fatal("hung ReadDir did not return after Lost")
}
waitFor(t, time.Second, "Lost event", func() bool { return ev.has(Lost) })
if ev.last().Err == nil || !errors.Is(ev.last().Err, ErrConnLost) {
t.Errorf("events = %+v", ev.snapshot())
}
if _, err := c.Client(); !errors.Is(err, ErrConnLost) {
t.Errorf("Client() after Lost: %v", err)
}
})
}
func TestReconnectAfterCut(t *testing.T) {
noLeak(t, func(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
var ev events
o := ConnOptions{KeepaliveInterval: time.Hour, OnEvent: ev.add}
c := e.connect(px.Addr, srv.Password, o)
dir := t.TempDir()
gen := c.Gen()
id := c.Identity()
px.CutAfter(1)
sc, _ := c.Client()
_, err := sc.ReadDir(dir)
if err == nil {
t.Fatal("ReadDir across a cut succeeded")
}
if !errors.Is(c.MapErr(err), ErrConnLost) {
t.Errorf("err = %v, want ErrConnLost", c.MapErr(err))
}
waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost })
if err := c.Reconnect(context.Background()); err != nil {
t.Fatalf("Reconnect: %v", err)
}
if c.State() != Ready || c.Gen() != gen+1 || c.Identity() != id {
t.Errorf("after reconnect: state %v gen %d (was %d) id %+v", c.State(), c.Gen(), gen, c.Identity())
}
sc2, err := c.Client()
if err != nil {
t.Fatal(err)
}
if _, err := sc2.ReadDir(dir); err != nil {
t.Fatalf("ReadDir after reconnect: %v", err)
}
// The old generation's client stays dead.
if _, err := sc.ReadDir(dir); !errors.Is(c.MapErr(err), ErrConnLost) {
t.Errorf("old-generation client: %v", err)
}
if err := c.Reconnect(context.Background()); err != nil {
t.Errorf("Reconnect on a Ready conn must be a no-op: %v", err)
}
if !ev.has(Connecting) || ev.last().State != Ready {
t.Errorf("events = %+v", ev.snapshot())
}
c.close()
if err := c.Reconnect(context.Background()); !errors.Is(err, ErrClosed) {
t.Errorf("Reconnect after close: %v", err)
}
if _, err := c.Client(); !errors.Is(err, ErrClosed) {
t.Errorf("Client after close: %v", err)
}
})
}
func TestReconnectFailsWhileServerDown(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour})
px.Freeze(true)
defer px.Freeze(false)
px.KillAll()
waitFor(t, 2*time.Second, "state Lost", func() bool { return c.State() == Lost })
c.d.opts.HandshakeTimeout = 200 * time.Millisecond
if err := c.Reconnect(context.Background()); err == nil {
t.Fatal("reconnect through a frozen link succeeded")
}
if c.State() != Lost {
t.Errorf("state = %v, want Lost", c.State())
}
}
func TestProbeMarksLost(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
px := e.proxy(srv)
c := e.connect(px.Addr, srv.Password, ConnOptions{KeepaliveInterval: time.Hour})
if err := c.Probe(context.Background(), time.Second); err != nil {
t.Fatalf("probe on a live link: %v", err)
}
px.Freeze(true)
defer px.Freeze(false)
if err := c.Probe(context.Background(), 100*time.Millisecond); !errors.Is(err, ErrConnLost) {
t.Fatalf("probe on a frozen link: %v", err)
}
if c.State() != Lost {
t.Errorf("state = %v", c.State())
}
}
// N-P2-15 / N-P1-7: Exec had no ctx and no timeout.
func TestExecCancelKills(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
ctx, cancel := context.WithCancel(context.Background())
time.AfterFunc(100*time.Millisecond, cancel)
start := time.Now()
_, _, err := c.Exec(ctx, []string{"sleep", "60"}, 0)
if el := time.Since(start); el > time.Second {
t.Errorf("cancel took %v", el)
}
if !errors.Is(err, context.Canceled) {
t.Errorf("err = %v", err)
}
// The connection is still usable.
out, code, err := c.Exec(context.Background(), []string{"echo", "it's ok"}, 0)
if err != nil || code != 0 || string(out) != "it's ok\n" {
t.Errorf("exec after cancel: %q %d %v", out, code, err)
}
}
func TestExecOutputLimit(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
start := time.Now()
out, _, err := c.Exec(context.Background(), []string{"yes"}, 1000)
if !errors.Is(err, ErrOutputLimit) {
t.Fatalf("err = %v, want ErrOutputLimit", err)
}
if len(out) != 1000 || !strings.HasPrefix(string(out), "y\ny\n") {
t.Errorf("output: %d bytes", len(out))
}
if el := time.Since(start); el > 2*time.Second {
t.Errorf("limited exec took %v", el)
}
}
func TestExecExitStatus(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
out, code, err := c.Exec(context.Background(), []string{"sh", "-c", "echo out; echo bad >&2; exit 3"}, 0)
var ee *ExitError
if !errors.As(err, &ee) || code != 3 || ee.Code != 3 || strings.TrimSpace(ee.Stderr) != "bad" || string(out) != "out\n" {
t.Errorf("out=%q code=%d err=%v", out, code, err)
}
if !c.ExecSupported(context.Background()) {
t.Error("ExecSupported = false on a server with exec")
}
}
func TestExecSupportedNoExec(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{NoExec: true})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
if c.ExecSupported(context.Background()) {
t.Error("ExecSupported = true with ForceCommand internal-sftp")
}
if _, err := c.Client(); err != nil {
t.Errorf("a refused exec must not break the connection: %v", err)
}
}
func TestQuote(t *testing.T) {
got := Quote([]string{"cp", "-r", "a b", "it's", "", "x;rm -rf /", "/ok/path_1.txt"})
want := `cp -r 'a b' 'it'\''s' '' 'x;rm -rf /' /ok/path_1.txt`
if got != want {
t.Errorf("Quote = %s\nwant %s", got, want)
}
}
func TestConnInfo(t *testing.T) {
e := newEnv(t)
srv := e.startTrusted(sshtest.Options{})
c := e.connect(srv.Addr, srv.Password, ConnOptions{})
if c.Identity().FingerprintSHA256 == "" || !strings.HasPrefix(c.ServerVersion(), "SSH-2.0-") {
t.Errorf("identity %+v version %q", c.Identity(), c.ServerVersion())
}
if !c.Caps().PosixRename {
t.Logf("caps: %+v", c.Caps())
}
if c.Key() != "u@"+srv.Addr {
t.Errorf("Key = %q", c.Key())
}
}