Skip to content

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

11.6 KB
Raw Blame
package lifecycle

import (
	"errors"
	"io/fs"
	"os"
	"path/filepath"
	"strings"
	"testing"

	endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/loggroup"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
	"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv"
	"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)

// A repair or package upgrade re-runs install, which rebuilds config.json. A restricted log that
// came back shared would be world-writable again with nobody having asked for it.
func TestBuildConfigKeepsTheLogAccessMode(t *testing.T) {
	testenv.SetHome(t, t.TempDir())
	writeInventoryConfig(t, true, `{"user_mode":true,"log_path":"/tmp/runtime.jsonl","log_access":"restricted"}`)
	if cfg := buildConfig(InstallOptions{UserMode: true}); cfg.LogAccess != "restricted" {
		t.Fatalf("LogAccess = %q, want the existing mode carried over", cfg.LogAccess)
	}
	if cfg := buildConfig(InstallOptions{UserMode: true, LogAccess: "shared"}); cfg.LogAccess != "shared" {
		t.Fatalf("LogAccess = %q, want the explicit option to win", cfg.LogAccess)
	}
}

func TestBuildConfigWithoutAnExistingConfigIsShared(t *testing.T) {
	testenv.SetHome(t, t.TempDir())
	if cfg := buildConfig(InstallOptions{UserMode: true}); cfg.LogAccess != "" || cfg.RestrictedLogAccess() {
		t.Fatalf("a fresh install has log access %q", cfg.LogAccess)
	}
}

// uninstall --keep-logs removes config.json but keeps the log, its archives and the marker. A
// reinstall without --log-access must keep them restricted rather than share them.
func TestBuildConfigWithoutAConfigKeepsTheModeTheMarkerRecords(t *testing.T) {
	testenv.SetHome(t, t.TempDir())
	if _, err := endpointconfig.Load(false); err == nil {
		t.Skip("this machine has a system endpoint config")
	}
	logPath := filepath.Join(t.TempDir(), "beacon-agent", "runtime.jsonl")
	// The real check trusts only a root-owned marker; this stands in for one beside logPath.
	prev := logIsRestricted
	logIsRestricted = func(path string) bool { return path == logPath }
	t.Cleanup(func() { logIsRestricted = prev })
	if cfg := buildConfig(InstallOptions{LogPath: logPath}); cfg.LogAccess != asymptoteobserve.LogAccessRestricted {
		t.Fatalf("LogAccess = %q, want the marker's restricted mode kept", cfg.LogAccess)
	}
	if cfg := buildConfig(InstallOptions{LogPath: logPath, LogAccess: "shared"}); cfg.LogAccess != "shared" {
		t.Fatalf("LogAccess = %q, want an explicit shared to win", cfg.LogAccess)
	}
}

func TestValidateLogAccess(t *testing.T) {
	system := func(mode string) endpointconfig.Config {
		return endpointconfig.Config{UserMode: false, LogAccess: mode}
	}
	for _, mode := range []string{"", "shared", "Shared"} {
		if err := validateLogAccess(system(mode)); err != nil {
			t.Errorf("validateLogAccess(%q) = %v", mode, err)
		}
	}
	if err := validateLogAccess(system("open")); err == nil {
		t.Error("accepted an unknown mode")
	}
	err := validateLogAccess(endpointconfig.Config{UserMode: true, LogAccess: "restricted"})
	if err == nil || !strings.Contains(err.Error(), "system install") {
		t.Errorf("restricted in user mode = %v, want a refusal naming the system install", err)
	}
	if err := validateLogAccess(system("restricted")); err != nil {
		t.Errorf("restricted on a system install = %v", err)
	}
}

type logAccessCalls struct {
	ensured      []string
	restricted   []int
	shared       int
	staleRemoved int
}

func fakeLogAccess(t *testing.T, gid int, created bool, ensureErr, restrictErr error) *logAccessCalls {
	t.Helper()
	calls := &logAccessCalls{}
	prevEnsure, prevRestrict, prevShare := ensureLogReadersGroup, restrictSystemLog, shareSystemLog
	t.Cleanup(func() { ensureLogReadersGroup, restrictSystemLog, shareSystemLog = prevEnsure, prevRestrict, prevShare })
	ensureLogReadersGroup = func(name string) (int, bool, error) {
		calls.ensured = append(calls.ensured, name)
		return gid, created, ensureErr
	}
	restrictSystemLog = func(path string, g int) error {
		calls.restricted = append(calls.restricted, g)
		return restrictErr
	}
	shareSystemLog = func(string) error {
		calls.shared++
		return nil
	}
	prevStale := removeStaleIngestSocket
	removeStaleIngestSocket = func(string) error { calls.staleRemoved++; return nil }
	t.Cleanup(func() { removeStaleIngestSocket = prevStale })
	return calls
}

func TestPrepareSystemLogRestricts(t *testing.T) {
	calls := fakeLogAccess(t, 4242, true, nil, nil)
	created, err := prepareSystemLog(endpointconfig.Config{LogPath: "/var/log/beacon-agent/runtime.jsonl", LogAccess: "restricted"})
	if err != nil || !created {
		t.Fatalf("prepareSystemLog = %v, %v", created, err)
	}
	if len(calls.ensured) != 1 || calls.ensured[0] != loggroup.Name {
		t.Fatalf("ensured groups %v", calls.ensured)
	}
	if len(calls.restricted) != 1 || calls.restricted[0] != 4242 || calls.shared != 0 {
		t.Fatalf("calls = %+v", calls)
	}
}

func TestPrepareSystemLogShares(t *testing.T) {
	calls := fakeLogAccess(t, 0, false, nil, nil)
	if _, err := prepareSystemLog(endpointconfig.Config{LogPath: "/var/log/beacon-agent/runtime.jsonl"}); err != nil {
		t.Fatal(err)
	}
	if calls.shared != 1 || calls.staleRemoved != 1 || len(calls.ensured) != 0 || len(calls.restricted) != 0 {
		t.Fatalf("calls = %+v", calls)
	}
}

func TestPrepareSystemLogStopsWhenTheGroupCannotBeMade(t *testing.T) {
	calls := fakeLogAccess(t, 0, false, errors.New("groupadd: permission denied"), nil)
	_, err := prepareSystemLog(endpointconfig.Config{LogPath: "/var/log/beacon-agent/runtime.jsonl", LogAccess: "restricted"})
	if err == nil || !strings.Contains(err.Error(), loggroup.Name) {
		t.Fatalf("err = %v", err)
	}
	if len(calls.restricted) != 0 {
		t.Fatal("narrowed the log without a group to give readers")
	}
}

func TestLogAccessOf(t *testing.T) {
	if got := logAccessOf(endpointconfig.Config{UserMode: true, LogAccess: "restricted"}); got != "" {
		t.Fatalf("user mode = %q", got)
	}
	if got := logAccessOf(endpointconfig.Config{}); got != "shared" {
		t.Fatalf("system default = %q", got)
	}
	if got := logAccessOf(endpointconfig.Config{LogAccess: "restricted"}); got != "restricted" {
		t.Fatalf("restricted = %q", got)
	}
}

func TestLogAccessRestorerPutsBackWhatAFailedInstallChanged(t *testing.T) {
	restricted := false
	prev := logIsRestricted
	logIsRestricted = func(string) bool { return restricted }
	t.Cleanup(func() { logIsRestricted = prev })
	calls := fakeLogAccess(t, 77, false, nil, nil)
	// An existing log: one with nothing beside it is removed instead (below).
	cfg := endpointconfig.Config{LogPath: filepath.Join(t.TempDir(), "runtime.jsonl")}
	if err := os.WriteFile(cfg.LogPath, []byte("{}\n"), 0o600); err != nil {
		t.Fatal(err)
	}

	// Shared before; the failed install restricted it.
	restore := logAccessRestorer(cfg)
	restricted = true
	restore()
	if calls.shared != 1 || len(calls.restricted) != 0 {
		t.Fatalf("restoring a shared log: %+v", calls)
	}

	// Restricted before; the failed install shared it.
	restricted = true
	restore = logAccessRestorer(cfg)
	restricted = false
	restore()
	if len(calls.restricted) != 1 || calls.restricted[0] != 77 {
		t.Fatalf("restoring a restricted log: %+v", calls)
	}

	// Unchanged: nothing to do.
	restore = logAccessRestorer(cfg)
	restore()
	if calls.shared != 1 || len(calls.restricted) != 1 {
		t.Fatalf("an unchanged mode was touched: %+v", calls)
	}
}

// A failed first install must leave no log behind. The package install scripts read a log without
// a system config as one kept by uninstall --keep-logs and keep its mode, so a leftover log would
// turn the retry of a first MSI install into a shared one, and stop every script adding the person
// who installed to the readers group.
func TestLogAccessRestorerRemovesTheFilesAFailedFirstInstallCreated(t *testing.T) {
	dir := t.TempDir()
	cfg := endpointconfig.Config{LogPath: filepath.Join(dir, "runtime.jsonl"), LogAccess: "restricted"}
	marker := asymptoteobserve.LogAccessMarkerPath(cfg.LogPath)
	calls := fakeLogAccess(t, 77, true, nil, nil)
	restricted := false
	prev := logIsRestricted
	logIsRestricted = func(string) bool { return restricted }
	t.Cleanup(func() { logIsRestricted = prev })

	restore := logAccessRestorer(cfg)
	// What restricting a missing log creates, plus a file the install did not create.
	for _, path := range []string{cfg.LogPath, cfg.LogPath + ".lock", marker, filepath.Join(dir, "other")} {
		if err := os.WriteFile(path, []byte("x"), 0o600); err != nil {
			t.Fatal(err)
		}
	}
	restricted = true
	restore()
	for _, path := range []string{cfg.LogPath, cfg.LogPath + ".lock", marker} {
		if _, err := os.Lstat(path); !errors.Is(err, fs.ErrNotExist) {
			t.Fatalf("%s survived the rollback of the install that created it (%v)", path, err)
		}
	}
	if _, err := os.Lstat(filepath.Join(dir, "other")); err != nil {
		t.Fatalf("removed a file the install did not create: %v", err)
	}
	if calls.shared != 0 || len(calls.restricted) != 0 {
		t.Fatalf("chose a mode for files it removed: %+v", calls)
	}
}

// A lock or marker that was already there, without a log, belongs to someone else's state: only
// the files that were absent are removed.
func TestLogAccessRestorerKeepsFilesThatExistedBefore(t *testing.T) {
	dir := t.TempDir()
	cfg := endpointconfig.Config{LogPath: filepath.Join(dir, "runtime.jsonl")}
	fakeLogAccess(t, 0, false, nil, nil)
	if err := os.WriteFile(cfg.LogPath+".lock", nil, 0o600); err != nil {
		t.Fatal(err)
	}
	restore := logAccessRestorer(cfg)
	if err := os.WriteFile(cfg.LogPath, []byte("x"), 0o600); err != nil {
		t.Fatal(err)
	}
	restore()
	if _, err := os.Lstat(cfg.LogPath); !errors.Is(err, fs.ErrNotExist) {
		t.Fatalf("the log the install created survived: %v", err)
	}
	if _, err := os.Lstat(cfg.LogPath + ".lock"); err != nil {
		t.Fatalf("removed a lock that existed before the install: %v", err)
	}
}

func TestRollbackRestoresTheLogAccessMode(t *testing.T) {
	called := false
	tx := newInstallRollback(service.Manager{UserMode: true, Kind: service.KindSupervised})
	tx.RestoreLogAccess = func() { called = true }
	tx.Rollback(Manifest{})
	if !called {
		t.Fatal("Rollback did not restore the log access mode")
	}
}

func TestAddLogReaders(t *testing.T) {
	var added []string
	prev := addLogReaderMember
	t.Cleanup(func() { addLogReaderMember = prev })
	addLogReaderMember = func(group, account string) error {
		if group != loggroup.Name {
			t.Fatalf("added to group %q, want %q", group, loggroup.Name)
		}
		if account == "nosuchuser" {
			return errors.New("user does not exist")
		}
		added = append(added, account)
		return nil
	}
	restricted := endpointconfig.Config{LogAccess: "restricted"}

	got, problems := addLogReaders(restricted, []string{"alice", " alice ", "", "nosuchuser", "svc_splunk"})
	if strings.Join(got, ",") != "alice,svc_splunk" || strings.Join(added, ",") != "alice,svc_splunk" {
		t.Fatalf("added = %v (calls %v), want alice and svc_splunk once each", got, added)
	}
	if len(problems) != 1 || !strings.Contains(problems[0], "nosuchuser") {
		t.Fatalf("problems = %v, want one naming nosuchuser", problems)
	}

	added = nil
	got, problems = addLogReaders(endpointconfig.Config{LogAccess: "shared"}, []string{"alice"})
	if len(got) != 0 || len(added) != 0 || len(problems) != 1 || !strings.Contains(problems[0], "shared") {
		t.Fatalf("shared log: added %v, calls %v, problems %v; want nothing added and one note", got, added, problems)
	}
	if got, problems := addLogReaders(endpointconfig.Config{UserMode: true, LogAccess: "restricted"}, []string{"alice"}); got != nil || problems != nil {
		t.Fatalf("user mode: %v, %v; want nothing", got, problems)
	}
	if got, problems := addLogReaders(restricted, nil); got != nil || problems != nil {
		t.Fatalf("no readers: %v, %v; want nothing", got, problems)
	}
}