e2e/system_test.go

v1.35.0
gitbay/e2e/system_test.go history · blame · raw

212 lines · 7250 bytes

  1package e2e
  2
  3import (
  4	"fmt"
  5	"net"
  6	"os"
  7	"os/exec"
  8	"os/user"
  9	"path/filepath"
 10	"strings"
 11	"testing"
 12	"time"
 13)
 14
 15// TestSystemSSHMode runs the M1/M2 scenarios against a real host sshd using
 16// AuthorizedKeysCommand + forced command instead of the embedded listener.
 17func TestSystemSSHMode(t *testing.T) {
 18	t.Parallel()
 19	sshdBin := "/usr/sbin/sshd"
 20	if _, err := os.Stat(sshdBin); err != nil {
 21		t.Skipf("no host sshd at %s", sshdBin)
 22	}
 23	me, err := user.Current()
 24	if err != nil {
 25		t.Fatal(err)
 26	}
 27
 28	// gitbayd in system mode: no embedded SSH listener; hookd + http still run.
 29	inst := startInstanceWith(t, "") // placeholder to reuse helpers; killed below
 30	inst.proc.Process.Kill()
 31	inst.proc.Wait()
 32	cfg := fmt.Sprintf(`
 33[server]
 34root = %q
 35site_url = "https://gitbay.test"
 36[ssh]
 37mode = "system"
 38[http]
 39addr = "127.0.0.1:%d"
 40tls = "off"
 41`, inst.root, inst.httpPort)
 42	if err := os.WriteFile(inst.config, []byte(cfg), 0o600); err != nil {
 43		t.Fatal(err)
 44	}
 45	inst.proc = exec.Command(inst.gitbayd, "--config", inst.config, "serve")
 46	inst.proc.Stderr = os.Stderr
 47	if err := inst.proc.Start(); err != nil {
 48		t.Fatal(err)
 49	}
 50	t.Cleanup(func() { inst.proc.Process.Kill(); inst.proc.Wait() })
 51
 52	aliceKey := inst.newKey(t, "alice")
 53	bobKey := inst.newKey(t, "bob")
 54	strangerKey := inst.newKey(t, "stranger")
 55	inst.admin(t, "admin", "user", "create", "alice", "--key", aliceKey+".pub")
 56	inst.admin(t, "admin", "user", "create", "bob", "--key", bobKey+".pub")
 57
 58	// Host sshd on a high port as the current user.
 59	sshdDir := t.TempDir()
 60	hostKey := filepath.Join(sshdDir, "host_ed25519")
 61	if out, err := exec.Command("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", hostKey).CombinedOutput(); err != nil {
 62		t.Fatalf("host keygen: %v\n%s", err, out)
 63	}
 64	// sshd requires the AuthorizedKeysCommand program itself to be owned by
 65	// root; a test-built binary is not. Use root-owned /bin/sh with a
 66	// wrapper script argument — only the command path is ownership-checked.
 67	wrapper := filepath.Join(sshdDir, "akc.sh")
 68	script := fmt.Sprintf("#!/bin/sh\nexec %q --config %q authorized-keys \"$1\" \"$2\"\n",
 69		inst.gitbayd, inst.config)
 70	if err := os.WriteFile(wrapper, []byte(script), 0o755); err != nil {
 71		t.Fatal(err)
 72	}
 73
 74	sshdPort := freePort(t)
 75	sshdConf := filepath.Join(sshdDir, "sshd_config")
 76	conf := fmt.Sprintf(`Port %d
 77ListenAddress 127.0.0.1
 78HostKey %s
 79PasswordAuthentication no
 80KbdInteractiveAuthentication no
 81PubkeyAuthentication yes
 82AuthorizedKeysFile none
 83AuthorizedKeysCommand /bin/sh %s %%t %%k
 84AuthorizedKeysCommandUser %s
 85StrictModes no
 86UsePAM no
 87PidFile %s
 88LogLevel ERROR
 89`, sshdPort, hostKey, wrapper, me.Username, filepath.Join(sshdDir, "sshd.pid"))
 90	if err := os.WriteFile(sshdConf, []byte(conf), 0o600); err != nil {
 91		t.Fatal(err)
 92	}
 93	sshd := exec.Command(sshdBin, "-D", "-e", "-f", sshdConf)
 94	sshd.Stderr = os.Stderr
 95	if err := sshd.Start(); err != nil {
 96		t.Fatal(err)
 97	}
 98	t.Cleanup(func() { sshd.Process.Kill(); sshd.Wait() })
 99
100	deadline := time.Now().Add(10 * time.Second)
101	for {
102		conn, err := net.DialTimeout("tcp", fmt.Sprintf("127.0.0.1:%d", sshdPort), 200*time.Millisecond)
103		if err == nil {
104			conn.Close()
105			break
106		}
107		if time.Now().After(deadline) {
108			t.Fatal("sshd did not start")
109		}
110		time.Sleep(100 * time.Millisecond)
111	}
112
113	// ssh helper against the host sshd (login user = current user; identity
114	// still comes from the key).
115	sysSSH := func(key, stdin string, args ...string) (string, string, int) {
116		base := []string{
117			"-p", fmt.Sprint(sshdPort),
118			"-i", key,
119			"-o", "IdentitiesOnly=yes",
120			"-o", "StrictHostKeyChecking=no",
121			"-o", "UserKnownHostsFile=" + filepath.Join(sshdDir, "kh"),
122			"-o", "BatchMode=yes",
123			me.Username + "@127.0.0.1",
124		}
125		cmd := exec.Command("ssh", append(base, args...)...)
126		if stdin != "" {
127			cmd.Stdin = strings.NewReader(stdin)
128		}
129		var out, errOut strings.Builder
130		cmd.Stdout = &out
131		cmd.Stderr = &errOut
132		err := cmd.Run()
133		code := 0
134		if ee, ok := err.(*exec.ExitError); ok {
135			code = ee.ExitCode()
136		} else if err != nil {
137			t.Fatalf("ssh: %v", err)
138		}
139		return out.String(), errOut.String(), code
140	}
141
142	// M1: whoami over the host sshd.
143	out, errOut, code := sysSSH(aliceKey, "", "whoami", "--json")
144	if code != 0 {
145		t.Fatalf("whoami via sshd: exit %d\nstdout: %s\nstderr: %s", code, out, errOut)
146	}
147	if !strings.Contains(out, `"username":"alice"`) || !strings.Contains(out, `"protocol_version":1`) {
148		t.Fatalf("whoami output: %s", out)
149	}
150
151	// Unknown key: authentication fails inside sshd (authorized-keys emits
152	// nothing), before any forge code runs.
153	_, _, code = sysSSH(strangerKey, "", "whoami")
154	if code == 0 {
155		t.Fatal("stranger authenticated via host sshd")
156	}
157
158	// Scoped key: registered with git-only scope, denied control commands.
159	scopedKey := inst.newKey(t, "scoped")
160	pub, _ := os.ReadFile(scopedKey + ".pub")
161	if _, errOut, code := sysSSH(aliceKey, string(pub), "keys", "add", "--scope", "git"); code != 0 {
162		t.Fatalf("keys add: %s", errOut)
163	}
164	_, errOut, code = sysSSH(scopedKey, "", "whoami")
165	if code != 4 || !strings.Contains(errOut, "does not allow control commands") {
166		t.Fatalf("scoped denial via sshd: exit %d, %s", code, errOut)
167	}
168
169	// M2: private repo, push, denial, protected branch — through host sshd.
170	if _, errOut, code = sysSSH(aliceKey, "", "repo", "create", "alice/proj", "--private"); code != 0 {
171		t.Fatalf("repo create: %s", errOut)
172	}
173	sysGitEnv := func(key string) []string {
174		return append(os.Environ(),
175			fmt.Sprintf("GIT_SSH_COMMAND=ssh -i %s -o IdentitiesOnly=yes -o StrictHostKeyChecking=no -o UserKnownHostsFile=%s -o BatchMode=yes",
176				key, filepath.Join(sshdDir, "kh")),
177			"GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null",
178			"GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.test",
179			"GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.test",
180		)
181	}
182	urlFor := func(repo string) string {
183		return fmt.Sprintf("ssh://%s@127.0.0.1:%d/%s.git", me.Username, sshdPort, repo)
184	}
185
186	work := t.TempDir()
187	aliceEnv := sysGitEnv(aliceKey)
188	mustGit(t, work, aliceEnv, "clone", urlFor("alice/proj"), "w")
189	dir := filepath.Join(work, "w")
190	os.WriteFile(filepath.Join(dir, "f"), []byte("x\n"), 0o644)
191	mustGit(t, dir, aliceEnv, "checkout", "-q", "-b", "main")
192	mustGit(t, dir, aliceEnv, "add", ".")
193	mustGit(t, dir, aliceEnv, "commit", "-q", "-m", "init")
194	mustGit(t, dir, aliceEnv, "push", "-q", "origin", "main")
195
196	// Bob: authenticated but no access — not-found, not permission-denied.
197	cloneOut, cloneCode := gitRun(t, t.TempDir(), sysGitEnv(bobKey), "clone", urlFor("alice/proj"))
198	if cloneCode == 0 || !strings.Contains(cloneOut, "repository not found") {
199		t.Fatalf("bob clone via sshd: %d\n%s", cloneCode, cloneOut)
200	}
201
202	// Protected branch: the hook path (forced command -> git -> pre-receive
203	// -> daemon unix socket) refuses the force-push.
204	if _, errOut, code = sysSSH(aliceKey, "", "repo", "settings", "protect", "alice/proj", "main"); code != 0 {
205		t.Fatalf("protect: %s", errOut)
206	}
207	mustGit(t, dir, aliceEnv, "commit", "-q", "--amend", "-m", "rewritten")
208	pushOut, pushCode := gitRun(t, dir, aliceEnv, "push", "--force", "origin", "main")
209	if pushCode == 0 || !strings.Contains(pushOut, "force-push refused") {
210		t.Fatalf("force-push via sshd: %d\n%s", pushCode, pushOut)
211	}
212}