vcom/internal/testutil/sshtest/sshtest_test.go
vrubelroman 05da3c0d30 test: add in-process SSH/SFTP server and fault proxy (internal/testutil/sshtest)
Ports the analysts' testbed into a reusable package: Start(Options{Password,
AuthorizedKeys, HostKeys, NoExec, Chroot}), NewProxy with SetDelay/Freeze/
CutAfter/KillAll, IsolatedHome, GenKeys. Exec reports exit-status and
stderr; NoExec rejects exec like ForceCommand internal-sftp. All goroutines
stop on t.Cleanup (checked via runtime.NumGoroutine).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:56:05 +03:00

264 lines
6.4 KiB
Go

package sshtest
import (
"bytes"
"errors"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/pkg/sftp"
"golang.org/x/crypto/ssh"
)
// 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(3 * 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)
}
func sftpClient(t *testing.T, c *ssh.Client) *sftp.Client {
t.Helper()
sc, err := sftp.NewClient(c)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { sc.Close() })
return sc
}
func TestServerSFTPRoundTrip(t *testing.T) {
noLeak(t, func(t *testing.T) {
srv := Start(t, Options{})
sc := sftpClient(t, srv.Dial(t, ""))
dir := t.TempDir()
p := filepath.Join(dir, "sub", "f.bin")
if err := sc.MkdirAll(filepath.Dir(p)); err != nil {
t.Fatal(err)
}
want := bytes.Repeat([]byte("vcom"), 50000)
f, err := sc.Create(p)
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(want); err != nil {
t.Fatal(err)
}
if err := f.Close(); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(p)
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("disk content mismatch: err=%v len=%d", err, len(got))
}
r, err := sc.Open(p)
if err != nil {
t.Fatal(err)
}
back, err := io.ReadAll(r)
r.Close()
if err != nil || !bytes.Equal(back, want) {
t.Fatalf("read back mismatch: err=%v len=%d", err, len(back))
}
})
}
func TestServerChrootWorkingDir(t *testing.T) {
root := t.TempDir()
WriteRandom(t, filepath.Join(root, "x.bin"), 10, 0o644)
srv := Start(t, Options{Chroot: root})
sc := sftpClient(t, srv.Dial(t, ""))
if _, err := sc.Stat("x.bin"); err != nil {
t.Fatalf("relative path should resolve inside Chroot: %v", err)
}
if srv.Root != root {
t.Fatalf("Root=%q want %q", srv.Root, root)
}
}
func TestServerExecStatusAndStderr(t *testing.T) {
noLeak(t, func(t *testing.T) {
srv := Start(t, Options{})
c := srv.Dial(t, "")
s, err := c.NewSession()
if err != nil {
t.Fatal(err)
}
var out, errb bytes.Buffer
s.Stdout, s.Stderr = &out, &errb
err = s.Run("echo hi; echo oops >&2; exit 3")
s.Close()
var ee *ssh.ExitError
if !errors.As(err, &ee) || ee.ExitStatus() != 3 {
t.Fatalf("want exit status 3, got %v", err)
}
if out.String() != "hi\n" || errb.String() != "oops\n" {
t.Fatalf("stdout=%q stderr=%q", out.String(), errb.String())
}
})
}
func TestServerNoExec(t *testing.T) {
srv := Start(t, Options{NoExec: true})
c := srv.Dial(t, "")
s, err := c.NewSession()
if err != nil {
t.Fatal(err)
}
defer s.Close()
if err := s.Run("true"); err == nil {
t.Fatal("exec must be rejected with NoExec")
}
sftpClient(t, c) // sftp still works
}
func TestServerPublicKeyAuth(t *testing.T) {
ed, _ := GenKeys(t)
srv := Start(t, Options{AuthorizedKeys: []ssh.PublicKey{ed.PublicKey()}})
cfg := srv.ClientConfig("")
if _, err := ssh.Dial("tcp", srv.Addr, cfg); err == nil {
t.Fatal("password auth must be disabled when only keys are configured")
}
cfg.Auth = []ssh.AuthMethod{ssh.PublicKeys(ed)}
c, err := ssh.Dial("tcp", srv.Addr, cfg)
if err != nil {
t.Fatal(err)
}
c.Close()
}
func rtt(t *testing.T, sc *sftp.Client, p string) time.Duration {
t0 := time.Now()
if _, err := sc.Stat(p); err != nil {
t.Fatal(err)
}
return time.Since(t0)
}
func TestProxyDelay(t *testing.T) {
noLeak(t, func(t *testing.T) {
srv := Start(t, Options{})
px := NewProxy(t, srv.Addr)
sc := sftpClient(t, srv.Dial(t, px.Addr))
dir := t.TempDir()
base := rtt(t, sc, dir)
const d = 40 * time.Millisecond
px.SetDelay(d)
got := rtt(t, sc, dir)
t.Logf("rtt without delay=%v with %v one-way delay=%v", base, d, got)
if got < d {
t.Fatalf("rtt %v < delay %v", got, d)
}
px.SetDelay(0)
})
}
func TestProxyFreeze(t *testing.T) {
noLeak(t, func(t *testing.T) {
srv := Start(t, Options{})
px := NewProxy(t, srv.Addr)
sc := sftpClient(t, srv.Dial(t, px.Addr))
dir := t.TempDir()
px.Freeze(true)
res := make(chan error, 1)
go func() { _, err := sc.ReadDir(dir); res <- err }()
select {
case err := <-res:
t.Fatalf("request completed while frozen: %v", err)
case <-time.After(300 * time.Millisecond):
}
px.Freeze(false)
select {
case err := <-res:
if err != nil {
t.Fatalf("request failed after unfreeze: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("request did not complete after unfreeze")
}
})
}
func TestProxyCut(t *testing.T) {
noLeak(t, func(t *testing.T) {
srv := Start(t, Options{})
px := NewProxy(t, srv.Addr)
c := srv.Dial(t, px.Addr)
sc := sftpClient(t, c)
dir := t.TempDir()
before := px.Sent()
px.CutAfter(256 << 10)
f, err := sc.Create(filepath.Join(dir, "big.bin"))
if err != nil {
t.Fatal(err)
}
_, werr := f.Write(make([]byte, 4<<20))
f.Close()
if werr == nil {
t.Fatal("write of 4 MiB should fail after cut at 256 KiB")
}
sent := px.Sent() - before
if sent > 1<<20 {
t.Fatalf("proxy forwarded %d bytes after a 256 KiB cut", sent)
}
done := make(chan struct{})
go func() { c.Wait(); close(done) }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("ssh connection still alive after cut")
}
// The proxy keeps accepting connections after a cut.
sc2 := sftpClient(t, srv.Dial(t, px.Addr))
if _, err := sc2.Stat(dir); err != nil {
t.Fatalf("new connection after cut: %v", err)
}
})
}
func TestProxyKillAll(t *testing.T) {
srv := Start(t, Options{})
px := NewProxy(t, srv.Addr)
c := srv.Dial(t, px.Addr)
px.KillAll()
done := make(chan error, 1)
go func() { done <- c.Wait() }()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("connection survived KillAll")
}
}
func TestIsolatedHome(t *testing.T) {
h := IsolatedHome(t)
if os.Getenv("HOME") != h || os.Getenv("SSH_AUTH_SOCK") != "" {
t.Fatal("env not isolated")
}
st, err := os.Stat(filepath.Join(h, ".ssh"))
if err != nil || st.Mode().Perm() != 0o700 {
t.Fatalf(".ssh: %v %v", st, err)
}
if !strings.HasPrefix(h, os.TempDir()) {
t.Logf("home outside TMPDIR: %s", h)
}
}