vcom/internal/ssh/sshconfig/resolver_test.go
vrubelroman 8584a638f1 feat(ssh): add sshconfig resolver and host store (2B.1)
Resolve host aliases through ~/.ssh/config with kevinburke/ssh_config:
HostName defaults to the alias, key=value syntax, Host * defaults,
Include, quotes, several IdentityFile, '#' inside values (N-P1-5).
Endpoint.Key includes the user (N-P2-3). Port the hosts.dat store with
atomic writes and a base64 password field.

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

285 lines
9.6 KiB
Go

package sshconfig
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
)
// newTestResolver writes config text to home/.ssh/config and returns a
// Resolver over it.
func newTestResolver(t *testing.T, config string, store *Store) (*Resolver, string) {
t.Helper()
home := t.TempDir()
writeFile(t, filepath.Join(home, ".ssh", "config"), config)
r, err := NewResolver(Options{Home: home, LocalUser: "local", Store: store})
if err != nil {
t.Fatalf("NewResolver: %v", err)
}
return r, home
}
func writeFile(t *testing.T, p, s string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
t.Fatal(err)
}
}
func mustResolve(t *testing.T, r *Resolver, alias string) Endpoint {
t.Helper()
ep, err := r.Resolve(alias)
if err != nil {
t.Fatalf("Resolve(%q): %v", alias, err)
}
return ep
}
// Ported from the testbed (B10): a Host without HostName dialed ":22",
// i.e. localhost; "HostName=10.0.0.1" was not parsed at all (N-P1-5).
func TestConfigNoHostName(t *testing.T) {
r, _ := newTestResolver(t, "Host myserver.example.com\n User bob\nHost alias\n HostName=10.0.0.1\n", nil)
ep := mustResolve(t, r, "myserver.example.com")
if ep.Host != "myserver.example.com" || ep.User != "bob" || ep.Port != 22 {
t.Errorf("no HostName: got %+v", ep)
}
if got := ep.Addr(); got != "myserver.example.com:22" {
t.Errorf("Addr = %q", got)
}
ep = mustResolve(t, r, "alias")
if ep.Host != "10.0.0.1" {
t.Errorf("HostName=10.0.0.1: got Host %q", ep.Host)
}
if ep.User != "local" {
t.Errorf("default user: got %q", ep.User)
}
for _, h := range r.Hosts() {
if h.Host == "" {
t.Errorf("host %q has empty Host", h.Alias)
}
}
}
func TestConfigEqualsAndSpaces(t *testing.T) {
r, _ := newTestResolver(t, "Host a\n HostName = 10.0.0.2\n Port=2222\n User\tcarol\n", nil)
ep := mustResolve(t, r, "a")
if ep.Host != "10.0.0.2" || ep.Port != 2222 || ep.User != "carol" {
t.Errorf("got %+v", ep)
}
}
func TestConfigHostStarDefaults(t *testing.T) {
cfg := `Host special
User alice
IdentityFile ~/.ssh/id_special
Host *
User defuser
IdentityFile ~/.ssh/id_star
ServerAliveInterval 7
ServerAliveCountMax 4
ConnectTimeout 3
`
r, home := newTestResolver(t, cfg, nil)
ep := mustResolve(t, r, "plain.example.com")
if ep.User != "defuser" {
t.Errorf("Host * User not applied: %q", ep.User)
}
if want := []string{filepath.Join(home, ".ssh", "id_star")}; !reflect.DeepEqual(ep.IdentityFiles, want) {
t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want)
}
if ep.ServerAliveInterval != 7*time.Second || ep.ServerAliveCountMax != 4 || ep.ConnectTimeout != 3*time.Second {
t.Errorf("alive/timeout: %+v", ep)
}
ep = mustResolve(t, r, "special")
if ep.User != "alice" {
t.Errorf("first match must win: User %q", ep.User)
}
want := []string{filepath.Join(home, ".ssh", "id_special"), filepath.Join(home, ".ssh", "id_star")}
if !reflect.DeepEqual(ep.IdentityFiles, want) {
t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want)
}
hosts := r.Hosts()
if len(hosts) != 1 || hosts[0].Alias != "special" {
t.Errorf("Hosts() must list only explicit hosts: %+v", hosts)
}
}
func TestConfigMultipleIdentityFiles(t *testing.T) {
r, home := newTestResolver(t, "Host m\n IdentityFile ~/.ssh/one\n IdentityFile two\n IdentityFile /abs/three\n IdentityFile ~/.ssh/one\n IdentitiesOnly yes\n", nil)
ep := mustResolve(t, r, "m")
want := []string{filepath.Join(home, ".ssh", "one"), filepath.Join(home, ".ssh", "two"), "/abs/three"}
if !reflect.DeepEqual(ep.IdentityFiles, want) {
t.Errorf("IdentityFiles = %v, want %v", ep.IdentityFiles, want)
}
if !ep.IdentitiesOnly {
t.Error("IdentitiesOnly not parsed")
}
}
func TestConfigQuotes(t *testing.T) {
r, home := newTestResolver(t, "Host q\n IdentityFile \"~/.ssh/my key\"\n HostName \"q.example.com\"\n", nil)
ep := mustResolve(t, r, "q")
if want := filepath.Join(home, ".ssh", "my key"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want {
t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want)
}
if ep.Host != "q.example.com" {
t.Errorf("Host = %q", ep.Host)
}
}
func TestConfigHashInValue(t *testing.T) {
cfg := "# leading comment\nHost h # trailing comment on Host\n IdentityFile ~/.ssh/key#1 # real comment\n User \"u#2\"\n"
r, home := newTestResolver(t, cfg, nil)
ep := mustResolve(t, r, "h")
if want := filepath.Join(home, ".ssh", "key#1"); len(ep.IdentityFiles) != 1 || ep.IdentityFiles[0] != want {
t.Errorf("IdentityFiles = %v, want [%s]", ep.IdentityFiles, want)
}
if ep.User != "u#2" {
t.Errorf("User = %q, want u#2", ep.User)
}
}
func TestConfigInclude(t *testing.T) {
home := t.TempDir()
writeFile(t, filepath.Join(home, ".ssh", "conf.d", "10-work"), "Host work\n HostName work.example.com\n User worker\n")
writeFile(t, filepath.Join(home, ".ssh", "conf.d", "20-misc"), "Host misc\n Port 2200\n")
abs := filepath.Join(home, "elsewhere.conf")
writeFile(t, abs, "Host abs\n HostName 192.168.1.1\n")
cfg := "Include conf.d/*\nHost outer\n Include " + abs + "\n User outeruser\nHost *\n User fallback\n"
writeFile(t, filepath.Join(home, ".ssh", "config"), cfg)
r, err := NewResolver(Options{Home: home, LocalUser: "local"})
if err != nil {
t.Fatal(err)
}
if ep := mustResolve(t, r, "work"); ep.Host != "work.example.com" || ep.User != "worker" {
t.Errorf("work: %+v", ep)
}
if ep := mustResolve(t, r, "misc"); ep.Port != 2200 || ep.User != "fallback" {
t.Errorf("misc: %+v", ep)
}
if ep := mustResolve(t, r, "abs"); ep.Host != "192.168.1.1" {
t.Errorf("abs: %+v", ep)
}
// Lines after an Include stay in the block that contained it.
if ep := mustResolve(t, r, "outer"); ep.User != "outeruser" {
t.Errorf("outer: User %q, want outeruser", ep.User)
}
var names []string
for _, h := range r.Hosts() {
names = append(names, h.Alias)
}
if want := []string{"work", "misc", "outer", "abs"}; !reflect.DeepEqual(names, want) {
t.Errorf("Hosts = %v, want %v", names, want)
}
}
func TestConfigUnsupportedMatchIgnored(t *testing.T) {
cfg := "Match user root\n User ignored\nMatch host *.corp,10.*\n User corp\nHost x\n HostName x.example.com\n"
r, _ := newTestResolver(t, cfg, nil)
if ep := mustResolve(t, r, "x"); ep.User != "local" {
t.Errorf("unsupported Match applied: %+v", ep)
}
if ep := mustResolve(t, r, "a.corp"); ep.User != "corp" {
t.Errorf("Match host not applied: %+v", ep)
}
if len(r.Warnings()) != 1 {
t.Errorf("warnings = %v", r.Warnings())
}
}
func TestConfigCaseInsensitiveHost(t *testing.T) {
r, _ := newTestResolver(t, "Host MyBox\n HostName 10.1.1.1\n", nil)
if ep := mustResolve(t, r, "mybox"); ep.Host != "10.1.1.1" {
t.Errorf("got %+v", ep)
}
if ep := mustResolve(t, r, "MYBOX"); ep.Host != "10.1.1.1" || ep.Alias != "MYBOX" {
t.Errorf("got %+v", ep)
}
}
func TestConfigInvalidPort(t *testing.T) {
r, _ := newTestResolver(t, "Host p\n Port abc\n", nil)
if _, err := r.Resolve("p"); err == nil {
t.Fatal("want error for invalid port")
}
}
func TestConfigProxyJump(t *testing.T) {
r, _ := newTestResolver(t, "Host target\n ProxyJump admin@bastion:2022,hop2\nHost bastion\n HostName b.example.com\n", nil)
ep := mustResolve(t, r, "target")
if len(ep.ProxyJump) != 2 {
t.Fatalf("ProxyJump = %+v", ep.ProxyJump)
}
if h := ep.ProxyJump[0]; h.Host != "b.example.com" || h.User != "admin" || h.Port != 2022 {
t.Errorf("hop 1: %+v", h)
}
if h := ep.ProxyJump[1]; h.Host != "hop2" || h.Port != 22 {
t.Errorf("hop 2: %+v", h)
}
}
func TestConfigMissingFile(t *testing.T) {
r, err := NewResolver(Options{Home: t.TempDir(), LocalUser: "me"})
if err != nil {
t.Fatalf("missing config must not be an error: %v", err)
}
ep := mustResolve(t, r, "anything")
if ep.Host != "anything" || ep.User != "me" || ep.Port != 22 {
t.Errorf("got %+v", ep)
}
}
// N-P2-3: SameAs ignored User, so two users on one host shared a client.
func TestEndpointKeyIncludesUser(t *testing.T) {
r, _ := newTestResolver(t, "Host a1\n HostName srv\n User alice\nHost a2\n HostName srv\n User alice\nHost b\n HostName srv\n User bob\n", nil)
a1, a2, b := mustResolve(t, r, "a1"), mustResolve(t, r, "a2"), mustResolve(t, r, "b")
if a1.Key() != a2.Key() {
t.Errorf("same user@host:port must share a key: %q vs %q", a1.Key(), a2.Key())
}
if a1.Key() == b.Key() {
t.Errorf("different users must not share a key: %q", a1.Key())
}
if !strings.HasPrefix(a1.Key(), "alice@") || a1.Key() != "alice@srv:22" {
t.Errorf("Key = %q", a1.Key())
}
v6 := Endpoint{User: "u", Host: "::1", Port: 2222}
if v6.Key() != "u@[::1]:2222" {
t.Errorf("IPv6 key = %q", v6.Key())
}
}
func TestResolverStoreHosts(t *testing.T) {
st, err := OpenStore(t.TempDir())
if err != nil {
t.Fatal(err)
}
if err := st.Put(StoredHost{Name: "mine", HostName: "10.9.9.9", Port: 2022, User: "me", Password: "secret"}); err != nil {
t.Fatal(err)
}
if err := st.Put(StoredHost{Name: "dup", HostName: "store.example.com"}); err != nil {
t.Fatal(err)
}
r, _ := newTestResolver(t, "Host dup\n HostName config.example.com\n", st)
ep := mustResolve(t, r, "mine")
if ep.Host != "10.9.9.9" || ep.Port != 2022 || ep.User != "me" || ep.Password != "secret" {
t.Errorf("store host: %+v", ep)
}
if ep := mustResolve(t, r, "dup"); ep.Host != "config.example.com" {
t.Errorf("ssh config must win over the store: %+v", ep)
}
hosts := r.Hosts()
if len(hosts) != 2 || hosts[0].Alias != "dup" || hosts[0].Source != FromSSHConfig ||
hosts[1].Alias != "mine" || hosts[1].Source != FromStore {
t.Errorf("Hosts = %+v", hosts)
}
if got := hosts[1].DisplayName(); got != "mine (me@10.9.9.9:2022)" {
t.Errorf("DisplayName = %q", got)
}
}