Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): remember where Fluxer is installed (#3679)

Hampusd9c3534ea1ca
diff --git a/fluxer_docs/src/content/docs/operator/rexctl.mdx b/fluxer_docs/src/content/docs/operator/rexctl.mdx
index 6091ae8c8..8c33fb56c 100644
--- a/fluxer_docs/src/content/docs/operator/rexctl.mdx
+++ b/fluxer_docs/src/content/docs/operator/rexctl.mdx
@@ -801,6 +801,14 @@ rexctl upgrade [flags]
Upgrade to this version, not the latest.
+## rexctl use
+
+Show which instance rexctl uses when you don't pass --dir and aren't in an instance folder, or pass a folder to use that instance from now on. rexctl remembers each instance it installs, so you only need this with more than one instance or one installed by an older rexctl. Each account has its own choice. Root's choice also applies to accounts that have no instance of their own. The services rexctl sets up for starting and upgrading Fluxer always name their folder, so this doesn't change them.
+
+```sh
+rexctl use [folder]
+```
+
## rexctl users
Manage accounts on your instance.
diff --git a/fluxer_docs/src/content/docs/operator/running.mdx b/fluxer_docs/src/content/docs/operator/running.mdx
index 0f06d30f6..3280562d5 100644
--- a/fluxer_docs/src/content/docs/operator/running.mdx
+++ b/fluxer_docs/src/content/docs/operator/running.mdx
@@ -66,6 +66,8 @@ rexctl install --dir /path/to/second-instance --project blue --behind-proxy --bi
rexctl chooses free voice and video ports for each instance and prints the ones it picked. `rexctl doctor` shows which instance uses which ports.
+rexctl remembers where it installed each instance. Outside an instance folder, commands use the default instance, which is the first one you installed. Run `rexctl use <folder>` to pick another default, or pass `--dir`. Each account has its own default.
+
## Manage people
Create an invite link that 10 people can use within a week.
diff --git a/fluxer_rexctl/cmd/app.go b/fluxer_rexctl/cmd/app.go
index 66abe03af..60451999a 100644
--- a/fluxer_rexctl/cmd/app.go
+++ b/fluxer_rexctl/cmd/app.go
@@ -51,6 +51,7 @@ type App struct {
held *instance.Instance
engine *engine.Engine
warned bool
+ located *instance.Located
keepLayout bool
}
@@ -112,16 +113,102 @@ func (w detailWriter) Write(p []byte) (int, error) {
func (a *App) SetExit(code int) { a.exit = code }
func (a *App) Dir() (string, error) {
- if a.Flags.Dir != "" {
- return a.Flags.Dir, nil
+ l, err := a.Locate()
+ return l.Dir, err
+}
+
+func (a *App) Locate() (instance.Located, error) {
+ first := a.located == nil
+ l, err := a.locate()
+ if err == nil && first && l.Stale != "" {
+ a.warnStale(l)
+ }
+ return l, err
+}
+
+func (a *App) warnStale(l instance.Located) {
+ a.UI.Warn(fmt.Sprintf("rexctl remembers Fluxer in %s as the default, but there's no instance there now. Using %s.", l.Stale, l.Dir), "Run rexctl use <folder> to pick another default.")
+}
+
+func (a *App) locate() (instance.Located, error) {
+ if a.located != nil {
+ return *a.located, nil
+ }
+ l, err := instance.Resolve(a.Flags.Dir)
+ var several *instance.SeveralError
+ switch {
+ case errors.As(err, &several):
+ if several.Stale != "" {
+ a.UI.Warn(fmt.Sprintf("rexctl remembers Fluxer in %s as the default, but there's no instance there now.", several.Stale), "")
+ }
+ if !a.UI.Interactive() {
+ return l, &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("This machine has Fluxer instances in %s.", ui.JoinAnd(several.Dirs)), Fix: "Pass --dir with the one you mean, or run rexctl use <folder> to make one the default.", Err: err}
+ }
+ opts := make([]ui.Option, len(several.Dirs))
+ for i, d := range several.Dirs {
+ opts[i] = ui.Option{Label: d, Value: d}
+ }
+ var dir string
+ if err := a.UI.Ask(nil, ui.Field{Title: "Which Fluxer instance?", Value: &dir, Options: opts}); err != nil {
+ return l, err
+ }
+ a.UI.Info("Run rexctl use %s to make it the default.", dir)
+ l = instance.Located{Dir: dir, From: instance.FromPicked}
+ case err != nil:
+ return l, untrustedRefusal(err)
+ }
+ a.located = &l
+ return l, nil
+}
+
+func untrustedRefusal(err error) error {
+ var untrusted *instance.UntrustedError
+ switch {
+ case !errors.As(err, &untrusted):
+ return err
+ case untrusted.Folder:
+ return &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("rexctl remembers Fluxer in %s, but accounts other than root can change that folder, so root doesn't use it.", untrusted.Path), Fix: "Pass --dir if you mean that folder, or run rexctl use <folder> as root with another folder.", Err: err}
+ }
+ return &ui.ExitError{Code: ui.ExitRefused, Msg: fmt.Sprintf("Accounts other than root can change %s, so root doesn't use it.", untrusted.Path), Fix: "Make root its owner and the only account that can write to it, or pass --dir.", Err: err}
+}
+
+func (a *App) pickedDir() string {
+ if a.located == nil || a.located.From == instance.FromFlag || a.located.From == instance.FromWorkdir {
+ return ""
+ }
+ return a.located.Dir
+}
+
+func (a *App) remember(dir string) {
+ if err := instance.Remember(instance.OwnScope(), dir, false); err != nil {
+ a.UI.Detail("recording the instance in %s: %v", instance.RecordPath(instance.OwnScope()), err)
+ }
+}
+
+func (a *App) rememberFirst(inst *instance.Instance) {
+ if inst.State == nil || inst.State.Ejected != nil {
+ return
+ }
+ if err := instance.RememberFirst(instance.OwnScope(), inst.Dir); err != nil {
+ a.UI.Detail("recording the instance in %s: %v", instance.RecordPath(instance.OwnScope()), err)
+ }
+}
+
+func (a *App) forget(dir string) {
+ s := instance.OwnScope()
+ if err := instance.Forget(s, dir); err != nil {
+ a.UI.Detail("%v", err)
+ a.UI.Warn(fmt.Sprintf("rexctl still lists %s in %s.", dir, instance.RecordPath(s)), "Remove it from that file.")
}
- return instance.Locate()
}
func (a *App) takeOverCommand() string {
if a.Flags.Dir != "" {
return "rexctl takeover --dir " + a.Flags.Dir
}
+ if dir := a.pickedDir(); dir != "" {
+ return "rexctl takeover --dir " + dir
+ }
return "rexctl takeover"
}
@@ -142,6 +229,7 @@ func (a *App) InstanceRepairing(keys []string) (*instance.Instance, error) {
return nil, err
}
a.warnUnknown(inst)
+ a.rememberFirst(inst)
return inst, nil
case errors.Is(err, instance.ErrNotFound):
return nil, ui.Refused(fmt.Sprintf("There's no Fluxer instance in %s.", dir), "Run rexctl install, or pass --dir.")
diff --git a/fluxer_rexctl/cmd/doctor.go b/fluxer_rexctl/cmd/doctor.go
index cb6b57235..0c89147d6 100644
--- a/fluxer_rexctl/cmd/doctor.go
+++ b/fluxer_rexctl/cmd/doctor.go
@@ -37,16 +37,18 @@ func newDoctorCmd(app *App) *cobra.Command {
}
func runDoctor(ctx context.Context, app *App, fix bool) error {
- dir, err := app.Dir()
+ l, err := app.Locate()
if err != nil {
return err
}
+ dir := l.Dir
env := &checks.Env{Dir: dir}
phase := checks.Installed
inst, err := instance.Find(dir)
switch {
case err == nil:
env.Instance = inst
+ app.UI.Info("Using %s (%s).", inst.Dir, l.Why())
case errors.Is(err, instance.ErrNotFound):
phase = checks.Preinstall
case errors.Is(err, instance.ErrLegacy):
@@ -58,6 +60,7 @@ func runDoctor(ctx context.Context, app *App, fix bool) error {
return err
}
if env.Instance != nil {
+ app.rememberFirst(env.Instance)
if fix {
if err := managed(env.Instance); err != nil {
return err
diff --git a/fluxer_rexctl/cmd/eject.go b/fluxer_rexctl/cmd/eject.go
index 088e00bd0..c1e78284d 100644
--- a/fluxer_rexctl/cmd/eject.go
+++ b/fluxer_rexctl/cmd/eject.go
@@ -70,6 +70,7 @@ func runEject(ctx context.Context, app *App) error {
}
return ui.Wrap(err, "Couldn't hand the instance over.", "Check that you can write to "+inst.Dir+", then try again.")
}
+ app.forget(inst.Dir)
if removed && host.BootUnitSupported() && engineErr == nil && e.Kind == engine.Podman && olderPodman(e.Version) {
u.Info("Your containers come back after a restart of this machine only once Podman's own podman-restart.service starts them.")
}
diff --git a/fluxer_rexctl/cmd/install.go b/fluxer_rexctl/cmd/install.go
index 977b0d4c2..e68e169ce 100644
--- a/fluxer_rexctl/cmd/install.go
+++ b/fluxer_rexctl/cmd/install.go
@@ -126,10 +126,19 @@ func runInstall(ctx context.Context, app *App, c *cobra.Command, f *installFlags
if names := f.Setup.passedNames(c); f.SetupWhere == "browser" && len(names) > 0 {
return &ui.ExitError{Code: ui.ExitUsage, Msg: fmt.Sprintf("--setup browser doesn't take %s.", ui.JoinAnd(names)), Fix: "Pass --setup terminal instead, or leave out the setup options and enter them in the browser."}
}
- dir, err := app.Dir()
+ l, err := app.locate()
if err != nil {
return err
}
+ dir := l.Dir
+ switch {
+ case l.Stale != "" && l.Chosen:
+ dir = l.Stale
+ app.located = &instance.Located{Dir: dir, From: instance.FromRecord, Scope: l.Scope}
+ app.UI.Info("Installing Fluxer in %s, the folder you picked with rexctl use.", dir)
+ case l.Stale != "":
+ app.warnStale(l)
+ }
dir, err = filepath.Abs(dir)
if err != nil {
return err
@@ -1169,6 +1178,7 @@ func (in *installer) resume(ctx context.Context, inst *instance.Instance) error
func (in *installer) start(ctx context.Context, inst *instance.Instance) error {
u := in.app.UI
+ in.app.remember(inst.Dir)
origin := inst.Origin()
token := setup.Token(inst.State.Secrets)
if token == "" && !inst.State.SetupDone {
diff --git a/fluxer_rexctl/cmd/restore.go b/fluxer_rexctl/cmd/restore.go
index 4c2dc3090..8ceab67f1 100644
--- a/fluxer_rexctl/cmd/restore.go
+++ b/fluxer_rexctl/cmd/restore.go
@@ -163,6 +163,7 @@ func restoreInto(ctx context.Context, app *App, e *engine.Engine, path, dir stri
return engineFailure(err)
}
restoreBootUnit(ctx, app, inst, e, p, existing, old)
+ app.remember(inst.Dir)
err = app.UI.Step(ctx, "Starting Fluxer", func(ctx context.Context, s *ui.Step) error {
if err := p.WaitReady(ctx, restoreReadyTimeout, showReadiness(s, "Starting Fluxer")); err != nil {
return err
diff --git a/fluxer_rexctl/cmd/root.go b/fluxer_rexctl/cmd/root.go
index a4d748099..e28887439 100644
--- a/fluxer_rexctl/cmd/root.go
+++ b/fluxer_rexctl/cmd/root.go
@@ -117,6 +117,7 @@ func newRoot(app *App) *cobra.Command {
newUninstallCmd(app),
newTakeoverCmd(app),
newEjectCmd(app),
+ newUseCmd(app),
newProxyCmd(app),
newUsersCmd(app),
newAdminsCmd(app),
@@ -159,7 +160,7 @@ const (
)
var commandGroups = map[string][]string{
- "run": {"install", "setup", "status", "doctor", "logs", "start", "stop", "restart", "upgrade", "auto-upgrade", "rollback", "backup", "restore", "proxy", "takeover", "eject", "uninstall"},
+ "run": {"install", "setup", "status", "doctor", "logs", "start", "stop", "restart", "upgrade", "auto-upgrade", "rollback", "backup", "restore", "proxy", "takeover", "eject", "use", "uninstall"},
"manage": {"users", "admins", "invites", "registration", "email", "branding", "search", "config"},
"other": {"version", "docs"},
}
diff --git a/fluxer_rexctl/cmd/takeover.go b/fluxer_rexctl/cmd/takeover.go
index cb6509b8f..a5da55271 100644
--- a/fluxer_rexctl/cmd/takeover.go
+++ b/fluxer_rexctl/cmd/takeover.go
@@ -125,6 +125,7 @@ func takeoverDir(ctx context.Context, app *App, dir string, opts takeoverOptions
return nil, nil, err
}
installTakeoverBootUnit(ctx, app, inst, e)
+ app.remember(inst.Dir)
if e != nil {
sendAdminImport(ctx, app, inst, e)
}
diff --git a/fluxer_rexctl/cmd/uninstall.go b/fluxer_rexctl/cmd/uninstall.go
index 787313e9a..0f7a6b06d 100644
--- a/fluxer_rexctl/cmd/uninstall.go
+++ b/fluxer_rexctl/cmd/uninstall.go
@@ -84,6 +84,7 @@ func runUninstall(ctx context.Context, app *App, keepData bool, confirm string)
if err != nil {
return err
}
+ app.forget(inst.Dir)
if keepData {
app.UI.Info("Your data and backups are still in %s.", inst.Dir)
return nil
diff --git a/fluxer_rexctl/cmd/upgrade.go b/fluxer_rexctl/cmd/upgrade.go
index e456eae06..3641a266b 100644
--- a/fluxer_rexctl/cmd/upgrade.go
+++ b/fluxer_rexctl/cmd/upgrade.go
@@ -220,7 +220,7 @@ func runUpgrade(ctx context.Context, app *App, f *upgradeFlags) error {
if err != nil {
return err
}
- if err := reexec(resumeArgs(os.Args[1:], release.PhaseSelfUpdated)); err != nil {
+ if err := reexec(resumeArgs(os.Args[1:], release.PhaseSelfUpdated, app.pickedDir())); err != nil {
return ui.Wrap(err, "Updated rexctl but couldn't start it again.", "Run rexctl upgrade again.")
}
return nil
@@ -249,7 +249,7 @@ func updateBeforeRecovery(ctx context.Context, app *App, resume, to, command str
if err != nil {
return false, keepRexctl(ctx, app, fmt.Sprintf("Couldn't update rexctl to %s.", next), err)
}
- if err := reexec(resumeArgs(os.Args[1:], release.ResumeRecovery)); err != nil {
+ if err := reexec(resumeArgs(os.Args[1:], release.ResumeRecovery, app.pickedDir())); err != nil {
return true, ui.Wrap(err, "Updated rexctl but couldn't start it again.", fmt.Sprintf("Run %s again.", command))
}
return true, nil
@@ -1244,8 +1244,8 @@ func phaseIndex(phase string) int {
return -1
}
-func resumeArgs(args []string, phase string) []string {
- out := make([]string, 0, len(args)+2)
+func resumeArgs(args []string, phase, dir string) []string {
+ out := make([]string, 0, len(args)+4)
flag := "--" + release.ResumeFlag
for i := 0; i < len(args); i++ {
a := args[i]
@@ -1258,6 +1258,9 @@ func resumeArgs(args []string, phase string) []string {
}
out = append(out, a)
}
+ if dir != "" {
+ out = append(out, "--dir", dir)
+ }
return append(out, flag, phase)
}
diff --git a/fluxer_rexctl/cmd/use.go b/fluxer_rexctl/cmd/use.go
new file mode 100644
index 000000000..ae962ff67
--- /dev/null
+++ b/fluxer_rexctl/cmd/use.go
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package cmd
+
+import (
+ "errors"
+ "fmt"
+ "path/filepath"
+
+ "github.com/spf13/cobra"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
+)
+
+func newUseCmd(app *App) *cobra.Command {
+ return &cobra.Command{
+ Use: "use [folder]",
+ Short: "Show or change which instance rexctl uses",
+ Long: "Show which instance rexctl uses when you don't pass --dir and aren't in an instance folder, or pass a folder to use that instance from now on. " +
+ "rexctl remembers each instance it installs, so you only need this with more than one instance or one installed by an older rexctl. " +
+ "Each account has its own choice. Root's choice also applies to accounts that have no instance of their own. " +
+ "The services rexctl sets up for starting and upgrading Fluxer always name their folder, so this doesn't change them.",
+ Args: maxArgs(1),
+ RunE: func(c *cobra.Command, args []string) error {
+ if len(args) == 0 {
+ return runUseShow(app)
+ }
+ return runUse(app, args[0])
+ },
+ }
+}
+
+func runUseShow(app *App) error {
+ l, err := instance.Resolve(app.Flags.Dir)
+ var several *instance.SeveralError
+ switch {
+ case errors.As(err, &several):
+ app.UI.Info("This machine has Fluxer instances in %s, and none of them is the default.", ui.JoinAnd(several.Dirs))
+ app.UI.Info("Run rexctl use <folder> to pick one.")
+ return nil
+ case err != nil:
+ return untrustedRefusal(err)
+ }
+ if l.Stale != "" {
+ app.warnStale(l)
+ }
+ if _, err := instance.Find(l.Dir); errors.Is(err, instance.ErrNotFound) {
+ app.UI.Info("There's no Fluxer instance in %s (%s).", l.Dir, l.Why())
+ app.UI.Info("Run rexctl use <folder> with the folder Fluxer is in.")
+ return nil
+ }
+ app.UI.Result(fmt.Sprintf("Using %s (%s).", l.Dir, l.Why()))
+ return nil
+}
+
+func runUse(app *App, arg string) error {
+ dir, err := filepath.Abs(arg)
+ if err != nil {
+ return err
+ }
+ switch _, err := instance.Find(dir); {
+ case err == nil, errors.Is(err, instance.ErrLegacy):
+ case errors.Is(err, instance.ErrNotFound):
+ return ui.Refused(fmt.Sprintf("There's no Fluxer instance in %s.", dir), "Pass the folder your instance is in.")
+ default:
+ return ui.Wrap(err, fmt.Sprintf("rexctl can't read the instance in %s.", dir), "Run rexctl as the account that installed Fluxer.")
+ }
+ s := instance.OwnScope()
+ if err := instance.Remember(s, dir, true); err != nil {
+ return ui.Wrap(untrustedRefusal(err), fmt.Sprintf("Couldn't save %s.", instance.RecordPath(s)), "Check that you can write to it, then try again.")
+ }
+ if s == instance.ScopeMachine {
+ app.UI.OK("rexctl uses the instance in %s from now on, for root and for accounts that have no instance of their own.", dir)
+ } else {
+ app.UI.OK("rexctl uses the instance in %s for your account from now on.", dir)
+ }
+ return nil
+}
diff --git a/fluxer_rexctl/cmd/use_test.go b/fluxer_rexctl/cmd/use_test.go
new file mode 100644
index 000000000..b79aabd93
--- /dev/null
+++ b/fluxer_rexctl/cmd/use_test.go
@@ -0,0 +1,155 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package cmd
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/instance"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/release"
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/ui"
+)
+
+func TestMain(m *testing.M) {
+ home, err := os.MkdirTemp("", "rexctl-home")
+ if err != nil {
+ panic(err)
+ }
+ os.Setenv("HOME", home)
+ os.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ os.Setenv("AppData", filepath.Join(home, "AppData"))
+ instance.MachineRecordPath = filepath.Join(home, "etc", "rexctl", instance.RecordFileName)
+ code := m.Run()
+ os.RemoveAll(home)
+ os.Exit(code)
+}
+
+func clearRecords(t *testing.T) {
+ t.Helper()
+ for _, s := range []instance.Scope{instance.ScopeUser, instance.ScopeMachine} {
+ if err := instance.SaveRecord(s, instance.Record{}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ t.Cleanup(func() {
+ for _, s := range []instance.Scope{instance.ScopeUser, instance.ScopeMachine} {
+ _ = instance.SaveRecord(s, instance.Record{})
+ }
+ })
+}
+
+func recordApp(t *testing.T) (*App, string) {
+ t.Helper()
+ clearRecords(t)
+ inst, err := instance.Create(t.TempDir(), "fluxer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ out := &bytes.Buffer{}
+ return &App{
+ Flags: GlobalFlags{Dir: inst.Dir},
+ UI: ui.New(ui.Options{Stdin: strings.NewReader(""), Stdout: out, Stderr: out}),
+ }, inst.Dir
+}
+
+func resolved(t *testing.T, dir string) string {
+ t.Helper()
+ real, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return real
+}
+
+func TestFirstUseRecordsInstance(t *testing.T) {
+ app, dir := recordApp(t)
+ if _, err := app.Instance(); err != nil {
+ t.Fatal(err)
+ }
+ if got := instance.ReadRecord(instance.OwnScope()).Instances; !slices.Equal(got, []string{resolved(t, dir)}) {
+ t.Errorf("recorded = %v, want %s", got, dir)
+ }
+}
+
+func TestForgetRemovesInstance(t *testing.T) {
+ app, dir := recordApp(t)
+ if _, err := app.Instance(); err != nil {
+ t.Fatal(err)
+ }
+ app.forget(dir)
+ if r := instance.ReadRecord(instance.OwnScope()); !r.Empty() {
+ t.Errorf("recorded = %+v, want nothing", r)
+ }
+}
+
+func TestRememberWithDirKeepsStandardFolder(t *testing.T) {
+ app, dir := recordApp(t)
+ home, _ := os.UserHomeDir()
+ standard := filepath.Join(home, "fluxer")
+ inst, err := instance.Create(standard, "fluxer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(standard) })
+ if fb, _ := instance.Fallback(); fb != standard {
+ t.Skipf("the standard folder here is %s", fb)
+ }
+ app.remember(dir)
+ t.Chdir(t.TempDir())
+ l, err := instance.Resolve("")
+ if err != nil || l.Dir != resolved(t, standard) || l.From != instance.FromRecord {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestRerunKeepsThePickedInstance(t *testing.T) {
+ app, dir := recordApp(t)
+ app.Flags.Dir = ""
+ app.located = &instance.Located{Dir: dir, From: instance.FromPicked}
+ args := resumeArgs([]string{"upgrade", "--yes"}, release.PhaseSelfUpdated, app.pickedDir())
+ if !slices.Equal(args, []string{"upgrade", "--yes", "--dir", dir, "--" + release.ResumeFlag, release.PhaseSelfUpdated}) {
+ t.Errorf("resume args %q", args)
+ }
+ if got := app.takeOverCommand(); got != "rexctl takeover --dir "+dir {
+ t.Errorf("takeover command %q", got)
+ }
+ app.located = &instance.Located{Dir: dir, From: instance.FromWorkdir}
+ if args := resumeArgs([]string{"upgrade"}, release.PhaseSelfUpdated, app.pickedDir()); slices.Contains(args, "--dir") {
+ t.Errorf("resume args %q added --dir for the current folder", args)
+ }
+}
+
+func TestUseOnlyChangesTheRecord(t *testing.T) {
+ clearRecords(t)
+ app, inst, out := oldInstance(t, true)
+ tree := func() []string {
+ var files []string
+ _ = filepath.WalkDir(inst.Dir, func(path string, _ os.DirEntry, err error) error {
+ files = append(files, path)
+ return err
+ })
+ return files
+ }
+ before := tree()
+ if err := runUseShow(app); err != nil {
+ t.Fatalf("%v\n%s", err, out)
+ }
+ if err := runUse(app, inst.Dir); err != nil {
+ t.Fatalf("%v\n%s", err, out)
+ }
+ if after := tree(); !slices.Equal(before, after) {
+ t.Fatalf("rexctl use changed the instance folder:\n%v\n%v", before, after)
+ }
+ requireOldLayout(t, inst)
+}
diff --git a/fluxer_rexctl/internal/instance/instance.go b/fluxer_rexctl/internal/instance/instance.go
index 8189f20e7..385ff14af 100644
--- a/fluxer_rexctl/internal/instance/instance.go
+++ b/fluxer_rexctl/internal/instance/instance.go
@@ -8,9 +8,9 @@ import (
"io/fs"
"net"
"os"
+ "os/user"
"path/filepath"
"regexp"
- "runtime"
"slices"
"strings"
"time"
@@ -55,8 +55,16 @@ type Instance struct {
State *State
}
+var rootHome = func() (string, error) {
+ u, err := user.LookupId("0")
+ if err != nil {
+ return "", err
+ }
+ return u.HomeDir, nil
+}
+
func DefaultDir() (string, error) {
- if runtime.GOOS != "windows" && os.Geteuid() == 0 {
+ if asRoot() {
return "/opt/fluxer", nil
}
home, err := os.UserHomeDir()
@@ -66,15 +74,12 @@ func DefaultDir() (string, error) {
return filepath.Join(home, "fluxer"), nil
}
-func Locate() (string, error) {
- if wd, err := os.Getwd(); err == nil && present(wd) {
- return wd, nil
- }
+func Fallback() (string, error) {
dir, err := DefaultDir()
- if err != nil || present(dir) || runtime.GOOS == "windows" || os.Geteuid() != 0 {
+ if err != nil || present(dir) || !asRoot() {
return dir, err
}
- if home, err := os.UserHomeDir(); err == nil && present(filepath.Join(home, "fluxer")) {
+ if home, err := rootHome(); err == nil && filepath.IsAbs(home) && present(filepath.Join(home, "fluxer")) {
return filepath.Join(home, "fluxer"), nil
}
return dir, nil
diff --git a/fluxer_rexctl/internal/instance/owner_unix.go b/fluxer_rexctl/internal/instance/owner_unix.go
index af8b91335..ffddd4473 100644
--- a/fluxer_rexctl/internal/instance/owner_unix.go
+++ b/fluxer_rexctl/internal/instance/owner_unix.go
@@ -14,6 +14,10 @@ func (i *Instance) OwnerUID() (int, bool) {
if err != nil {
return 0, false
}
+ return ownerOf(info)
+}
+
+func ownerOf(info os.FileInfo) (int, bool) {
st, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return 0, false
diff --git a/fluxer_rexctl/internal/instance/owner_windows.go b/fluxer_rexctl/internal/instance/owner_windows.go
index 2e317dc49..1e8bf5d2f 100644
--- a/fluxer_rexctl/internal/instance/owner_windows.go
+++ b/fluxer_rexctl/internal/instance/owner_windows.go
@@ -4,6 +4,10 @@
package instance
+import "os"
+
func (i *Instance) OwnerUID() (int, bool) { return 0, false }
+func ownerOf(os.FileInfo) (int, bool) { return 0, false }
+
func (i *Instance) giveToOwner(string) error { return nil }
diff --git a/fluxer_rexctl/internal/instance/record.go b/fluxer_rexctl/internal/instance/record.go
new file mode 100644
index 000000000..fc77f6791
--- /dev/null
+++ b/fluxer_rexctl/internal/instance/record.go
@@ -0,0 +1,416 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package instance
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "time"
+
+ "github.com/fluxerapp/fluxer/fluxer_rexctl/internal/envfile"
+)
+
+const RecordFileName = "instances.json"
+
+var MachineRecordPath = "/etc/rexctl/" + RecordFileName
+
+var (
+ asRoot = func() bool { return runtime.GOOS != "windows" && euid() == 0 }
+ rootUID = 0
+)
+
+type Scope string
+
+const (
+ ScopeUser Scope = "user"
+ ScopeMachine Scope = "machine"
+)
+
+func OwnScope() Scope {
+ if asRoot() {
+ return ScopeMachine
+ }
+ return ScopeUser
+}
+
+type Record struct {
+ Default string `json:"default,omitempty"`
+ Used bool `json:"used,omitempty"`
+ Instances []string `json:"instances"`
+}
+
+type From int
+
+const (
+ FromFlag From = iota
+ FromWorkdir
+ FromRecord
+ FromOnly
+ FromPicked
+ FromFallback
+)
+
+type Located struct {
+ Dir string
+ From From
+ Scope Scope
+ Stale string
+ Chosen bool
+}
+
+func (l Located) Why() string {
+ switch l.From {
+ case FromFlag:
+ return "from --dir"
+ case FromWorkdir:
+ return "the current folder"
+ case FromPicked:
+ return "the one you picked"
+ case FromOnly:
+ return "the only instance rexctl remembers"
+ case FromRecord:
+ if l.Scope == ScopeMachine {
+ return "the default for this machine"
+ }
+ return "the default for your account"
+ }
+ return "the standard folder"
+}
+
+type SeveralError struct {
+ Dirs []string
+ Stale string
+}
+
+func (e *SeveralError) Error() string {
+ return fmt.Sprintf("instance: %d instances are recorded and none is the default", len(e.Dirs))
+}
+
+type UntrustedError struct {
+ Path string
+ Folder bool
+}
+
+func (e *UntrustedError) Error() string {
+ return fmt.Sprintf("instance: accounts other than root can change %s", e.Path)
+}
+
+func RecordPath(s Scope) string {
+ if s == ScopeMachine {
+ if runtime.GOOS == "windows" {
+ return ""
+ }
+ return MachineRecordPath
+ }
+ dir, err := os.UserConfigDir()
+ if err != nil {
+ return ""
+ }
+ return filepath.Join(dir, "rexctl", RecordFileName)
+}
+
+func scopes() []Scope {
+ if asRoot() {
+ return []Scope{ScopeMachine}
+ }
+ return []Scope{ScopeUser, ScopeMachine}
+}
+
+func ReadRecord(s Scope) Record {
+ r, _ := loadRecord(s)
+ return r
+}
+
+func loadRecord(s Scope) (Record, error) {
+ var r Record
+ path := RecordPath(s)
+ if path == "" {
+ return r, nil
+ }
+ if s == ScopeMachine && asRoot() {
+ for _, p := range []string{filepath.Dir(path), path} {
+ if !rootOnly(p, true) {
+ return r, &UntrustedError{Path: p}
+ }
+ }
+ }
+ data, err := os.ReadFile(path)
+ if err != nil || json.Unmarshal(data, &r) != nil {
+ return Record{}, nil
+ }
+ return r, nil
+}
+
+func rootOnly(path string, owned bool) bool {
+ info, err := os.Stat(path)
+ if errors.Is(err, fs.ErrNotExist) {
+ return true
+ }
+ if err != nil || info.Mode().Perm()&0o022 != 0 {
+ return false
+ }
+ if !owned {
+ return true
+ }
+ uid, ok := ownerOf(info)
+ return ok && uid == rootUID
+}
+
+func (r Record) Has(dir string) bool {
+ return slices.ContainsFunc(r.Instances, func(d string) bool { return same(d, dir) })
+}
+
+func (r Record) Empty() bool { return len(r.Instances) == 0 && r.Default == "" }
+
+func (r Record) With(dir string) Record {
+ dir = clean(dir)
+ out := Record{Default: r.Default, Used: r.Used}
+ for _, d := range r.Instances {
+ if !same(d, dir) && !gone(d) {
+ out.Instances = append(out.Instances, d)
+ }
+ }
+ out.Instances = append(out.Instances, dir)
+ if out.Default != "" && !out.Used && gone(out.Default) {
+ out.Default = ""
+ }
+ return out
+}
+
+func (r Record) Without(dir string) Record {
+ out := Record{Default: r.Default, Used: r.Used, Instances: slices.DeleteFunc(slices.Clone(r.Instances), func(d string) bool { return same(d, dir) })}
+ if same(out.Default, dir) {
+ out.Default, out.Used = "", false
+ }
+ return out
+}
+
+func (r Record) pruned() Record {
+ out := Record{Default: r.Default, Used: r.Used}
+ for _, d := range r.Instances {
+ if !gone(d) {
+ out.Instances = append(out.Instances, d)
+ }
+ }
+ if out.Default != "" && !out.Used && gone(out.Default) {
+ out.Default = ""
+ }
+ return out
+}
+
+func (r Record) remember(dir string, makeDefault bool) Record {
+ dir = clean(dir)
+ if r.Empty() && !makeDefault {
+ if fb, err := Fallback(); err == nil && present(fb) && !same(fb, dir) {
+ r = Record{Default: clean(fb), Instances: []string{clean(fb)}}
+ }
+ }
+ var others []string
+ for _, d := range r.Instances {
+ if !same(d, dir) && !gone(d) {
+ others = append(others, d)
+ }
+ }
+ out := r.With(dir)
+ switch {
+ case makeDefault:
+ out.Default, out.Used = dir, true
+ case out.Default == "" && len(others) == 1:
+ out.Default, out.Used = others[0], false
+ }
+ return out
+}
+
+func (r Record) Encode() []byte {
+ if r.Instances == nil {
+ r.Instances = []string{}
+ }
+ data, _ := json.MarshalIndent(r, "", " ")
+ return append(data, '\n')
+}
+
+func SaveRecord(s Scope, r Record) error {
+ path := RecordPath(s)
+ if path == "" {
+ return errors.New("instance: no place to record instances on this system")
+ }
+ if r.Empty() {
+ if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ return err
+ }
+ return nil
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ return envfile.WriteFileAtomic(path, r.Encode(), false)
+}
+
+func updateRecord(s Scope, fn func(Record) Record) error {
+ path := RecordPath(s)
+ if path == "" {
+ return errors.New("instance: no place to record instances on this system")
+ }
+ if s == ScopeUser && asRoot() {
+ return errors.New("instance: root doesn't keep a record per account")
+ }
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ f, err := os.OpenFile(path+".lock", os.O_RDWR|os.O_CREATE, 0o644)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ err := tryLock(f)
+ if err == nil {
+ break
+ }
+ if !errors.Is(err, ErrLocked) || time.Now().After(deadline) {
+ return err
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ defer unlock(f)
+ r, err := loadRecord(s)
+ if err != nil {
+ return err
+ }
+ next := fn(r)
+ if slices.Equal(next.Encode(), r.Encode()) {
+ return nil
+ }
+ return SaveRecord(s, next)
+}
+
+func Remember(s Scope, dir string, makeDefault bool) error {
+ return updateRecord(s, func(r Record) Record { return r.remember(dir, makeDefault) })
+}
+
+func RememberFirst(s Scope, dir string) error {
+ return updateRecord(s, func(r Record) Record {
+ if !r.Empty() {
+ return r
+ }
+ return r.remember(dir, false)
+ })
+}
+
+func Forget(s Scope, dir string) error {
+ return updateRecord(s, func(r Record) Record { return r.Without(dir) })
+}
+
+func pickRecorded(r Record, s Scope) (Located, bool, error) {
+ var live []string
+ for _, d := range r.Instances {
+ if !gone(d) && (s == ScopeUser || asRoot() || readable(d)) {
+ live = append(live, clean(d))
+ }
+ }
+ l := Located{Scope: s}
+ if r.Default != "" {
+ def := clean(r.Default)
+ if !gone(def) && (s == ScopeUser || asRoot() || readable(def)) {
+ l.Dir, l.From = def, FromRecord
+ return l, true, nil
+ }
+ if gone(def) {
+ l.Stale, l.Chosen = def, r.Used
+ }
+ }
+ switch len(live) {
+ case 0:
+ return l, false, nil
+ case 1:
+ l.Dir, l.From = live[0], FromOnly
+ return l, true, nil
+ }
+ return l, false, &SeveralError{Dirs: live, Stale: l.Stale}
+}
+
+func Resolve(flag string) (Located, error) {
+ if flag != "" {
+ return Located{Dir: flag, From: FromFlag}, nil
+ }
+ if wd, err := os.Getwd(); err == nil && present(wd) {
+ return Located{Dir: wd, From: FromWorkdir}, nil
+ }
+ var stale Located
+ for _, s := range scopes() {
+ if s == ScopeMachine && !asRoot() {
+ if dir, err := DefaultDir(); err == nil && present(dir) {
+ return Located{Dir: dir, From: FromFallback, Stale: stale.Stale, Chosen: stale.Chosen}, nil
+ }
+ }
+ r, err := loadRecord(s)
+ if err != nil {
+ return Located{}, err
+ }
+ l, ok, err := pickRecorded(r, s)
+ if err != nil {
+ return l, err
+ }
+ if ok && asRoot() && !rootOnly(l.Dir, false) {
+ return l, &UntrustedError{Path: l.Dir, Folder: true}
+ }
+ if ok {
+ if l.Stale == "" {
+ l.Stale, l.Chosen = stale.Stale, stale.Chosen
+ }
+ return l, nil
+ }
+ if stale.Stale == "" {
+ stale = l
+ }
+ if s == OwnScope() && !r.Empty() {
+ _ = updateRecord(s, Record.pruned)
+ }
+ }
+ dir, err := Fallback()
+ return Located{Dir: dir, From: FromFallback, Stale: stale.Stale, Chosen: stale.Chosen}, err
+}
+
+func gone(dir string) bool {
+ _, err := os.Stat(filepath.Join(dir, StateDirName, StateFileName))
+ return errors.Is(err, fs.ErrNotExist) && !isLegacy(dir)
+}
+
+func readable(dir string) bool {
+ f, err := os.Open(filepath.Join(dir, StateDirName, StateFileName))
+ if err == nil {
+ f.Close()
+ return true
+ }
+ return isLegacy(dir)
+}
+
+func clean(dir string) string {
+ abs, err := filepath.Abs(dir)
+ if err != nil {
+ return filepath.Clean(dir)
+ }
+ if real, err := filepath.EvalSymlinks(abs); err == nil {
+ return real
+ }
+ return abs
+}
+
+func same(a, b string) bool {
+ if a == "" || b == "" {
+ return a == b
+ }
+ a, b = clean(a), clean(b)
+ if runtime.GOOS == "windows" {
+ return strings.EqualFold(a, b)
+ }
+ return a == b
+}
diff --git a/fluxer_rexctl/internal/instance/record_test.go b/fluxer_rexctl/internal/instance/record_test.go
new file mode 100644
index 000000000..d3a87c133
--- /dev/null
+++ b/fluxer_rexctl/internal/instance/record_test.go
@@ -0,0 +1,415 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package instance
+
+import (
+ "errors"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+)
+
+func isolateRecords(t *testing.T) string {
+ t.Helper()
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("AppData", filepath.Join(home, "AppData"))
+ old := MachineRecordPath
+ MachineRecordPath = filepath.Join(t.TempDir(), "etc", "rexctl", RecordFileName)
+ t.Cleanup(func() { MachineRecordPath = old })
+ oldRoot := asRoot
+ asRoot = func() bool { return false }
+ t.Cleanup(func() { asRoot = oldRoot })
+ t.Chdir(t.TempDir())
+ return home
+}
+
+func actAsRoot(t *testing.T) {
+ t.Helper()
+ if runtime.GOOS == "windows" {
+ t.Skip("there's no machine record on Windows")
+ }
+ oldRoot, oldUID := asRoot, rootUID
+ asRoot, rootUID = func() bool { return true }, os.Getuid()
+ t.Cleanup(func() { asRoot, rootUID = oldRoot, oldUID })
+}
+
+func managedAt(t *testing.T, dir string) string {
+ t.Helper()
+ inst, err := Create(dir, "fluxer")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := inst.Save(); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(inst.Dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return clean(inst.Dir)
+}
+
+func record(t *testing.T, s Scope, r Record) {
+ t.Helper()
+ if err := SaveRecord(s, r); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func remember(t *testing.T, s Scope, dir string, makeDefault bool) {
+ t.Helper()
+ if err := Remember(s, dir, makeDefault); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestResolveOrder(t *testing.T) {
+ isolateRecords(t)
+ here := managedAt(t, t.TempDir())
+ saved := managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Default: saved, Instances: []string{saved}})
+ elsewhere, _ := os.Getwd()
+
+ t.Chdir(here)
+ if l, _ := Resolve("/srv/other"); l.From != FromFlag || l.Dir != "/srv/other" {
+ t.Errorf("with --dir = %+v", l)
+ }
+ if l, _ := Resolve(""); l.From != FromWorkdir || clean(l.Dir) != here {
+ t.Errorf("inside an instance = %+v", l)
+ }
+ t.Chdir(elsewhere)
+ if l, _ := Resolve(""); l.From != FromRecord || l.Dir != saved {
+ t.Errorf("with a record = %+v", l)
+ }
+ record(t, ScopeUser, Record{})
+ fallback, _ := Fallback()
+ if l, _ := Resolve(""); l.From != FromFallback || l.Dir != fallback {
+ t.Errorf("with nothing recorded = %+v, want %s", l, fallback)
+ }
+}
+
+func TestResolveSeveralAsks(t *testing.T) {
+ isolateRecords(t)
+ a, b := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Instances: []string{a, b}})
+ _, err := Resolve("")
+ var several *SeveralError
+ if !errors.As(err, &several) || !slices.Equal(several.Dirs, []string{a, b}) {
+ t.Errorf("err = %v", err)
+ }
+}
+
+func TestOnlyRecordSaysSo(t *testing.T) {
+ isolateRecords(t)
+ dir := managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Instances: []string{dir}})
+ l, err := Resolve("")
+ if err != nil || l.Dir != dir || l.Why() != "the only instance rexctl remembers" {
+ t.Errorf("Resolve = %+v (%s), %v", l, l.Why(), err)
+ }
+}
+
+func TestStaleDefaultUsesTheLiveOne(t *testing.T) {
+ isolateRecords(t)
+ old, live := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Default: old, Instances: []string{old, live}})
+ if err := os.RemoveAll(old); err != nil {
+ t.Fatal(err)
+ }
+ l, err := Resolve("")
+ if err != nil || l.Dir != live || l.Stale != old {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestStaleDefaultWithSeveralListsThem(t *testing.T) {
+ isolateRecords(t)
+ old, a, b := managedAt(t, t.TempDir()), managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Default: old, Instances: []string{old, a, b}})
+ if err := os.RemoveAll(old); err != nil {
+ t.Fatal(err)
+ }
+ _, err := Resolve("")
+ var several *SeveralError
+ if !errors.As(err, &several) || !slices.Equal(several.Dirs, []string{a, b}) || several.Stale != old {
+ t.Errorf("err = %+v", err)
+ }
+}
+
+func TestAllGoneFallsBackAndForgets(t *testing.T) {
+ isolateRecords(t)
+ dir := managedAt(t, t.TempDir())
+ remember(t, ScopeUser, dir, false)
+ if err := os.RemoveAll(dir); err != nil {
+ t.Fatal(err)
+ }
+ l, err := Resolve("")
+ if fb, _ := Fallback(); err != nil || l.From != FromFallback || l.Dir != fb || l.Stale != "" {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+ if r := ReadRecord(ScopeUser); !r.Empty() {
+ t.Errorf("record kept %+v", r)
+ }
+}
+
+func TestOnlyAChosenStaleDefaultIsKept(t *testing.T) {
+ isolateRecords(t)
+ chosen := managedAt(t, t.TempDir())
+ remember(t, ScopeUser, chosen, true)
+ if err := os.RemoveAll(chosen); err != nil {
+ t.Fatal(err)
+ }
+ l, err := Resolve("")
+ if err != nil || l.From != FromFallback || l.Stale != chosen || !l.Chosen {
+ t.Errorf("chosen: Resolve = %+v, %v", l, err)
+ }
+ if l, _ := Resolve(""); l.Stale != chosen {
+ t.Errorf("the chosen default was forgotten: %+v", l)
+ }
+
+ auto, other := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{})
+ remember(t, ScopeUser, auto, false)
+ remember(t, ScopeUser, other, false)
+ if r := ReadRecord(ScopeUser); r.Default != auto || r.Used {
+ t.Fatalf("record %+v", r)
+ }
+ if err := os.RemoveAll(auto); err != nil {
+ t.Fatal(err)
+ }
+ if l, err := Resolve(""); err != nil || l.Chosen || l.Dir != other {
+ t.Errorf("automatic: Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestRememberKeepsTheFirstAsDefault(t *testing.T) {
+ isolateRecords(t)
+ first, second := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
+ remember(t, ScopeUser, first, false)
+ remember(t, ScopeUser, second, false)
+ if l, err := Resolve(""); err != nil || l.Dir != first {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestRememberTakesTheDefaultFromItsOwnScope(t *testing.T) {
+ isolateRecords(t)
+ machine := managedAt(t, t.TempDir())
+ record(t, ScopeMachine, Record{Instances: []string{machine}})
+ first, second := managedAt(t, t.TempDir()), managedAt(t, t.TempDir())
+ remember(t, ScopeUser, first, false)
+ remember(t, ScopeUser, second, false)
+ r := ReadRecord(ScopeUser)
+ if r.Default != first || !slices.Equal(r.Instances, []string{first, second}) {
+ t.Errorf("user record = %+v", r)
+ }
+}
+
+func TestRememberFirstKeepsStandardFolder(t *testing.T) {
+ home := isolateRecords(t)
+ standard := managedAt(t, filepath.Join(home, "fluxer"))
+ other := managedAt(t, t.TempDir())
+ if fb, _ := Fallback(); clean(fb) != standard {
+ t.Skipf("the standard folder here is %s", fb)
+ }
+ if err := RememberFirst(ScopeUser, other); err != nil {
+ t.Fatal(err)
+ }
+ if r := ReadRecord(ScopeUser); r.Default != standard || !slices.Equal(r.Instances, []string{standard, other}) {
+ t.Errorf("record = %+v", r)
+ }
+}
+
+func TestRememberFirstLooksOnlyAtItsOwnScope(t *testing.T) {
+ isolateRecords(t)
+ machine := managedAt(t, t.TempDir())
+ record(t, ScopeMachine, Record{Default: machine, Instances: []string{machine}})
+ mine := managedAt(t, t.TempDir())
+ if err := RememberFirst(ScopeUser, mine); err != nil {
+ t.Fatal(err)
+ }
+ if r := ReadRecord(ScopeUser); !slices.Equal(r.Instances, []string{mine}) {
+ t.Errorf("user record = %+v", r)
+ }
+ if l, err := Resolve(""); err != nil || l.Dir != mine {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestStandardFolderComesBeforeTheMachineRecord(t *testing.T) {
+ home := isolateRecords(t)
+ if asRoot() {
+ t.Skip("runs as root")
+ }
+ standard := managedAt(t, filepath.Join(home, "fluxer"))
+ machine := managedAt(t, t.TempDir())
+ record(t, ScopeMachine, Record{Default: machine, Instances: []string{machine}})
+ if l, err := Resolve(""); err != nil || clean(l.Dir) != standard || l.From != FromFallback {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestMachineRecordSkipsInstancesYouCantRead(t *testing.T) {
+ isolateRecords(t)
+ if runtime.GOOS == "windows" || os.Geteuid() == 0 {
+ t.Skip("needs file permissions that keep this account out")
+ }
+ theirs := managedAt(t, t.TempDir())
+ record(t, ScopeMachine, Record{Default: theirs, Instances: []string{theirs}})
+ if err := os.Chmod(filepath.Join(theirs, StateDirName), 0); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.Chmod(filepath.Join(theirs, StateDirName), 0o700) })
+ if l, err := Resolve(""); err != nil || l.From != FromFallback {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestRootIgnoresTheUserRecord(t *testing.T) {
+ isolateRecords(t)
+ user := managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Default: user, Instances: []string{user}})
+ actAsRoot(t)
+ if l, err := Resolve(""); err != nil || l.From != FromFallback {
+ t.Errorf("only a user record: Resolve = %+v, %v", l, err)
+ }
+ machine := managedAt(t, t.TempDir())
+ if OwnScope() != ScopeMachine {
+ t.Fatal("root records in the user scope")
+ }
+ remember(t, OwnScope(), machine, false)
+ if l, err := Resolve(""); err != nil || l.Dir != machine || l.Scope != ScopeMachine {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+ if err := Remember(ScopeUser, user, true); err == nil {
+ t.Error("root wrote a user record")
+ }
+}
+
+func TestRootRefusesRecordsOthersCanChange(t *testing.T) {
+ isolateRecords(t)
+ actAsRoot(t)
+ dir := managedAt(t, t.TempDir())
+ remember(t, ScopeMachine, dir, true)
+ if l, err := Resolve(""); err != nil || l.Dir != dir {
+ t.Fatalf("Resolve = %+v, %v", l, err)
+ }
+ if err := os.Chmod(MachineRecordPath, 0o666); err != nil {
+ t.Fatal(err)
+ }
+ var untrusted *UntrustedError
+ if _, err := Resolve(""); !errors.As(err, &untrusted) || untrusted.Path != MachineRecordPath {
+ t.Errorf("writable record: err = %v", err)
+ }
+ if err := os.Chmod(MachineRecordPath, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(dir, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Resolve(""); !errors.As(err, &untrusted) || !untrusted.Folder || clean(untrusted.Path) != dir {
+ t.Errorf("writable folder: err = %v", err)
+ }
+ rootUID = os.Getuid() + 1
+ if _, err := Resolve(""); !errors.As(err, &untrusted) || untrusted.Folder {
+ t.Errorf("record owned by another account: err = %v", err)
+ }
+}
+
+func TestSymlinkRecordsTheSameInstance(t *testing.T) {
+ isolateRecords(t)
+ dir := managedAt(t, t.TempDir())
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Skip(err)
+ }
+ remember(t, ScopeUser, dir, false)
+ remember(t, ScopeUser, link, false)
+ if r := ReadRecord(ScopeUser); !slices.Equal(r.Instances, []string{dir}) {
+ t.Errorf("record = %+v", r)
+ }
+}
+
+func TestSameIgnoresCaseOnWindows(t *testing.T) {
+ if runtime.GOOS != "windows" {
+ t.Skip("only Windows paths ignore case")
+ }
+ if !same(`C:\Fluxer`, `c:\fluxer`) {
+ t.Error("the same folder in another case counts as another instance")
+ }
+}
+
+func TestRememberAtTheSameTimeKeepsEveryInstance(t *testing.T) {
+ isolateRecords(t)
+ var dirs []string
+ for range 12 {
+ dirs = append(dirs, managedAt(t, t.TempDir()))
+ }
+ var wg sync.WaitGroup
+ errs := make(chan error, len(dirs))
+ for _, d := range dirs {
+ wg.Go(func() { errs <- Remember(ScopeUser, d, false) })
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ got := ReadRecord(ScopeUser).Instances
+ for _, d := range dirs {
+ if !slices.Contains(got, d) {
+ t.Fatalf("lost %s, record has %d of %d", d, len(got), len(dirs))
+ }
+ }
+}
+
+func TestUserRecordLivesInHome(t *testing.T) {
+ home := isolateRecords(t)
+ want := map[string]string{
+ "linux": filepath.Join(home, ".config"),
+ "darwin": filepath.Join(home, "Library", "Application Support"),
+ "windows": filepath.Join(home, "AppData"),
+ }[runtime.GOOS]
+ if want == "" {
+ t.Skipf("no known config folder on %s", runtime.GOOS)
+ }
+ want = filepath.Join(want, "rexctl", RecordFileName)
+ if got := RecordPath(ScopeUser); got != want || !strings.HasPrefix(got, home) {
+ t.Fatalf("user record = %s, want %s", got, want)
+ }
+ dir := managedAt(t, t.TempDir())
+ record(t, ScopeUser, Record{Instances: []string{dir}})
+ if _, err := os.Stat(want); err != nil {
+ t.Fatal(err)
+ }
+ if l, err := Resolve(""); err != nil || l.Dir != dir || l.Scope != ScopeUser {
+ t.Errorf("Resolve = %+v, %v", l, err)
+ }
+}
+
+func TestRootLooksInItsOwnHomeNotHOME(t *testing.T) {
+ home := isolateRecords(t)
+ actAsRoot(t)
+ rootsHome := t.TempDir()
+ prev := rootHome
+ rootHome = func() (string, error) { return rootsHome, nil }
+ t.Cleanup(func() { rootHome = prev })
+ theirs := managedAt(t, filepath.Join(home, "fluxer"))
+ if fb, err := Fallback(); err != nil || same(fb, theirs) {
+ t.Fatalf("root followed $HOME to %s, %v", fb, err)
+ }
+ if l, err := Resolve(""); err != nil || same(l.Dir, theirs) {
+ t.Fatalf("Resolve = %+v, %v", l, err)
+ }
+ mine := managedAt(t, filepath.Join(rootsHome, "fluxer"))
+ if fb, err := Fallback(); err != nil || !same(fb, mine) {
+ t.Fatalf("Fallback = %s, %v, want root's own %s", fb, err, mine)
+ }
+}