1package git
  2
  3import (
  4	"fmt"
  5	"net"
  6	"os"
  7	"os/exec"
  8	"path/filepath"
  9	"strings"
 10	"sync"
 11	"testing"
 12
 13	"github.com/charmbracelet/keygen"
 14	"github.com/charmbracelet/wish"
 15	"github.com/gliderlabs/ssh"
 16)
 17
 18func TestGitMiddleware(t *testing.T) {
 19	pubkey, pkPath := createKeyPair(t)
 20
 21	l, err := net.Listen("tcp", "127.0.0.1:0")
 22	requireNoError(t, err)
 23	remote := "ssh://" + l.Addr().String()
 24
 25	repoDir := t.TempDir()
 26	hooks := &testHooks{
 27		pushes:  []action{},
 28		fetches: []action{},
 29		access: []accessDetails{
 30			{pubkey, "repo1", AdminAccess},
 31			{pubkey, "repo2", AdminAccess},
 32			{pubkey, "repo3", AdminAccess},
 33			{pubkey, "repo4", AdminAccess},
 34			{pubkey, "repo5", NoAccess},
 35			{pubkey, "repo6", ReadOnlyAccess},
 36			{pubkey, "repo7", AdminAccess},
 37		},
 38	}
 39	srv, err := wish.NewServer(
 40		wish.WithMiddleware(Middleware(repoDir, hooks)),
 41		wish.WithPublicKeyAuth(func(ctx ssh.Context, key ssh.PublicKey) bool {
 42			return true
 43		}),
 44	)
 45	requireNoError(t, err)
 46	go func() { srv.Serve(l) }()
 47	t.Cleanup(func() { _ = srv.Close() })
 48
 49	t.Run("create repo on master", func(t *testing.T) {
 50		cwd := t.TempDir()
 51		requireNoError(t, runGitHelper(t, pkPath, cwd, "init", "-b", "master"))
 52		requireNoError(t, runGitHelper(t, pkPath, cwd, "remote", "add", "origin", remote+"/repo1"))
 53		requireNoError(t, runGitHelper(t, pkPath, cwd, "commit", "--allow-empty", "-m", "initial commit"))
 54		requireNoError(t, runGitHelper(t, pkPath, cwd, "push", "origin", "master"))
 55		requireHasAction(t, hooks.pushes, pubkey, "repo1")
 56	})
 57
 58	t.Run("create repo on main", func(t *testing.T) {
 59		cwd := t.TempDir()
 60		requireNoError(t, runGitHelper(t, pkPath, cwd, "init", "-b", "main"))
 61		requireNoError(t, runGitHelper(t, pkPath, cwd, "remote", "add", "origin", remote+"/repo2"))
 62		requireNoError(t, runGitHelper(t, pkPath, cwd, "commit", "--allow-empty", "-m", "initial commit"))
 63		requireNoError(t, runGitHelper(t, pkPath, cwd, "push", "origin", "main"))
 64		requireHasAction(t, hooks.pushes, pubkey, "repo2")
 65	})
 66
 67	t.Run("create and clone repo", func(t *testing.T) {
 68		cwd := t.TempDir()
 69		requireNoError(t, runGitHelper(t, pkPath, cwd, "init", "-b", "main"))
 70		requireNoError(t, runGitHelper(t, pkPath, cwd, "remote", "add", "origin", remote+"/repo3"))
 71		requireNoError(t, runGitHelper(t, pkPath, cwd, "commit", "--allow-empty", "-m", "initial commit"))
 72		requireNoError(t, runGitHelper(t, pkPath, cwd, "push", "origin", "main"))
 73
 74		cwd = t.TempDir()
 75		requireNoError(t, runGitHelper(t, pkPath, cwd, "clone", remote+"/repo3"))
 76
 77		requireHasAction(t, hooks.pushes, pubkey, "repo3")
 78		requireHasAction(t, hooks.fetches, pubkey, "repo3")
 79	})
 80
 81	t.Run("clone repo that doesn't exist", func(t *testing.T) {
 82		cwd := t.TempDir()
 83		requireError(t, runGitHelper(t, pkPath, cwd, "clone", remote+"/repo4"))
 84	})
 85
 86	t.Run("clone repo with no access", func(t *testing.T) {
 87		cwd := t.TempDir()
 88		requireError(t, runGitHelper(t, pkPath, cwd, "clone", remote+"/repo5"))
 89	})
 90
 91	t.Run("push repo with with readonly", func(t *testing.T) {
 92		cwd := t.TempDir()
 93		requireNoError(t, runGitHelper(t, pkPath, cwd, "init", "-b", "main"))
 94		requireNoError(t, runGitHelper(t, pkPath, cwd, "remote", "add", "origin", remote+"/repo6"))
 95		requireNoError(t, runGitHelper(t, pkPath, cwd, "commit", "--allow-empty", "-m", "initial commit"))
 96		requireError(t, runGitHelper(t, pkPath, cwd, "push", "origin", "main"))
 97	})
 98
 99	t.Run("create and clone repo on weird branch", func(t *testing.T) {
100		cwd := t.TempDir()
101		requireNoError(t, runGitHelper(t, pkPath, cwd, "init", "-b", "a-weird-branch-name"))
102		requireNoError(t, runGitHelper(t, pkPath, cwd, "remote", "add", "origin", remote+"/repo7"))
103		requireNoError(t, runGitHelper(t, pkPath, cwd, "commit", "--allow-empty", "-m", "initial commit"))
104		requireNoError(t, runGitHelper(t, pkPath, cwd, "push", "origin", "a-weird-branch-name"))
105
106		cwd = t.TempDir()
107		requireNoError(t, runGitHelper(t, pkPath, cwd, "clone", remote+"/repo7"))
108
109		requireHasAction(t, hooks.pushes, pubkey, "repo7")
110		requireHasAction(t, hooks.fetches, pubkey, "repo7")
111	})
112}
113
114func runGitHelper(t *testing.T, pk, cwd string, args ...string) error {
115	t.Helper()
116
117	allArgs := []string{
118		"-c", "user.name='wish'",
119		"-c", "user.email='test@wish'",
120		"-c", "commit.gpgSign=false",
121		"-c", "tag.gpgSign=false",
122		"-c", "log.showSignature=false",
123		"-c", "ssh.variant=ssh",
124	}
125	allArgs = append(allArgs, args...)
126
127	cmd := exec.Command("git", allArgs...)
128	cmd.Dir = cwd
129	cmd.Env = []string{fmt.Sprintf(`GIT_SSH_COMMAND=ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i "%s" -F /dev/null`, pk)}
130	out, err := cmd.CombinedOutput()
131	t.Log("git out:", string(out))
132	return err
133}
134
135func requireNoError(t *testing.T, err error) {
136	t.Helper()
137
138	if err != nil {
139		t.Fatalf("expected no error, got %q", err.Error())
140	}
141}
142
143func requireError(t *testing.T, err error) {
144	t.Helper()
145
146	if err == nil {
147		t.Fatalf("expected an error, got nil")
148	}
149}
150
151func requireHasAction(t *testing.T, actions []action, key ssh.PublicKey, repo string) {
152	t.Helper()
153
154	for _, action := range actions {
155		if repo == strings.TrimSuffix(action.repo, ".git") && ssh.KeysEqual(key, action.key) {
156			return
157		}
158	}
159	t.Fatalf("expected action for %q, got none", repo)
160}
161
162func createKeyPair(t *testing.T) (ssh.PublicKey, string) {
163	t.Helper()
164
165	keyDir := t.TempDir()
166	t.Logf("Tempdir %s", keyDir)
167	kp, err := keygen.NewWithWrite(filepath.Join(keyDir, "id"), nil, keygen.Ed25519)
168	kp.KeyPairExists()
169	requireNoError(t, err)
170	pk := filepath.Join(keyDir, "id_ed25519")
171	t.Logf("pk %s", pk)
172	pubBytes, err := os.ReadFile(filepath.Join(keyDir, "id_ed25519.pub"))
173	requireNoError(t, err)
174	pubkey, _, _, _, err := ssh.ParseAuthorizedKey(pubBytes)
175	requireNoError(t, err)
176	return pubkey, pk
177}
178
179type accessDetails struct {
180	key   ssh.PublicKey
181	repo  string
182	level AccessLevel
183}
184
185type action struct {
186	key  ssh.PublicKey
187	repo string
188}
189
190type testHooks struct {
191	sync.Mutex
192	pushes  []action
193	fetches []action
194	access  []accessDetails
195}
196
197func (h *testHooks) AuthRepo(repo string, key ssh.PublicKey) AccessLevel {
198	for _, dets := range h.access {
199		if dets.repo == repo && ssh.KeysEqual(key, dets.key) {
200			return dets.level
201		}
202	}
203	return NoAccess
204}
205
206func (h *testHooks) Push(repo string, key ssh.PublicKey) {
207	h.Lock()
208	defer h.Unlock()
209
210	h.pushes = append(h.pushes, action{key, repo})
211}
212
213func (h *testHooks) Fetch(repo string, key ssh.PublicKey) {
214	h.Lock()
215	defer h.Unlock()
216
217	h.fetches = append(h.fetches, action{key, repo})
218}