From 1e5b91f73d70d9df47aefe0d8ae7b9336e665887 Mon Sep 17 00:00:00 2001 From: Sanskar Jaiswal Date: Thu, 25 May 2023 01:55:33 +0530 Subject: [PATCH] git/gogit: set `HostKeyCallback` for parent `PublicKeys` object Set `HostKeyCallback` for the parent `PublicKeys` object to avoid setting the callback to one that uses the system's known_hosts. Signed-off-by: Sanskar Jaiswal --- git/gogit/transport.go | 8 ++++---- git/gogit/transport_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/git/gogit/transport.go b/git/gogit/transport.go index 4a365742..8229d857 100644 --- a/git/gogit/transport.go +++ b/git/gogit/transport.go @@ -114,14 +114,15 @@ func (a *CustomPublicKeys) String() string { } func (a *CustomPublicKeys) ClientConfig() (*gossh.ClientConfig, error) { + if a.callback != nil { + a.pk.HostKeyCallback = a.callback + } + config, err := a.pk.ClientConfig() if err != nil { return nil, err } - if a.callback != nil { - config.HostKeyCallback = a.callback - } if len(git.KexAlgos) > 0 { config.Config.KeyExchanges = git.KexAlgos } @@ -149,7 +150,6 @@ func (a *DefaultAuth) ClientConfig() (*gossh.ClientConfig, error) { if err != nil { return nil, err } - config.HostKeyCallback, err = ssh.NewKnownHostsCallback() if err != nil { return nil, err } diff --git a/git/gogit/transport_test.go b/git/gogit/transport_test.go index f150dcf5..d1d75195 100644 --- a/git/gogit/transport_test.go +++ b/git/gogit/transport_test.go @@ -25,7 +25,9 @@ import ( "github.com/go-git/go-git/v5/plumbing/transport" "github.com/go-git/go-git/v5/plumbing/transport/http" + "github.com/go-git/go-git/v5/plumbing/transport/ssh" . "github.com/onsi/gomega" + gossh "golang.org/x/crypto/ssh" "golang.org/x/crypto/ssh/agent" "github.com/fluxcd/pkg/git" @@ -284,6 +286,29 @@ func Test_transportAuth(t *testing.T) { } } +func TestCustomPublicKeys_ClientConfig(t *testing.T) { + g := NewWithT(t) + pk, err := ssh.NewPublicKeys("user", []byte(privateKeyFixture), "password") + g.Expect(err).ToNot(HaveOccurred()) + + var count int + customCallback := func(hostname string, remote net.Addr, key gossh.PublicKey) error { + count += 1 + return nil + } + customPK := CustomPublicKeys{ + pk: pk, + callback: customCallback, + } + cfg, err := customPK.ClientConfig() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(cfg.HostKeyCallback).ToNot(BeNil()) + + err = cfg.HostKeyCallback("", nil, nil) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(count).To(Equal(1)) +} + func Test_defaultKnownHosts(t *testing.T) { g := NewWithT(t) tmp, err := os.MkdirTemp("", "ssh_agent")