Skip to content

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

feat(windows): run the collector as a Windows service

shukieshah8f66ae6a768a
diff --git a/beacon-sandbox/scenarios/w01-install-service.yaml b/beacon-sandbox/scenarios/w01-install-service.yaml
new file mode 100644
index 00000000..7443fb15
--- /dev/null
+++ b/beacon-sandbox/scenarios/w01-install-service.yaml
@@ -0,0 +1,45 @@
+id: w01-install-service
+platform: windows
+# Exercises `beacon endpoint install --system` on Windows: does it register a service with the
+# Service Control Manager, does that service reach running, and does the endpoint report the
+# backend it actually selected?
+#
+# The service question is settled before the agent is involved. expect_service_kind is what makes
+# this scenario mean what it claims: "running" alone is satisfied by the supervised fallback too,
+# so without it a host where SCM registration failed would pass while testing the wrong backend
+# entirely -- the same trap the Linux systemd scenario documents.
+#
+# Capture is asserted only optionally, and that is deliberate rather than lax. Hook installation on
+# Windows still emits a POSIX `VAR=value cmd` string that neither Windows shell accepts, so nothing
+# reaches the collector through hooks yet. Marking these required would make the scenario fail for
+# a known reason and stop it reporting the service facts it exists to establish. They become
+# required in the change that fixes the hook command format.
+prompt: >-
+ Run exactly this PowerShell command and then report its output verbatim:
+ Write-Output '{{canary}}' | Tee-Object -FilePath '{{sentinel}}'
+sentinel: '{{workdir}}\w01.sentinel'
+budget_usd: 1.0
+timeout_seconds: 420
+
+install:
+ mode: system
+ service: windows-service
+ expect_status_running: true
+ expect_service_kind: windows-service
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ optional: true
+ why: >-
+ Capture through an installed Windows endpoint. Optional until hook installation emits a
+ command Windows can execute; the service assertions above are what this scenario gates on
+ today, and they are checked before the session runs.
+
+ - action: command.executed
+ fields: ["command.command"]
+ optional: true
+ why: >-
+ e.command.command is the detection surface for the whole rules/risky-command/ category. The
+ exporter now reads it from Claude Code's PowerShell tool, so this is the assertion that will
+ prove the fix end to end once hooks deliver events at all.
diff --git a/beacon-sandbox/scenarios/w02-install-supervised.yaml b/beacon-sandbox/scenarios/w02-install-supervised.yaml
new file mode 100644
index 00000000..affae5af
--- /dev/null
+++ b/beacon-sandbox/scenarios/w02-install-supervised.yaml
@@ -0,0 +1,32 @@
+id: w02-install-supervised
+platform: windows
+# User-mode install on Windows, which is the supervised backend rather than a second service.
+#
+# Windows has no per-user service manager -- no equivalent of `systemctl --user` or launchd's
+# gui/<uid> domain -- so `--user` falls back to a detached child tracked by a pidfile. That is a
+# real limitation, and this scenario exists to pin it: expect_service_kind asserts the fallback
+# actually happened rather than a service being registered under the user's name, which is what a
+# future change to the routing would silently do.
+#
+# The honest consequence, which status reports in-band: nothing restarts this collector, and it
+# does not survive logout.
+prompt: >-
+ Run exactly this PowerShell command and then report its output verbatim:
+ Write-Output '{{canary}}' | Tee-Object -FilePath '{{sentinel}}'
+sentinel: '{{workdir}}\w02.sentinel'
+budget_usd: 1.0
+timeout_seconds: 420
+
+install:
+ mode: user
+ expect_status_running: true
+ expect_service_kind: none
+
+expect:
+ - action: prompt.submitted
+ contains: ["{{canary}}"]
+ optional: true
+ why: >-
+ Same reason as w01: hook installation on Windows does not yet emit a command Windows can
+ execute, so capture is recorded rather than gated. The backend selection above is what this
+ scenario asserts today.
diff --git a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
index 56e5c9f6..92692573 100644
--- a/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
+++ b/cli/beacon/internal/endpoint/diagnostics/diagnostics.go
@@ -4,10 +4,13 @@ import (
"fmt"
"os"
"os/user"
+ "path/filepath"
+ "runtime"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/collector"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/service"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
)
type Check struct {
@@ -120,6 +123,9 @@ func checkLogPermissions(path string) Check {
if err != nil {
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusWarn, Severity: SeverityLow, Message: "runtime log not created yet", Evidence: "runtime_log_missing"}
}
+ if runtime.GOOS == "windows" {
+ return checkLogACL(path)
+ }
mode := info.Mode().Perm()
if mode&0222 == 0 {
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusFail, Severity: SeverityHigh, Message: fmt.Sprintf("runtime log is not writable: %o", mode), Evidence: "not_writable"}
@@ -129,3 +135,36 @@ func checkLogPermissions(path string) Check {
}
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusOK, Severity: SeverityInfo, Message: fmt.Sprintf("mode %o", mode), Evidence: fmt.Sprintf("mode_%o", mode)}
}
+
+// checkLogACL is the Windows form of the same question: can the people whose sessions this
+// endpoint captures write to its log?
+//
+// The mode-bit check above cannot answer it there. Windows reports 0666 for any ordinary file
+// regardless of its ACL, so `mode&0222 == 0` is never true and the check would report OK for
+// exactly the configuration it exists to catch -- a %ProgramData% log that only administrators can
+// write, with every hook write failing silently.
+//
+// Read from the ACL rather than by attempting a write, because doctor usually runs elevated: a
+// test write would succeed for the very user whose access is not in question.
+func checkLogACL(path string) Check {
+ dir := filepath.Dir(path)
+ ok, err := writer.SystemLogWritableByUsers(dir)
+ switch {
+ case err != nil:
+ // Unknown is reported as unknown. Claiming either answer here would be worse than saying
+ // the check could not run.
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusWarn,
+ Severity: SeverityLow, Message: "could not read the log directory ACL: " + err.Error(),
+ Evidence: "acl_unreadable"}
+ case !ok:
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusFail,
+ Severity: SeverityHigh,
+ Message: "interactive users cannot write to the log directory, so agent hooks will " +
+ "fail silently while the collector reports healthy",
+ Evidence: "acl_missing_interactive_write"}
+ default:
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusOK,
+ Severity: SeverityInfo, Message: "interactive users may write to the log directory",
+ Evidence: "acl_interactive_write"}
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
index 17a36637..43fe5311 100644
--- a/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
+++ b/cli/beacon/internal/endpoint/lifecycle/lifecycle.go
@@ -182,6 +182,24 @@ func Install(opts InstallOptions) (InstallResult, error) {
LogPath: cfg.LogPath,
}
+ // Make the log directory writable by the people whose sessions this endpoint captures, before
+ // anything writes to it.
+ //
+ // A no-op on POSIX, where the file mode carries the same guarantee. On Windows a system-mode
+ // log lives under %ProgramData%, which denies ordinary users write access -- and hooks run as
+ // the console user. Skipping this produces an install where every visible signal is healthy
+ // (the service runs, status and doctor agree) and nothing the agent does is ever recorded,
+ // because all of those describe the collector rather than the hooks exporting to it.
+ //
+ // Only for system mode: a user-mode log lives in that user's own profile, which they can
+ // already write, and widening its ACL would hand their prompt text to every interactive
+ // account on the machine.
+ if !cfg.UserMode {
+ if err := writer.EnsureSystemLogWritable(filepath.Dir(cfg.LogPath)); err != nil {
+ return InstallResult{}, fmt.Errorf("prepare the log directory: %w", err)
+ }
+ }
+
tx := newInstallRollback(manager)
tx.Track(cfg.Collector.ConfigPath)
manifest.Files = append(manifest.Files, cfg.Collector.ConfigPath)
diff --git a/cli/beacon/internal/endpoint/service/service.go b/cli/beacon/internal/endpoint/service/service.go
index 01951dff..9e4ae4f6 100644
--- a/cli/beacon/internal/endpoint/service/service.go
+++ b/cli/beacon/internal/endpoint/service/service.go
@@ -31,6 +31,13 @@ const (
// short lowercase names rather than launchd's reverse-DNS labels.
SystemdSystemUnit = "beacon-collector.service"
SystemdUserUnit = "beacon-collector.service"
+
+ // WindowsServiceName is the SCM service name. Windows convention is a short PascalCase
+ // identifier rather than launchd's reverse-DNS label or systemd's unit filename.
+ WindowsServiceName = "BeaconCollector"
+ // WindowsServiceDisplayName is what an operator sees in services.msc, where the terse
+ // service name is not the column people read.
+ WindowsServiceDisplayName = "Beacon endpoint collector"
)
// Kind identifies which service manager backs a Manager.
@@ -47,6 +54,8 @@ const (
// KindSupervised is a detached child process tracked by a pidfile. No OS service
// manager is involved, so it works in containers, CI, and on systems without systemd.
KindSupervised Kind = "none"
+ // KindWindowsService is the Windows Service Control Manager.
+ KindWindowsService Kind = "windows-service"
)
// ParseKind validates a user-supplied service kind.
@@ -60,8 +69,10 @@ func ParseKind(s string) (Kind, error) {
return KindSystemd, nil
case KindSupervised, "supervised":
return KindSupervised, nil
+ case KindWindowsService, "scm", "windows":
+ return KindWindowsService, nil
default:
- return "", fmt.Errorf("unsupported service kind %q; want auto, launchd, systemd, or none", s)
+ return "", fmt.Errorf("unsupported service kind %q; want auto, launchd, systemd, windows-service, or none", s)
}
}
@@ -97,6 +108,8 @@ func (k Kind) ServiceNoun() string {
return "launchd service definition"
case KindSystemd:
return "systemd unit definition"
+ case KindWindowsService:
+ return "Windows service registration"
case KindSupervised:
return "supervised collector state (no service manager on this host)"
default:
@@ -159,6 +172,8 @@ func DetectKind() Kind {
return KindSystemd
}
return KindSupervised
+ case "windows":
+ return KindWindowsService
default:
return KindSupervised
}
@@ -177,6 +192,16 @@ func (m Manager) backend() backend {
return launchdBackend{}
case KindSystemd:
return systemdBackend{}
+ case KindWindowsService:
+ // User mode falls back to supervised, because Windows has no per-user service manager:
+ // there is no equivalent of `systemctl --user` or launchd's gui/<uid> domain. Reported
+ // honestly by the supervised backend's status rather than pretended around -- a user-mode
+ // collector there does not survive logout, and saying so is the whole point of having the
+ // supervised backend be a real answer instead of a failure.
+ if m.UserMode {
+ return supervisedBackend{}
+ }
+ return windowsBackend{}
default:
return supervisedBackend{}
}
diff --git a/cli/beacon/internal/endpoint/service/windows.go b/cli/beacon/internal/endpoint/service/windows.go
new file mode 100644
index 00000000..26c6865b
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/windows.go
@@ -0,0 +1,99 @@
+package service
+
+import (
+ "fmt"
+ "runtime"
+)
+
+// windowsBackend manages the collector through the Windows Service Control Manager.
+//
+// Mapping from the two backends it joins:
+//
+// RunAtLoad / WantedBy=multi-user.target -> StartType automatic, plus an explicit Start
+// KeepAlive / Restart=always -> SCM recovery actions: restart, with a delay
+// StandardOutPath / journal -> the collector's own file logging; the SCM
+// captures no stdout, so there is nothing to redirect
+// a plist or unit file -> no file at all; the definition lives in the
+// registry, which unitPath reports instead
+//
+// The collector is registered directly, with no service host in front of it. That is possible
+// because the builder-generated main_windows.go calls svc.Run(otelcol.NewSvcHandler(params)) and
+// falls back to running interactively when it is not launched by the SCM, so one binary serves
+// both. Whether it really speaks the control protocol is not taken on trust -- the Windows sandbox
+// registers a scratch service and polls for RUNNING before this backend is relied on.
+//
+// System mode only. Manager routes user mode to the supervised backend, because Windows has no
+// per-user service manager to route it to.
+type windowsBackend struct{}
+
+func (windowsBackend) kind() Kind { return KindWindowsService }
+
+func (windowsBackend) available() bool {
+ return runtime.GOOS == "windows"
+}
+
+func (windowsBackend) unsupportedReason() string {
+ if runtime.GOOS != "windows" {
+ return "Windows service management is available only on Windows"
+ }
+ // Reaching the SCM needs administrator rights. Reported as a reason rather than surfacing
+ // "Access is denied" from three call sites, since the fix is the same for all of them.
+ return "the Windows Service Control Manager could not be opened; run this from an elevated shell"
+}
+
+// label is the SCM service name. Both scopes report the same name because only system mode reaches
+// this backend at all -- user mode is routed to supervised before it gets here.
+func (windowsBackend) label(userMode bool) string { return WindowsServiceName }
+
+// unitPath reports the registry key that holds the service definition.
+//
+// There is no unit file to point at, and callers show this to a human, so naming where the
+// definition actually lives beats returning an error or an empty string. The supervised backend
+// makes the same trade by reporting its pidfile.
+func (windowsBackend) unitPath(userMode bool) (string, error) {
+ return `HKLM\SYSTEM\CurrentControlSet\Services\` + WindowsServiceName, nil
+}
+
+func (b windowsBackend) writeUnit(userMode bool, program, configPath string) (string, error) {
+ if !b.available() {
+ return "", fmt.Errorf("%s", b.unsupportedReason())
+ }
+ if err := createOrUpdateService(program, configPath); err != nil {
+ return "", err
+ }
+ return b.unitPath(userMode)
+}
+
+func (b windowsBackend) load(userMode bool) error {
+ if !b.available() {
+ return fmt.Errorf("%s", b.unsupportedReason())
+ }
+ return startService()
+}
+
+// unload stops and deletes the service, tolerating its absence.
+//
+// Uninstall and repair both call this speculatively, so a missing service is success rather than
+// an error -- the same contract the launchd and systemd backends keep.
+func (b windowsBackend) unload(userMode bool) error {
+ if !b.available() {
+ return nil
+ }
+ return removeService()
+}
+
+func (b windowsBackend) restart(userMode bool) error {
+ if !b.available() {
+ return fmt.Errorf("%s", b.unsupportedReason())
+ }
+ return restartService()
+}
+
+func (b windowsBackend) status(userMode bool) Status {
+ status := Status{Label: WindowsServiceName}
+ if !b.available() {
+ status.Message = b.unsupportedReason()
+ return status
+ }
+ return queryService()
+}
diff --git a/cli/beacon/internal/endpoint/service/windows_other.go b/cli/beacon/internal/endpoint/service/windows_other.go
new file mode 100644
index 00000000..2769413f
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/windows_other.go
@@ -0,0 +1,37 @@
+//go:build !windows
+
+package service
+
+import "fmt"
+
+// The Service Control Manager exists only on Windows, so these report rather than pretend.
+//
+// windowsBackend.available() already gates every one of them, and Manager checks available()
+// before dispatching -- so reaching one of these means a caller constructed the backend directly
+// with an explicit --service=windows-service on the wrong platform. That deserves the same
+// actionable error the launchd backend gives off macOS, not a silent no-op: an install that
+// reports success while registering nothing is the failure mode this whole package is shaped
+// around avoiding.
+
+func errNotWindows(action string) error {
+ return fmt.Errorf("cannot %s a Windows service on this platform; "+
+ "use --service=auto, or systemd/launchd/none as appropriate", action)
+}
+
+func createOrUpdateService(program, configPath string) error { return errNotWindows("register") }
+
+func startService() error { return errNotWindows("start") }
+
+// removeService is the one exception, and deliberately so: uninstall and repair call unload
+// speculatively on every backend, and failing there would block removing an endpoint that was
+// never a Windows service to begin with.
+func removeService() error { return nil }
+
+func restartService() error { return errNotWindows("restart") }
+
+func queryService() Status {
+ return Status{
+ Label: WindowsServiceName,
+ Message: "Windows service management is available only on Windows",
+ }
+}
diff --git a/cli/beacon/internal/endpoint/service/windows_scm.go b/cli/beacon/internal/endpoint/service/windows_scm.go
new file mode 100644
index 00000000..710e6e33
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/windows_scm.go
@@ -0,0 +1,277 @@
+//go:build windows
+
+package service
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "golang.org/x/sys/windows"
+ "golang.org/x/sys/windows/svc"
+ "golang.org/x/sys/windows/svc/mgr"
+)
+
+// serviceStopTimeout bounds how long unload waits for a graceful stop before deleting anyway.
+//
+// The collector flushes on shutdown, so cutting this short loses whatever the exporter had
+// buffered -- the same reason the supervised backend signals before it kills.
+const serviceStopTimeout = 20 * time.Second
+
+// withManager opens the SCM and hands it to fn.
+//
+// Every entry point needs it, and every one of them fails the same way without administrator
+// rights, so the "run elevated" advice is attached once here rather than at each call site.
+func withManager(fn func(*mgr.Mgr) error) error {
+ m, err := mgr.Connect()
+ if err != nil {
+ return fmt.Errorf("open the Windows Service Control Manager (this needs an elevated shell): %w", err)
+ }
+ defer m.Disconnect()
+ return fn(m)
+}
+
+// createOrUpdateService registers the collector, or points an existing registration at the new
+// binary and config.
+//
+// Updating in place rather than delete-and-recreate: a delete only takes effect once every handle
+// to the service closes, so a recreate immediately afterwards can fail with "marked for deletion"
+// on a machine where services.msc happens to be open. Reconfiguring has no such window, and an
+// upgrade that changes the binary path is the common case.
+func createOrUpdateService(program, configPath string) error {
+ return withManager(func(m *mgr.Mgr) error {
+ cfg := mgr.Config{
+ DisplayName: WindowsServiceDisplayName,
+ Description: "Collects local AI agent telemetry and writes the Beacon endpoint log.",
+ // Automatic is the equivalent of launchd's RunAtLoad and systemd's
+ // WantedBy=multi-user.target: the endpoint must come back after a reboot without
+ // anyone logging in.
+ StartType: mgr.StartAutomatic,
+ // The collector binds loopback and writes a local log. Delayed start keeps it out of
+ // the boot-time contention that would otherwise have it restarting while the network
+ // stack settles -- the same reasoning as the systemd unit's After=network.target.
+ DelayedAutoStart: true,
+ }
+
+ existing, err := m.OpenService(WindowsServiceName)
+ if err == nil {
+ defer existing.Close()
+ current, cerr := existing.Config()
+ if cerr != nil {
+ return fmt.Errorf("read the existing %s service configuration: %w", WindowsServiceName, cerr)
+ }
+ current.DisplayName = cfg.DisplayName
+ current.Description = cfg.Description
+ current.StartType = cfg.StartType
+ current.DelayedAutoStart = cfg.DelayedAutoStart
+ current.BinaryPathName = serviceBinaryPath(program, configPath)
+ if err := existing.UpdateConfig(current); err != nil {
+ return fmt.Errorf("update the %s service: %w", WindowsServiceName, err)
+ }
+ return setRecoveryActions(existing)
+ }
+
+ created, err := m.CreateService(WindowsServiceName, program, cfg, "--config", configPath)
+ if err != nil {
+ return fmt.Errorf("register the %s service: %w", WindowsServiceName, err)
+ }
+ defer created.Close()
+ return setRecoveryActions(created)
+ })
+}
+
+// setRecoveryActions is the KeepAlive / Restart=always equivalent.
+//
+// Without it a collector that crashes stays down until the next reboot, which is the difference
+// between a service manager and a one-shot launcher -- and the whole reason to prefer the SCM over
+// the supervised backend. Three escalating restarts rather than infinite immediate ones: a
+// collector that cannot start at all should stop thrashing and leave a visible stopped service,
+// not loop forever writing the same error.
+func setRecoveryActions(s *mgr.Service) error {
+ actions := []mgr.RecoveryAction{
+ {Type: mgr.ServiceRestart, Delay: 5 * time.Second},
+ {Type: mgr.ServiceRestart, Delay: 15 * time.Second},
+ {Type: mgr.ServiceRestart, Delay: 60 * time.Second},
+ }
+ // The reset period returns the failure count to zero after a day of health, so a service that
+ // dies once a week does not eventually exhaust its restarts.
+ if err := s.SetRecoveryActions(actions, uint32((24 * time.Hour).Seconds())); err != nil {
+ return fmt.Errorf("set restart-on-failure for %s: %w", WindowsServiceName, err)
+ }
+ return nil
+}
+
+// serviceBinaryPath renders the ImagePath for an update.
+//
+// CreateService takes the executable and its arguments separately and quotes them itself, but
+// UpdateConfig takes one string, so the quoting is ours to get right. An unquoted path breaks at
+// the first space -- and the default install location is under %ProgramFiles%, which contains one.
+func serviceBinaryPath(program, configPath string) string {
+ return fmt.Sprintf("%q --config %q", program, configPath)
+}
+
+func startService() error {
+ return withManager(func(m *mgr.Mgr) error {
+ s, err := m.OpenService(WindowsServiceName)
+ if err != nil {
+ return fmt.Errorf("open the %s service (was it installed?): %w", WindowsServiceName, err)
+ }
+ defer s.Close()
+
+ status, err := s.Query()
+ if err == nil && status.State == svc.Running {
+ return nil // already running; install and repair both call this speculatively
+ }
+ if err := s.Start(); err != nil {
+ // An already-running service is not a failure, and the SCM reports it as an error.
+ if errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) {
+ return nil
+ }
+ return fmt.Errorf("start the %s service: %w", WindowsServiceName, err)
+ }
+ return nil
+ })
+}
+
+// removeService stops and deletes the registration, treating an absent service as success.
+func removeService() error {
+ return withManager(func(m *mgr.Mgr) error {
+ s, err := m.OpenService(WindowsServiceName)
+ if err != nil {
+ // Nothing registered. Uninstall and repair both call this speculatively.
+ return nil
+ }
+ defer s.Close()
+
+ if err := stopAndWait(s); err != nil {
+ return err
+ }
+ if err := s.Delete(); err != nil && !errors.Is(err, windows.ERROR_SERVICE_MARKED_FOR_DELETE) {
+ return fmt.Errorf("delete the %s service: %w", WindowsServiceName, err)
+ }
+ return nil
+ })
+}
+
+// stopAndWait asks the service to stop and waits for it, so a delete does not race a running
+// process. A service that will not stop is reported rather than force-killed: the SCM has no
+// equivalent of SIGKILL for a service, and pretending otherwise would hide a wedged collector.
+func stopAndWait(s *mgr.Service) error {
+ status, err := s.Query()
+ if err != nil {
+ return fmt.Errorf("query the %s service: %w", WindowsServiceName, err)
+ }
+ if status.State == svc.Stopped {
+ return nil
+ }
+ if _, err := s.Control(svc.Stop); err != nil {
+ // Already stopped between the query and the control request; that is the outcome we want.
+ if errors.Is(err, windows.ERROR_SERVICE_NOT_ACTIVE) {
+ return nil
+ }
+ return fmt.Errorf("stop the %s service: %w", WindowsServiceName, err)
+ }
+
+ deadline := time.Now().Add(serviceStopTimeout)
+ for time.Now().Before(deadline) {
+ status, err := s.Query()
+ if err != nil {
+ return fmt.Errorf("query the %s service while stopping: %w", WindowsServiceName, err)
+ }
+ if status.State == svc.Stopped {
+ return nil
+ }
+ time.Sleep(300 * time.Millisecond)
+ }
+ return fmt.Errorf("the %s service did not stop within %s", WindowsServiceName, serviceStopTimeout)
+}
+
+func restartService() error {
+ if err := withManager(func(m *mgr.Mgr) error {
+ s, err := m.OpenService(WindowsServiceName)
+ if err != nil {
+ // Not installed. Installing it is the right recovery, and mirrors the systemd
+ // backend's restart-falls-back-to-load behavior.
+ return errServiceNotInstalled
+ }
+ defer s.Close()
+ return stopAndWait(s)
+ }); err != nil {
+ if errors.Is(err, errServiceNotInstalled) {
+ return startService()
+ }
+ return err
+ }
+ return startService()
+}
+
+// errServiceNotInstalled distinguishes "there is nothing to restart" from a real failure, so
+// restart can fall back to starting rather than reporting an error for a recoverable state.
+var errServiceNotInstalled = errors.New("service is not installed")
+
+func queryService() Status {
+ status := Status{Label: WindowsServiceName}
+ err := withManager(func(m *mgr.Mgr) error {
+ s, err := m.OpenService(WindowsServiceName)
+ if err != nil {
+ status.Message = "service not installed"
+ return nil
+ }
+ defer s.Close()
+
+ // Loaded means registered and intended to run, matching what the other backends report
+ // for an enabled unit or a bootstrapped job.
+ cfg, cerr := s.Config()
+ if cerr == nil {
+ status.Loaded = cfg.StartType == mgr.StartAutomatic || cfg.StartType == mgr.StartManual
+ }
+ st, qerr := s.Query()
+ if qerr != nil {
+ status.Message = "could not query the service: " + qerr.Error()
+ return nil
+ }
+ status.Running = st.State == svc.Running
+ if status.Running {
+ // A running service is registered regardless of how it was configured to start.
+ status.Loaded = true
+ } else {
+ status.Message = "service state: " + serviceStateName(st.State)
+ }
+ return nil
+ })
+ if err != nil {
+ status.Message = firstLineOf(err.Error())
+ }
+ return status
+}
+
+// serviceStateName renders an SCM state for a human. The raw numbers appear in `sc query` output
+// and mean nothing to most readers.
+func serviceStateName(state svc.State) string {
+ switch state {
+ case svc.Stopped:
+ return "stopped"
+ case svc.StartPending:
+ return "starting"
+ case svc.StopPending:
+ return "stopping"
+ case svc.Running:
+ return "running"
+ case svc.ContinuePending:
+ return "resuming"
+ case svc.PausePending:
+ return "pausing"
+ case svc.Paused:
+ return "paused"
+ default:
+ return fmt.Sprintf("unknown (%d)", state)
+ }
+}
+
+func firstLineOf(s string) string {
+ if i := strings.IndexByte(s, '\n'); i >= 0 {
+ return strings.TrimSpace(s[:i])
+ }
+ return strings.TrimSpace(s)
+}
diff --git a/cli/beacon/internal/endpoint/service/windows_test.go b/cli/beacon/internal/endpoint/service/windows_test.go
new file mode 100644
index 00000000..65550b69
--- /dev/null
+++ b/cli/beacon/internal/endpoint/service/windows_test.go
@@ -0,0 +1,125 @@
+package service
+
+import (
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// Detection must pick the SCM on Windows. Falling through to the supervised backend there would
+// produce an endpoint that works until the machine reboots and then silently stops collecting,
+// which is exactly the difference a service manager exists to make.
+func TestDetectKindPicksTheServiceManagerPerPlatform(t *testing.T) {
+ got := DetectKind()
+ switch runtime.GOOS {
+ case "windows":
+ if got != KindWindowsService {
+ t.Errorf("DetectKind() = %q on Windows, want %q", got, KindWindowsService)
+ }
+ case "darwin":
+ if got != KindLaunchd {
+ t.Errorf("DetectKind() = %q on macOS, want %q", got, KindLaunchd)
+ }
+ case "linux":
+ if got != KindSystemd && got != KindSupervised {
+ t.Errorf("DetectKind() = %q on Linux, want systemd or supervised", got)
+ }
+ }
+}
+
+// Windows has no per-user service manager -- no equivalent of `systemctl --user` or launchd's
+// gui/<uid> domain -- so user mode is routed to the supervised backend. That is a real limitation
+// rather than a shortcut, and status has to say so: a supervised collector does not survive logout.
+func TestWindowsUserModeFallsBackToSupervised(t *testing.T) {
+ system := Manager{Kind: KindWindowsService}
+ if got := system.backend().kind(); got != KindWindowsService {
+ t.Errorf("system mode backend = %q, want %q", got, KindWindowsService)
+ }
+
+ user := Manager{Kind: KindWindowsService, UserMode: true}
+ if got := user.backend().kind(); got != KindSupervised {
+ t.Errorf("user mode backend = %q, want %q -- Windows has no per-user service manager",
+ got, KindSupervised)
+ }
+ if runtime.GOOS == "windows" {
+ st := user.Status()
+ if !strings.Contains(strings.ToLower(st.Message), "restart") {
+ t.Errorf("user-mode status must disclose that nothing restarts it, got %q", st.Message)
+ }
+ }
+}
+
+// The kind has to survive a round trip through the flag, or `--service=windows-service` in a
+// scenario or an operator's command line silently selects something else.
+func TestParseKindAcceptsTheWindowsSpellings(t *testing.T) {
+ for _, in := range []string{"windows-service", "scm", "windows", "WINDOWS-SERVICE"} {
+ got, err := ParseKind(in)
+ if err != nil {
+ t.Errorf("ParseKind(%q) returned %v", in, err)
+ continue
+ }
+ if got != KindWindowsService {
+ t.Errorf("ParseKind(%q) = %q, want %q", in, got, KindWindowsService)
+ }
+ }
+ if _, err := ParseKind("services.msc"); err == nil {
+ t.Error("an unrecognized kind must be rejected rather than defaulting")
+ }
+}
+
+// unitPath is shown to a human. There is no file to point at, so it names the registry key that
+// actually holds the definition -- the same trade the supervised backend makes by reporting its
+// pidfile rather than an error.
+func TestWindowsUnitPathNamesTheRegistryKey(t *testing.T) {
+ path, err := windowsBackend{}.unitPath(false)
+ if err != nil {
+ t.Fatalf("unitPath returned %v", err)
+ }
+ if !strings.Contains(path, WindowsServiceName) {
+ t.Errorf("unitPath = %q, want it to name the service %q", path, WindowsServiceName)
+ }
+ if !strings.HasPrefix(path, `HKLM\`) {
+ t.Errorf("unitPath = %q, want the registry key holding the definition", path)
+ }
+}
+
+// Off Windows the backend must refuse rather than quietly do nothing. An install that reports
+// success while registering no service is the failure this package is shaped around avoiding.
+func TestWindowsBackendRefusesOffWindows(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("this asserts the off-platform contract")
+ }
+ b := windowsBackend{}
+ if b.available() {
+ t.Fatal("the Windows backend must not report itself available off Windows")
+ }
+ if reason := b.unsupportedReason(); !strings.Contains(reason, "Windows") {
+ t.Errorf("unsupportedReason = %q, want it to name the platform", reason)
+ }
+ if _, err := b.writeUnit(false, "beacon-otelcol", "otelcol.yaml"); err == nil {
+ t.Error("writeUnit must fail off Windows rather than report a registration it did not make")
+ }
+ if err := b.load(false); err == nil {
+ t.Error("load must fail off Windows")
+ }
+ if err := b.restart(false); err == nil {
+ t.Error("restart must fail off Windows")
+ }
+ // Unload is the deliberate exception: uninstall calls it speculatively on every backend, and
+ // failing would block removing an endpoint that was never a Windows service.
+ if err := b.unload(false); err != nil {
+ t.Errorf("unload must stay a no-op off Windows so uninstall can call it, got %v", err)
+ }
+ if st := b.status(false); st.Message == "" {
+ t.Error("status off Windows must explain itself rather than look like a stopped service")
+ }
+}
+
+// The noun appears in install plans and doctor output, so every kind needs one that reads as the
+// artifact it installs.
+func TestWindowsServiceNounIsSpecific(t *testing.T) {
+ noun := KindWindowsService.ServiceNoun()
+ if noun == "" || strings.Contains(noun, "collector service definition") {
+ t.Errorf("ServiceNoun() = %q, want wording specific to the Windows SCM", noun)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/writer/acl_other.go b/cli/beacon/internal/endpoint/writer/acl_other.go
new file mode 100644
index 00000000..96aeb260
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/acl_other.go
@@ -0,0 +1,14 @@
+//go:build !windows
+
+package writer
+
+// POSIX carries this in the file mode instead: openRuntimeFile creates the runtime log 0666 so
+// hooks running as the console user can append to a log the elevated collector created. There is
+// no separate ACL step to perform, and no separate state to check.
+
+func grantInteractiveUsersWrite(dir string) error { return nil }
+
+// interactiveUsersCanWrite reports true because the equivalent guarantee is the file mode, which
+// EnsureRuntimeFile already establishes. Reporting false here would make doctor demand a fix that
+// does not exist on this platform.
+func interactiveUsersCanWrite(dir string) (bool, error) { return true, nil }
diff --git a/cli/beacon/internal/endpoint/writer/acl_windows.go b/cli/beacon/internal/endpoint/writer/acl_windows.go
new file mode 100644
index 00000000..78310931
--- /dev/null
+++ b/cli/beacon/internal/endpoint/writer/acl_windows.go
@@ -0,0 +1,71 @@
+//go:build windows
+
+package writer
+
+import (
+ "fmt"
+ "os/exec"
+ "strings"
+)
+
+// grantInteractiveUsersWrite makes a machine-wide log directory writable by ordinary users.
+//
+// This is the Windows counterpart to the 0666 runtime log on POSIX, and it exists for the same
+// reason: a system-mode collector runs elevated and creates the log, while hooks run as the person
+// at the keyboard and append to it. On POSIX the file mode carries that. Windows has no mode --
+// %ProgramData% subdirectories inherit an ACL where only administrators and SYSTEM may write, so
+// without an explicit grant every hook write fails with access denied.
+//
+// The failure that makes it worth doing at install time is the quiet one. Nothing errors visibly:
+// the collector is healthy, `endpoint status` reports running, and `doctor` agrees -- because all
+// of them describe the collector, not the hooks that export to it. The log simply stays empty of
+// anything the agent did. That is the same shape as the Linux SUDO_USER bug, where a package
+// install produced a perfectly healthy collector that captured nothing.
+//
+// Granted to INTERACTIVE rather than Users or Everyone. INTERACTIVE covers anyone logged on at the
+// machine, which is exactly the set whose agent sessions this endpoint is meant to capture, and
+// excludes service and network logons that have no business writing here.
+//
+// (OI)(CI) makes the grant inherit to files and subdirectories created later, so the log and its
+// rotated archives are covered without re-running this after every rotation.
+func grantInteractiveUsersWrite(dir string) error {
+ // icacls rather than the security APIs directly: it is present on every supported Windows,
+ // its argument form is stable, and the equivalent through SetNamedSecurityInfo means building
+ // an ACL by hand for a grant an administrator can read and audit in one line.
+ cmd := exec.Command("icacls", dir, "/grant", `*S-1-5-4:(OI)(CI)(M)`, "/T")
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("grant interactive users write access to %s: %w: %s",
+ dir, err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+// interactiveUsersCanWrite reports whether the grant is in place, for doctor.
+//
+// Checked by reading the ACL rather than by attempting a write: doctor runs elevated, so a test
+// write would succeed regardless and report healthy for exactly the configuration that is broken.
+// That is the trap this check exists to avoid, so it must not fall into it.
+func interactiveUsersCanWrite(dir string) (bool, error) {
+ out, err := exec.Command("icacls", dir).CombinedOutput()
+ if err != nil {
+ return false, fmt.Errorf("read the ACL on %s: %w: %s", dir, err, strings.TrimSpace(string(out)))
+ }
+ text := string(out)
+ // icacls renders the well-known SID as a localized account name, so the SID itself is not
+ // reliably present in the output. Both spellings are accepted: the localized name varies by
+ // system language, and matching only the English one would report a correct grant as missing
+ // on a German or Japanese install.
+ for _, marker := range []string{"S-1-5-4", "INTERACTIVE"} {
+ for _, line := range strings.Split(text, "\n") {
+ if !strings.Contains(strings.ToUpper(line), strings.ToUpper(marker)) {
+ continue
+ }
+ // (M) is modify, (F) is full control; either is enough to append.
+ if strings.Contains(line, "(M)") || strings.Contains(line, "(F)") || strings.Contains(line, "(W)") {
+ return true, nil
+ }
+ }
+ }
+ return false, nil
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index 7fd0ad04..59eb9204 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -88,6 +88,23 @@ func AppendEvent(event schema.Event, opts Options) (string, error) {
return opts.Path, nil
}
+// EnsureSystemLogWritable makes a machine-wide log directory writable by the people whose agent
+// sessions this endpoint captures.
+//
+// A no-op on POSIX, where the file mode carries the same guarantee. On Windows it is the step
+// without which a system-mode install produces a healthy collector that records nothing the agent
+// did: %ProgramData% denies ordinary users write access, hooks run as the console user, and
+// nothing reports an error because status and doctor both describe the collector rather than the
+// hooks exporting to it.
+func EnsureSystemLogWritable(dir string) error {
+ return grantInteractiveUsersWrite(dir)
+}
+
+// SystemLogWritableByUsers reports whether that grant is in place, for doctor.
+func SystemLogWritableByUsers(dir string) (bool, error) {
+ return interactiveUsersCanWrite(dir)
+}
+
// EnsureRuntimeFile creates the shared runtime log with the shared writable
// mode without appending an event, for doctor --fix and setup flows that
// pre-create the log so user-run hooks can append to it later.