package main import ( "context" "os" "path/filepath" "strings" "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 (openerRun, 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, so an opener still running past the bound keeps running and // finishes on its own. func TestOpenerRunStopsWaitingWithoutKillingTheProcess(t *testing.T) { marker := filepath.Join(t.TempDir(), "ran") ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) defer cancel() start := time.Now() res := openerRun(ctx, os.Environ(), nil, "sh", "-c", "sleep 0.15; touch "+marker) if !res.TimedOut { t.Fatalf("expected TimedOut, got %+v", res) } if since := time.Since(start); since > 200*time.Millisecond { t.Fatalf("openerRun waited past its own bound: %s", since) } deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { if _, err := os.Stat(marker); err == nil { return // the process kept running after openerRun gave up waiting, and finished: not killed } time.Sleep(10 * time.Millisecond) } t.Fatal("the opener process was killed: it never finished past the bound") } // 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) } }