vcom/internal/ssh/conn/helpers_test.go
vrubelroman 351970078f feat(ssh): add Conn with keepalive, states, reconnect and exec (2B.3)
Keepalive with a per-reply timeout marks a frozen link Lost and closes
it so hung SFTP calls fail with ErrConnLost (N-P1-2). Reconnect installs
a new generation in the same Conn. Exec takes a ctx (SIGKILL + close on
cancel) and an output limit (N-P2-15, N-P1-7).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 23:37:01 +03:00

401 lines
9.2 KiB
Go

package conn
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/pem"
"errors"
"net"
"os"
"path/filepath"
"runtime"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/knownhosts"
"vcom/internal/testutil/sshtest"
)
// noLeak runs fn as a subtest (so its Cleanups run) and then checks that the
// goroutine count returns to the baseline within ±2.
func noLeak(t *testing.T, fn func(t *testing.T)) {
t.Helper()
runtime.GC()
base := runtime.NumGoroutine()
t.Run("body", fn)
deadline := time.Now().Add(5 * time.Second)
var n int
for time.Now().Before(deadline) {
n = runtime.NumGoroutine()
if n <= base+2 {
return
}
time.Sleep(20 * time.Millisecond)
}
buf := make([]byte, 1<<20)
buf = buf[:runtime.Stack(buf, true)]
t.Errorf("goroutines: base=%d after cleanup=%d\n%s", base, n, buf)
}
// waitFor polls cond until it holds or d elapses.
func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(d)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out after %v waiting for %s", d, what)
}
time.Sleep(5 * time.Millisecond)
}
}
// env is an isolated HOME with helpers to dial the in-process server.
type env struct {
t *testing.T
home string
kh string // ~/.ssh/known_hosts
}
func newEnv(t *testing.T) *env {
t.Helper()
home := sshtest.IsolatedHome(t)
return &env{t: t, home: home, kh: filepath.Join(home, ".ssh", "known_hosts")}
}
// dialer returns a dialer rooted at the env HOME; the agent is disabled
// unless o.AgentSocket is set.
func (e *env) dialer(o DialOptions) *dialer {
if o.Home == "" {
o.Home = e.home
}
if o.AgentSocket == "" {
o.AgentSocket = "-"
}
if o.KnownHostsFiles == nil {
o.KnownHostsFiles = []string{e.kh}
}
d := newDialer(o)
e.t.Cleanup(d.close)
return d
}
// trust writes known_hosts lines for addr.
func (e *env) trust(addr string, keys ...ssh.PublicKey) {
e.t.Helper()
var data []byte
for _, k := range keys {
data = append(data, knownhosts.Line([]string{knownhosts.Normalize(addr)}, k)+"\n"...)
}
if err := os.WriteFile(e.kh, data, 0o600); err != nil {
e.t.Fatal(err)
}
}
func endpointFor(addr, password string) Endpoint {
host, port, _ := net.SplitHostPort(addr)
p, _ := strconv.Atoi(port)
return Endpoint{Alias: "test", User: "u", Host: host, Port: p, Password: password}
}
// proxy starts a proxy in front of srv and trusts srv's keys at the proxy
// address too.
func (e *env) proxy(srv *sshtest.Server) *sshtest.Proxy {
px := sshtest.NewProxy(e.t, srv.Addr)
old, _ := os.ReadFile(e.kh)
var pubs []ssh.PublicKey
for _, k := range srv.HostKeys {
pubs = append(pubs, k.PublicKey())
}
e.trust(px.Addr, pubs...)
added, _ := os.ReadFile(e.kh)
if err := os.WriteFile(e.kh, append(old, added...), 0o600); err != nil {
e.t.Fatal(err)
}
return px
}
// startTrusted starts a server whose host keys are in known_hosts.
func (e *env) startTrusted(o sshtest.Options) *sshtest.Server {
srv := sshtest.Start(e.t, o)
var pubs []ssh.PublicKey
for _, k := range srv.HostKeys {
pubs = append(pubs, k.PublicKey())
}
e.trust(srv.Addr, pubs...)
return srv
}
func (l *link) closeOnCleanup(t *testing.T) *link {
t.Cleanup(l.close)
return l
}
// fakePrompter records calls and answers with the configured functions.
type fakePrompter struct {
mu sync.Mutex
hostKeys []hostKeyCall
passwords int
kiCalls [][]string
kiEcho [][]bool
kiInstr []string
phrases []string
hostKey func(ctx context.Context, changed bool) (HostKeyDecision, error)
password func(ctx context.Context) (string, error)
ki func(qs []string) ([]string, error)
passphrase func(path string) ([]byte, error)
}
type hostKeyCall struct {
id HostIdentity
known []HostIdentity
changed bool
}
func (p *fakePrompter) HostKey(ctx context.Context, ep Endpoint, id HostIdentity, known []HostIdentity, changed bool) (HostKeyDecision, error) {
p.mu.Lock()
p.hostKeys = append(p.hostKeys, hostKeyCall{id, known, changed})
p.mu.Unlock()
if p.hostKey == nil {
return Reject, nil
}
return p.hostKey(ctx, changed)
}
func (p *fakePrompter) Password(ctx context.Context, ep Endpoint) (string, error) {
p.mu.Lock()
p.passwords++
p.mu.Unlock()
if p.password == nil {
return "", errors.New("no password")
}
return p.password(ctx)
}
func (p *fakePrompter) KeyboardInteractive(ctx context.Context, ep Endpoint, instr string, qs []string, echo []bool) ([]string, error) {
p.mu.Lock()
p.kiCalls = append(p.kiCalls, append([]string(nil), qs...))
p.kiEcho = append(p.kiEcho, append([]bool(nil), echo...))
p.kiInstr = append(p.kiInstr, instr)
p.mu.Unlock()
if p.ki == nil {
return nil, errors.New("no answers")
}
return p.ki(qs)
}
func (p *fakePrompter) Passphrase(ctx context.Context, path string) ([]byte, error) {
p.mu.Lock()
p.phrases = append(p.phrases, path)
p.mu.Unlock()
if p.passphrase == nil {
return nil, errors.New("no passphrase")
}
return p.passphrase(path)
}
func (p *fakePrompter) counts() (hostKeys, passwords, ki, phrases int) {
p.mu.Lock()
defer p.mu.Unlock()
return len(p.hostKeys), p.passwords, len(p.kiCalls), len(p.phrases)
}
// newKey returns a fresh ed25519 private key and its signer.
func newKey(t *testing.T) (ed25519.PrivateKey, ssh.Signer) {
t.Helper()
_, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
s, err := ssh.NewSignerFromKey(priv)
if err != nil {
t.Fatal(err)
}
return priv, s
}
// writeKey stores priv in OpenSSH format (encrypted when passphrase != "").
func writeKey(t *testing.T, path string, priv ed25519.PrivateKey, passphrase string) {
t.Helper()
var blk *pem.Block
var err error
if passphrase == "" {
blk, err = ssh.MarshalPrivateKey(priv, "test")
} else {
blk, err = ssh.MarshalPrivateKeyWithPassphrase(priv, "test", []byte(passphrase))
}
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, pem.EncodeToMemory(blk), 0o600); err != nil {
t.Fatal(err)
}
}
// fakeAgent serves an in-memory keyring on a unix socket.
type fakeAgent struct {
sock string
accepts atomic.Int32
active atomic.Int32
}
func startAgent(t *testing.T, keys ...ed25519.PrivateKey) *fakeAgent {
t.Helper()
kr := agent.NewKeyring()
for _, k := range keys {
if err := kr.Add(agent.AddedKey{PrivateKey: k}); err != nil {
t.Fatal(err)
}
}
dir, err := os.MkdirTemp("", "agent")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
a := &fakeAgent{sock: filepath.Join(dir, "s")}
ln, err := net.Listen("unix", a.sock)
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
var conns []net.Conn
wg.Add(1)
go func() {
defer wg.Done()
for {
c, err := ln.Accept()
if err != nil {
return
}
a.accepts.Add(1)
a.active.Add(1)
mu.Lock()
conns = append(conns, c)
mu.Unlock()
wg.Add(1)
go func() {
defer wg.Done()
defer a.active.Add(-1)
agent.ServeAgent(kr, c)
c.Close()
}()
}
}()
t.Cleanup(func() {
ln.Close()
mu.Lock()
for _, c := range conns {
c.Close()
}
mu.Unlock()
wg.Wait()
})
return a
}
// kiServer is a minimal SSH server that only allows keyboard-interactive
// auth with the given questions; answers must equal want. It serves SFTP so
// the full dial path succeeds.
func kiServer(t *testing.T, questions []string, echo []bool, want []string) (string, ssh.PublicKey) {
t.Helper()
ed, _ := sshtest.GenKeys(t)
cfg := &ssh.ServerConfig{
KeyboardInteractiveCallback: func(_ ssh.ConnMetadata, ch ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
ans, err := ch("vcom-test", "Two factors please", questions, echo)
if err != nil {
return nil, err
}
if len(ans) != len(want) {
return nil, errors.New("wrong answer count")
}
for i := range want {
if ans[i] != want[i] {
return nil, errors.New("wrong answer")
}
}
return nil, nil
},
}
cfg.AddHostKey(ed)
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
var conns []net.Conn
wg.Add(1)
go func() {
defer wg.Done()
for {
nc, err := ln.Accept()
if err != nil {
return
}
mu.Lock()
conns = append(conns, nc)
mu.Unlock()
wg.Add(1)
go func() {
defer wg.Done()
defer nc.Close()
sc, chans, reqs, err := ssh.NewServerConn(nc, cfg)
if err != nil {
return
}
defer sc.Close()
go ssh.DiscardRequests(reqs)
for nch := range chans {
ch, creqs, err := nch.Accept()
if err != nil {
continue
}
wg.Add(1)
go func() {
defer wg.Done()
defer ch.Close()
for req := range creqs {
if req.Type == "subsystem" {
req.Reply(true, nil)
srv, err := sftp.NewServer(ch)
if err != nil {
return
}
go func() {
for range creqs {
}
}()
srv.Serve()
srv.Close()
return
}
req.Reply(false, nil)
}
}()
}
}()
}
}()
t.Cleanup(func() {
ln.Close()
mu.Lock()
for _, c := range conns {
c.Close()
}
mu.Unlock()
wg.Wait()
})
return ln.Addr().String(), ed.PublicKey()
}