Skip to content

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

feat(endpoint): install the enterprise edition with enforcement enable

shukieshah0af5dd792078
diff --git a/CLAUDE.md b/CLAUDE.md
index 93fcc126..2c1b5084 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -553,9 +553,9 @@ unpacked through Chrome's developer mode.
- `cli/beacon/internal/pricing` estimates list-price cost for reports: integer-microdollar math over the gen_ai.usage counts (disjoint input/output/cache read/cache write, a one-hour write subset, reasoning inside output), long-context bands only for a single request, and a strict model-name ladder (exact, canonical via `NormalizeModelName`, dotted version, Bedrock route prefix, then stripping a `[1m]` marker, snapshot date or effort suffix) that leaves a model unpriced rather than guess, including when two entries tie with different prices. Its `catalog.json` is embedded, offline and report-time only (hooks never import it); it is generated from LiteLLM's MIT-licensed `model_prices_and_context_window.json` and records the upstream URL, commit and fetch/generation dates. Regenerate with `cd cli/beacon && go run ./internal/pricing/internal/gen` (resolves LiteLLM's main with `git ls-remote` and fetches that commit; `-src`/`-commit` for a local copy) and review the one-model-per-line diff; the generator never runs in builds or tests. Operators price what the catalog cannot (internal models, new releases, gateway aliases, negotiated rates) in a local overrides file, `<BaseDir>/pricing/overrides.json` (`pricing.DefaultOverridesPath`, user or system mode; `--pricing-file` on `beacon token-usage` and `beacon pricing` names another), schema `beacon.pricing.overrides/v1`, documented in `docs/cli/pricing.mdx`. It is offline and Beacon never writes it: the CLI reads it per run, and the dashboard re-reads it per `/api/tokens` request, read-only, falling back to the catalog with `pricing.overrides.error` when it is invalid (the CLI fails instead). Rates are USD per MTok converted exactly to microdollars; zero, negative, quoted, sub-microdollar, absurd, unknown and duplicate keys are refused with the key named. `Pricer.Lookup` runs the same ladder over the file's names first and a row replaces the catalog row whole (omitted cache rates are unpublished, priced by the usual fallbacks); aliases map a reported name to an exact row or catalog key. Reports record `source` (`override`/`catalog`), `alias`, and the file's path and SHA-256. `beacon pricing show|list|info|validate` (`cli/beacon/cmd/pricing.go`) inspects resolution, the catalog, its provenance and the file.
- When adding a new signal, include stable identifiers/counts/hashes alongside any retained raw content, and route raw fields through redaction, sanitization, truncation, and event-size controls.
- Keep the dashboard read-only. It should inspect local status and JSONL events but must not mutate endpoint configuration or telemetry.
-- A few no-op extension points let a separately distributed build compile in files of its own: `claudeExtraHookGroups` and `claudeSettingsChanged` (`cli/beacon/internal/endpoint/hooks/claude.go`), `version.Edition` (both modules; reported by `beacon version`, `endpoint status --json` and the inventory heartbeat only when it is not `community`), and `updatecheck.PublicReleases` (false turns off the startup notice, `beacon version check` and the self-updater). In this repository they stay unset, and with them unset Beacon must behave exactly as before: `TestInstallClaudeSettingsUnchangedWithoutExtensions` compares the written Claude settings to a golden file. Keep them neutral, with no product logic behind them here, and CI refuses any file built only with an `enterprise` tag.
+- A few no-op extension points let a separately distributed build compile in files of its own: `claudeExtraHookGroups` and `claudeSettingsChanged` (`cli/beacon/internal/endpoint/hooks/claude.go`), `version.Edition` (both modules; reported by `beacon version`, `endpoint status --json` and the inventory heartbeat only when it is not `community`), and `updatecheck.PublicReleases` (false turns off the startup notice, `beacon version check` and the self-updater). In this repository they stay unset, and with them unset Beacon must behave exactly as before: `TestInstallClaudeSettingsUnchangedWithoutExtensions` compares the written Claude settings to a golden file. Keep them neutral, with no product logic behind them here, and CI refuses any file built only with an `enterprise` tag. The one exception is `beacon endpoint enforcement enable` (`cli/beacon/cmd/endpoint_enforcement.go`), the public installer for the enterprise edition: on an Apple Silicon Mac connected in system mode, with no user-mode Beacon running for the console user, it asks `<dashboard>/api/cli/enforcement/download` for the enterprise package (`internal/endpoint/edition`), installs it with `selfupdate.Applier.InstallPackage` (the self-updater's steps after discovery, with no version gate; the package must match the checksum, be signed by the Apple team pinned in `edition.AppleTeamID`, pass Gatekeeper and report the version and `enterprise` edition once installed, or it is rolled back), then runs the installed binary's own `enable`. A build that carries enforcement sets `activateEnforcement`, which `enable` runs instead, and adds its other subcommands to `endpointEnforcementCmd`. It contains no enforcement logic, never runs from hooks or in the background, and with `activateEnforcement` unset nothing else changes.
- The local trace history (`~/.beacon/endpoint/history.db`, `cli/beacon/internal/endpoint/dashboard/history_*.go`) is opt-in: only `beacon endpoint traces reindex`, a yes to the first-run prompt, or (later) `beacon mcp setup` creates it, and nothing non-interactive is ever prompted. Once it exists, `list`, `search` and `show` must return exactly what the JSONL scan returns for the same log (`TestHistoryAnswersExactlyLikeTheJSONLScan`), so it stores every event and projects it with the same code. A change to the trace projection bumps `historyDerivationVersion`, which rebuilds derived data from the stored lines. The stored lines keep only the raw keys in `historyRawKeys`, and a test fails if the dashboard reads one that is missing. The line dictionary (`historyLineDictionary`) must never change without a new codec.
-- The Asymptote device key has exactly one home, `<BaseDir>/asymptote/vector-secrets.json`, read by Vector's `secret` file backend. Never copy it into `config.json`, `vector.toml`, a service unit, an environment variable, a log line, or a `--json` result; `HasSecretDestinations` is unchanged because the key is not in `config.json`. `internal/auth` is flow-agnostic (PKCE, loopback callback server with an injected exchange function, browser opener, `PostJSON`); new browser flows reuse it rather than adding a second callback server. `connect` must fail before opening a browser when Vector or a service manager is missing, or when Vector rejects the rendered config, so no key is minted or rotated that cannot be used; enrollment rotates a connected device's key in place, so every local check runs ahead of it; the steps that can only fail after the exchange (storing the key, writing the config and unit, starting the service) are covered by the `asymptote/connect-pending` marker, written as soon as the key arrives and removed only when connect finishes, so status reports an incomplete connect instead of the previous connection. A failed first connect stops and removes any partial forwarder before returning, which keeps a later local-only onboarding choice local.
+- The Asymptote device key has exactly one home, `<BaseDir>/asymptote/vector-secrets.json`, read by Vector's `secret` file backend. Never copy it into `config.json`, `vector.toml`, a service unit, an environment variable, a log line, or a `--json` result. Besides Vector, only the root CLI reads it, into memory, to authenticate the one request `beacon endpoint enforcement enable` makes to the platform (and that a build carrying enforcement makes to turn it on or update it); `HasSecretDestinations` is unchanged because the key is not in `config.json`. `internal/auth` is flow-agnostic (PKCE, loopback callback server with an injected exchange function, browser opener, `PostJSON`); new browser flows reuse it rather than adding a second callback server. `connect` must fail before opening a browser when Vector or a service manager is missing, or when Vector rejects the rendered config, so no key is minted or rotated that cannot be used; enrollment rotates a connected device's key in place, so every local check runs ahead of it; the steps that can only fail after the exchange (storing the key, writing the config and unit, starting the service) are covered by the `asymptote/connect-pending` marker, written as soon as the key arrives and removed only when connect finishes, so status reports an incomplete connect instead of the previous connection. A failed first connect stops and removes any partial forwarder before returning, which keeps a later local-only onboarding choice local.
- Keep the release readiness guidance in `README.md` up to date when install, packaging, collector, or dashboard behavior changes.
## CI Expectations
diff --git a/cli/beacon/cmd/endpoint_enforcement.go b/cli/beacon/cmd/endpoint_enforcement.go
new file mode 100644
index 00000000..1385f650
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_enforcement.go
@@ -0,0 +1,259 @@
+package cmd
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "os"
+ "os/exec"
+ "os/user"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/asymptote"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/edition"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/lifecycle"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/version"
+)
+
+// `beacon endpoint enforcement enable` turns on policy enforcement for Claude Code. Enforcement is
+// part of Beacon's enterprise edition, not this one, so here enable installs that edition on a Mac
+// connected to its organization in system mode, then runs the installed binary's own enable. A
+// build that carries enforcement sets activateEnforcement, which enable runs instead, and adds its
+// other subcommands to endpointEnforcementCmd.
+
+// activateEnforcement turns enforcement on in a build that carries it. Nil in this repository.
+var activateEnforcement func(cmd *cobra.Command, dashboardURL string) error
+
+// enforcementHandoffEnv marks the installed binary's enable as started by this one, so a binary
+// without enforcement refuses instead of installing again.
+const enforcementHandoffEnv = "BEACON_ENFORCEMENT_HANDOFF"
+
+const (
+ enforcementLocateTimeout = 30 * time.Second
+ enforcementInstallTimeout = 15 * time.Minute
+)
+
+var endpointEnforcementOpts struct {
+ dashboardURL string
+}
+
+var endpointEnforcementCmd = &cobra.Command{
+ Use: "enforcement",
+ Short: "Policy enforcement for Claude Code (enterprise edition)",
+ Long: `Policy enforcement for Claude Code, part of Beacon's enterprise edition.
+
+enable installs the enterprise edition on a Mac that is connected to its organization in system
+mode (beacon endpoint connect --system), if the organization has enforcement, and turns it on.`,
+}
+
+var endpointEnforcementEnableCmd = &cobra.Command{
+ Use: "enable",
+ Short: "Turn on policy enforcement on this machine (needs sudo)",
+ Args: cobra.NoArgs,
+ SilenceUsage: true,
+ RunE: runEndpointEnforcementEnable,
+}
+
+// Seams, so tests reach none of the machine, the platform or the installer.
+var (
+ enforcementPlatformSupported = func() bool { return runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" }
+ enforcementHasRoot = lifecycle.HasSystemPrivileges
+ enforcementConnected = func() bool { return asymptote.Connected(false) }
+ enforcementCredentials = systemEnforcementCredentials
+ enforcementUserModeProbe = probeConsoleUserMode
+ installedBeaconVersionLine = defaultInstalledBeaconVersionLine
+ locateEnterpriseRelease = edition.Locate
+ installEnterpriseRelease = edition.Install
+ runInstalledEnforcementEnable = defaultRunInstalledEnforcementEnable
+)
+
+func init() {
+ endpointEnforcementEnableCmd.Flags().StringVar(&endpointEnforcementOpts.dashboardURL, "dashboard-url", "",
+ "platform to ask (default: the one this machine connected to)")
+ endpointEnforcementCmd.AddCommand(endpointEnforcementEnableCmd)
+ endpointCmd.AddCommand(endpointEnforcementCmd)
+}
+
+func runEndpointEnforcementEnable(cmd *cobra.Command, _ []string) error {
+ if activateEnforcement != nil {
+ return activateEnforcement(cmd, endpointEnforcementOpts.dashboardURL)
+ }
+ if os.Getenv(enforcementHandoffEnv) != "" {
+ return errors.New("the installed beacon does not carry policy enforcement")
+ }
+ if err := checkEnforcementPrerequisites(); err != nil {
+ return err
+ }
+ out := cmd.OutOrStdout()
+
+ ctx, cancel := context.WithTimeout(cmd.Context(), enforcementInstallTimeout)
+ defer cancel()
+ if selfupdate.VersionLineEdition(installedBeaconVersionLine(ctx)) == edition.Enterprise {
+ fmt.Fprintln(out, "The enterprise edition is already installed.")
+ } else if err := installEnterpriseEdition(ctx, out); err != nil {
+ return err
+ }
+ return runInstalledEnforcementEnable(cmd.Context(), endpointEnforcementOpts.dashboardURL)
+}
+
+// checkEnforcementPrerequisites refuses, before anything is downloaded, on a machine that cannot
+// run enforcement: anything but a Mac in system mode connected to its organization, with no
+// user-mode Beacon running for the person at the console.
+func checkEnforcementPrerequisites() error {
+ if !enforcementPlatformSupported() {
+ return errors.New("policy enforcement is available for macOS on Apple Silicon only")
+ }
+ if !enforcementHasRoot() {
+ return fmt.Errorf("turning on enforcement installs Beacon's enterprise edition, which needs root:\n sudo %s endpoint enforcement enable", runningBeaconPath())
+ }
+ if !enforcementConnected() {
+ return fmt.Errorf("this machine is not connected to an organization in system mode. Connect it first:\n sudo %s endpoint connect --system --dashboard-url https://asymptotelabs.ai", selfupdate.SystemBeaconPath())
+ }
+ who, found, err := enforcementUserModeProbe()
+ if err != nil {
+ return fmt.Errorf("checking for a user-mode Beacon: %w", err)
+ }
+ if len(found) > 0 {
+ return userModeActiveError(who, found)
+ }
+ return nil
+}
+
+func installEnterpriseEdition(ctx context.Context, out io.Writer) error {
+ dashboard, deviceKey, err := enforcementCredentials()
+ if err != nil {
+ return err
+ }
+ if flag := strings.TrimSpace(endpointEnforcementOpts.dashboardURL); flag != "" {
+ dashboard = flag
+ }
+ locateCtx, cancel := context.WithTimeout(ctx, enforcementLocateTimeout)
+ rel, err := locateEnterpriseRelease(locateCtx, nil, dashboard, deviceKey, "")
+ cancel()
+ if err != nil {
+ return explainEnterpriseRefusal(dashboard, err)
+ }
+ fmt.Fprintf(out, "Installing Beacon %s, enterprise edition (%.0f MB)…\n", rel.Version, float64(rel.Size)/1e6)
+ res, err := installEnterpriseRelease(ctx, rel, version.GetVersion(), endpointSystemLogPath())
+ if err != nil {
+ if res.RolledBack {
+ fmt.Fprintln(out, "The install failed and was rolled back; Beacon is as it was.")
+ }
+ return fmt.Errorf("installing the enterprise edition: %w", err)
+ }
+ fmt.Fprintf(out, "Installed Beacon %s, enterprise edition (verified: %s).\n", rel.Version, res.Verification)
+ return nil
+}
+
+// systemEnforcementCredentials reads the platform this machine connected to and its device key.
+// The key is read into memory for the one request that proves the device; it is never copied.
+func systemEnforcementCredentials() (string, string, error) {
+ enrollment, err := asymptote.LoadEnrollment(false)
+ if err != nil {
+ return "", "", fmt.Errorf("reading this machine's enrollment: %w", err)
+ }
+ key, err := asymptote.ReadDeviceKey(false)
+ if err != nil {
+ return "", "", fmt.Errorf("reading this machine's device key: %w", err)
+ }
+ return enrollment.DashboardURL, key, nil
+}
+
+func explainEnterpriseRefusal(dashboard string, err error) error {
+ var refused *edition.HTTPError
+ if !errors.As(err, &refused) {
+ return fmt.Errorf("asking %s for the enterprise edition: %w", dashboard, err)
+ }
+ switch refused.Status {
+ case http.StatusUnauthorized:
+ return fmt.Errorf("%s did not accept this machine's device key (revoked or expired?). Reconnect with:\n sudo %s endpoint connect --system --dashboard-url %s",
+ dashboard, selfupdate.SystemBeaconPath(), dashboard)
+ case http.StatusForbidden, http.StatusNotFound:
+ return fmt.Errorf("%s refused: %s", dashboard, firstNonEmpty(refused.Detail, "policy enforcement is not available for this organization"))
+ default:
+ return fmt.Errorf("%s could not provide the enterprise edition: %v", dashboard, refused)
+ }
+}
+
+// probeConsoleUserMode reports what shows the console user running Beacon in user mode: its
+// collector or forwarder loaded in their launchd session, or Claude Code hooks that write to their
+// own runtime log. Enforcement runs in system mode only, and enabling it would repoint those hooks.
+func probeConsoleUserMode() (string, []string, error) {
+ info, ok, err := activeConsoleUser()
+ if err != nil || !ok {
+ return "", nil, err
+ }
+ var found []string
+ if u, err := user.Lookup(info.Username); err == nil {
+ for _, label := range []string{service.UserLabel, service.ForwarderLabel} {
+ if exec.Command("launchctl", "print", "gui/"+u.Uid+"/"+label).Run() == nil {
+ found = append(found, fmt.Sprintf("%s is loaded in %s's session", label, info.Username))
+ }
+ }
+ }
+ userLog := filepath.Join(info.HomeDir, writer.UserLogPath)
+ settings := filepath.Join(info.HomeDir, ".claude", "settings.json")
+ if data, err := os.ReadFile(settings); err == nil && strings.Contains(string(data), userLog) {
+ found = append(found, fmt.Sprintf("Claude Code hooks in %s write to %s", settings, userLog))
+ }
+ return info.Username, found, nil
+}
+
+func userModeActiveError(who string, found []string) error {
+ var b strings.Builder
+ fmt.Fprintf(&b, "Beacon is running in user mode for %s, and enforcement runs in system mode only:\n", who)
+ for _, f := range found {
+ fmt.Fprintf(&b, " - %s\n", f)
+ }
+ fmt.Fprintf(&b, "Stop user mode first. As %s:\n", who)
+ for _, label := range []string{service.UserLabel, service.ForwarderLabel, service.InventoryLabel} {
+ fmt.Fprintf(&b, " launchctl bootout gui/$(id -u)/%s; launchctl disable gui/$(id -u)/%s\n", label, label)
+ }
+ fmt.Fprintf(&b, "then point the hooks at system mode and run this again:\n")
+ fmt.Fprintf(&b, " sudo %s endpoint user-config repair-installed --system --harness claude,codex", selfupdate.SystemBeaconPath())
+ return errors.New(b.String())
+}
+
+func defaultInstalledBeaconVersionLine(ctx context.Context) string {
+ ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ out, err := exec.CommandContext(ctx, selfupdate.SystemBeaconPath(), "version").Output()
+ if err != nil {
+ return ""
+ }
+ return string(out)
+}
+
+// defaultRunInstalledEnforcementEnable runs the installed binary's enable, which turns enforcement
+// on. It inherits this process's terminal.
+func defaultRunInstalledEnforcementEnable(ctx context.Context, dashboardURL string) error {
+ args := []string{"endpoint", "enforcement", "enable"}
+ if dashboardURL != "" {
+ args = append(args, "--dashboard-url", dashboardURL)
+ }
+ bin := selfupdate.SystemBeaconPath()
+ child := exec.CommandContext(ctx, bin, args...)
+ child.Env = append(os.Environ(), enforcementHandoffEnv+"=1")
+ child.Stdin, child.Stdout, child.Stderr = os.Stdin, os.Stdout, os.Stderr
+ if err := child.Run(); err != nil {
+ return fmt.Errorf("the enterprise edition is installed, but turning enforcement on did not finish (%v). Run it again with:\n sudo %s endpoint enforcement enable", err, bin)
+ }
+ return nil
+}
+
+func runningBeaconPath() string {
+ if exe, err := os.Executable(); err == nil {
+ return exe
+ }
+ return "beacon"
+}
diff --git a/cli/beacon/cmd/endpoint_enforcement_test.go b/cli/beacon/cmd/endpoint_enforcement_test.go
new file mode 100644
index 00000000..f520fbda
--- /dev/null
+++ b/cli/beacon/cmd/endpoint_enforcement_test.go
@@ -0,0 +1,252 @@
+package cmd
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/spf13/cobra"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/edition"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"
+)
+
+// enforcementFakes replaces every seam the public enable reaches with a fake that records what
+// ran. The defaults describe a connected Mac in system mode with the community edition installed.
+type enforcementFakes struct {
+ supported, root, connected bool
+ userMode []string
+ installedLine string
+ locateErr, installErr error
+ rolledBack bool
+
+ located, installed []edition.Release
+ locatedWith []string
+ handedOff []string
+}
+
+func stubEnforcement(t *testing.T) *enforcementFakes {
+ t.Helper()
+ f := &enforcementFakes{
+ supported: true, root: true, connected: true,
+ installedLine: "beacon version 1.3.40 (abc) built on today\n",
+ }
+ rel := edition.Release{Version: "1.3.41", URL: "https://x.example/p", SHA256: strings.Repeat("a", 64), Size: 74_700_000}
+
+ saved := []func(){
+ swapEnforcementSeam(&enforcementPlatformSupported, func() bool { return f.supported }),
+ swapEnforcementSeam(&enforcementHasRoot, func() bool { return f.root }),
+ swapEnforcementSeam(&enforcementConnected, func() bool { return f.connected }),
+ swapEnforcementSeam(&enforcementCredentials, func() (string, string, error) {
+ return "https://platform.example", "bcn_device_test", nil
+ }),
+ swapEnforcementSeam(&enforcementUserModeProbe, func() (string, []string, error) { return "dev", f.userMode, nil }),
+ swapEnforcementSeam(&installedBeaconVersionLine, func(context.Context) string { return f.installedLine }),
+ swapEnforcementSeam(&locateEnterpriseRelease, func(_ context.Context, _ *http.Client, dashboard, key, version string) (edition.Release, error) {
+ f.locatedWith = append(f.locatedWith, dashboard+" "+key+" "+version)
+ if f.locateErr != nil {
+ return edition.Release{}, f.locateErr
+ }
+ f.located = append(f.located, rel)
+ return rel, nil
+ }),
+ swapEnforcementSeam(&installEnterpriseRelease, func(_ context.Context, r edition.Release, _, _ string) (selfupdate.ApplyResult, error) {
+ f.installed = append(f.installed, r)
+ if f.installErr != nil {
+ return selfupdate.ApplyResult{RolledBack: f.rolledBack}, f.installErr
+ }
+ return selfupdate.ApplyResult{Applied: true, Verification: "sha256+notarization"}, nil
+ }),
+ swapEnforcementSeam(&runInstalledEnforcementEnable, func(_ context.Context, dashboard string) error {
+ f.handedOff = append(f.handedOff, dashboard)
+ return nil
+ }),
+ swapEnforcementSeam(&activateEnforcement, nil),
+ }
+ t.Cleanup(func() {
+ for _, restore := range saved {
+ restore()
+ }
+ endpointEnforcementOpts.dashboardURL = ""
+ })
+ t.Setenv(enforcementHandoffEnv, "")
+ return f
+}
+
+func swapEnforcementSeam[T any](target *T, value T) func() {
+ old := *target
+ *target = value
+ return func() { *target = old }
+}
+
+func runEnforcementEnableForTest(t *testing.T) (string, error) {
+ t.Helper()
+ var out bytes.Buffer
+ cmd := &cobra.Command{}
+ cmd.SetOut(&out)
+ cmd.SetContext(context.Background())
+ err := runEndpointEnforcementEnable(cmd, nil)
+ return out.String(), err
+}
+
+func TestEnforcementEnableInstallsTheEnterpriseEditionThenHandsOff(t *testing.T) {
+ f := stubEnforcement(t)
+ out, err := runEnforcementEnableForTest(t)
+ if err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if len(f.installed) != 1 || f.installed[0].Version != "1.3.41" {
+ t.Fatalf("installed = %+v", f.installed)
+ }
+ if strings.Join(f.locatedWith, ",") != "https://platform.example bcn_device_test " {
+ t.Fatalf("located with = %q", f.locatedWith)
+ }
+ if len(f.handedOff) != 1 || f.handedOff[0] != "" {
+ t.Fatalf("handed off = %q", f.handedOff)
+ }
+ for _, want := range []string{"Installing Beacon 1.3.41, enterprise edition (75 MB)", "verified: sha256+notarization"} {
+ if !strings.Contains(out, want) {
+ t.Fatalf("output %q lacks %q", out, want)
+ }
+ }
+ if strings.Contains(out, "bcn_device_test") {
+ t.Fatal("the device key reached the output")
+ }
+}
+
+func TestEnforcementEnableSkipsTheInstallWhenTheEnterpriseEditionIsInstalled(t *testing.T) {
+ f := stubEnforcement(t)
+ f.installedLine = "beacon version 1.3.41 (abc) built on today, enterprise edition\n"
+ endpointEnforcementOpts.dashboardURL = "https://other.example"
+ out, err := runEnforcementEnableForTest(t)
+ if err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if len(f.locatedWith) != 0 || len(f.installed) != 0 {
+ t.Fatalf("located %v, installed %v", f.locatedWith, f.installed)
+ }
+ if !strings.Contains(out, "already installed") || len(f.handedOff) != 1 || f.handedOff[0] != "https://other.example" {
+ t.Fatalf("out %q, handed off %q", out, f.handedOff)
+ }
+}
+
+func TestEnforcementEnableUsesTheDashboardFlag(t *testing.T) {
+ f := stubEnforcement(t)
+ endpointEnforcementOpts.dashboardURL = "https://other.example"
+ if _, err := runEnforcementEnableForTest(t); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if !strings.HasPrefix(f.locatedWith[0], "https://other.example ") {
+ t.Fatalf("located with %q", f.locatedWith)
+ }
+}
+
+func TestEnforcementEnableRefusesBeforeAskingThePlatform(t *testing.T) {
+ cases := map[string]struct {
+ set func(*enforcementFakes)
+ want string
+ }{
+ "not a Mac": {func(f *enforcementFakes) { f.supported = false }, "macOS on Apple Silicon only"},
+ "not root": {func(f *enforcementFakes) { f.root = false }, "needs root"},
+ "not connected": {func(f *enforcementFakes) { f.connected = false }, "endpoint connect --system"},
+ "user mode": {func(f *enforcementFakes) {
+ f.userMode = []string{"com.beacon.endpoint.collector.user is loaded in dev's session"}
+ }, "running in user mode for dev"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ f := stubEnforcement(t)
+ tc.set(f)
+ _, err := runEnforcementEnableForTest(t)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("err = %v, want %q", err, tc.want)
+ }
+ if len(f.locatedWith)+len(f.installed)+len(f.handedOff) != 0 {
+ t.Fatalf("located %v, installed %v, handed off %v", f.locatedWith, f.installed, f.handedOff)
+ }
+ })
+ }
+}
+
+func TestEnforcementEnableExplainsThePlatformsRefusal(t *testing.T) {
+ cases := map[string]struct {
+ err error
+ want string
+ }{
+ "revoked device": {&edition.HTTPError{Status: 401, Detail: "invalid or revoked device key"}, "did not accept this machine's device key"},
+ "org off": {&edition.HTTPError{Status: 403, Detail: "policy enforcement is not enabled for this organization"},
+ "refused: policy enforcement is not enabled for this organization"},
+ "unreachable": {errors.New("dial tcp: connection refused"), "asking https://platform.example for the enterprise edition"},
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ f := stubEnforcement(t)
+ f.locateErr = tc.err
+ _, err := runEnforcementEnableForTest(t)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("err = %v, want %q", err, tc.want)
+ }
+ if len(f.installed)+len(f.handedOff) != 0 {
+ t.Fatalf("installed %v, handed off %v", f.installed, f.handedOff)
+ }
+ })
+ }
+}
+
+func TestEnforcementEnableStopsWhenTheInstallFails(t *testing.T) {
+ f := stubEnforcement(t)
+ f.installErr, f.rolledBack = errors.New("verify checksum: sha256 mismatch"), true
+ out, err := runEnforcementEnableForTest(t)
+ if err == nil || !strings.Contains(err.Error(), "sha256 mismatch") {
+ t.Fatalf("err = %v", err)
+ }
+ if !strings.Contains(out, "rolled back") || len(f.handedOff) != 0 {
+ t.Fatalf("out %q, handed off %v", out, f.handedOff)
+ }
+}
+
+func TestEnforcementEnableRunsTheBuildsOwnActivation(t *testing.T) {
+ f := stubEnforcement(t)
+ var activated []string
+ activateEnforcement = func(_ *cobra.Command, dashboard string) error {
+ activated = append(activated, dashboard)
+ return nil
+ }
+ endpointEnforcementOpts.dashboardURL = "https://other.example"
+ f.root = false // the build's own activation does its own checks
+ if _, err := runEnforcementEnableForTest(t); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if strings.Join(activated, ",") != "https://other.example" || len(f.locatedWith)+len(f.handedOff) != 0 {
+ t.Fatalf("activated %v, located %v, handed off %v", activated, f.locatedWith, f.handedOff)
+ }
+}
+
+func TestEnforcementEnableRefusesAHandoffToABuildWithoutEnforcement(t *testing.T) {
+ f := stubEnforcement(t)
+ t.Setenv(enforcementHandoffEnv, "1")
+ _, err := runEnforcementEnableForTest(t)
+ if err == nil || !strings.Contains(err.Error(), "does not carry policy enforcement") {
+ t.Fatalf("err = %v", err)
+ }
+ if len(f.locatedWith)+len(f.installed)+len(f.handedOff) != 0 {
+ t.Fatal("a handed-off enable must never install again")
+ }
+}
+
+func TestUserModeActiveErrorNamesWhatToStop(t *testing.T) {
+ err := userModeActiveError("dev", []string{"Claude Code hooks in /Users/dev/.claude/settings.json write to /Users/dev/.beacon/endpoint/logs/runtime.jsonl"})
+ for _, want := range []string{
+ "launchctl bootout gui/$(id -u)/com.beacon.endpoint.collector.user",
+ "launchctl bootout gui/$(id -u)/com.beacon.endpoint.asymptote-forwarder",
+ "endpoint user-config repair-installed --system --harness claude,codex",
+ "write to /Users/dev/.beacon/endpoint/logs/runtime.jsonl",
+ } {
+ if !strings.Contains(err.Error(), want) {
+ t.Fatalf("%q lacks %q", err, want)
+ }
+ }
+}
diff --git a/cli/beacon/internal/endpoint/edition/edition.go b/cli/beacon/internal/endpoint/edition/edition.go
new file mode 100644
index 00000000..22cf16c2
--- /dev/null
+++ b/cli/beacon/internal/endpoint/edition/edition.go
@@ -0,0 +1,160 @@
+// Package edition installs Beacon's enterprise edition on a machine that is connected to its
+// organization. The platform the machine enrolled with decides, per organization, whether it may
+// have it: the root CLI proves the device with its managed-ingest device key (read into memory for
+// one request, never copied), and the platform answers with the package's version, SHA-256 and a
+// short-lived download link. The package is then installed with the self-updater's steps.
+//
+// The platform can stop an install but never choose what gets installed: the package must match
+// the checksum, carry a Developer ID signature from the Apple team pinned here, pass Gatekeeper,
+// and report the expected version and edition once installed, or the install is rolled back.
+package edition
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/selfupdate"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/updatecheck"
+)
+
+const (
+ // Enterprise is the edition this package installs.
+ Enterprise = "enterprise"
+ // DownloadPath is the platform route that answers with a package for a device key.
+ DownloadPath = "/api/cli/enforcement/download"
+ // AppleTeamID is the Apple Developer team that signs every Beacon package. Pinned here
+ // rather than taken from the platform's answer.
+ AppleTeamID = "3A98D35XJR"
+
+ requestTimeout = 30 * time.Second
+ maxAnswer = 64 << 10
+)
+
+var sha256Hex = regexp.MustCompile(`^[0-9a-f]{64}$`)
+
+// Release is the platform's answer: one signed package and a link to it.
+type Release struct {
+ Version string `json:"version"`
+ Name string `json:"name"`
+ URL string `json:"url"`
+ SHA256 string `json:"sha256"`
+ Size int64 `json:"size"`
+}
+
+// HTTPError is a refusal from the platform, with its own explanation.
+type HTTPError struct {
+ Status int
+ Detail string
+}
+
+func (e *HTTPError) Error() string {
+ if e.Detail != "" {
+ return fmt.Sprintf("HTTP %d: %s", e.Status, e.Detail)
+ }
+ return fmt.Sprintf("HTTP %d", e.Status)
+}
+
+// Locate asks the platform for the enterprise package: the latest release when version is empty,
+// otherwise exactly that version. client may be nil.
+func Locate(ctx context.Context, client *http.Client, dashboardURL, deviceKey, version string) (Release, error) {
+ endpoint, err := credentialURL(dashboardURL, DownloadPath)
+ if err != nil {
+ return Release{}, err
+ }
+ body := []byte("{}")
+ if version != "" {
+ body, _ = json.Marshal(map[string]string{"version": strings.TrimPrefix(version, "v")})
+ }
+ if client == nil {
+ client = &http.Client{Timeout: requestTimeout}
+ }
+ c := *client
+ // The device key is a bearer credential: it must never follow a redirect.
+ c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
+ if err != nil {
+ return Release{}, err
+ }
+ req.Header.Set("Authorization", "Bearer "+deviceKey)
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ resp, err := c.Do(req)
+ if err != nil {
+ return Release{}, err
+ }
+ defer resp.Body.Close()
+ data, err := io.ReadAll(io.LimitReader(resp.Body, maxAnswer))
+ if err != nil {
+ return Release{}, err
+ }
+ if resp.StatusCode != http.StatusOK {
+ var refusal struct {
+ Detail any `json:"detail"`
+ }
+ _ = json.Unmarshal(data, &refusal)
+ detail, _ := refusal.Detail.(string)
+ return Release{}, &HTTPError{Status: resp.StatusCode, Detail: detail}
+ }
+ var rel Release
+ if err := json.Unmarshal(data, &rel); err != nil {
+ return Release{}, fmt.Errorf("the platform's answer is not JSON: %w", err)
+ }
+ rel.SHA256 = strings.ToLower(strings.TrimSpace(rel.SHA256))
+ switch {
+ case !updatecheck.CanCheckVersion(rel.Version):
+ return Release{}, fmt.Errorf("the platform named no release version (%q)", rel.Version)
+ case version != "" && rel.Version != strings.TrimPrefix(version, "v"):
+ return Release{}, fmt.Errorf("asked for %s, the platform answered with %s", version, rel.Version)
+ case !sha256Hex.MatchString(rel.SHA256):
+ return Release{}, errors.New("the platform's answer has no SHA-256")
+ case !strings.HasPrefix(rel.URL, "https://"):
+ return Release{}, errors.New("the platform's answer has no https download link")
+ }
+ return rel, nil
+}
+
+// Install verifies and installs rel with the self-updater's steps, rolling back if the result
+// does not report rel's version and the enterprise edition. currentVersion is the running CLI's,
+// for the update record; logPath is where that record goes (empty: the system log).
+func Install(ctx context.Context, rel Release, currentVersion, logPath string) (selfupdate.ApplyResult, error) {
+ a := selfupdate.NewApplier(currentVersion)
+ a.LogPath = logPath
+ return a.InstallPackage(ctx, selfupdate.Package{
+ URL: rel.URL,
+ SHA256: rel.SHA256,
+ Version: rel.Version,
+ TeamID: AppleTeamID,
+ Edition: Enterprise,
+ })
+}
+
+// credentialURL joins base and path, and requires https (plain http only to a loopback host,
+// for tests), because the request carries the device key.
+func credentialURL(base, path string) (string, error) {
+ u, err := url.Parse(strings.TrimRight(strings.TrimSpace(base), "/"))
+ if err != nil || u.Host == "" {
+ return "", fmt.Errorf("invalid platform URL %q", base)
+ }
+ if u.Scheme != "https" && !(u.Scheme == "http" && loopback(u.Hostname())) {
+ return "", fmt.Errorf("refusing to send the device key to %s: https is required", u.Redacted())
+ }
+ return u.JoinPath(path).String(), nil
+}
+
+func loopback(host string) bool {
+ if host == "localhost" {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
diff --git a/cli/beacon/internal/endpoint/edition/edition_test.go b/cli/beacon/internal/endpoint/edition/edition_test.go
new file mode 100644
index 00000000..258c1495
--- /dev/null
+++ b/cli/beacon/internal/endpoint/edition/edition_test.go
@@ -0,0 +1,127 @@
+package edition
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+const testKey = "bcn_device_abcd1234_secretpart"
+
+var testSHA = strings.Repeat("ab", 32)
+
+func platform(t *testing.T, handler http.HandlerFunc) *httptest.Server {
+ t.Helper()
+ srv := httptest.NewServer(handler)
+ t.Cleanup(srv.Close)
+ return srv
+}
+
+func answer(w http.ResponseWriter, status int, body any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(body)
+}
+
+func TestLocateSendsTheDeviceKeyAndReadsTheRelease(t *testing.T) {
+ var gotAuth, gotBody, gotPath string
+ srv := platform(t, func(w http.ResponseWriter, r *http.Request) {
+ gotAuth, gotPath = r.Header.Get("Authorization"), r.URL.Path
+ data, _ := io.ReadAll(r.Body)
+ gotBody = string(data)
+ answer(w, 200, map[string]any{
+ "version": "1.3.41", "name": "BeaconEnterprise-1.3.41-arm64.pkg",
+ "url": "https://release-assets.example/pkg?sig=x", "sha256": strings.ToUpper(testSHA), "size": 74725771,
+ })
+ })
+
+ rel, err := Locate(context.Background(), nil, srv.URL+"/", testKey, "")
+ if err != nil {
+ t.Fatalf("Locate: %v", err)
+ }
+ if gotAuth != "Bearer "+testKey || gotPath != DownloadPath || gotBody != "{}" {
+ t.Fatalf("request = %q %q %q", gotAuth, gotPath, gotBody)
+ }
+ want := Release{Version: "1.3.41", Name: "BeaconEnterprise-1.3.41-arm64.pkg",
+ URL: "https://release-assets.example/pkg?sig=x", SHA256: testSHA, Size: 74725771}
+ if rel != want {
+ t.Fatalf("release = %+v", rel)
+ }
+
+ if _, err := Locate(context.Background(), nil, srv.URL, testKey, "v1.3.41"); err != nil {
+ t.Fatalf("Locate with a version: %v", err)
+ }
+ if gotBody != `{"version":"1.3.41"}` {
+ t.Fatalf("body = %q", gotBody)
+ }
+}
+
+func TestLocateRefusesToSendTheKeyOverPlainHTTP(t *testing.T) {
+ _, err := Locate(context.Background(), nil, "http://platform.example", testKey, "")
+ if err == nil || !strings.Contains(err.Error(), "https is required") {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestLocateNeverFollowsARedirect(t *testing.T) {
+ var followed atomic.Bool
+ elsewhere := platform(t, func(http.ResponseWriter, *http.Request) { followed.Store(true) })
+ srv := platform(t, func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, elsewhere.URL+DownloadPath, http.StatusTemporaryRedirect)
+ })
+ _, err := Locate(context.Background(), nil, srv.URL, testKey, "")
+ var refused *HTTPError
+ if !errors.As(err, &refused) || refused.Status != http.StatusTemporaryRedirect {
+ t.Fatalf("err = %v", err)
+ }
+ if followed.Load() {
+ t.Fatal("the device key followed a redirect")
+ }
+}
+
+func TestLocateReturnsThePlatformsRefusal(t *testing.T) {
+ srv := platform(t, func(w http.ResponseWriter, _ *http.Request) {
+ answer(w, 403, map[string]string{"detail": "policy enforcement is not enabled for this organization"})
+ })
+ _, err := Locate(context.Background(), nil, srv.URL, testKey, "")
+ var refused *HTTPError
+ if !errors.As(err, &refused) || refused.Status != 403 ||
+ refused.Detail != "policy enforcement is not enabled for this organization" {
+ t.Fatalf("err = %v", err)
+ }
+}
+
+func TestLocateRejectsAnAnswerItCannotInstall(t *testing.T) {
+ good := map[string]any{"version": "1.3.41", "url": "https://x.example/p", "sha256": testSHA, "size": 1}
+ for name, tc := range map[string]struct {
+ change map[string]any
+ version string
+ want string
+ }{
+ "no version": {change: map[string]any{"version": "latest"}, want: "no release version"},
+ "another version": {version: "1.3.40", want: "answered with 1.3.41"},
+ "no checksum": {change: map[string]any{"sha256": "abc"}, want: "no SHA-256"},
+ "plain http link": {change: map[string]any{"url": "http://x.example/p"}, want: "no https download link"},
+ } {
+ t.Run(name, func(t *testing.T) {
+ body := map[string]any{}
+ for k, v := range good {
+ body[k] = v
+ }
+ for k, v := range tc.change {
+ body[k] = v
+ }
+ srv := platform(t, func(w http.ResponseWriter, _ *http.Request) { answer(w, 200, body) })
+ _, err := Locate(context.Background(), nil, srv.URL, testKey, tc.version)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("err = %v, want %q", err, tc.want)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/endpoint/selfupdate/apply.go b/cli/beacon/internal/endpoint/selfupdate/apply.go
index 5a7e0e45..ede44b1c 100644
--- a/cli/beacon/internal/endpoint/selfupdate/apply.go
+++ b/cli/beacon/internal/endpoint/selfupdate/apply.go
@@ -152,7 +152,51 @@ func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
a.emit(false, result, fmt.Sprintf("no update artifact this host can install (looked for %s)", key))
return result, fmt.Errorf("no update artifact this host can install (looked for %s)", key)
}
+ pkg := Package{URL: artifact.URL, SHA256: artifact.SHA256, Version: manifest.Version, TeamID: manifest.TeamID}
+ return a.installPackage(ctx, pkg, result, fmt.Sprintf("updated %s -> %s", a.CurrentVersion, manifest.Version))
+}
+
+// Package is one release artifact to install: where it is, what it must hash to, and what the
+// installed beacon must report afterwards.
+type Package struct {
+ URL string
+ SHA256 string
+ Version string
+ // TeamID is the Apple team that must have signed the package. Empty skips only the team
+ // match; the signature and Gatekeeper checks still run.
+ TeamID string
+ // Edition, when set, must be the edition the installed `beacon version` reports.
+ Edition string
+}
+
+// InstallPackage downloads, verifies and installs one package, then health-checks the result and
+// rolls back on failure, exactly as Apply does after it has picked an artifact. It consults no
+// manifest and has no version gate, so it can install the same version again or another edition
+// of it; deciding whether to install is the caller's job.
+func (a *Applier) InstallPackage(ctx context.Context, pkg Package) (ApplyResult, error) {
+ if a.SkipGatekeeper && !a.AllowInsecureTest {
+ return ApplyResult{}, fmt.Errorf("SkipGatekeeper requires AllowInsecureTest")
+ }
+ if a.AllowInsecureTest && filepath.Clean(a.prefix()) == string(filepath.Separator) {
+ return ApplyResult{}, fmt.Errorf("AllowInsecureTest requires a non-root install prefix")
+ }
+ result := ApplyResult{FromVersion: a.CurrentVersion, ToVersion: pkg.Version}
+ if !updatecheck.CanCheckVersion(pkg.Version) {
+ return result, fmt.Errorf("package version %q is not a release version", pkg.Version)
+ }
+ if !a.AllowInsecureTest && !strings.HasPrefix(pkg.URL, "https://") {
+ return result, fmt.Errorf("refusing to download a package over %q: https is required", pkg.URL)
+ }
+ message := "installed " + pkg.Version
+ if pkg.Edition != "" {
+ message += ", " + pkg.Edition + " edition"
+ }
+ return a.installPackage(ctx, pkg, result, message)
+}
+// installPackage is everything after discovery: download, verify, snapshot, install, restart,
+// health check, and rollback when any step after the install fails.
+func (a *Applier) installPackage(ctx context.Context, pkg Package, result ApplyResult, success string) (ApplyResult, error) {
// Serialize concurrent updaters.
stage := a.stageDir()
if err := os.MkdirAll(stage, 0o755); err != nil {
@@ -166,14 +210,14 @@ func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
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 {
+ pkgPath := filepath.Join(stage, "download"+packageExt(pkg.URL))
+ if err := a.download(ctx, pkg.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 {
+ if err := verifySHA256(pkgPath, pkg.SHA256); err != nil {
a.emit(false, result, err.Error())
return result, fmt.Errorf("verify checksum: %w", err)
}
@@ -197,7 +241,7 @@ func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
result.Verification = "sha256 (notarization check skipped)"
default:
result.Verification = "sha256+notarization"
- if err := a.verifyGatekeeper(ctx, pkgPath, manifest.TeamID); err != nil {
+ if err := a.verifyGatekeeper(ctx, pkgPath, pkg.TeamID); err != nil {
a.emit(false, result, err.Error())
return result, fmt.Errorf("verify signature/notarization: %w", err)
}
@@ -236,7 +280,7 @@ func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
}
}
- if err := a.healthCheck(ctx, manifest.Version); err != nil {
+ if err := a.healthCheck(ctx, pkg.Version, pkg.Edition); err != nil {
rollbackErr := a.rollback(backup, &result)
message := "post-install health check failed: " + err.Error()
if rollbackErr != nil {
@@ -248,7 +292,7 @@ func (a *Applier) Apply(ctx context.Context) (ApplyResult, error) {
}
result.Applied = true
- result.Message = fmt.Sprintf("updated %s -> %s", a.CurrentVersion, manifest.Version)
+ result.Message = success
a.cleanupSuccessfulUpdate()
a.emit(true, result, result.Message)
return result, nil
@@ -556,8 +600,9 @@ func (a *Applier) rollback(backup string, result *ApplyResult) error {
}
// 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 {
+// version (and edition, when one is expected) and, in production, that the
+// collector service is running.
+func (a *Applier) healthCheck(ctx context.Context, wantVersion, wantEdition string) error {
bin := filepath.Join(a.binDir(), "beacon")
out, err := a.runner()(ctx, bin, "version")
if err != nil {
@@ -566,6 +611,9 @@ func (a *Applier) healthCheck(ctx context.Context, wantVersion string) error {
if !versionLineMatches(out, wantVersion) {
return fmt.Errorf("installed binary reports %q, expected version %s", strings.TrimSpace(out), wantVersion)
}
+ if wantEdition != "" && VersionLineEdition(out) != wantEdition {
+ return fmt.Errorf("installed binary reports %q, expected the %s edition", strings.TrimSpace(out), wantEdition)
+ }
if a.AllowInsecureTest {
return nil
}
@@ -605,6 +653,21 @@ func versionLineMatches(out, want string) bool {
return false
}
+// VersionLineEdition returns the edition `beacon version` output names ("…, <edition> edition"
+// at the end of the line), or "" for a build that reports none, which is the default edition.
+func VersionLineEdition(out string) string {
+ line, _, _ := strings.Cut(strings.TrimSpace(out), "\n")
+ rest, ok := strings.CutSuffix(strings.TrimSpace(line), " edition")
+ if !ok {
+ return ""
+ }
+ i := strings.LastIndex(rest, ", ")
+ if i < 0 {
+ return ""
+ }
+ return rest[i+2:]
+}
+
// selectArtifact picks the release artifact this host can actually install.
//
// One key per architecture is not enough on Linux, because two incompatible package formats share
diff --git a/cli/beacon/internal/endpoint/selfupdate/apply_test.go b/cli/beacon/internal/endpoint/selfupdate/apply_test.go
index c30cb658..0d27f121 100644
--- a/cli/beacon/internal/endpoint/selfupdate/apply_test.go
+++ b/cli/beacon/internal/endpoint/selfupdate/apply_test.go
@@ -21,9 +21,13 @@ import (
// 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) {
+func makeBeaconTarball(t *testing.T, version string, edition ...string) ([]byte, string) {
t.Helper()
- script := "#!/bin/sh\necho \"beacon version " + version + " (test) built on test\"\n"
+ line := "beacon version " + version + " (test) built on test"
+ if len(edition) > 0 {
+ line += ", " + edition[0] + " edition"
+ }
+ script := "#!/bin/sh\necho \"" + line + "\"\n"
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
tw := tar.NewWriter(gz)
diff --git a/cli/beacon/internal/endpoint/selfupdate/install_package_test.go b/cli/beacon/internal/endpoint/selfupdate/install_package_test.go
new file mode 100644
index 00000000..9bf76599
--- /dev/null
+++ b/cli/beacon/internal/endpoint/selfupdate/install_package_test.go
@@ -0,0 +1,216 @@
+package selfupdate
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+// packageServer serves one artifact at /artifact.tar.gz and counts the downloads.
+func packageServer(t *testing.T, artifact []byte) (*httptest.Server, *atomic.Int32) {
+ t.Helper()
+ var hits atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/artifact.tar.gz" {
+ http.NotFound(w, r)
+ return
+ }
+ hits.Add(1)
+ _, _ = w.Write(artifact)
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &hits
+}
+
+func packageApplier(t *testing.T, current string) *Applier {
+ t.Helper()
+ a := NewApplier(current)
+ a.ManifestURL = "http://127.0.0.1:1/never-fetched.json"
+ a.StageDir = t.TempDir()
+ a.InstallPrefix = t.TempDir()
+ a.AllowInsecureTest = true
+ a.SkipGatekeeper = true
+ a.LogPath = filepath.Join(t.TempDir(), "runtime.jsonl")
+ return a
+}
+
+func installedVersionLine(t *testing.T, a *Applier) string {
+ t.Helper()
+ out, err := execRun(context.Background(), filepath.Join(a.binDir(), "beacon"), "version")
+ if err != nil {
+ t.Fatalf("run installed beacon: %v: %s", err, out)
+ }
+ return strings.TrimSpace(out)
+}
+
+func skipWithoutShellStubs(t *testing.T) {
+ t.Helper()
+ if runtime.GOOS == "windows" {
+ t.Skip("the POSIX install flow stages an executable shell stub; the Windows flow is not implemented yet")
+ }
+}
+
+func TestInstallPackageInstallsTheSameVersionWithoutAManifest(t *testing.T) {
+ skipWithoutShellStubs(t)
+ artifact, sha := makeBeaconTarball(t, "1.3.41", "partner")
+ srv, hits := packageServer(t, artifact)
+
+ // The running version equals the package's: Apply would stop at "already up to date".
+ a := packageApplier(t, "1.3.41")
+ res, err := a.InstallPackage(context.Background(), Package{
+ URL: srv.URL + "/artifact.tar.gz", SHA256: sha, Version: "1.3.41", Edition: "partner",
+ })
+ if err != nil {
+ t.Fatalf("InstallPackage: %v", err)
+ }
+ if !res.Applied || res.RolledBack || res.FromVersion != "1.3.41" || res.ToVersion != "1.3.41" {
+ t.Fatalf("result = %+v", res)
+ }
+ if res.Message != "installed 1.3.41, partner edition" {
+ t.Fatalf("message = %q", res.Message)
+ }
+ if hits.Load() != 1 {
+ t.Fatalf("downloads = %d", hits.Load())
+ }
+ if got := installedVersionLine(t, a); got != "beacon version 1.3.41 (test) built on test, partner edition" {
+ t.Fatalf("installed = %q", got)
+ }
+ log, err := os.ReadFile(a.LogPath)
+ if err != nil || !strings.Contains(string(log), "update.applied") {
+ t.Fatalf("telemetry = %q, %v", log, err)
+ }
+}
+
+func TestInstallPackageRollsBackWhenTheEditionIsWrong(t *testing.T) {
+ skipWithoutShellStubs(t)
+ a := packageApplier(t, "1.3.40")
+ before, beforeSHA := makeBeaconTarball(t, "1.3.40")
+ srv, _ := packageServer(t, before)
+ if _, err := a.InstallPackage(context.Background(), Package{
+ URL: srv.URL + "/artifact.tar.gz", SHA256: beforeSHA, Version: "1.3.40",
+ }); err != nil {
+ t.Fatalf("first install: %v", err)
+ }
+
+ // A package that installs a community build where the partner edition was expected.
+ wrong, wrongSHA := makeBeaconTarball(t, "1.3.41")
+ srv2, _ := packageServer(t, wrong)
+ res, err := a.InstallPackage(context.Background(), Package{
+ URL: srv2.URL + "/artifact.tar.gz", SHA256: wrongSHA, Version: "1.3.41", Edition: "partner",
+ })
+ if err == nil || !strings.Contains(err.Error(), "expected the partner edition") {
+ t.Fatalf("err = %v", err)
+ }
+ if !res.RolledBack || res.Applied {
+ t.Fatalf("result = %+v", res)
+ }
+ if got := installedVersionLine(t, a); got != "beacon version 1.3.40 (test) built on test" {
+ t.Fatalf("after rollback = %q", got)
+ }
+}
+
+func TestInstallPackageChecksumMismatchInstallsNothing(t *testing.T) {
+ skipWithoutShellStubs(t)
+ artifact, _ := makeBeaconTarball(t, "1.3.41")
+ srv, _ := packageServer(t, artifact)
+ a := packageApplier(t, "1.3.40")
+ _, err := a.InstallPackage(context.Background(), Package{
+ URL: srv.URL + "/artifact.tar.gz", SHA256: strings.Repeat("0", 64), Version: "1.3.41",
+ })
+ if err == nil || !strings.Contains(err.Error(), "sha256 mismatch") {
+ t.Fatalf("err = %v", err)
+ }
+ if _, statErr := os.Stat(filepath.Join(a.binDir(), "beacon")); !os.IsNotExist(statErr) {
+ t.Fatalf("a package that failed its checksum was installed: %v", statErr)
+ }
+}
+
+func TestInstallPackageRefusesBeforeDownloading(t *testing.T) {
+ artifact, sha := makeBeaconTarball(t, "1.3.41")
+ srv, hits := packageServer(t, artifact)
+
+ cases := map[string]struct {
+ insecure bool
+ pkg Package
+ want string
+ }{
+ "plain http": {
+ pkg: Package{URL: srv.URL + "/artifact.tar.gz", SHA256: sha, Version: "1.3.41"},
+ want: "https is required",
+ },
+ "not a release version": {
+ insecure: true,
+ pkg: Package{URL: srv.URL + "/artifact.tar.gz", SHA256: sha, Version: "latest"},
+ want: "not a release version",
+ },
+ }
+ for name, tc := range cases {
+ t.Run(name, func(t *testing.T) {
+ a := packageApplier(t, "1.3.40")
+ a.AllowInsecureTest, a.SkipGatekeeper = tc.insecure, tc.insecure
+ _, err := a.InstallPackage(context.Background(), tc.pkg)
+ if err == nil || !strings.Contains(err.Error(), tc.want) {
+ t.Fatalf("err = %v, want %q", err, tc.want)
+ }
+ })
+ }
+ if hits.Load() != 0 {
+ t.Fatalf("downloads = %d, want none", hits.Load())
+ }
+}
+
+func TestInstallPackageChecksTheTeamItWasGiven(t *testing.T) {
+ if runtime.GOOS != "darwin" {
+ t.Skip("Gatekeeper verification is macOS-only")
+ }
+ artifact, sha := makeBeaconTarball(t, "1.3.41")
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write(artifact)
+ }))
+ defer srv.Close()
+
+ a := NewApplier("1.3.40")
+ a.HTTPClient = srv.Client()
+ a.StageDir = t.TempDir()
+ a.InstallPrefix = t.TempDir()
+ a.LogPath = filepath.Join(t.TempDir(), "runtime.jsonl")
+ var calls []string
+ a.run = func(_ context.Context, name string, _ ...string) (string, error) {
+ calls = append(calls, name)
+ if name == "pkgutil" {
+ return "1. Developer ID Installer: Someone Else (OTHERTEAM1)", nil
+ }
+ return "", fmt.Errorf("%s must not run", name)
+ }
+ _, err := a.InstallPackage(context.Background(), Package{
+ URL: srv.URL + "/artifact.pkg", SHA256: sha, Version: "1.3.41", TeamID: "3A98D35XJR",
+ })
+ if err == nil || !strings.Contains(err.Error(), "expected team id 3A98D35XJR") {
+ t.Fatalf("err = %v", err)
+ }
+ if strings.Join(calls, ",") != "pkgutil" {
+ t.Fatalf("calls = %v; nothing may run after a signature from another team", calls)
+ }
+}
+
+func TestVersionLineEdition(t *testing.T) {
+ for out, want := range map[string]string{
+ "beacon version 1.3.41 (abc1234) built on 2026-10-15\n": "",
+ "beacon version 1.3.41 (abc1234) built on 2026-10-15, enterprise edition\n": "enterprise",
+ "beacon version 1.3.41 (abc) built on x, partner edition\nextra line": "partner",
+ "beacon version dev (unknown) built on unknown": "",
+ "": "",
+ "special edition": "",
+ } {
+ if got := VersionLineEdition(out); got != want {
+ t.Errorf("VersionLineEdition(%q) = %q, want %q", out, got, want)
+ }
+ }
+}