Skip to content

Commit

Permalink
Fix race condition on gittestserver
Browse files Browse the repository at this point in the history
Prevent multiple ssh server initialisations with a mutex.

Signed-off-by: Paulo Gomes <[email protected]>
  • Loading branch information
Paulo Gomes committed Mar 21, 2022
1 parent 386f3bd commit 49ca364
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions gittestserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"net/url"
"os"
"path/filepath"
"sync"
"time"

"github.com/go-git/go-billy/v5/memfs"
Expand All @@ -36,6 +37,8 @@ import (
"github.com/sosedoff/gitkit"
)

var m sync.RWMutex

// NewTempGitServer returns a GitServer with a newly created temp
// dir as repository docroot.
func NewTempGitServer() (*GitServer, error) {
Expand Down Expand Up @@ -188,12 +191,20 @@ func (s *GitServer) StopHTTP() {
// unlike StartSSH(), and the server URL is available with
// SSHAddress() after calling this.
func (s *GitServer) ListenSSH() error {
if s.sshServer == nil {
m.RLock()
sshServer := s.sshServer
m.RUnlock()

if sshServer == nil {
m.Lock()
defer m.Unlock()
s.sshServer = gitkit.NewSSH(s.config)

// This is where authentication would happen, when needed.
s.sshServer.PublicKeyLookupFunc = func(content string) (*gitkit.PublicKey, error) {
return &gitkit.PublicKey{Id: "test-user"}, nil
}

// :0 should result in an OS assigned free port; 127.0.0.1
// forces the lowest common denominator of TCPv4 on localhost.
return s.sshServer.Listen("127.0.0.1:0")
Expand All @@ -216,8 +227,12 @@ func (s *GitServer) StartSSH() error {

// StopSSH stops the SSH git server.
func (s *GitServer) StopSSH() error {
if s.sshServer != nil {
return s.sshServer.Stop()
m.RLock()
sshServer := s.sshServer
m.RUnlock()

if sshServer != nil {
return sshServer.Stop()
}
return nil
}
Expand Down

0 comments on commit 49ca364

Please sign in to comment.