1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
|
package git
import (
"bytes"
"crypto/rand"
"crypto/rsa"
"fmt"
"io"
"net"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"
"github.com/google/shlex"
"golang.org/x/crypto/ssh"
)
func TestListRemotes(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
_, err := repo.Remotes.Create("test", "git://foo/bar")
checkFatal(t, err)
expected := []string{
"test",
}
actual, err := repo.Remotes.List()
checkFatal(t, err)
compareStringList(t, expected, actual)
}
/*
func assertHostname(cert *Certificate, valid bool, hostname string, t *testing.T) ErrorCode {
if hostname != "github.com" {
t.Fatal("Hostname does not match")
return ErrorCodeUser
}
return ErrorCodeOK
}
func TestCertificateCheck(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository")
checkFatal(t, err)
options := FetchOptions{
RemoteCallbacks: RemoteCallbacks{
CertificateCheckCallback: func(cert *Certificate, valid bool, hostname string) ErrorCode {
return assertHostname(cert, valid, hostname, t)
},
},
}
err = remote.Fetch([]string{}, &options, "")
checkFatal(t, err)
}
func TestRemoteConnect(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository")
checkFatal(t, err)
err = remote.ConnectFetch(nil, nil, nil)
checkFatal(t, err)
}
func TestRemoteLs(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository")
checkFatal(t, err)
err = remote.ConnectFetch(nil, nil, nil)
checkFatal(t, err)
heads, err := remote.Ls()
checkFatal(t, err)
if len(heads) == 0 {
t.Error("Expected remote heads")
}
}
func TestRemoteLsFiltering(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
remote, err := repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository")
checkFatal(t, err)
err = remote.ConnectFetch(nil, nil, nil)
checkFatal(t, err)
heads, err := remote.Ls("master")
checkFatal(t, err)
if len(heads) != 1 {
t.Fatalf("Expected one head for master but I got %d", len(heads))
}
if heads[0].Id == nil {
t.Fatalf("Expected head to have an Id, but it's nil")
}
if heads[0].Name == "" {
t.Fatalf("Expected head to have a name, but it's empty")
}
}
func TestRemotePruneRefs(t *testing.T) {
t.Parallel()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
config, err := repo.Config()
checkFatal(t, err)
defer config.Free()
err = config.SetBool("remote.origin.prune", true)
checkFatal(t, err)
_, err = repo.Remotes.Create("origin", "https://github.com/libgit2/TestGitRepository")
checkFatal(t, err)
remote, err := repo.Remotes.Lookup("origin")
checkFatal(t, err)
if !remote.PruneRefs() {
t.Fatal("Expected remote to be configured to prune references")
}
}
func TestRemotePrune(t *testing.T) {
t.Parallel()
remoteRepo := createTestRepo(t)
defer cleanupTestRepo(t, remoteRepo)
head, _ := seedTestRepo(t, remoteRepo)
commit, err := remoteRepo.LookupCommit(head)
checkFatal(t, err)
defer commit.Free()
remoteRef, err := remoteRepo.CreateBranch("test-prune", commit, true)
checkFatal(t, err)
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
config, err := repo.Config()
checkFatal(t, err)
defer config.Free()
remoteUrl := fmt.Sprintf("file://%s", remoteRepo.Workdir())
remote, err := repo.Remotes.Create("origin", remoteUrl)
checkFatal(t, err)
err = remote.Fetch([]string{"test-prune"}, nil, "")
checkFatal(t, err)
_, err = repo.References.Create("refs/remotes/origin/test-prune", head, true, "remote reference")
checkFatal(t, err)
err = remoteRef.Delete()
checkFatal(t, err)
err = config.SetBool("remote.origin.prune", true)
checkFatal(t, err)
rr, err := repo.Remotes.Lookup("origin")
checkFatal(t, err)
err = rr.ConnectFetch(nil, nil, nil)
checkFatal(t, err)
err = rr.Prune(nil)
checkFatal(t, err)
_, err = repo.References.Lookup("refs/remotes/origin/test-prune")
if err == nil {
t.Fatal("Expected error getting a pruned reference")
}
}
*/
func newChannelPipe(t *testing.T, w io.Writer, wg *sync.WaitGroup) (*os.File, error) {
pr, pw, err := os.Pipe()
if err != nil {
return nil, err
}
wg.Add(1)
go func() {
_, err := io.Copy(w, pr)
if err != nil && err != io.EOF {
t.Logf("Failed to copy: %v", err)
}
wg.Done()
}()
return pw, nil
}
func startSSHServer(t *testing.T, hostKey ssh.Signer, authorizedKeys []ssh.PublicKey) net.Listener {
t.Helper()
marshaledAuthorizedKeys := make([][]byte, len(authorizedKeys))
for i, authorizedKey := range authorizedKeys {
marshaledAuthorizedKeys[i] = authorizedKey.Marshal()
}
config := &ssh.ServerConfig{
PublicKeyCallback: func(c ssh.ConnMetadata, pubKey ssh.PublicKey) (*ssh.Permissions, error) {
marshaledPubKey := pubKey.Marshal()
for _, marshaledAuthorizedKey := range marshaledAuthorizedKeys {
if bytes.Equal(marshaledPubKey, marshaledAuthorizedKey) {
return &ssh.Permissions{
// Record the public key used for authentication.
Extensions: map[string]string{
"pubkey-fp": ssh.FingerprintSHA256(pubKey),
},
}, nil
}
}
t.Logf("unknown public key for %q:\n\t%+v\n\t%+v\n", c.User(), pubKey.Marshal(), authorizedKeys)
return nil, fmt.Errorf("unknown public key for %q", c.User())
},
}
config.AddHostKey(hostKey)
listener, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Failed to listen for connection: %v", err)
}
go func() {
nConn, err := listener.Accept()
if err != nil {
if strings.Contains(err.Error(), "use of closed network connection") {
return
}
t.Logf("Failed to accept incoming connection: %v", err)
return
}
defer nConn.Close()
conn, chans, reqs, err := ssh.NewServerConn(nConn, config)
if err != nil {
t.Logf("failed to handshake: %+v, %+v", conn, err)
return
}
// The incoming Request channel must be serviced.
go func() {
for newRequest := range reqs {
t.Logf("new request %v", newRequest)
}
}()
// Service only the first channel request
newChannel := <-chans
defer func() {
for newChannel := range chans {
t.Logf("new channel %v", newChannel)
newChannel.Reject(ssh.UnknownChannelType, "server closing")
}
}()
// Channels have a type, depending on the application level
// protocol intended. In the case of a shell, the type is
// "session" and ServerShell may be used to present a simple
// terminal interface.
if newChannel.ChannelType() != "session" {
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
return
}
channel, requests, err := newChannel.Accept()
if err != nil {
t.Logf("Could not accept channel: %v", err)
return
}
defer channel.Close()
// Sessions have out-of-band requests such as "shell",
// "pty-req" and "env". Here we handle only the
// "exec" request.
req := <-requests
if req.Type != "exec" {
req.Reply(false, nil)
return
}
// RFC 4254 Section 6.5.
var payload struct {
Command string
}
if err := ssh.Unmarshal(req.Payload, &payload); err != nil {
t.Logf("invalid payload on channel %v: %v", channel, err)
req.Reply(false, nil)
return
}
args, err := shlex.Split(payload.Command)
if err != nil {
t.Logf("invalid command on channel %v: %v", channel, err)
req.Reply(false, nil)
return
}
if len(args) < 2 || (args[0] != "git-upload-pack" && args[0] != "git-receive-pack") {
t.Logf("invalid command (%v) on channel %v: %v", args, channel, err)
req.Reply(false, nil)
return
}
req.Reply(true, nil)
go func(in <-chan *ssh.Request) {
for req := range in {
t.Logf("draining request %v", req)
}
}(requests)
// The first parameter is the (absolute) path of the repository.
args[1] = "./testdata" + args[1]
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdin = channel
var wg sync.WaitGroup
stdoutPipe, err := newChannelPipe(t, channel, &wg)
if err != nil {
t.Logf("Failed to create stdout pipe: %v", err)
return
}
cmd.Stdout = stdoutPipe
stderrPipe, err := newChannelPipe(t, channel.Stderr(), &wg)
if err != nil {
t.Logf("Failed to create stderr pipe: %v", err)
return
}
cmd.Stderr = stderrPipe
go func() {
wg.Wait()
channel.CloseWrite()
}()
err = cmd.Start()
if err != nil {
t.Logf("Failed to start %v: %v", args, err)
return
}
// Once the process has started, we need to close the write end of the
// pipes from this process so that we can know when the child has done
// writing to it.
stdoutPipe.Close()
stderrPipe.Close()
timer := time.AfterFunc(5*time.Second, func() {
t.Log("process timed out, terminating")
cmd.Process.Kill()
})
defer timer.Stop()
err = cmd.Wait()
if err != nil {
t.Logf("Failed to run %v: %v", args, err)
return
}
}()
return listener
}
func TestRemoteSSH(t *testing.T) {
t.Parallel()
pubKeyUsername := "testuser"
hostPrivKey, err := rsa.GenerateKey(rand.Reader, 512)
if err != nil {
t.Fatalf("Failed to generate the host RSA private key: %v", err)
}
hostSigner, err := ssh.NewSignerFromKey(hostPrivKey)
if err != nil {
t.Fatalf("Failed to generate SSH hostSigner: %v", err)
}
privKey, err := rsa.GenerateKey(rand.Reader, 512)
if err != nil {
t.Fatalf("Failed to generate the user RSA private key: %v", err)
}
signer, err := ssh.NewSignerFromKey(privKey)
if err != nil {
t.Fatalf("Failed to generate SSH signer: %v", err)
}
// This is in the format "xx:xx:xx:...", so we remove the colons so that it
// matches the fmt.Sprintf() below.
// Note that not all libssh2 implementations support the SHA256 fingerprint,
// so we use MD5 here for testing.
publicKeyFingerprint := strings.Replace(ssh.FingerprintLegacyMD5(hostSigner.PublicKey()), ":", "", -1)
listener := startSSHServer(t, hostSigner, []ssh.PublicKey{signer.PublicKey()})
defer listener.Close()
repo := createTestRepo(t)
defer cleanupTestRepo(t, repo)
certificateCheckCallbackCalled := false
fetchOpts := FetchOptions{
RemoteCallbacks: RemoteCallbacks{
CertificateCheckCallback: func(cert *Certificate, valid bool, hostname string) ErrorCode {
hostkeyFingerprint := fmt.Sprintf("%x", cert.Hostkey.HashMD5[:])
if hostkeyFingerprint != publicKeyFingerprint {
t.Logf("server hostkey %q, want %q", hostkeyFingerprint, publicKeyFingerprint)
return ErrorCodeAuth
}
certificateCheckCallbackCalled = true
return ErrorCodeOK
},
CredentialsCallback: func(url, username string, allowedTypes CredentialType) (*Credential, error) {
if allowedTypes&(CredentialTypeSSHKey|CredentialTypeSSHCustom|CredentialTypeSSHMemory) != 0 {
return NewCredentialSSHKeyFromSigner(pubKeyUsername, signer)
}
if (allowedTypes & CredentialTypeUsername) != 0 {
return NewCredentialUsername(pubKeyUsername)
}
return nil, fmt.Errorf("unknown credential type %+v", allowedTypes)
},
},
}
remote, err := repo.Remotes.Create(
"origin",
fmt.Sprintf("ssh://%s/TestGitRepository", listener.Addr().String()),
)
checkFatal(t, err)
defer remote.Free()
err = remote.Fetch(nil, &fetchOpts, "")
checkFatal(t, err)
if !certificateCheckCallbackCalled {
t.Fatalf("CertificateCheckCallback was not called")
}
heads, err := remote.Ls()
checkFatal(t, err)
if len(heads) == 0 {
t.Error("Expected remote heads")
}
}
|