Skip to content

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

feat(endpoint): add manual self-update apply

shukieshah64ed2f81e977
diff --git a/cli/beacon/cmd/endpoint_test.go b/cli/beacon/cmd/endpoint_test.go
index 7753c5b0..02eba5bb 100644
--- a/cli/beacon/cmd/endpoint_test.go
+++ b/cli/beacon/cmd/endpoint_test.go
@@ -1,6 +1,7 @@
package cmd
import (
+ "context"
"encoding/json"
"errors"
"fmt"
@@ -1251,6 +1252,28 @@ func TestRequireSystemPackageForUpdater(t *testing.T) {
}
}
+func TestEndpointUpdateApplyFlagRegistered(t *testing.T) {
+ cmd, _, err := endpointCmd.Find([]string{"update"})
+ if err != nil {
+ t.Fatalf("find endpoint update: %v", err)
+ }
+ if cmd.Flags().Lookup("apply") == nil {
+ t.Fatal("endpoint update missing --apply")
+ }
+}
+
+func TestApplyUpdateRequiresRoot(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root can apply updates")
+ }
+ oldAllow := endpointUpdateOpts.allowInsecure
+ t.Cleanup(func() { endpointUpdateOpts.allowInsecure = oldAllow })
+ endpointUpdateOpts.allowInsecure = false
+ if err := applyUpdate(context.Background(), "0.0.1"); err == nil || !strings.Contains(err.Error(), "requires root") {
+ t.Fatalf("applyUpdate error = %v, want root requirement", err)
+ }
+}
+
func TestCompletionAndDocsCommandsRegistered(t *testing.T) {
for _, name := range []string{"completion", "docs"} {
cmd, _, err := rootCmd.Find([]string{name})
diff --git a/cli/beacon/cmd/endpoint_update.go b/cli/beacon/cmd/endpoint_update.go
index 8f97614d..0eab099f 100644
--- a/cli/beacon/cmd/endpoint_update.go
+++ b/cli/beacon/cmd/endpoint_update.go
@@ -3,8 +3,10 @@ package cmd
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"os"
+ "path/filepath"
"time"
"github.com/spf13/cobra"
@@ -15,7 +17,10 @@ import (
)
var endpointUpdateOpts struct {
- check bool
+ check bool
+ apply bool
+ allowInsecure bool
+ installPrefix string
}
var detectUpdateInstall = selfupdate.DetectInstall
@@ -24,8 +29,8 @@ var endpointUpdateCmd = &cobra.Command{
Use: "update",
Short: "Check for Beacon endpoint agent updates",
Long: `Check for a newer signed and notarized Beacon endpoint package without
-downloading or applying it. Phase 1 is check-only: it can surface update status
-and write local system-log events, but it never mutates the install.`,
+downloading or applying it by default. Use --apply explicitly to download,
+verify, install, health-check, and roll back if needed.`,
SilenceUsage: true,
RunE: runEndpointUpdate,
}
@@ -35,6 +40,11 @@ func init() {
// intentionally not exposed (the public command-tree smoke test forbids it).
endpointCmd.AddCommand(endpointUpdateCmd)
endpointUpdateCmd.Flags().BoolVar(&endpointUpdateOpts.check, "check", false, "Only report whether an update is available; do not apply")
+ endpointUpdateCmd.Flags().BoolVar(&endpointUpdateOpts.apply, "apply", false, "Download, verify, and apply an available endpoint package update")
+ endpointUpdateCmd.Flags().BoolVar(&endpointUpdateOpts.allowInsecure, "allow-insecure-test", false, "Test only: apply into --install-prefix and skip package notarization checks")
+ endpointUpdateCmd.Flags().StringVar(&endpointUpdateOpts.installPrefix, "install-prefix", "", "Test only: install root instead of /")
+ _ = endpointUpdateCmd.Flags().MarkHidden("allow-insecure-test")
+ _ = endpointUpdateCmd.Flags().MarkHidden("install-prefix")
}
// configAutoUpdateMode returns the locally configured auto-update mode.
@@ -92,7 +102,7 @@ func runEndpointUpdate(cmd *cobra.Command, args []string) error {
current := version.GetVersion()
res, err := selfupdate.CheckWithMode(ctx, current, configAutoUpdateMode())
if err != nil {
- _ = selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{
+ _ = emitManualCheckEvent(selfupdate.CheckEventOptions{
Result: res,
Action: selfupdate.EventCheckFailed,
Reason: err.Error(),
@@ -102,7 +112,7 @@ func runEndpointUpdate(cmd *cobra.Command, args []string) error {
return fmt.Errorf("update check failed: %w", err)
}
action, reason := selfupdate.CheckOutcome(res)
- if err := selfupdate.EmitCheckEvent(selfupdate.CheckEventOptions{
+ if err := emitManualCheckEvent(selfupdate.CheckEventOptions{
Result: res,
Action: action,
Reason: reason,
@@ -131,21 +141,76 @@ func runEndpointUpdate(cmd *cobra.Command, args []string) error {
fmt.Printf("This build is below the minimum supported version; updating is strongly recommended.\n")
}
- switch res.Install.Kind {
- case selfupdate.InstallHomebrew:
- fmt.Println("Installed via Homebrew. Update with:")
- fmt.Println(" brew upgrade beacon")
- return nil
- case selfupdate.InstallOther:
- fmt.Printf("Endpoint package checks apply only to the system package install.\n")
+ if !endpointUpdateOpts.apply {
+ switch res.Install.Kind {
+ case selfupdate.InstallHomebrew:
+ fmt.Println("Installed via Homebrew. Update with:")
+ fmt.Println(" brew upgrade beacon")
+ return nil
+ case selfupdate.InstallOther:
+ fmt.Printf("Endpoint package checks apply only to the system package install.\n")
+ return nil
+ }
+ if !res.HasArtifact {
+ fmt.Printf("No signed endpoint package artifact is available for %s.\n", res.ArchKey)
+ return nil
+ }
+ fmt.Println("Check-only mode: no package was downloaded or applied.")
return nil
}
- if !res.HasArtifact {
- fmt.Printf("No signed endpoint package artifact is available for %s.\n", res.ArchKey)
+ return applyUpdate(cmd.Context(), current)
+}
+
+func emitManualCheckEvent(opts selfupdate.CheckEventOptions) error {
+ err := selfupdate.EmitCheckEvent(opts)
+ if err == nil {
+ return nil
+ }
+ if errors.Is(err, os.ErrPermission) || os.IsPermission(err) {
+ fmt.Fprintf(os.Stderr, "warning: could not write update check event to system log: %v\n", err)
return nil
}
+ return err
+}
+
+func applyUpdate(parent context.Context, current string) error {
+ insecure := endpointUpdateOpts.allowInsecure
+ if !insecure {
+ if os.Geteuid() != 0 {
+ return fmt.Errorf("applying an update requires root; rerun with sudo")
+ }
+ if install := detectUpdateInstall(); !install.SupportsSeamlessUpdate() {
+ return fmt.Errorf("automatic apply is only supported for the system package install (detected: %s)", install.Kind)
+ }
+ }
- fmt.Println("Check-only mode: no package was downloaded or applied.")
+ ctx, cancel := context.WithTimeout(parent, 15*time.Minute)
+ defer cancel()
+
+ applier := selfupdate.NewApplier(current)
+ applier.LogPath = endpointSystemLogPath()
+ if insecure {
+ applier.AllowInsecureTest = true
+ applier.SkipGatekeeper = true
+ if endpointUpdateOpts.installPrefix != "" {
+ applier.InstallPrefix = endpointUpdateOpts.installPrefix
+ applier.StageDir = filepath.Join(endpointUpdateOpts.installPrefix, "stage")
+ applier.LogPath = filepath.Join(endpointUpdateOpts.installPrefix, "system.jsonl")
+ }
+ }
+
+ res, err := applier.Apply(ctx)
+ if err != nil {
+ if res.RolledBack {
+ fmt.Println("Update failed; rolled back to the previous version.")
+ }
+ return err
+ }
+ if !res.Applied {
+ fmt.Printf("No update applied: %s\n", res.Message)
+ return nil
+ }
+ fmt.Printf("Updated Beacon to %s.\n", res.ToVersion)
return nil
}
diff --git a/cli/beacon/internal/endpoint/selfupdate/apply.go b/cli/beacon/internal/endpoint/selfupdate/apply.go
new file mode 100644
index 00000000..0df5f852
--- /dev/null
+++ b/cli/beacon/internal/endpoint/selfupdate/apply.go
@@ -0,0 +1,419 @@
+package selfupdate
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/updatecheck"
+)
+
+// maxPackageBytes caps a downloaded update artifact. The signed .pkg is tens of
+// MB; this is a generous ceiling that still bounds a hostile response.
+const maxPackageBytes = 512 << 20
+
+// runnerFunc executes an external command and returns combined output. It is
+// injectable so tests can avoid real installer/pkgutil/launchctl calls.
+type runnerFunc func(ctx context.Context, name string, args ...string) (string, error)
+
+func execRun(ctx context.Context, name string, args ...string) (string, error) {
+ out, err := exec.CommandContext(ctx, name, args...).CombinedOutput()
+ return string(out), err
+}
+
+// ApplyResult summarizes an apply attempt.
+type ApplyResult struct {
+ FromVersion string
+ ToVersion string
+ Applied bool
+ RolledBack bool
+ Message string
+}
+
+// Applier performs the full download → verify → install → health-check →
+// rollback flow. Zero value is not usable; use NewApplier.
+type Applier struct {
+ CurrentVersion string
+ ManifestURL string // override; empty uses resolveManifestURL()
+ StageDir string // default StateDir()
+ InstallPrefix string // default "/" (real installer); a temp dir in tests
+ LogPath string // telemetry log; empty uses the system runtime log
+
+ // AllowInsecureTest enables the install-prefix tarball seam and is required
+ // for SkipGatekeeper. It is never set by the launchd job or normal CLI use.
+ AllowInsecureTest bool
+ // SkipGatekeeper relaxes notarization/staple checks. Requires
+ // AllowInsecureTest. The sha256 check is always enforced regardless.
+ SkipGatekeeper bool
+
+ HTTPClient *http.Client
+ run runnerFunc
+ now func() time.Time
+}
+
+// NewApplier returns an Applier with production defaults.
+func NewApplier(currentVersion string) *Applier {
+ return &Applier{
+ CurrentVersion: currentVersion,
+ StageDir: StateDir(),
+ InstallPrefix: "/",
+ HTTPClient: &http.Client{Timeout: 10 * time.Minute},
+ run: execRun,
+ now: time.Now,
+ }
+}
+
+func (a *Applier) runner() runnerFunc {
+ if a.run != nil {
+ return a.run
+ }
+ return execRun
+}
+
+func (a *Applier) clock() func() time.Time {
+ if a.now != nil {
+ return a.now
+ }
+ return time.Now
+}
+
+// Apply runs the full update flow. It is safe to call when no update is
+// available (returns Applied=false). Any failure before the install step leaves
+// the system untouched; a failed install triggers a binary rollback.
+func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
+ if a.SkipGatekeeper && !a.AllowInsecureTest {
+ return ApplyResult{}, fmt.Errorf("SkipGatekeeper requires AllowInsecureTest")
+ }
+ result := ApplyResult{FromVersion: a.CurrentVersion}
+ current := strings.TrimSpace(a.CurrentVersion)
+ if current == "dev" {
+ result.Message = "dev build; skipping"
+ return result, nil
+ }
+ if !updatecheck.CanCheckVersion(current) {
+ result.Message = "current version cannot be compared to releases"
+ return result, nil
+ }
+
+ // Discover.
+ src := updatecheck.ManifestSource{
+ Client: &http.Client{Timeout: 30 * time.Second},
+ Endpoint: a.manifestURL(),
+ }
+ manifest, err := src.Fetch(ctx)
+ if err != nil {
+ a.emit(false, result, "fetch update manifest: "+err.Error())
+ return result, fmt.Errorf("fetch update manifest: %w", err)
+ }
+ eval, err := updatecheck.EvaluateManifest(a.CurrentVersion, manifest)
+ if err != nil {
+ a.emit(false, result, err.Error())
+ return result, err
+ }
+ if eval.CurrentIsDev {
+ result.Message = "dev build; skipping"
+ return result, nil
+ }
+ if !eval.UpdateAvailable {
+ result.Message = "already up to date"
+ return result, nil
+ }
+ result.ToVersion = manifest.Version
+
+ artifact, ok := manifest.ArtifactFor(updatecheck.RuntimeArchKey())
+ if !ok {
+ a.emit(false, result, fmt.Sprintf("no update artifact for %s", updatecheck.RuntimeArchKey()))
+ return result, fmt.Errorf("no update artifact for %s", updatecheck.RuntimeArchKey())
+ }
+
+ // Serialize concurrent updaters.
+ stage := a.stageDir()
+ if err := os.MkdirAll(stage, 0o755); err != nil {
+ return result, fmt.Errorf("create staging dir: %w", err)
+ }
+ unlock, err := acquireLock(filepath.Join(stage, ".update.lock"))
+ if err != nil {
+ a.emit(false, result, "another update is already running: "+err.Error())
+ return result, fmt.Errorf("another update is already running: %w", err)
+ }
+ defer unlock()
+
+ // Download + verify before touching the system.
+ pkgPath := filepath.Join(stage, "download"+packageExt(artifact.URL))
+ if err := a.download(ctx, artifact.URL, pkgPath); err != nil {
+ a.emit(false, result, "download update: "+err.Error())
+ return result, fmt.Errorf("download update: %w", err)
+ }
+ defer os.Remove(pkgPath)
+
+ if err := verifySHA256(pkgPath, artifact.SHA256); err != nil {
+ a.emit(false, result, err.Error())
+ return result, fmt.Errorf("verify checksum: %w", err)
+ }
+ if !a.SkipGatekeeper {
+ if err := a.verifyGatekeeper(ctx, pkgPath, manifest.TeamID); err != nil {
+ a.emit(false, result, err.Error())
+ return result, fmt.Errorf("verify signature/notarization: %w", err)
+ }
+ }
+
+ // Snapshot the whole install tree for rollback, then install. A snapshot
+ // failure on an existing install aborts before we touch anything: proceeding
+ // would leave us unable to roll back.
+ backup, err := a.snapshotInstall()
+ if err != nil {
+ a.emit(false, result, "rollback snapshot failed: "+err.Error())
+ return result, fmt.Errorf("snapshot current install for rollback: %w", err)
+ }
+
+ if err := a.install(ctx, pkgPath); err != nil {
+ a.rollback(backup, &result)
+ a.emit(false, result, err.Error())
+ return result, fmt.Errorf("install update: %w", err)
+ }
+
+ if err := a.healthCheck(ctx, manifest.Version); err != nil {
+ a.rollback(backup, &result)
+ a.emit(false, result, "post-install health check failed: "+err.Error())
+ return result, fmt.Errorf("post-install health check failed: %w", err)
+ }
+
+ result.Applied = true
+ result.Message = fmt.Sprintf("updated %s -> %s", a.CurrentVersion, manifest.Version)
+ a.emit(true, result, result.Message)
+ return result, nil
+}
+
+func (a *Applier) manifestURL() string {
+ if strings.TrimSpace(a.ManifestURL) != "" {
+ return a.ManifestURL
+ }
+ return resolveManifestURL()
+}
+
+func (a *Applier) stageDir() string {
+ if a.StageDir != "" {
+ return a.StageDir
+ }
+ return StateDir()
+}
+
+func (a *Applier) prefix() string {
+ if a.InstallPrefix != "" {
+ return a.InstallPrefix
+ }
+ return "/"
+}
+
+// download streams the artifact to dest with a size cap.
+func (a *Applier) download(ctx context.Context, url, dest string) error {
+ client := a.HTTPClient
+ if client == nil {
+ client = &http.Client{Timeout: 10 * time.Minute}
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("User-Agent", "beacon-self-update")
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return fmt.Errorf("HTTP %d", resp.StatusCode)
+ }
+ f, err := os.Create(dest)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ n, err := io.Copy(f, io.LimitReader(resp.Body, maxPackageBytes+1))
+ if err != nil {
+ return err
+ }
+ if n > maxPackageBytes {
+ return fmt.Errorf("artifact exceeds %d bytes", maxPackageBytes)
+ }
+ return nil
+}
+
+func verifySHA256(path, want string) error {
+ f, err := os.Open(path)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ h := sha256.New()
+ if _, err := io.Copy(h, f); err != nil {
+ return err
+ }
+ got := hex.EncodeToString(h.Sum(nil))
+ if !strings.EqualFold(got, strings.TrimSpace(want)) {
+ return fmt.Errorf("sha256 mismatch: got %s want %s", got, want)
+ }
+ return nil
+}
+
+// verifyGatekeeper confirms the .pkg is a Developer ID Installer-signed,
+// notarized, and stapled package before it is run.
+func (a *Applier) verifyGatekeeper(ctx context.Context, pkgPath, teamID string) error {
+ run := a.runner()
+ out, err := run(ctx, "pkgutil", "--check-signature", pkgPath)
+ if err != nil {
+ return fmt.Errorf("pkgutil --check-signature: %s: %w", strings.TrimSpace(out), err)
+ }
+ if teamID != "" && !strings.Contains(out, teamID) {
+ return fmt.Errorf("package signature does not match expected team id %s", teamID)
+ }
+ if out, err := run(ctx, "stapler", "validate", pkgPath); err != nil {
+ return fmt.Errorf("stapler validate: %s: %w", strings.TrimSpace(out), err)
+ }
+ if out, err := run(ctx, "spctl", "--assess", "--type", "install", "-vv", pkgPath); err != nil {
+ return fmt.Errorf("spctl assessment failed: %s: %w", strings.TrimSpace(out), err)
+ }
+ return nil
+}
+
+// install applies the package. Production runs the macOS installer into "/";
+// the insecure test seam expands a tarball into a temp prefix instead.
+func (a *Applier) install(ctx context.Context, pkgPath string) error {
+ if a.AllowInsecureTest {
+ return extractTarballInto(pkgPath, a.prefix())
+ }
+ out, err := a.runner()(ctx, "installer", "-pkg", pkgPath, "-target", a.prefix())
+ if err != nil {
+ return fmt.Errorf("%s: %w", strings.TrimSpace(out), err)
+ }
+ return nil
+}
+
+// installDir is the root of the installed tree under the active prefix.
+func (a *Applier) installDir() string {
+ return filepath.Join(a.prefix(), "opt", "beacon")
+}
+
+// binDir is the install tree's binary directory under the active prefix.
+func (a *Applier) binDir() string {
+ return filepath.Join(a.installDir(), "bin")
+}
+
+// snapshotInstall copies the whole /opt/beacon tree (binaries and scripts) to a
+// rollback location so a failed update can be reverted as a unit, not just its
+// binaries. It returns ("", nil) when there is nothing installed yet (a fresh
+// install — no rollback is possible or needed), and an error only on a real
+// copy failure, which the caller treats as fatal before touching the system.
+func (a *Applier) snapshotInstall() (string, error) {
+ src := a.installDir()
+ info, err := os.Stat(src)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return "", nil
+ }
+ return "", err
+ }
+ if !info.IsDir() {
+ return "", fmt.Errorf("%s is not a directory", src)
+ }
+ dst := filepath.Join(a.stageDir(), "rollback", "beacon")
+ if err := os.RemoveAll(dst); err != nil {
+ return "", err
+ }
+ if err := copyTree(src, dst); err != nil {
+ return "", err
+ }
+ return dst, nil
+}
+
+// rollback restores the pre-update install tree and restarts the collector. It
+// sets result.RolledBack only when a snapshot existed and was restored
+// successfully; with no snapshot (a first update) the failed new version stays
+// in place and RolledBack remains false, so telemetry never over-claims a
+// rollback that did not happen. Endpoint config/plists live outside the tree but
+// reference stable paths and a release-stable schema, so the restored older
+// binaries run against them consistently after the collector restarts.
+func (a *Applier) rollback(backup string, result *ApplyResult) {
+ if backup == "" {
+ return
+ }
+ if err := os.RemoveAll(a.installDir()); err != nil {
+ return
+ }
+ if err := copyTree(backup, a.installDir()); err != nil {
+ return
+ }
+ result.RolledBack = true
+ if !a.AllowInsecureTest {
+ _ = a.restartCollector()
+ }
+}
+
+// healthCheck confirms the freshly installed beacon reports the expected
+// version and, in production, that the collector service is running.
+func (a *Applier) healthCheck(ctx context.Context, wantVersion string) error {
+ bin := filepath.Join(a.binDir(), "beacon")
+ out, err := a.runner()(ctx, bin, "version")
+ if err != nil {
+ return fmt.Errorf("run %s version: %s: %w", bin, strings.TrimSpace(out), err)
+ }
+ if !versionLineMatches(out, wantVersion) {
+ return fmt.Errorf("installed binary reports %q, expected version %s", strings.TrimSpace(out), wantVersion)
+ }
+ if a.AllowInsecureTest {
+ return nil
+ }
+ // Give launchd a moment to relaunch the collector via the pkg postinstall.
+ mgr := service.Manager{UserMode: false}
+ deadline := a.clock()().Add(15 * time.Second)
+ for {
+ if mgr.Status().Running {
+ return nil
+ }
+ if !a.clock()().Before(deadline) {
+ return fmt.Errorf("collector service is not running after update")
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+}
+
+func (a *Applier) restartCollector() error {
+ mgr := service.Manager{UserMode: false}
+ _ = mgr.Unload()
+ return mgr.Load()
+}
+
+// versionLineMatches reports whether `beacon version` output
+// ("beacon version <V> (<commit>) built on <date>") reports exactly wantVersion.
+// It matches the version token after "version" for equality rather than a
+// substring, so e.g. an installed 0.0.6 does not satisfy an expected 0.0.69.
+func versionLineMatches(out, want string) bool {
+ want = strings.TrimPrefix(strings.TrimSpace(want), "v")
+ fields := strings.Fields(out)
+ for i := 0; i+1 < len(fields); i++ {
+ if fields[i] == "version" {
+ return strings.TrimPrefix(fields[i+1], "v") == want
+ }
+ }
+ return false
+}
+
+func packageExt(url string) string {
+ switch {
+ case strings.HasSuffix(url, ".tar.gz"):
+ return ".tar.gz"
+ case strings.HasSuffix(url, ".tgz"):
+ return ".tgz"
+ default:
+ return ".pkg"
+ }
+}
diff --git a/cli/beacon/internal/endpoint/selfupdate/apply_test.go b/cli/beacon/internal/endpoint/selfupdate/apply_test.go
new file mode 100644
index 00000000..96168005
--- /dev/null
+++ b/cli/beacon/internal/endpoint/selfupdate/apply_test.go
@@ -0,0 +1,255 @@
+package selfupdate
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/updatecheck"
+)
+
+// makeBeaconTarball builds a gzipped tar containing opt/beacon/bin/beacon as an
+// executable script that prints the given version, returning the bytes + sha256.
+func makeBeaconTarball(t *testing.T, version string) ([]byte, string) {
+ t.Helper()
+ script := "#!/bin/sh\necho \"beacon version " + version + " (test) built on test\"\n"
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ hdr := &tar.Header{Name: "opt/beacon/bin/beacon", Mode: 0o755, Size: int64(len(script)), Typeflag: tar.TypeReg}
+ if err := tw.WriteHeader(hdr); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write([]byte(script)); err != nil {
+ t.Fatal(err)
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(buf.Bytes())
+ return buf.Bytes(), hex.EncodeToString(sum[:])
+}
+
+// manifestServer serves a manifest pointing at /artifact.tar.gz and the artifact.
+func manifestServer(t *testing.T, version, sha string, artifact []byte) *httptest.Server {
+ t.Helper()
+ mux := http.NewServeMux()
+ srv := httptest.NewServer(mux)
+ mux.HandleFunc("/manifest.json", func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, `{"schema":1,"version":%q,"team_id":"TEAMID","artifacts":{%q:{"url":%q,"sha256":%q}}}`,
+ version, updatecheck.RuntimeArchKey(), srv.URL+"/artifact.tar.gz", sha)
+ })
+ mux.HandleFunc("/artifact.tar.gz", func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write(artifact)
+ })
+ return srv
+}
+
+func testApplier(t *testing.T, current string, srv *httptest.Server) *Applier {
+ t.Helper()
+ prefix := t.TempDir()
+ a := NewApplier(current)
+ a.ManifestURL = srv.URL + "/manifest.json"
+ a.StageDir = t.TempDir()
+ a.InstallPrefix = prefix
+ a.AllowInsecureTest = true
+ a.SkipGatekeeper = true
+ a.LogPath = filepath.Join(t.TempDir(), "runtime.jsonl")
+ return a
+}
+
+func TestApplyHappyPath(t *testing.T) {
+ artifact, sha := makeBeaconTarball(t, "9.9.9")
+ srv := manifestServer(t, "9.9.9", sha, artifact)
+ defer srv.Close()
+
+ a := testApplier(t, "0.0.1", srv)
+ res, err := a.Apply(context.Background())
+ if err != nil {
+ t.Fatalf("Apply: %v", err)
+ }
+ if !res.Applied || res.ToVersion != "9.9.9" {
+ t.Fatalf("unexpected result: %+v", res)
+ }
+ bin := filepath.Join(a.InstallPrefix, "opt/beacon/bin/beacon")
+ if _, err := os.Stat(bin); err != nil {
+ t.Fatalf("beacon not installed: %v", err)
+ }
+ // Telemetry written.
+ data, err := os.ReadFile(a.LogPath)
+ if err != nil || !strings.Contains(string(data), "update.applied") {
+ t.Fatalf("expected update.applied telemetry, got err=%v data=%s", err, data)
+ }
+}
+
+func TestApplySHA256Mismatch(t *testing.T) {
+ artifact, _ := makeBeaconTarball(t, "9.9.9")
+ srv := manifestServer(t, "9.9.9", "deadbeefbad", artifact)
+ defer srv.Close()
+
+ a := testApplier(t, "0.0.1", srv)
+ res, err := a.Apply(context.Background())
+ if err == nil {
+ t.Fatalf("expected checksum error")
+ }
+ if res.Applied {
+ t.Fatalf("must not apply on sha mismatch")
+ }
+ // System untouched: nothing extracted into the prefix.
+ if _, err := os.Stat(filepath.Join(a.InstallPrefix, "opt/beacon/bin/beacon")); !os.IsNotExist(err) {
+ t.Fatalf("install prefix should be untouched, stat err=%v", err)
+ }
+ if !strings.Contains(string(mustRead(t, a.LogPath)), "update.failed") {
+ t.Fatalf("expected update.failed telemetry")
+ }
+}
+
+func TestApplyUpToDate(t *testing.T) {
+ artifact, sha := makeBeaconTarball(t, "9.9.9")
+ srv := manifestServer(t, "9.9.9", sha, artifact)
+ defer srv.Close()
+
+ a := testApplier(t, "9.9.9", srv) // current == manifest
+ res, err := a.Apply(context.Background())
+ if err != nil {
+ t.Fatalf("Apply: %v", err)
+ }
+ if res.Applied {
+ t.Fatalf("should not apply when up to date")
+ }
+ if !strings.Contains(res.Message, "up to date") {
+ t.Fatalf("message = %q", res.Message)
+ }
+}
+
+func TestApplySkipsManifestFetchForDevBuild(t *testing.T) {
+ called := false
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ called = true
+ http.Error(w, "should not be called", http.StatusInternalServerError)
+ }))
+ defer srv.Close()
+ a := NewApplier("dev")
+ a.ManifestURL = srv.URL + "/manifest.json"
+
+ res, err := a.Apply(context.Background())
+ if err != nil {
+ t.Fatalf("Apply: %v", err)
+ }
+ if called {
+ t.Fatal("manifest server was called for dev build")
+ }
+ if res.Applied {
+ t.Fatalf("dev build should not apply: %+v", res)
+ }
+}
+
+func TestApplyHealthFailRollsBack(t *testing.T) {
+ // New artifact installs a beacon that reports the WRONG version, so the
+ // health check (which expects manifest.version 9.9.9) fails and rolls back.
+ artifact, sha := makeBeaconTarball(t, "1.1.1")
+ srv := manifestServer(t, "9.9.9", sha, artifact)
+ defer srv.Close()
+
+ a := testApplier(t, "0.0.1", srv)
+ // Pre-seed an OLD binary so a rollback snapshot exists.
+ oldBin := filepath.Join(a.InstallPrefix, "opt/beacon/bin/beacon")
+ if err := os.MkdirAll(filepath.Dir(oldBin), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(oldBin, []byte("#!/bin/sh\necho OLD-BINARY\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := a.Apply(context.Background())
+ if err == nil {
+ t.Fatalf("expected health-check failure")
+ }
+ if !res.RolledBack {
+ t.Fatalf("expected rollback, got %+v", res)
+ }
+ got := mustRead(t, oldBin)
+ if !strings.Contains(string(got), "OLD-BINARY") {
+ t.Fatalf("rollback did not restore old binary, got %q", got)
+ }
+}
+
+func TestApplyGatekeeperAbortsBeforeInstall(t *testing.T) {
+ artifact, sha := makeBeaconTarball(t, "9.9.9")
+ srv := manifestServer(t, "9.9.9", sha, artifact)
+ defer srv.Close()
+
+ a := NewApplier("0.0.1")
+ a.ManifestURL = srv.URL + "/manifest.json"
+ a.StageDir = t.TempDir()
+ a.InstallPrefix = t.TempDir()
+ a.LogPath = filepath.Join(t.TempDir(), "runtime.jsonl")
+ // SkipGatekeeper stays false; stub the runner so pkgutil fails and records calls.
+ var calls []string
+ a.run = func(ctx context.Context, name string, args ...string) (string, error) {
+ calls = append(calls, name)
+ if name == "pkgutil" {
+ return "bad signature", fmt.Errorf("exit 1")
+ }
+ return "", nil
+ }
+
+ if _, err := a.Apply(context.Background()); err == nil {
+ t.Fatalf("expected signature verification error")
+ }
+ for _, c := range calls {
+ if c == "installer" {
+ t.Fatalf("installer must not run after signature failure; calls=%v", calls)
+ }
+ }
+}
+
+func TestSkipGatekeeperRequiresInsecureFlag(t *testing.T) {
+ a := NewApplier("0.0.1")
+ a.SkipGatekeeper = true // without AllowInsecureTest
+ if _, err := a.Apply(context.Background()); err == nil || !strings.Contains(err.Error(), "AllowInsecureTest") {
+ t.Fatalf("expected guard error, got %v", err)
+ }
+}
+
+func TestVersionLineMatches(t *testing.T) {
+ out := "beacon version 0.0.69 (abc1234) built on 2026-01-01"
+ if !versionLineMatches(out, "0.0.69") {
+ t.Error("exact version should match")
+ }
+ if !versionLineMatches(out, "v0.0.69") {
+ t.Error("v-prefixed want should match")
+ }
+ // The substring bug: an expected 0.0.6 must NOT match a 0.0.69 binary.
+ if versionLineMatches(out, "0.0.6") {
+ t.Error("0.0.6 must not match 0.0.69 (substring)")
+ }
+ if versionLineMatches("beacon version 0.0.10 (x) built on y", "0.0.101") {
+ t.Error("0.0.101 must not match 0.0.10")
+ }
+ if versionLineMatches("garbage output", "0.0.1") {
+ t.Error("unparseable output should not match")
+ }
+}
+
+func mustRead(t *testing.T, path string) []byte {
+ t.Helper()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("read %s: %v", path, err)
+ }
+ return data
+}
diff --git a/cli/beacon/internal/endpoint/selfupdate/fsutil.go b/cli/beacon/internal/endpoint/selfupdate/fsutil.go
new file mode 100644
index 00000000..3f13a753
--- /dev/null
+++ b/cli/beacon/internal/endpoint/selfupdate/fsutil.go
@@ -0,0 +1,144 @@
+package selfupdate
+
+import (
+ "archive/tar"
+ "compress/gzip"
+ "fmt"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "syscall"
+)
+
+// maxTarEntryBytes bounds a single file extracted from a test artifact.
+const maxTarEntryBytes = 256 << 20
+
+// acquireLock takes an exclusive advisory lock on path and returns a release
+// func. It is non-blocking: if another process holds the lock it returns an
+// error rather than waiting, so overlapping updater runs do not pile up.
+func acquireLock(path string) (func(), error) {
+ f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
+ if err != nil {
+ return nil, err
+ }
+ if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
+ _ = f.Close()
+ return nil, err
+ }
+ return func() {
+ _ = syscall.Flock(int(f.Fd()), syscall.LOCK_UN)
+ _ = f.Close()
+ }, nil
+}
+
+// safeJoin resolves an archive entry name against dest and rejects anything that
+// would escape dest (path traversal / "zip slip"). It rejects absolute paths and
+// any entry whose cleaned, joined path is not contained within dest.
+func safeJoin(dest, name string) (string, error) {
+ if filepath.IsAbs(name) || strings.HasPrefix(name, "/") || strings.HasPrefix(name, "\\") {
+ return "", fmt.Errorf("absolute path in archive entry: %q", name)
+ }
+ cleanDest := filepath.Clean(dest)
+ target := filepath.Clean(filepath.Join(cleanDest, name))
+ if target != cleanDest && !strings.HasPrefix(target, cleanDest+string(os.PathSeparator)) {
+ return "", fmt.Errorf("archive entry escapes destination: %q", name)
+ }
+ return target, nil
+}
+
+// extractTarballInto expands a gzipped tar into dest, guarding against path
+// traversal. It is used only by the insecure test seam; production installs go
+// through the macOS installer.
+func extractTarballInto(tarball, dest string) error {
+ f, err := os.Open(tarball)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ gz, err := gzip.NewReader(f)
+ if err != nil {
+ return fmt.Errorf("gzip: %w", err)
+ }
+ defer gz.Close()
+ tr := tar.NewReader(gz)
+ cleanDest := filepath.Clean(dest)
+ for {
+ hdr, err := tr.Next()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ target, err := safeJoin(cleanDest, hdr.Name)
+ if err != nil {
+ return err
+ }
+ switch hdr.Typeflag {
+ case tar.TypeDir:
+ if err := os.MkdirAll(target, 0o755); err != nil {
+ return err
+ }
+ case tar.TypeReg:
+ if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
+ return err
+ }
+ out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, os.FileMode(hdr.Mode)&0o777)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, io.LimitReader(tr, maxTarEntryBytes)); err != nil {
+ _ = out.Close()
+ return err
+ }
+ if err := out.Close(); err != nil {
+ return err
+ }
+ }
+ }
+}
+
+// copyTree recursively copies src to dst, preserving file modes.
+func copyTree(src, dst string) error {
+ info, err := os.Stat(src)
+ if err != nil {
+ return err
+ }
+ if info.IsDir() {
+ if err := os.MkdirAll(dst, info.Mode().Perm()); err != nil {
+ return err
+ }
+ entries, err := os.ReadDir(src)
+ if err != nil {
+ return err
+ }
+ for _, e := range entries {
+ if err := copyTree(filepath.Join(src, e.Name()), filepath.Join(dst, e.Name())); err != nil {
+ return err
+ }
+ }
+ return nil
+ }
+ return copyFile(src, dst, info.Mode().Perm())
+}
+
+func copyFile(src, dst string, mode os.FileMode) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer in.Close()
+ if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil {
+ return err
+ }
+ out, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode)
+ if err != nil {
+ return err
+ }
+ if _, err := io.Copy(out, in); err != nil {
+ _ = out.Close()
+ return err
+ }
+ return out.Close()
+}
diff --git a/cli/beacon/internal/endpoint/selfupdate/fsutil_test.go b/cli/beacon/internal/endpoint/selfupdate/fsutil_test.go
new file mode 100644
index 00000000..2c078450
--- /dev/null
+++ b/cli/beacon/internal/endpoint/selfupdate/fsutil_test.go
@@ -0,0 +1,77 @@
+package selfupdate
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestSafeJoinRejectsTraversal(t *testing.T) {
+ dest := "/tmp/dest"
+ bad := []string{
+ "../escape",
+ "../../etc/passwd",
+ "a/../../escape",
+ "/etc/passwd",
+ "\\windows\\system32",
+ }
+ for _, name := range bad {
+ if _, err := safeJoin(dest, name); err == nil {
+ t.Errorf("safeJoin(%q) should be rejected", name)
+ }
+ }
+
+ ok := map[string]string{
+ "opt/beacon/bin/beacon": "/tmp/dest/opt/beacon/bin/beacon",
+ "a/b/c": "/tmp/dest/a/b/c",
+ "file": "/tmp/dest/file",
+ }
+ for name, want := range ok {
+ got, err := safeJoin(dest, name)
+ if err != nil {
+ t.Errorf("safeJoin(%q) unexpected error: %v", name, err)
+ continue
+ }
+ if got != want {
+ t.Errorf("safeJoin(%q) = %q, want %q", name, got, want)
+ }
+ }
+}
+
+func TestExtractTarballRejectsTraversal(t *testing.T) {
+ // Build a tarball with a traversal entry and confirm extraction refuses it
+ // and writes nothing outside dest.
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ body := []byte("pwned")
+ hdr := &tar.Header{Name: "../escape.txt", Mode: 0o644, Size: int64(len(body)), Typeflag: tar.TypeReg}
+ if err := tw.WriteHeader(hdr); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ tw.Close()
+ gz.Close()
+
+ dir := t.TempDir()
+ dest := filepath.Join(dir, "dest")
+ if err := os.MkdirAll(dest, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ tarball := filepath.Join(dir, "a.tar.gz")
+ if err := os.WriteFile(tarball, buf.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := extractTarballInto(tarball, dest); err == nil {
+ t.Fatal("expected extraction to reject traversal entry")
+ }
+ if _, err := os.Stat(filepath.Join(dir, "escape.txt")); !os.IsNotExist(err) {
+ t.Fatalf("traversal file was written outside dest: %v", err)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/selfupdate/systemlog.go b/cli/beacon/internal/endpoint/selfupdate/systemlog.go
index e0ab0ac5..9d4705a4 100644
--- a/cli/beacon/internal/endpoint/selfupdate/systemlog.go
+++ b/cli/beacon/internal/endpoint/selfupdate/systemlog.go
@@ -14,6 +14,8 @@ const (
EventCurrent = "update.current"
EventUnsupported = "update.unsupported"
EventCheckFailed = "update.check_failed"
+ EventApplied = "update.applied"
+ EventFailed = "update.failed"
)
// SystemLogPath returns the local-only Beacon system/debug log that sits beside
diff --git a/cli/beacon/internal/endpoint/selfupdate/telemetry.go b/cli/beacon/internal/endpoint/selfupdate/telemetry.go
new file mode 100644
index 00000000..782ef34f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/selfupdate/telemetry.go
@@ -0,0 +1,45 @@
+package selfupdate
+
+import (
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+)
+
+// emit appends an update.applied / update.failed event to Beacon's local-only
+// system log. Failures to write telemetry are non-fatal: they must not block or
+// fail an update/rollback attempt.
+func (a *Applier) emit(success bool, r ApplyResult, message string) {
+ action := EventFailed
+ severity := schema.SeverityMedium
+ // Report the version the agent is on after this event: the newly installed
+ // version on success, the unchanged current version on failure.
+ agentVersion := a.CurrentVersion
+ if success {
+ action = EventApplied
+ severity = schema.SeverityInfo
+ if r.ToVersion != "" {
+ agentVersion = r.ToVersion
+ }
+ }
+ event := schema.NewEvent(schema.NewEventOptions{
+ Action: action,
+ Category: "system",
+ Severity: severity,
+ AgentVersion: agentVersion,
+ Harness: schema.HarnessInfo{Name: "beacon"},
+ Message: message,
+ })
+ event.Event.Kind = "beacon_system"
+ event.Raw = map[string]interface{}{
+ "component": "selfupdate",
+ "from_version": r.FromVersion,
+ "to_version": r.ToVersion,
+ "rolled_back": r.RolledBack,
+ "reason": message,
+ }
+ path := a.LogPath
+ if path == "" {
+ path = SystemLogPath(writer.DefaultPath(false), false)
+ }
+ _, _ = writer.AppendEvent(event, writer.Options{Path: path, UserMode: false})
+}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index dda418e1..33f0d6d7 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -14,6 +14,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
### Unreleased
- **Check-only endpoint update monitoring** · Apple Silicon package installs can opt into a local `launchd` job that checks the release manifest every 10 minutes and writes local-only update status events to `system.jsonl`. This phase does not download or apply packages.
+- **Manual endpoint package apply** · Apple Silicon package installs can explicitly run `sudo /opt/beacon/bin/beacon endpoint update --apply` to download the signed package from the release manifest, verify its checksum/signature/notarization/staple, install it with Apple's `installer`, health-check it, and roll back the `/opt/beacon` tree if the new install is unhealthy.
### v0.0.76 · June 24, 2026
diff --git a/docs/cli/upgrade.mdx b/docs/cli/upgrade.mdx
index 47a0f773..fed7db9d 100644
--- a/docs/cli/upgrade.mdx
+++ b/docs/cli/upgrade.mdx
@@ -41,6 +41,17 @@ Disable the background check job with:
sudo /opt/beacon/bin/beacon endpoint update disable
```
+When a newer signed endpoint package is available, apply it manually with:
+
+```bash title="Manually apply an endpoint package update"
+sudo /opt/beacon/bin/beacon endpoint update --apply
+```
+
+Manual apply downloads the package from the release manifest, verifies the
+checksum, Developer ID signature, stapled notarization ticket, and Gatekeeper
+assessment, then installs it with Apple's `installer`. If the updated install is
+unhealthy, Beacon restores the previous `/opt/beacon` tree.
+
## Repair endpoint configuration
If you run Beacon as a local endpoint service, reapply managed service files and telemetry configuration after upgrading: