Files
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

221 lines
11 KiB
Go

//go:build darwin || linux
package server
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"github.com/coder/websocket"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// terminalHome points the operator's home at a fresh directory, the login
// shell at /bin/sh (so tests never read the operator's own profile) and su
// at the fake below.
func terminalHome(t *testing.T) string {
t.Helper()
home, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
original := operatorHomeDirectory
operatorHomeDirectory = func() (string, error) { return home, nil }
t.Cleanup(func() { operatorHomeDirectory = original })
t.Setenv("SHELL", "/bin/sh")
t.Setenv("ENV", "")
fakeTerminalSu(t)
return home
}
// fakeSuPassword is the only password the fake su accepts.
const fakeSuPassword = "test-password"
// fakeSuScript stands in for su on PATH, so tests never need a real
// password: `su -l <user> -c <script>` prints "Password:", reads a line with
// echo off, and runs the script in /bin/sh when it is fakeSuPassword.
// FAKE_SU_MODE=noprompt runs the script without asking, silent never
// prompts, notty fails as su does without a terminal.
const fakeSuScript = `#!/bin/sh
[ "$1" = -l ] && [ "$3" = -c ] || { echo "fake su: bad arguments: $*"; exit 2; }
case "$FAKE_SU_MODE" in
noprompt) SHELL=/bin/sh exec /bin/sh -c "$4" ;;
silent) exec sleep 30 ;;
notty) echo "su: must be run from a terminal"; exit 1 ;;
esac
stty -echo 2>/dev/null
printf 'Password:'
IFS= read -r password
stty echo 2>/dev/null
printf '\r\n'
[ "$password" = "` + fakeSuPassword + `" ] || { echo "su: Authentication failed"; exit 1; }
SHELL=/bin/sh exec /bin/sh -c "$4"
`
// fakeTerminalSu puts the fake su first on PATH.
func fakeTerminalSu(t *testing.T) {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "su"), []byte(fakeSuScript), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("FAKE_SU_MODE", "")
}
// terminalLogIn types the fake su's password into terminal id.
func terminalLogIn(t *testing.T, ctx context.Context, conn *websocket.Conn, id string) {
t.Helper()
terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalInput, "password", protocol.TerminalRequest{TerminalID: id, Data: fakeSuPassword + "\r"}))
}
func terminalRequest(kind, id string, body protocol.TerminalRequest) protocol.Message {
return protocol.Message{Type: kind, ID: id, TerminalRequest: &body}
}
// terminalReply sends request and returns its reply (skipping pushes).
func terminalReply(t *testing.T, ctx context.Context, conn *websocket.Conn, request protocol.Message) protocol.Message {
t.Helper()
writeChat(t, ctx, conn, request)
return readShellFrame(t, ctx, conn, func(m protocol.Message) bool { return m.ID == request.ID })
}
// readTerminalUntil reads output frames of id from end on, in order, until
// the collected text contains want; it returns the text and the new end.
func readTerminalUntil(t *testing.T, ctx context.Context, conn *websocket.Conn, id string, end int64, want string) (string, int64) {
t.Helper()
var seen strings.Builder
for !strings.Contains(seen.String(), want) {
frame := readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.TerminalID == id && m.TerminalEvent.Terminal == nil
}).TerminalEvent
if frame.Offset != end {
t.Fatalf("frame at %d after %d", frame.Offset, end)
}
seen.WriteString(frame.Output)
end = frame.End
}
return seen.String(), end
}
// One client opens a shell, types into it, resizes it; a second client
// lists it, resumes its output by offset and closes it.
func TestTerminalOverWebsocket(t *testing.T) {
home := terminalHome(t)
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 2)
opened := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cols: 80, Rows: 24}))
term := opened.Terminal
if opened.Type != protocol.TerminalOpen || term == nil || term.Cwd != home || term.Status != protocol.TerminalRunning || term.Cols != 80 || !strings.HasSuffix(strings.Fields(term.Shell)[0], "/su") {
t.Fatalf("open reply = %+v", opened)
}
terminalLogIn(t, ctx, conns[0], term.ID)
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "in", protocol.TerminalRequest{TerminalID: term.ID, Data: "pwd; echo sum-$((40+2))\r"})); got.Type != protocol.TerminalInput {
t.Fatalf("input reply = %+v", got)
}
_, end := readTerminalUntil(t, ctx, conns[0], term.ID, 0, "sum-42")
resized := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalResize, "size", protocol.TerminalRequest{TerminalID: term.ID, Cols: 120, Rows: 33}))
if resized.Type != protocol.TerminalResize || resized.Terminal.Cols != 120 || resized.Terminal.Rows != 33 {
t.Fatalf("resize reply = %+v", resized)
}
list := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalList, "list", protocol.TerminalRequest{}))
if len(list.Terminals) != 1 || list.Terminals[0].ID != term.ID || list.Terminals[0].Cols != 120 || list.Terminals[0].Output != "" {
t.Fatalf("list = %+v", list.Terminals)
}
// The second client reads everything once, then only what follows.
all := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "all", protocol.TerminalRequest{TerminalID: term.ID})).Terminal
if all.OutputStart != 0 || !strings.Contains(all.Output, "Password:") || !strings.Contains(all.Output, home) || !strings.Contains(all.Output, "sum-42") ||
strings.Contains(all.Output, fakeSuPassword) {
t.Fatalf("output = %+v", all)
}
terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalInput, "in2", protocol.TerminalRequest{TerminalID: term.ID, Data: "stty size\r"}))
readTerminalUntil(t, ctx, conns[0], term.ID, end, "33 120")
resume := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalOutput, "resume", protocol.TerminalRequest{TerminalID: term.ID, After: end})).Terminal
if resume.OutputStart != end || strings.Contains(resume.Output, "sum-42") || !strings.Contains(resume.Output, "33 120") {
t.Fatalf("resume = %+v", resume)
}
closed := terminalReply(t, ctx, conns[1], terminalRequest(protocol.TerminalClose, "close", protocol.TerminalRequest{TerminalID: term.ID}))
if closed.Type != protocol.TerminalClose || closed.Terminal.Status != protocol.TerminalClosed {
t.Fatalf("close reply = %+v", closed)
}
// Every connection hears the close; the list forgets it.
event := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.Terminal != nil && m.TerminalEvent.Terminal.Status == protocol.TerminalClosed
})
if event.TerminalEvent.TerminalID != term.ID {
t.Fatalf("close event = %+v", event)
}
if list := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalList, "list2", protocol.TerminalRequest{})); len(list.Terminals) != 0 {
t.Fatalf("list after close = %+v", list.Terminals)
}
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "late", protocol.TerminalRequest{TerminalID: term.ID, Data: "x"})); got.Type != protocol.Error {
t.Fatalf("late input = %+v", got)
}
}
// A shell that exits by itself is listed as exited with its status and
// keeps its output until it is closed.
func TestTerminalShellExit(t *testing.T) {
terminalHome(t)
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 1)
term := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{})).Terminal
terminalLogIn(t, ctx, conns[0], term.ID)
terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalInput, "in", protocol.TerminalRequest{TerminalID: term.ID, Data: "echo bye; exit 3\r"}))
exited := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool {
return m.Type == protocol.TerminalEvent && m.TerminalEvent.Terminal != nil && m.TerminalEvent.Terminal.Status == protocol.TerminalExited
}).TerminalEvent.Terminal
if exited.ExitCode == nil || *exited.ExitCode != 3 || exited.EndedAt == 0 {
t.Fatalf("exited = %+v", exited)
}
out := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalOutput, "out", protocol.TerminalRequest{TerminalID: term.ID})).Terminal
if !strings.Contains(out.Output, "bye") || out.Status != protocol.TerminalExited {
t.Fatalf("output = %+v", out)
}
if got := terminalReply(t, ctx, conns[0], terminalRequest(protocol.TerminalClose, "close", protocol.TerminalRequest{TerminalID: term.ID})); got.Terminal == nil || got.Terminal.Status != protocol.TerminalClosed {
t.Fatalf("close = %+v", got)
}
}
// Requests outside the bounds are refused: directories outside home or
// missing, input bounds, unknown terminals, the open limit.
func TestTerminalLimitsAndValidation(t *testing.T) {
home := terminalHome(t)
ctx, _, conns := dialChatConns(t, Options{OperatorRegistry: newOperatorStore(t)}, 1)
conn := conns[0]
for i, cwd := range []string{"/", filepath.Join(home, "missing"), "relative", "~other"} {
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "bad", protocol.TerminalRequest{Cwd: cwd})); got.Type != protocol.Error {
t.Fatalf("cwd %d %q = %+v", i, cwd, got)
}
}
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOutput, "none", protocol.TerminalRequest{TerminalID: "term_nope"})); got.Type != protocol.Error {
t.Fatalf("unknown = %+v", got)
}
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalInput, "noid", protocol.TerminalRequest{Data: "x"})); got.Type != protocol.Error {
t.Fatalf("no id = %+v", got)
}
var ids []string
for i := 0; i < protocol.TerminalOpenLimit; i++ {
got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "open", protocol.TerminalRequest{Cwd: "~"}))
if got.Terminal == nil {
t.Fatalf("open %d = %+v", i, got)
}
ids = append(ids, got.Terminal.ID)
}
over := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "over", protocol.TerminalRequest{}))
if over.Type != protocol.Error || !strings.Contains(over.Error, "8 open terminals") {
t.Fatalf("over limit = %+v", over)
}
for _, bad := range []string{"", strings.Repeat("x", protocol.ChatShellInputLimit+1)} {
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalInput, "bad-in", protocol.TerminalRequest{TerminalID: ids[0], Data: bad})); got.Type != protocol.Error {
t.Fatalf("input %q = %+v", bad[:min(len(bad), 4)], got)
}
}
terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalClose, "close", protocol.TerminalRequest{TerminalID: ids[0]}))
if got := terminalReply(t, ctx, conn, terminalRequest(protocol.TerminalOpen, "again", protocol.TerminalRequest{})); got.Terminal == nil {
t.Fatalf("open after close = %+v", got)
}
}