Files
mesh-catalog/modules/i3/cmd/i3-tools/open_test.go
T
jochen 9a3149df88 i3: test the opener's no-kill run with pipes, never a real sleep
Code review round 2 (C-5 follow-up). openerRun's core is now runWithoutKilling(ctx,
*exec.Cmd), callable directly by a test with a command of its own. The test's child
blocks reading its stdin (a pipe held open past the bound); after confirming
TimedOut, the test closes the pipe to unblock it, then waits on the child's own
end (a byte written to an extra file just before it exits, read with a plain
blocking read) instead of sleeping and polling for a marker file. A kill at the
bound now leaves that read empty, which the test checked by reintroducing the old
signal and watching it fail.

Builds: design 08 sign-in-page §3, §29
2026-11-25 01:13:18 +01:00

272 lines
10 KiB
Go

package main
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession"
"i3/internal/desktop"
)
// runCall records one call the stood-in opener saw, so a test can check the exact argv it was
// handed (design 08 sign-in-page §29, R2-9: one argument, no shell).
type runCall struct {
name string
args []string
}
// stubOpener builds an i3 whose session is found (unless find answers an error), whose xdg-mime
// query answers xdgMime, and whose opener answers the systemd-run call with opener (nil runs it is
// never reached). Every call, to either, is recorded in calls.
func stubOpener(t *testing.T, find func() (*desktop.Session, error), xdgMime desktop.Result, opener desktop.Runner) (*i3, *[]runCall) {
t.Helper()
calls := &[]runCall{}
run := func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
*calls = append(*calls, runCall{name, args})
if name != "xdg-mime" {
t.Fatalf("unexpected command on the session's own run: %s %v", name, args)
}
return xdgMime
}
var wrapped desktop.Runner
if opener != nil {
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
*calls = append(*calls, runCall{name, args})
return opener(ctx, env, stdin, name, args...)
}
} else {
wrapped = func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
t.Fatalf("the opener never runs: %s %v", name, args)
return desktop.Result{}
}
}
return &i3{d: desktop.Desk{Find: find, Run: run}, opener: wrapped, openBound: 50 * time.Millisecond}, calls
}
// resultOpener is an opener stub that answers res, blocking on ctx when res.TimedOut (as a real
// still-running opener would appear to this call).
func resultOpener(res desktop.Result) desktop.Runner {
return func(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result {
if res.TimedOut {
<-ctx.Done()
return desktop.Result{TimedOut: true}
}
return res
}
}
func foundSession() (*desktop.Session, error) {
return &desktop.Session{}, nil
}
func writeDesktopEntry(t *testing.T, entry, execLine string) {
t.Helper()
dir := t.TempDir()
t.Setenv("XDG_DATA_HOME", dir)
apps := filepath.Join(dir, "applications")
if err := os.MkdirAll(apps, 0o755); err != nil {
t.Fatal(err)
}
text := "[Desktop Entry]\nType=Application\nName=Browser\nExec=" + execLine + "\n"
if err := os.WriteFile(filepath.Join(apps, entry), []byte(text), 0o644); err != nil {
t.Fatal(err)
}
}
// 935/I-1: every scheme but http and https, and a file path, is refused.
func TestOpenRefusesEveryOtherScheme(t *testing.T) {
x, calls := stubOpener(t, foundSession, desktop.Result{}, nil)
for _, address := range []string{
"/etc/passwd", // no scheme: a file path
"file:///etc/passwd", // a scheme other than http or https
"ftp://example.net/f", // a scheme other than http or https
"mailto:a@example.net", // a scheme other than http or https, no //
"http://", // no host
"https:///path", // no host
} {
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
t.Errorf("%s: not refused", address)
}
}
if len(*calls) != 0 {
t.Fatalf("a refused address never reaches xdg-mime or the opener: %v", *calls)
}
}
// 935/I-1: an address over 2048 bytes once encoded is refused.
func TestOpenRefusesAnAddressTooLongOnceEncoded(t *testing.T) {
x, _ := stubOpener(t, foundSession, desktop.Result{}, nil)
address := "https://example.net/" + strings.Repeat("a", 2048)
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": address}); err == nil {
t.Fatal("not refused")
}
}
// 935/I-1: with no graphical session it refuses, as its other tools answer.
func TestOpenRefusesWithNoGraphicalSession(t *testing.T) {
x, _ := stubOpener(t, func() (*desktop.Session, error) {
return nil, &desktop.NoSession{Reason: "none"}
}, desktop.Result{}, nil)
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if !desktop.IsNoSession(err) {
t.Fatalf("%v", err)
}
}
// 935/I-1: no default program for the scheme is refused.
func TestOpenRefusesWithNoDefaultProgram(t *testing.T) {
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: ""}, nil)
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err == nil {
t.Fatal("not refused")
}
}
// 935/I-2 (R2-9): every character outside the kept set is percent-encoded, as the bytes of its
// UTF-8 form, and the address reaches the opener as one argument, never a shell command line.
func TestOpenEncodesEveryOtherCharacterAsOneArgument(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, calls := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
address := `https://example.net/a'b;c d$(e),f"g`
got, err := run(t, x, "node-display-session.open", map[string]any{"address": address})
if err != nil {
t.Fatal(err)
}
want := `https://example.net/a%27b%3Bc%20d%24%28e%29%2Cf%22g`
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Address != want {
t.Fatalf("got %q, want %q", answer.Address, want)
}
var last runCall
for _, c := range *calls {
if c.name == "systemd-run" {
last = c
}
}
if len(last.args) == 0 || last.args[len(last.args)-1] != want {
t.Fatalf("the address is not the opener's last, whole argument: %v", last.args)
}
for _, a := range last.args {
if strings.Contains(a, "'") || strings.Contains(a, ";") || strings.Contains(a, " ") {
t.Fatalf("an argument still carries a shell character: %q", a)
}
}
}
// 935/I-3: an opener that fails is refused with its status and names no program.
func TestOpenRefusesWhenTheOpenerFails(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"},
resultOpener(desktop.Result{Code: 1, Stderr: "no such unit"}))
_, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err == nil || !strings.Contains(err.Error(), "no such unit") {
t.Fatalf("%v", err)
}
}
// 935/I-3: an opener that ends well answers opened with the program.
func TestOpenAnswersOpenedWithTheProgram(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err != nil {
t.Fatal(err)
}
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Started != nodedisplaysession.OpenAnswerStartedOpened || answer.Program != "browser.desktop" || answer.Command != "firefox" {
t.Fatalf("%+v", answer)
}
}
// 935/I-3: one still running at its bound answers opening, with the program (H-M2: the answer
// names the program only once the opener started).
func TestOpenAnswersOpeningWhenStillRunningAtItsBound(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{TimedOut: true}))
got, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"})
if err != nil {
t.Fatal(err)
}
answer := got.(nodedisplaysession.OpenAnswer)
if answer.Started != nodedisplaysession.OpenAnswerStartedOpening || answer.Program != "browser.desktop" {
t.Fatalf("%+v", answer)
}
}
// C-5: cmd/i3-tools runs the opener with its own run (runWithoutKilling, not internal/desktop's
// Exec, which kills a command's process group at its deadline, run.go:82-86): it stops waiting at
// its bound without killing what it started. The child blocks reading its stdin, a pipe this test
// holds open past the bound and only then closes; once unblocked, the child writes one byte on an
// extra file before it exits, its own end, which this test waits on instead of sleeping — a byte
// the child could reach only by surviving the bound, never by being killed at it.
func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) {
stdinR, stdinW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer stdinW.Close()
doneR, doneW, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer doneR.Close()
cmd := exec.Command("sh", "-c", "cat >/dev/null; printf x >&3")
cmd.Stdin = stdinR
cmd.ExtraFiles = []*os.File{doneW}
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} // as openerRun starts it
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer cancel()
res := runWithoutKilling(ctx, cmd)
stdinR.Close()
doneW.Close() // this process's own copy: only the child's, closed when it exits, is left
if !res.TimedOut {
t.Fatalf("expected TimedOut, got %+v", res)
}
// Unblock the child: were it killed at the bound, this would reach nobody.
if err := stdinW.Close(); err != nil {
t.Fatal(err)
}
// Wait on the child's own end: blocks until the child writes its byte and exits, closing its
// copy of doneW: never a timer, never a kill.
b := make([]byte, 1)
n, _ := doneR.Read(b)
if n != 1 || b[0] != 'x' {
t.Fatalf("the opener process was killed instead of left to finish: read %d byte(s)", n)
}
}
// DQ-7 (lead answer note (b)): every call writes one act to the log of acts done by hand, with its
// caller and why — a successful one and a refused one alike.
func TestOpenWritesOneActDoneByHandForEveryCall(t *testing.T) {
writeDesktopEntry(t, "browser.desktop", "firefox %u")
x, _ := stubOpener(t, foundSession, desktop.Result{Code: 0, Stdout: "browser.desktop\n"}, resultOpener(desktop.Result{Code: 0}))
var recorded []string
x.handAct = func(what, why string) error {
recorded = append(recorded, what+"|"+why)
return nil
}
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "https://example.net"}); err != nil {
t.Fatal(err)
}
if len(recorded) != 1 || !strings.Contains(recorded[0], "https://example.net") {
t.Fatalf("%v", recorded)
}
recorded = nil
if _, err := run(t, x, "node-display-session.open", map[string]any{"address": "ftp://example.net"}); err == nil {
t.Fatal("expected a refusal")
}
if len(recorded) != 1 || !strings.Contains(recorded[0], "refused") || !strings.Contains(recorded[0], "ftp://example.net") {
t.Fatalf("a refusal writes an act too (note (b)): %v", recorded)
}
}