Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(endpoint): read logind session state and seat from the authoritative properties

shukieshah16e84a966405
diff --git a/cli/beacon/cmd/endpoint_console_user_test.go b/cli/beacon/cmd/endpoint_console_user_test.go
index 2debf93a..811b556f 100644
--- a/cli/beacon/cmd/endpoint_console_user_test.go
+++ b/cli/beacon/cmd/endpoint_console_user_test.go
@@ -1,6 +1,7 @@
package cmd
import (
+ "fmt"
"os"
"os/user"
"path/filepath"
@@ -120,15 +121,33 @@ func TestLinuxActiveConsoleUserWithoutSudoOrLogindIsNotAnError(t *testing.T) {
_ = os.Getenv("PATH")
}
-// fakeLoginctl puts a stub `loginctl` on PATH that answers list-sessions with the given table and
-// reports every session active. A fake binary is the only way to drive this: the resolution shells
-// out, and the answer depends on which session logind names first.
-func fakeLoginctl(t *testing.T, sessionTable string) {
+// fakeLoginctl puts a stub `loginctl` on PATH that reproduces what systemd 255 actually prints.
+//
+// The fixture matters as much as the assertion here. The first version emitted a 3-column table with
+// a blank seat for unseated rows, so the test passed against code that treated any non-empty seat
+// column as seated -- while real loginctl prints `-` there and the code misclassified every ssh
+// session. These strings were captured from a live logind in a container, not written from memory:
+//
+// 11 1002 remoteuser - "" active online no -
+// 9 1001 tester seat0 tty7 online no -
+//
+// and per session, `show-session -p Name -p State -p Seat` printing self-labeling Key=Value lines.
+func fakeLoginctl(t *testing.T, sessions []fakeSession) {
t.Helper()
+ var table, cases strings.Builder
+ for _, sess := range sessions {
+ seat := sess.seat
+ if seat == "" {
+ seat = "-" // what loginctl really prints for an unseated session
+ }
+ fmt.Fprintf(&table, "%s 1000 %s %s tty1 %s no -\n", sess.id, sess.user, seat, sess.state)
+ fmt.Fprintf(&cases, " %s) printf 'Name=%s\\nSeat=%s\\nState=%s\\n' ;;\n",
+ sess.id, sess.user, sess.seat, sess.state)
+ }
dir := t.TempDir()
script := "#!/bin/sh\ncase \"$1\" in\n" +
- "list-sessions) printf '%s' " + shellSingleQuote(sessionTable) + " ;;\n" +
- "show-session) echo active ;;\n" +
+ "list-sessions) printf '%s' " + shellSingleQuote(table.String()) + " ;;\n" +
+ "show-session)\n case \"$2\" in\n" + cases.String() + " esac ;;\n" +
"esac\n"
if err := os.WriteFile(filepath.Join(dir, "loginctl"), []byte(script), 0o755); err != nil {
t.Fatal(err)
@@ -136,57 +155,97 @@ func fakeLoginctl(t *testing.T, sessionTable string) {
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
}
+type fakeSession struct {
+ id, user, seat, state string
+}
+
func shellSingleQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
-// A host with both a graphical login and an earlier ssh or service session must resolve the person
-// at the machine. loginctl lists sessions oldest-first, so taking the first active one picks the ssh
-// session -- and the postinstall would configure the wrong user's agent runtime. The comment claimed
-// this ordering before the code implemented it.
-func TestLinuxActiveConsoleUserPrefersASeatedSession(t *testing.T) {
- if runtime.GOOS != "linux" {
- t.Skip("linux-only resolution")
- }
- t.Setenv("SUDO_USER", "")
- // Unseated session listed first, seated second -- the order that exposes the bug.
- fakeLoginctl(t, " 7 1002 remote \n 3 1001 desktop seat0 tty2\n")
-
- var asked []string
+func stubLookup(t *testing.T) {
+ t.Helper()
restore := lookupConsoleUser
lookupConsoleUser = func(name string) (consoleUserInfo, bool, error) {
- asked = append(asked, name)
return consoleUserInfo{Username: name, HomeDir: "/home/" + name}, true, nil
}
t.Cleanup(func() { lookupConsoleUser = restore })
+}
+
+// The case verified against real logind: the person at the machine is seated but reports state
+// "online" (they are not the foreground session on their seat), while an ssh login reports "active".
+// Requiring "active" therefore picks the *remote* user and rejects the one at the keyboard -- the
+// opposite of the intent -- and reading the table's seat column classifies the ssh row as seated,
+// which collapses the preference entirely.
+func TestLinuxActiveConsoleUserPrefersTheUserAtTheMachine(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("linux-only resolution")
+ }
+ t.Setenv("SUDO_USER", "")
+ stubLookup(t)
+ // Listed remote-first, which is what loginctl does: sessions come out oldest first.
+ fakeLoginctl(t, []fakeSession{
+ {id: "11", user: "remoteuser", seat: "", state: "active"},
+ {id: "9", user: "desktop", seat: "seat0", state: "online"},
+ })
info, ok, err := linuxActiveConsoleUser()
if err != nil || !ok {
t.Fatalf("linuxActiveConsoleUser() = %+v, %v, %v; want the seated user", info, ok, err)
}
if info.Username != "desktop" {
- t.Errorf("resolved %q, want the seated session's user; lookups=%v", info.Username, asked)
+ t.Errorf("resolved %q, want the seated user even though the remote one is \"active\"",
+ info.Username)
}
}
-// An unseated session is still a real human whose agent runs on that host, so it is accepted when
-// there is no seated one -- the preference is an ordering, not a filter.
-func TestLinuxActiveConsoleUserAcceptsAnUnseatedSessionWhenItIsAll(t *testing.T) {
+// A foreground seated session outranks a background one, so a shared workstation resolves whoever is
+// actually in front.
+func TestLinuxActiveConsoleUserPrefersTheForegroundSeatedSession(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("linux-only resolution")
}
t.Setenv("SUDO_USER", "")
- fakeLoginctl(t, " 7 1002 remote \n")
+ stubLookup(t)
+ fakeLoginctl(t, []fakeSession{
+ {id: "3", user: "background", seat: "seat0", state: "online"},
+ {id: "5", user: "foreground", seat: "seat0", state: "active"},
+ })
- restore := lookupConsoleUser
- lookupConsoleUser = func(name string) (consoleUserInfo, bool, error) {
- return consoleUserInfo{Username: name, HomeDir: "/home/" + name}, true, nil
+ info, _, _ := linuxActiveConsoleUser()
+ if info.Username != "foreground" {
+ t.Errorf("resolved %q, want the foreground seated session", info.Username)
}
- t.Cleanup(func() { lookupConsoleUser = restore })
+}
+
+// An unseated session is still a real human whose agent runs on this host, so the preference is an
+// ordering and not a filter.
+func TestLinuxActiveConsoleUserAcceptsAnUnseatedSessionWhenItIsAll(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("linux-only resolution")
+ }
+ t.Setenv("SUDO_USER", "")
+ stubLookup(t)
+ fakeLoginctl(t, []fakeSession{{id: "7", user: "remoteuser", seat: "", state: "active"}})
info, ok, err := linuxActiveConsoleUser()
- if err != nil || !ok || info.Username != "remote" {
+ if err != nil || !ok || info.Username != "remoteuser" {
t.Fatalf("linuxActiveConsoleUser() = %+v, %v, %v; want the unseated user accepted",
info, ok, err)
}
}
+
+// A session mid-transition is nobody to configure, and skipping it must not be mistaken for having
+// found them.
+func TestLinuxActiveConsoleUserIgnoresClosingSessions(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("linux-only resolution")
+ }
+ t.Setenv("SUDO_USER", "")
+ stubLookup(t)
+ fakeLoginctl(t, []fakeSession{{id: "4", user: "leaving", seat: "seat0", state: "closing"}})
+
+ if info, ok, _ := linuxActiveConsoleUser(); ok {
+ t.Errorf("resolved %+v from a closing session", info)
+ }
+}
diff --git a/cli/beacon/cmd/endpoint_hooks_repair.go b/cli/beacon/cmd/endpoint_hooks_repair.go
index 8f726f0c..057bf900 100644
--- a/cli/beacon/cmd/endpoint_hooks_repair.go
+++ b/cli/beacon/cmd/endpoint_hooks_repair.go
@@ -8,6 +8,7 @@ import (
"os/exec"
"os/user"
"runtime"
+ "sort"
"strings"
"time"
@@ -191,41 +192,92 @@ func linuxActiveConsoleUser() (consoleUserInfo, bool, error) {
if u := strings.TrimSpace(os.Getenv("SUDO_USER")); u != "" {
return lookupConsoleUser(u)
}
- // loginctl lists sessions as: SESSION UID USER SEAT [TTY]. A session with a seat is someone at
- // the machine; one without is an ssh login or a service. Both can be a real human whose agent
- // runs there, so both are acceptable -- but a seated session is the better answer when a host
- // has both, which is why this makes two passes instead of taking whichever loginctl printed
- // first. An earlier version claimed that ordering in a comment while the code took the first
- // active session it saw.
+ // The session table is used only to enumerate ids. Every other column is read back through
+ // `show-session`, which reports `Key=Value` lines -- unambiguous, self-labeling, and free of the
+ // table's placeholders.
+ //
+ // Parsing the table directly is a trap, and two separate ones. Its unseated rows print `-` in
+ // the seat column rather than leaving it blank, so "non-empty means seated" classifies every ssh
+ // session as seated. And `--value` returns properties in alphabetical order, not the order
+ // requested, so reading two values positionally silently swaps them. Both were verified against
+ // systemd 255 rather than assumed.
out, err := exec.Command("loginctl", "list-sessions", "--no-legend").Output()
if err != nil {
// No logind, or it refused. Not an error worth failing an install over: this is a
// best-effort identification, and the caller already handles "unknown".
return consoleUserInfo{}, false, nil
}
- lines := strings.Split(string(out), "\n")
- for _, seatedOnly := range []bool{true, false} {
- for _, line := range lines {
- fields := strings.Fields(line)
- if len(fields) < 3 {
- continue
- }
- seated := len(fields) > 3 && strings.TrimSpace(fields[3]) != ""
- if seated != seatedOnly {
- continue
- }
- st, err := exec.Command("loginctl", "show-session", fields[0], "-p", "State", "--value").Output()
- if err != nil || strings.TrimSpace(string(st)) != "active" {
- continue
- }
- if info, ok, err := lookupConsoleUser(fields[2]); ok || err != nil {
- return info, ok, err
- }
+ var sessions []logindSession
+ for _, line := range strings.Split(string(out), "\n") {
+ fields := strings.Fields(line)
+ if len(fields) == 0 {
+ continue
+ }
+ if s, ok := describeLogindSession(fields[0]); ok {
+ sessions = append(sessions, s)
+ }
+ }
+ // Best answer first: someone at the machine in the foreground, then anyone at the machine, then
+ // a remote login. Ranked rather than filtered -- a remote session is still a real human whose
+ // agent runs on this host, so it is the right answer when it is the only one.
+ sort.SliceStable(sessions, func(i, j int) bool { return sessions[i].rank() > sessions[j].rank() })
+ for _, sess := range sessions {
+ if info, ok, err := lookupConsoleUser(sess.user); ok || err != nil {
+ return info, ok, err
}
}
return consoleUserInfo{}, false, nil
}
+// logindSession is what one session says about itself.
+type logindSession struct {
+ user string
+ seated bool
+ // foreground is logind's "active" state: the session currently in front on its seat. A logged-in
+ // user who is not in front reports "online" instead, which is still a real login -- requiring
+ // "active" alone would reject a seated graphical session in favour of an ssh one, since that is
+ // exactly what systemd 255 reports for each.
+ foreground bool
+}
+
+func (s logindSession) rank() int {
+ score := 0
+ if s.seated {
+ score += 2
+ }
+ if s.foreground {
+ score++
+ }
+ return score
+}
+
+// describeLogindSession reads one session's properties, skipping anything that is not a live login.
+func describeLogindSession(id string) (logindSession, bool) {
+ out, err := exec.Command("loginctl", "show-session", id, "-p", "Name", "-p", "State", "-p", "Seat").Output()
+ if err != nil {
+ return logindSession{}, false
+ }
+ props := map[string]string{}
+ for _, line := range strings.Split(string(out), "\n") {
+ if k, v, found := strings.Cut(strings.TrimSpace(line), "="); found {
+ props[k] = v
+ }
+ }
+ // closing and opening sessions are mid-transition and are not somebody to configure.
+ state := props["State"]
+ if state != "active" && state != "online" {
+ return logindSession{}, false
+ }
+ if props["Name"] == "" {
+ return logindSession{}, false
+ }
+ return logindSession{
+ user: props["Name"],
+ seated: strings.TrimSpace(props["Seat"]) != "",
+ foreground: state == "active",
+ }, true
+}
+
// resolveConsoleUser validates a username and resolves its home directory.
//
// root is rejected: a system install has already configured root, and treating it as the console
diff --git a/cli/beacon/cmd/endpoint_update_service.go b/cli/beacon/cmd/endpoint_update_service.go
index 0145d8b5..0b4571d1 100644
--- a/cli/beacon/cmd/endpoint_update_service.go
+++ b/cli/beacon/cmd/endpoint_update_service.go
@@ -166,9 +166,7 @@ func runUpdateDisable(cmd *cobra.Command, args []string) error {
if err := mgr.Unload(); err != nil {
return fmt.Errorf("unload updater job: %w", err)
}
- for _, path := range mgr.UnitPaths() {
- _ = os.Remove(path)
- }
+ mgr.RemoveUnits()
fmt.Println("Update checks disabled; background updater removed.")
return nil
}
@@ -197,9 +195,7 @@ func runUpdateInstallDaemon(cmd *cobra.Command, args []string) error {
mgr := service.UpdaterManager{}
if mode == selfupdate.ModeOff {
_ = mgr.Unload()
- for _, path := range mgr.UnitPaths() {
- _ = os.Remove(path)
- }
+ mgr.RemoveUnits()
fmt.Println("Auto-update is off; updater daemon not installed.")
return nil
}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 9ba1315d..17a36637 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -29,9 +29,7 @@ var (
removeUpdaterJob = func() {
updater := service.UpdaterManager{}
_ = updater.Unload()
- for _, path := range updater.UnitPaths() {
- _ = os.Remove(path)
- }
+ updater.RemoveUnits()
}
)
@@ -345,7 +343,7 @@ func reconcileUpdaterFromConfig(logPath string) error {
mgr := service.UpdaterManager{}
if mode == selfupdate.ModeOff {
_ = mgr.Unload()
- _ = os.Remove(mgr.UnitPath())
+ mgr.RemoveUnits()
return nil
}
if _, err := mgr.WriteUnit(selfupdate.SystemBeaconPath()); err != nil {
diff --git a/cli/beacon/internal/endpoint/service/updater.go b/cli/beacon/internal/endpoint/service/updater.go
index 60cf81cc..e2fc9074 100644
--- a/cli/beacon/internal/endpoint/service/updater.go
+++ b/cli/beacon/internal/endpoint/service/updater.go
@@ -102,6 +102,19 @@ func (m UpdaterManager) UnitPaths() []string {
return []string{m.UnitPath()}
}
+// RemoveUnits deletes every file WriteUnit installed.
+//
+// Exists so no caller has to remember that systemd needs two files removed and launchd one. The
+// previous shape -- callers looping over UnitPaths themselves -- was better than callers using
+// UnitPath, but it still left the knowledge duplicated at four sites, and one of them was missed:
+// `reconcileUpdaterFromConfig` kept removing only the timer, so turning auto-update off left
+// beacon-updater.service behind. A method that owns the whole set cannot be half-adopted.
+func (m UpdaterManager) RemoveUnits() {
+ for _, path := range m.UnitPaths() {
+ _ = os.Remove(path)
+ }
+}
+
// WriteUnit installs the updater definition invoking the given program.
func (m UpdaterManager) WriteUnit(program string) (string, error) {
if !m.Supported() {