Files
pipelines/internal/server/terminal_login_test.go
T
alan 227c036aa5 Start machine terminals at the su login prompt instead of tmux
A new terminal runs su -l for the server's own account in its PTY, so the
operator types the account password before getting a shell. Opening is
refused when su is missing, the server runs as root, or su opens a shell
without asking. The Pipelines-owned tmux backing, its reattach and its
persisted session names are removed: terminals end with the server and
are listed as ended. A starting server ends leftover pipelines-term_*
sessions on tmux -L pipelines only.
2026-11-10 00:37:11 +00:00

334 lines
11 KiB
Go

//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)
}
}
// A terminal ends with its server: the stop is recorded as ended, and a
// record a crashed (or tmux-era) server left running is listed as ended
// after the restart, saying why.
func TestTerminalEndsWithServer(t *testing.T) {
terminalHome(t)
store := newOperatorStore(t)
first, stop := newTestTerminals(t, store)
term, err := first.Open(context.Background(), "", "", 0, 0)
if err != nil {
t.Fatal(err)
}
if err := first.Input(term.ID, fakeSuPassword+"\r"); err != nil {
t.Fatal(err)
}
stop()
first.Wait()
crashed := protocol.TerminalRecord{ID: "term_crashed", Cwd: "/", CreatedAt: 1, Status: protocol.TerminalRunning, Cols: 80, Rows: 24}
if err := store.SaveTerminal(context.Background(), crashed, 0); err != nil {
t.Fatal(err)
}
second, _ := newTestTerminals(t, store)
list, err := second.List(context.Background())
if err != nil {
t.Fatal(err)
}
reasons := map[string]string{}
for _, record := range list {
if record.Status != protocol.TerminalExited || record.EndedAt == 0 {
t.Fatalf("record = %+v", record)
}
reasons[record.ID] = record.Reason
}
if len(reasons) != 2 || reasons[term.ID] != terminalStopReason || reasons["term_crashed"] != terminalRestartReason {
t.Fatalf("reasons = %+v", reasons)
}
if _, err := second.Close(context.Background(), "term_crashed"); err != nil {
t.Fatal(err)
}
if list, _ := second.List(context.Background()); len(list) != 1 {
t.Fatalf("list after closing an ended terminal = %+v", list)
}
}
// The window title the shell sets is followed across reads and recorded.
func TestTerminalTitles(t *testing.T) {
var titles terminalTitles
if _, ok := titles.feed([]byte("plain \x1b[1mtext")); ok {
t.Fatal("title from plain text")
}
if _, ok := titles.feed([]byte("\x1b]0;~/src")); ok {
t.Fatal("title before its end")
}
if title, ok := titles.feed([]byte("/app\x07more")); !ok || title != "~/src/app" {
t.Fatalf("title = %q %v", title, ok)
}
if title, ok := titles.feed([]byte("\x1b]2;vim\x01 x\x1b\\")); !ok || title != "vim x" {
t.Fatalf("ST title = %q %v", title, ok)
}
if _, ok := titles.feed([]byte("\x1b]8;;https://x\x07")); ok {
t.Fatal("a hyperlink is not a title")
}
if _, ok := titles.feed(terminalLoginMarker); ok {
t.Fatal("the login marker is not a title")
}
if title, _ := titles.feed([]byte("\x1b]0;" + strings.Repeat("é", protocol.TerminalTitleLimit) + "\x07")); len(title) > protocol.TerminalTitleLimit {
t.Fatalf("title of %d bytes", len(title))
}
terminalHome(t)
m, _ := newTestTerminals(t, newOperatorStore(t))
term, err := m.Open(context.Background(), "", "", 0, 0)
if err != nil {
t.Fatal(err)
}
if err := m.Input(term.ID, fakeSuPassword+"\r"); err != nil {
t.Fatal(err)
}
if err := m.Input(term.ID, "printf '\\033]0;build-%s\\007' ok\r"); err != nil {
t.Fatal(err)
}
waitTerminalTitle(t, m, "build-ok")
}
func waitTerminalTitle(t *testing.T, m *terminalManager, want string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for {
list, _ := m.List(context.Background())
if len(list) == 1 && list[0].Title == want {
return
}
if time.Now().After(deadline) {
t.Fatalf("list = %+v", list)
}
time.Sleep(50 * time.Millisecond)
}
}