diff --git a/modules/i3/README.md b/modules/i3/README.md index ec5defdd3..bb8b631f7 100644 --- a/modules/i3/README.md +++ b/modules/i3/README.md @@ -5,7 +5,8 @@ The window manager as a module (novox/hq ADR 0208, research 026, to-be 42 phase - **Claims `node-display-session`** and serves its verbs `reload`, `workspaces` and `windows`. - **Requires `x11-display`**, which only `xorg` on the same machine provides. - **Packages:** `i3-wm`, and `dex`, which the configuration has always run for XDG autostart. `dex` - was missing on the desktop, so its autostart entries never started there. + was missing on the desktop, so its autostart entries never started there. `xdg-utils` (ADR 0303 §2), + for `open`'s `xdg-mime` and `xdg-open`. - **Environment** (ADR 0203): `XDG_CURRENT_DESKTOP=i3` and `XDG_SESSION_DESKTOP=i3`. They reach shells, the session (through `xorg`'s block) and the user manager (`environment.d`). The portal keys off the first. @@ -49,6 +50,7 @@ own business. | `node-display-session.reload` | a | checks, then reloads, keeping windows. Refused with the errors when the check fails; `force` reloads anyway | | `node-display-session.workspaces` | r | number, name, output, visible, focused, urgent | | `node-display-session.windows` | r | container id, X id, class, instance, role, title, workspace, output, focused, urgent, floating, fullscreen, scratchpad, marks; narrowed to one workspace | +| `node-display-session.open` | a | opens an http or https address in the session's default browser, for any caller over the bus | | `i3_focus` | d | a window by criteria, or a workspace | | `i3_move` | d | windows to a workspace or output; a workspace to an output | | `i3_layout_save` | d | a workspace's arrangement as a named layout of placeholders (class, instance, role), in `~/.local/state/mesh/i3/layouts/` | @@ -65,6 +67,33 @@ value a caller gives is quoted before it reaches an i3 command. With no i3 runni `{"error": "no-graphical-session", …}`. The bundle's binary is `i3-tools`, so nothing that looks for `i3` by name finds it. +## `open` (novox/hq design 08 sign-in-page §3, §29, §30, §31; issue 935) + +Opens an address in the session's default browser, for any caller over the bus — the sign-in +reaction (`networkmanager`'s watcher) never calls it, so this is for every other caller. It does not +go through i3's IPC `exec`, which hands a shell a command line; instead it asks the account's own +program chooser (`xdg-mime query default x-scheme-handler/`) and starts the program through +the account's service manager (`systemd-run --user --collect --quiet --wait -- xdg-open
`), +the address as one argument, never a shell. The run is bound to 10 s: within it, success answers +`opened` and a failure is refused naming the opener's status; still running at the bound, the page +may still be opening, so the run is left to go on and the answer says `opening`. `program` and +`command` (the desktop entry and the first word of its `Exec` line) are given only once the opener +started. + +**Refused**, naming the reason: a scheme other than `http` or `https` (named), no scheme (a file +path), no host, an address over 2048 bytes once encoded, no graphical session running, no default +program for the scheme, the opener ending with a failure (its status named). + +**The encoding** (RFC 3986): letters, digits, `-` `.` `_` `~` and the separators `:` `/` `?` `#` `[` +`]` `@` `&` `=` `+` `%` are kept as they are; every other character — a space, a quote, `;`, `$(`, +a comma among them — is percent-encoded, as the bytes of its UTF-8 form. Nothing is refused for a +character, and no shell ever reads the address. + +**Every call that is acted on is written to the log of acts done by hand** +(`seat:mesh-hand-acts.hand-act`), with its caller and why; a call refused before the opener ran +writes no act. It hears nothing of the uplink and reads no kept event at its own start: `i3` consumes +no `node-uplink` event (ADR 0689 §3). + ## What it improves over today's configuration Both workstations ran the same configuration. These changes are against it: diff --git a/modules/i3/cmd/i3-tools/main.go b/modules/i3/cmd/i3-tools/main.go index a8fd4a857..cb9a4ba33 100644 --- a/modules/i3/cmd/i3-tools/main.go +++ b/modules/i3/cmd/i3-tools/main.go @@ -14,6 +14,7 @@ import ( "path/filepath" "time" + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" stdio "git.novox.be/novox/mesh-sdk/go" "i3/internal/desktop" @@ -53,7 +54,8 @@ func machine() *i3 { if state == "" { state = filepath.Join(home, ".local", "state") } - t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts")} + t := &i3{d: desktop.Machine("i3"), configDir: filepath.Join(cfg, "i3"), layouts: filepath.Join(state, "mesh", "i3", "layouts"), + handAct: liveHandAct, opener: openerRun} t.socket = func() (string, error) { runtime := filepath.Join("/run/user", fmt.Sprint(os.Getuid())) i3sock := "" @@ -83,6 +85,16 @@ func tools(t *i3) []stdio.Tool { Input: desktop.Schema(map[string]any{"force": desktop.Flag("reload even when the check finds errors")}), Run: call(t.reload), }, + { + Name: nodedisplaysession.Seat + "." + nodedisplaysession.VerbOpen, + Description: "Open an http or https address in the person's default browser, for any caller over the bus " + + "(not the sign-in reaction, which never calls it). Refused for any other scheme, no host, an address " + + "too long once encoded, no graphical session or no default program for the scheme; the opener's " + + "failure is refused naming its status. Answers once the opener has started: opened within its bound, " + + "or opening when it still runs. Every call is an act, recorded in the log of acts done by hand.", + Input: desktop.Schema(map[string]any{"address": desktop.Str("the http or https address to open")}, "address"), + Run: call(t.open), + }, { Name: "node-display-session.workspaces", Description: "The session's workspaces: number, name, output, and whether each is visible, focused or urgent.", diff --git a/modules/i3/cmd/i3-tools/manifest_test.go b/modules/i3/cmd/i3-tools/manifest_test.go index d41fb7adc..5be02a970 100644 --- a/modules/i3/cmd/i3-tools/manifest_test.go +++ b/modules/i3/cmd/i3-tools/manifest_test.go @@ -17,6 +17,7 @@ import ( type manifest struct { Capabilities []string `json:"capabilities"` Requires []string `json:"requires"` + Invokes []string `json:"invokes"` Claims []struct { Name string `json:"name"` Scope string `json:"scope"` @@ -82,7 +83,7 @@ func resource(t *testing.T, m manifest, id string) map[string]any { func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) { m := readManifest(t) - if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows" { + if m.Seats != nil || len(m.Claims) != 1 || m.Claims[0].Name != "node-display-session" || strings.Join(m.Claims[0].Serves, ",") != "reload,workspaces,windows,open" { t.Fatalf("%+v", m.Claims) } if strings.Join(m.Requires, ",") != "x11-display" { @@ -97,7 +98,7 @@ func TestItHoldsTheSessionSeatOnAMachineWithAnXDisplay(t *testing.T) { t.Errorf("the seat's %s is not served", v) } } - if len(served) != len(m.Tools)+3 { + if len(served) != len(m.Tools)+4 { t.Fatalf("served %d, listed %d", len(served), len(m.Tools)) } for _, n := range m.Tools { @@ -175,6 +176,23 @@ func TestTheConfigurationIsTheModulesFileImprovedAndEndsWithTheDropIns(t *testin } } +// open is an act (design 08 sign-in-page §29, DQ-7): the manifest invokes the hand-act log, the +// package the opener needs is present (ADR 0303 §2), and open is among node-display-session's +// served verbs. +func TestOpenIsAnActWithItsPackageAndInvoke(t *testing.T) { + m := readManifest(t) + if strings.Join(m.Invokes, ",") != "seat:mesh-hand-acts.hand-act" { + t.Fatalf("invokes: %v", m.Invokes) + } + served := map[string]bool{} + for _, v := range m.Claims[0].Serves { + served[v] = true + } + if !served["open"] { + t.Fatal("node-display-session does not serve open") + } +} + func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) { m := readManifest(t) r := resource(t, m, "session") @@ -194,7 +212,7 @@ func TestTheLoginManagersEntryRunsTheSessionsStart(t *testing.T) { pkgs[x["package"].(string)] = true } } - if !pkgs["i3-wm"] || !pkgs["dex"] || len(pkgs) != 2 { + if !pkgs["i3-wm"] || !pkgs["dex"] || !pkgs["xdg-utils"] || len(pkgs) != 3 { t.Fatalf("%v", pkgs) } a := m.Build.Artifacts[0] diff --git a/modules/i3/cmd/i3-tools/open.go b/modules/i3/cmd/i3-tools/open.go new file mode 100644 index 000000000..8721fff9b --- /dev/null +++ b/modules/i3/cmd/i3-tools/open.go @@ -0,0 +1,300 @@ +// node-display-session.open (design 08 sign-in-page §3, §29, §30, §31): opens an http or https +// address in the person's default browser, outside i3's own IPC (which hands a shell a command +// line); this verb takes the address as one argument, through the account's own program chooser +// (xdg-mime) and the account's service manager (systemd-run --user), never a shell. It is an act +// (ADR 0565 §10): every call, refused or not, is written to the log of acts done by hand (lead +// answer note (b), DQ-7: "each call"). +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "os" + "os/exec" + "path/filepath" + "regexp" + "strings" + "syscall" + "time" + + nodedisplaysession "git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession" + stdio "git.novox.be/novox/mesh-sdk/go" + + "i3/internal/desktop" +) + +// defaultOpenTimeout is open's own bound on the opener command (design 08 sign-in-page §18, §29; a +// stated constant, lead answer R2-7): run beyond it, the page may still be opening, so the opener +// is left to go on and the answer says opening. A test shortens it with the i3's openBound field. +const defaultOpenTimeout = 10 * time.Second + +// openMaxAddress is the limit on an address once encoded (design 08 sign-in-page §3). +const openMaxAddress = 2048 + +// schemePattern is a URI's scheme (RFC 3986): letters, digits, +, . and - after the first letter, +// ended by a colon. +var schemePattern = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.-]*):`) + +// openKept are the characters open's encoding never touches, beside the unreserved ones (letters, +// digits, -, ., _, ~): the separators a URL needs, and % itself, so an address already encoded is +// not doubled (design 08 sign-in-page §3, lead answer U-M2/R2-9). +const openKept = "-._~:/?#[]@&=+%" + +// checkAddressShape is the refusals of §3 that do not need the session or the opener: a scheme +// other than http or https, no scheme (a file path), no host. +func checkAddressShape(address string) (scheme string, err error) { + m := schemePattern.FindStringSubmatch(address) + if m == nil { + return "", fmt.Errorf("no scheme: %q is a file path, not an http or https address", address) + } + scheme = strings.ToLower(m[1]) + if scheme != "http" && scheme != "https" { + return "", fmt.Errorf("a scheme other than http or https: %s", scheme) + } + afterScheme := address[len(m[0]):] + if !strings.HasPrefix(afterScheme, "//") { + return "", fmt.Errorf("no host: %s has no // after its scheme", scheme) + } + rest := afterScheme[2:] + end := strings.IndexAny(rest, "/?#") + authority := rest + if end >= 0 { + authority = rest[:end] + } + if at := strings.LastIndex(authority, "@"); at >= 0 { + authority = authority[at+1:] + } + if authority == "" { + return "", fmt.Errorf("no host") + } + return scheme, nil +} + +// encodeAddress is §3's encoding: RFC 3986's unreserved characters and the separators a URL needs +// (openKept) are kept; every other character is percent-encoded, as the bytes of its UTF-8 form. +// Nothing is refused for a character, and the result is never read by a shell. +func encodeAddress(address string) string { + var b strings.Builder + for i := 0; i < len(address); i++ { + c := address[i] + switch { + case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9': + b.WriteByte(c) + case strings.IndexByte(openKept, c) >= 0: + b.WriteByte(c) + default: + fmt.Fprintf(&b, "%%%02X", c) + } + } + return b.String() +} + +// defaultProgram asks xdg-mime for the scheme's default handler, as §18 does for the same reason: +// the desktop entry's name (such as "firefox.desktop"), or an error naming the scheme when there is +// none. +func defaultProgram(ctx context.Context, d desktop.Desk, env []string, scheme string) (string, error) { + res := d.Run(ctx, env, nil, "xdg-mime", "query", "default", "x-scheme-handler/"+scheme) + name := strings.TrimSpace(res.Stdout) + if !res.OK() || name == "" { + return "", fmt.Errorf("no default program for x-scheme-handler/%s", scheme) + } + return name, nil +} + +// entryCommand is the first word of a desktop entry's Exec line, read from the XDG data +// directories (design 08 sign-in-page §29): the program the entry runs, without its field codes +// and arguments. +func entryCommand(entry string) string { + for _, dir := range xdgDataDirs() { + b, err := os.ReadFile(filepath.Join(dir, "applications", entry)) + if err != nil { + continue + } + inEntry := false + for _, line := range strings.Split(string(b), "\n") { + line = strings.TrimSpace(line) + switch { + case strings.HasPrefix(line, "["): + inEntry = line == "[Desktop Entry]" + case inEntry: + if exec, ok := strings.CutPrefix(line, "Exec="); ok { + if fields := strings.Fields(exec); len(fields) > 0 { + return fields[0] + } + return "" + } + } + } + } + return "" +} + +// xdgDataDirs is where desktop entries are found, most specific first: the account's own, then the +// system's (XDG_DATA_DIRS, or its default). +func xdgDataDirs() []string { + dirs := []string{os.Getenv("XDG_DATA_HOME")} + if dirs[0] == "" { + dirs[0] = filepath.Join(desktop.Home(), ".local", "share") + } + extra := os.Getenv("XDG_DATA_DIRS") + if extra == "" { + extra = "/usr/local/share:/usr/share" + } + for _, d := range strings.Split(extra, ":") { + if d != "" { + dirs = append(dirs, d) + } + } + return dirs +} + +// openerRun runs the opener (systemd-run --wait -- xdg-open ...) through runWithoutKilling: it +// stops waiting at its bound without killing what it started (design 08 sign-in-page §18, §29; +// DMC-8, lead answer C-5), unlike internal/desktop's Exec (run.go), which kills the command's +// process group at its deadline. A page still opening at the bound is left to open: the browser +// outlives this call either way, since it runs under the account's own service manager +// (systemd-run --user), not as this process's child. +func openerRun(ctx context.Context, env []string, stdin []byte, name string, args ...string) desktop.Result { + cmd := exec.Command(name, args...) + cmd.Env = env + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if stdin != nil { + cmd.Stdin = bytes.NewReader(stdin) + } + return runWithoutKilling(ctx, cmd) +} + +// runWithoutKilling starts cmd and waits for it, but stops waiting at ctx's deadline without +// sending cmd any signal (design 08 sign-in-page §18, §29; DMC-8, lead answer C-5): left to go on, +// never torn down by the bound that only governs how long this call waits. A test calls this +// directly, with a command of its own whose Stdin and ExtraFiles it controls, to prove the started +// process is never killed, without a real sleep on either side. +func runWithoutKilling(ctx context.Context, cmd *exec.Cmd) desktop.Result { + res := desktop.Result{Command: append([]string{cmd.Path}, cmd.Args[1:]...)} + var out, errb bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errb + if err := cmd.Start(); err != nil { + res.Code = 127 + res.Stderr = err.Error() + return res + } + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + select { + case err := <-done: + res.Stdout, res.Stderr = out.String(), errb.String() + var exit *exec.ExitError + switch { + case err == nil: + case errors.As(err, &exit): + res.Code = exit.ExitCode() + if res.Code < 0 { + res.Code = 128 + } + default: + res.Code = 1 + if res.Stderr == "" { + res.Stderr = err.Error() + } + } + case <-ctx.Done(): + // Left to go on (DMC-8, C-5): no signal is sent, so the process it started keeps running; + // the goroutine above still reads its exit, harmlessly, once it does. + res.TimedOut = true + } + return res +} + +// open is node-display-session.open (design 08 sign-in-page §29): opens address in the session's +// default browser for the scheme, and answers once the opener has started. +func (t *i3) open(ctx context.Context, a desktop.Args) (ret any, err error) { + caller := stdio.CallerOf(map[string]any(a)) + why := fmt.Sprintf("asked by %s", caller) + var address, encoded, program, started string + + defer func() { + switch { + case err != nil: + t.journalOpen(address, "refused", err.Error()) + t.recordHandAct(fmt.Sprintf("refused %s: %s", address, err), why) + default: + t.journalOpen(address, started, program) + t.recordHandAct(fmt.Sprintf("%s %s in %s", started, encoded, program), why) + } + }() + + address, err = a.Text("address") + if err != nil { + return nil, err + } + scheme, err := checkAddressShape(address) + if err != nil { + return nil, err + } + encoded = encodeAddress(address) + if len(encoded) > openMaxAddress { + err = fmt.Errorf("the address is %d bytes once encoded, over %d", len(encoded), openMaxAddress) + return nil, err + } + + s, err := t.d.Find() + if err != nil { + return nil, err + } + env := s.Env(t.d.Base) + + program, err = defaultProgram(ctx, t.d, env, scheme) + if err != nil { + return nil, err + } + + bound := t.openBound + if bound == 0 { + bound = defaultOpenTimeout + } + runCtx, cancel := context.WithTimeout(ctx, bound) + defer cancel() + runner := t.opener + if runner == nil { + runner = openerRun + } + res := runner(runCtx, env, nil, "systemd-run", "--user", "--collect", "--quiet", "--wait", "--", "xdg-open", encoded) + + if !res.OK() && !res.TimedOut { + err = fmt.Errorf("the opener failed: %s", res.Err().Error()) + return nil, err + } + + started = nodedisplaysession.OpenAnswerStartedOpened + if res.TimedOut { + started = nodedisplaysession.OpenAnswerStartedOpening + } + command := entryCommand(program) + return nodedisplaysession.OpenAnswer{Address: encoded, Program: program, Command: command, Started: started}, nil +} + +// journalOpen is open's one journal line per call (design 08 sign-in-page §29; lead answer R2-14): +// the address, opened or refused, and the program or the reason. +func (t *i3) journalOpen(address, outcome, programOrReason string) { + fmt.Fprintf(os.Stderr, "i3: open %s: %s (%s)\n", address, outcome, programOrReason) +} + +// recordHandAct writes one call of open to the log of acts done by hand (design 08 sign-in-page +// §29; ADR 0565 §10; lead answer note (b)): every call, refused or not, with its caller and why. +func (t *i3) recordHandAct(what, why string) { + if t.handAct == nil { + return + } + if err := t.handAct(what, why); err != nil { + fmt.Fprintf(os.Stderr, "i3: open: the hand-act log did not take %q: %v\n", what, err) + } +} + +// liveHandAct is the real hand-act writer: seat:mesh-hand-acts.hand-act, asked as this module +// (design 08 sign-in-page §29). +func liveHandAct(what, why string) error { + _, err := stdio.Ask("seat:mesh-hand-acts.hand-act", map[string]any{"what": what, "why": why, "verb": "open"}) + return err +} diff --git a/modules/i3/cmd/i3-tools/open_test.go b/modules/i3/cmd/i3-tools/open_test.go new file mode 100644 index 000000000..3a16ae8b8 --- /dev/null +++ b/modules/i3/cmd/i3-tools/open_test.go @@ -0,0 +1,271 @@ +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) + } +} diff --git a/modules/i3/cmd/i3-tools/tools.go b/modules/i3/cmd/i3-tools/tools.go index 0142b6963..73c812006 100644 --- a/modules/i3/cmd/i3-tools/tools.go +++ b/modules/i3/cmd/i3-tools/tools.go @@ -19,6 +19,15 @@ type i3 struct { configDir string layouts string watcher *Watcher + // handAct writes one call of open to the log of acts done by hand (design 08 sign-in-page §29); + // nil in a test that does not check it. + handAct func(what, why string) error + // openBound is open's own bound on the opener command, defaultOpenTimeout unless a test shortens + // it so a still-running opener is seen without waiting out the real bound. + openBound time.Duration + // opener runs the opener command: openerRun (design 08 sign-in-page §29; DMC-8, lead answer C-5) + // unless a test replaces it to control the opener's outcome directly. + opener desktop.Runner } func (t *i3) ask(kind uint32, payload string, out any) error { diff --git a/modules/i3/go.mod b/modules/i3/go.mod index 645d3fdbe..c5901cd6d 100644 --- a/modules/i3/go.mod +++ b/modules/i3/go.mod @@ -2,7 +2,10 @@ module i3 go 1.26.0 -require git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +require ( + git.novox.be/novox/mesh-contracts/go/seats/nodedisplaysession v0.0.0-00010101000000-000000000000 + git.novox.be/novox/mesh-sdk/go v0.0.0-00010101000000-000000000000 +) require ( github.com/klauspost/compress v1.20.1 // indirect diff --git a/modules/i3/module.json b/modules/i3/module.json index 315b77deb..02dafc062 100644 --- a/modules/i3/module.json +++ b/modules/i3/module.json @@ -16,10 +16,14 @@ "serves": [ "reload", "workspaces", - "windows" + "windows", + "open" ] } ], + "invokes": [ + "seat:mesh-hand-acts.hand-act" + ], "tools": [ "i3_focus", "i3_move", @@ -68,6 +72,11 @@ "type": "package", "package": "dex" }, + { + "id": "package-xdg-utils", + "type": "package", + "package": "xdg-utils" + }, { "id": "config-dir", "type": "directory", diff --git a/retired-words b/retired-words index c7a00a95a..577b69406 100644 --- a/retired-words +++ b/retired-words @@ -2,6 +2,7 @@ # *Not:* words with no scope or with (tools). A copy, so a catalogue merge needs nothing else; novox/hq's # words.py compares it with the glossary. Regenerate with: python3 00-META/checks/words.py --list tools build machine +captive portal catalogue change plan control plane