//go:build darwin || linux package server import ( "context" "encoding/json" "os" "path/filepath" "strings" "testing" "time" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" ) // newTestTerminals is one server process's terminal manager over store. func newTestTerminals(t *testing.T, store *pipeline.Store) (*terminalManager, context.CancelFunc) { t.Helper() ctx, cancel := context.WithCancel(context.Background()) m := newTerminalManager(ctx, store) m.recover(ctx) t.Cleanup(func() { cancel(); m.Wait() }) return m, cancel } // waitTerminalOutput polls a terminal's retained output until it contains // want. func waitTerminalOutput(t *testing.T, m *terminalManager, id, want string) protocol.TerminalRecord { t.Helper() deadline := time.Now().Add(10 * time.Second) for { record, err := m.Output(context.Background(), id, 0) if err != nil { t.Fatal(err) } if strings.Contains(record.Output, want) { return record } if time.Now().After(deadline) { t.Fatalf("output of %s never contained %q: %q", id, want, record.Output) } time.Sleep(50 * time.Millisecond) } } // waitTerminalStatus polls the list until terminal id has status. func waitTerminalStatus(t *testing.T, m *terminalManager, id, status string) protocol.TerminalRecord { t.Helper() deadline := time.Now().Add(10 * time.Second) for { list, err := m.List(context.Background()) if err != nil { t.Fatal(err) } for _, record := range list { if record.ID == id && record.Status == status { return record } } if time.Now().After(deadline) { t.Fatalf("terminal %s never became %s: %+v", id, status, list) } time.Sleep(50 * time.Millisecond) } } // The login command is su for the server's own account on macOS and Linux // (su looked up in each one's usual directories); a root server, a missing // su and other systems are refused. func TestTerminalLoginCommandPerOS(t *testing.T) { dir := "/home/a/it's here" for _, goos := range []string{"darwin", "linux"} { args, err := terminalLoginArgs(goos, 501, "/usr/bin/su", "alan", dir) if err != nil { t.Fatalf("%s: %v", goos, err) } want := []string{"/usr/bin/su", "-l", "alan", "-c", `printf '\033]6973;pipelines-login\007'; cd '/home/a/it'\''s here' || cd; exec "$SHELL" -l`} if strings.Join(args, "\x00") != strings.Join(want, "\x00") { t.Fatalf("%s args = %q", goos, args) } } if terminalSuDirs["darwin"][0] != "/usr/bin" || strings.Join(terminalSuDirs["linux"], ":") != "/bin:/usr/bin" { t.Fatalf("su directories = %v", terminalSuDirs) } refusals := map[string]struct { goos string euid int su, user string wantPhrase string }{ "root": {"linux", 0, "/bin/su", "root", "runs as root"}, "no su": {"darwin", 501, "", "alan", "su is not installed"}, "no user": {"linux", 1000, "/bin/su", "", "no user name"}, "windows": {"windows", 1000, "su", "alan", "does not support on windows"}, "freebsd": {"freebsd", 1000, "/usr/bin/su", "alan", "does not support on freebsd"}, } for name, c := range refusals { if _, err := terminalLoginArgs(c.goos, c.euid, c.su, c.user, dir); err == nil || !strings.Contains(err.Error(), c.wantPhrase) { t.Fatalf("%s: err = %v", name, err) } } } // Without su on PATH or in the usual directories the server refuses to // open a terminal (no unauthenticated fallback) and lists nothing. func TestTerminalRefusedWithoutSu(t *testing.T) { if os.Geteuid() == 0 { t.Skip("runs as root") } terminalHome(t) empty := t.TempDir() t.Setenv("PATH", empty) original := terminalSuDirs terminalSuDirs = map[string][]string{"darwin": {empty}, "linux": {empty}} t.Cleanup(func() { terminalSuDirs = original }) if found := findTerminalSu("darwin"); found != "" { t.Fatalf("found su %q", found) } m, _ := newTestTerminals(t, newOperatorStore(t)) if _, err := m.Open(context.Background(), "", "", 0, 0); err == nil || !strings.Contains(err.Error(), "su is not installed") { t.Fatalf("open without su = %v", err) } if list, _ := m.List(context.Background()); len(list) != 0 { t.Fatalf("list = %+v", list) } fakeTerminalSu(t) if found := findTerminalSu("linux"); !strings.HasSuffix(found, "/su") || filepath.Dir(found) == empty { t.Fatalf("fake su = %q", found) } } // A new terminal shows the login prompt in a real PTY and runs su, not a // shell or tmux; a wrong password ends it with a clear reason, the right // one gives a shell in the start folder. func TestTerminalShowsLoginPrompt(t *testing.T) { home := terminalHome(t) sub := filepath.Join(home, "sub dir") if err := os.Mkdir(sub, 0o755); err != nil { t.Fatal(err) } m, _ := newTestTerminals(t, newOperatorStore(t)) wrong, err := m.Open(context.Background(), "", "", 0, 0) if err != nil { t.Fatal(err) } if !strings.HasSuffix(strings.Fields(wrong.Shell)[0], "/su") || strings.Contains(wrong.Shell, "tmux") { t.Fatalf("shell = %q", wrong.Shell) } if raw, _ := json.Marshal(wrong); strings.Contains(string(raw), "tmux") { t.Fatalf("record mentions tmux: %s", raw) } if out, _ := m.Output(context.Background(), wrong.ID, 0); !strings.Contains(out.Output, "Password:") { t.Fatalf("output = %q", out.Output) } if err := m.Input(wrong.ID, "not-it\r"); err != nil { t.Fatal(err) } ended := waitTerminalStatus(t, m, wrong.ID, protocol.TerminalExited) if ended.Reason != terminalLoginFailedReason || ended.ExitCode == nil || *ended.ExitCode != 1 { t.Fatalf("wrong password = %+v", ended) } waitTerminalOutput(t, m, wrong.ID, "Authentication failed") right, err := m.Open(context.Background(), "", "~/sub dir", 0, 0) if err != nil { t.Fatal(err) } if err := m.Input(right.ID, fakeSuPassword+"\r"); err != nil { t.Fatal(err) } if err := m.Input(right.ID, "pwd; echo in-$((6*7))\r"); err != nil { t.Fatal(err) } out := waitTerminalOutput(t, m, right.ID, "in-42") if !strings.Contains(out.Output, sub) || strings.Contains(out.Output, fakeSuPassword) { t.Fatalf("output = %q", out.Output) } if p := m.process(right.ID); p == nil || !loggedIn(p) { t.Fatal("the login was not recorded") } } func loggedIn(p *terminalProcess) bool { login, _ := p.loginState() return login.loggedIn } // The watch sees the prompt across reads, the marker after it as a login, // and the marker before any prompt as an unprompted login. func TestTerminalLoginWatch(t *testing.T) { var w terminalLoginWatch if w.feed([]byte("Pass")) || !w.feed([]byte("word:")) || !w.prompted || w.loggedIn { t.Fatalf("prompt = %+v", w) } if !w.feed(append([]byte("\r\n"), terminalLoginMarker...)) || !w.loggedIn || w.unprompted { t.Fatalf("login = %+v", w) } if w.feed([]byte("password")) { t.Fatal("output after the login is not watched") } var bare terminalLoginWatch bare.feed(append(append([]byte("motd\r\n"), terminalLoginMarker...), "change your password"...)) if !bare.loggedIn || !bare.unprompted || bare.prompted { t.Fatalf("unprompted = %+v", bare) } } // A login that never asks for a password is refused and never listed: one // that opens a shell at once (an account without a password), one that // stays silent, one that fails without a terminal. func TestTerminalRefusesUnpromptedLogin(t *testing.T) { terminalHome(t) m, _ := newTestTerminals(t, newOperatorStore(t)) m.promptWait = 500 * time.Millisecond for mode, phrase := range map[string]string{ "noprompt": "without asking for a password", "silent": "did not ask for a password", "notty": "su: must be run from a terminal", } { t.Setenv("FAKE_SU_MODE", mode) if record, err := m.Open(context.Background(), "", "", 0, 0); err == nil || !strings.Contains(err.Error(), phrase) { t.Fatalf("%s: open = %+v, %v", mode, record, err) } } if list, _ := m.List(context.Background()); len(list) != 0 { t.Fatalf("list = %+v", list) } m.mu.Lock() running := m.runningLocked() m.mu.Unlock() if running != 0 { t.Fatalf("%d refused terminals still running", running) } }