Skip to content

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

endpoint: offer --log-access restricted on Windows system installs

Claudec0763267a113
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e041f21d..ac99dcab 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -938,6 +938,12 @@ jobs:
}
exit 0
+ # The restricted log access mode against a real ordinary account on the installed endpoint: its
+ # hook reaches the log only through the collector's pipe, stamped as itself; it can neither read
+ # nor append to the log; it spools while the collector is stopped; and shared puts it all back.
+ - name: Restricted log access must hold against an ordinary account
+ run: pwsh -NoProfile -File packaging/windows/smoke-restricted-log.ps1
+
- name: Uninstall must remove the service and keep the data
run: |
$logDir = Join-Path $env:ProgramData 'Beacon\Endpoint\logs'
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 63869e24..4969e16f 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -539,8 +539,12 @@ func defaultEndpointIngest() localingest.Deliverer {
return localingest.Deliverer{}
}
dir := filepath.Join(os.TempDir(), fmt.Sprintf("beacon-hooks-test-%d", os.Getpid()))
+ socket := filepath.Join(dir, "no-collector.sock")
+ if runtime.GOOS == "windows" {
+ socket = fmt.Sprintf(`\\.\pipe\beacon-hooks-test-%d-none`, os.Getpid())
+ }
return localingest.Deliverer{
- Client: localingest.Client{SocketPath: filepath.Join(dir, "no-collector.sock")},
+ Client: localingest.Client{SocketPath: socket},
Spool: localingest.Spool{Dir: filepath.Join(dir, "spool")},
}
}
diff --git a/cli/beacon/cmd/endpoint_install.go b/cli/beacon/cmd/endpoint_install.go
index 5912e001..ddc14b02 100644
--- a/cli/beacon/cmd/endpoint_install.go
+++ b/cli/beacon/cmd/endpoint_install.go
@@ -364,7 +364,7 @@ func runEndpointStatus(cmd *cobra.Command, args []string) error {
case status.LogAccess == asymptoteobserve.LogAccessRestricted && !readable(status.LogPath):
// A restricted log is unreadable to an account outside its readers group, which is not the
// same as empty.
- fmt.Println("Last event: unknown (this account cannot read the restricted log; run with sudo)")
+ fmt.Printf("Last event: unknown (this account cannot read the restricted log; run %s)\n", elevatedRunHint())
default:
fmt.Println("Last event: none")
}
diff --git a/cli/beacon/cmd/endpoint_logaccess.go b/cli/beacon/cmd/endpoint_logaccess.go
index c4988999..9d5b4271 100644
--- a/cli/beacon/cmd/endpoint_logaccess.go
+++ b/cli/beacon/cmd/endpoint_logaccess.go
@@ -12,9 +12,10 @@ import (
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
)
-const logAccessUsage = "System log access: shared (hooks append to a world-writable log; the default) or restricted " +
- "(only the root collector writes it, hooks send events over a local socket, and only root and the " +
- asymptoteobserve.RuntimeLogReadersGroup + " group can read it). Empty keeps the current mode. System installs on macOS and Linux only"
+const logAccessUsage = "System log access: shared (hooks append to a log every account can write; the default) or restricted " +
+ "(only the privileged collector writes it, hooks send events over a local socket or, on Windows, a named pipe, and only " +
+ "root -- SYSTEM and Administrators on Windows -- and the " + asymptoteobserve.RuntimeLogReadersGroup +
+ " group can read it). Empty keeps the current mode. System installs only"
// reportLogAccess says what the system log's access mode means for the people who read it. A
// restricted log is unreadable to an existing log shipper that does not run as root until its
@@ -22,7 +23,11 @@ const logAccessUsage = "System log access: shared (hooks append to a world-writa
func reportLogAccess(w io.Writer, result lifecycle.InstallResult) {
switch result.LogAccess {
case asymptoteobserve.LogAccessRestricted:
- fmt.Fprintf(w, "Runtime log access: restricted (0640 root:%s; hooks send events to %s)\n", loggroup.Name, localingest.DefaultSocketPath)
+ if runtime.GOOS == "windows" {
+ fmt.Fprintf(w, "Runtime log access: restricted (SYSTEM, Administrators and the %s group only; hooks send events to %s)\n", loggroup.Name, localingest.DefaultSocketPath)
+ } else {
+ fmt.Fprintf(w, "Runtime log access: restricted (0640 root:%s; hooks send events to %s)\n", loggroup.Name, localingest.DefaultSocketPath)
+ }
if result.LogReadersGroupCreated {
fmt.Fprintf(w, "Created the %s group. Add each account that should read the log, such as a log shipper's: %s\n", loggroup.Name, addToGroupHint("<account>"))
} else {
@@ -34,12 +39,23 @@ func reportLogAccess(w io.Writer, result lifecycle.InstallResult) {
}
func addToGroupHint(account string) string {
+ if runtime.GOOS == "windows" {
+ return fmt.Sprintf("net localgroup %s %s /add (from an elevated shell)", loggroup.Name, account)
+ }
if runtime.GOOS == "darwin" {
return fmt.Sprintf("sudo dseditgroup -o edit -a %s -t user %s", account, loggroup.Name)
}
return fmt.Sprintf("sudo usermod -aG %s %s", loggroup.Name, account)
}
+// elevatedRunHint says how to rerun a command with the privilege a restricted log needs.
+func elevatedRunHint() string {
+ if runtime.GOOS == "windows" {
+ return "from an elevated shell"
+ }
+ return "with sudo"
+}
+
// readable reports whether this account can open path for reading.
func readable(path string) bool {
f, err := os.Open(path)
diff --git a/cli/beacon/internal/endpoint/collector/logaccess_test.go b/cli/beacon/internal/endpoint/collector/logaccess_test.go
index d92a22fc..c7c4cd50 100644
--- a/cli/beacon/internal/endpoint/collector/logaccess_test.go
+++ b/cli/beacon/internal/endpoint/collector/logaccess_test.go
@@ -2,7 +2,6 @@ package collector
import (
"context"
- "runtime"
"strings"
"testing"
@@ -27,9 +26,6 @@ func parsedYAML(t *testing.T, text string) map[string]interface{} {
}
func TestConfigYAMLServesTheIngestSocketInTheRestrictedMode(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no restricted mode on Windows")
- }
doc := parsedYAML(t, ConfigYAML(restrictedConfig(false)))
extensions := doc["extensions"].(map[string]interface{})
ingest, ok := extensions[IngestExtension].(map[string]interface{})
@@ -84,3 +80,15 @@ func TestCheckComponentsRequiresTheIngestExtensionWhenAsked(t *testing.T) {
t.Fatalf("a collector with %s: %v", IngestExtension, err)
}
}
+
+// A Windows log path reaches the extension intact: its backslashes are escaped in the YAML, not
+// read as escape sequences.
+func TestConfigYAMLCarriesAWindowsLogPath(t *testing.T) {
+ cfg := restrictedConfig(false)
+ cfg.LogPath = `C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl`
+ doc := parsedYAML(t, ConfigYAML(cfg))
+ ingest := doc["extensions"].(map[string]interface{})[IngestExtension].(map[string]interface{})
+ if ingest["log_path"] != cfg.LogPath {
+ t.Fatalf("log_path = %q, want %q", ingest["log_path"], cfg.LogPath)
+ }
+}
diff --git a/cli/beacon/internal/endpoint/config/config.go b/cli/beacon/internal/endpoint/config/config.go
index 8a89715c..86701d50 100644
--- a/cli/beacon/internal/endpoint/config/config.go
+++ b/cli/beacon/internal/endpoint/config/config.go
@@ -115,16 +115,16 @@ type Config struct {
ManagedIngest *ManagedIngest `json:"managed_ingest,omitempty"`
AutoUpdate *AutoUpdate `json:"auto_update,omitempty"`
// LogAccess is the system log's access mode: "shared" (empty, the default) or "restricted".
- // Read it through RestrictedLogAccess, which also accounts for user mode and the platform.
+ // Read it through RestrictedLogAccess, which also accounts for user mode.
LogAccess string `json:"log_access,omitempty"`
}
// RestrictedLogAccess reports whether this endpoint's system log is in the restricted access mode:
-// written only by the root collector, readable by root and the beacon-log group, with hooks
-// sending their events over the local ingest socket. It is never true in user mode, whose log is
-// already private, or on Windows, which has no ingest socket.
+// written only by the privileged collector, readable by root (SYSTEM and Administrators on
+// Windows) and the beacon-log group, with hooks sending their events over the local ingest socket
+// or pipe. It is never true in user mode, whose log is already private.
func (c Config) RestrictedLogAccess() bool {
- return !c.UserMode && runtime.GOOS != "windows" && strings.EqualFold(strings.TrimSpace(c.LogAccess), "restricted")
+ return !c.UserMode && strings.EqualFold(strings.TrimSpace(c.LogAccess), "restricted")
}
// ManagedIngest records that this endpoint forwards to Asymptote managed ingest. It holds
diff --git a/cli/beacon/internal/endpoint/config/logaccess_test.go b/cli/beacon/internal/endpoint/config/logaccess_test.go
index c4b9453c..d8879f5a 100644
--- a/cli/beacon/internal/endpoint/config/logaccess_test.go
+++ b/cli/beacon/internal/endpoint/config/logaccess_test.go
@@ -1,9 +1,6 @@
package config
-import (
- "runtime"
- "testing"
-)
+import "testing"
func TestRestrictedLogAccess(t *testing.T) {
cases := []struct {
@@ -12,8 +9,8 @@ func TestRestrictedLogAccess(t *testing.T) {
}{
{Config{}, false},
{Config{LogAccess: "shared"}, false},
- {Config{LogAccess: "restricted"}, runtime.GOOS != "windows"},
- {Config{LogAccess: " Restricted "}, runtime.GOOS != "windows"},
+ {Config{LogAccess: "restricted"}, true},
+ {Config{LogAccess: " Restricted "}, true},
{Config{UserMode: true, LogAccess: "restricted"}, false},
{Config{LogAccess: "restricted-ish"}, false},
}
diff --git a/cli/beacon/internal/endpoint/diagnostics/logaccess.go b/cli/beacon/internal/endpoint/diagnostics/logaccess.go
index de0c9cab..d3c5ba49 100644
--- a/cli/beacon/internal/endpoint/diagnostics/logaccess.go
+++ b/cli/beacon/internal/endpoint/diagnostics/logaccess.go
@@ -6,14 +6,51 @@ import (
"io/fs"
"os"
"path/filepath"
+ "runtime"
+ "strings"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/loggroup"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
)
-const repairSystemAction = "sudo beacon endpoint repair --system"
+// repairSystemAction repairs a system install with the privilege it needs on this platform.
+var repairSystemAction = func() string {
+ if runtime.GOOS == "windows" {
+ return "beacon endpoint repair --system (from an elevated shell)"
+ }
+ return "sudo beacon endpoint repair --system"
+}()
+
+// repairSystemWith is repairSystemAction with more flags.
+func repairSystemWith(flags string) string {
+ if runtime.GOOS == "windows" {
+ return "beacon endpoint repair --system " + flags + " (from an elevated shell)"
+ }
+ return "sudo beacon endpoint repair --system " + flags
+}
+
+// elevated says how to run doctor with the privilege a restricted log needs on this platform.
+func elevated() string {
+ if runtime.GOOS == "windows" {
+ return "from an elevated shell"
+ }
+ return "with sudo"
+}
+
+// privilegedWriters names who writes a restricted log: root, or SYSTEM and Administrators.
+func privilegedWriters() string {
+ if runtime.GOOS == "windows" {
+ return "SYSTEM and Administrators"
+ }
+ return "root"
+}
+
+// restrictedLogProblems reads a restricted log's ACL on Windows (writer.CheckRestrictedSystemLogACL);
+// a variable for tests.
+var restrictedLogProblems = writer.CheckRestrictedSystemLogACL
// logMarkedRestricted reads the log's restricted marker. A variable because only a marker root owns
// counts, and tests cannot be root.
@@ -32,6 +69,9 @@ func checkLogPermissionsFor(cfg endpointconfig.Config) Check {
// can reach. Doctor usually runs with sudo; run without it, it cannot look inside the directory,
// which is itself the restricted mode working, and says so instead of guessing.
func checkRestrictedLogPermissions(path string) Check {
+ if runtime.GOOS == "windows" {
+ return checkRestrictedLogACL(path)
+ }
dir := filepath.Dir(path)
dirInfo, err := os.Stat(dir)
if err != nil {
@@ -47,7 +87,7 @@ func checkRestrictedLogPermissions(path string) Check {
switch {
case errors.Is(err, fs.ErrPermission):
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusOK, Severity: SeverityInfo,
- Message: "this account cannot open the restricted log, as intended; run doctor with sudo to inspect it",
+ Message: "this account cannot open the restricted log, as intended; run doctor " + elevated() + " to inspect it",
Evidence: "restricted_log_not_readable_by_caller"}
case err != nil:
return Check{Name: "runtime_log_permissions", Target: path, Status: StatusWarn, Severity: SeverityLow,
@@ -81,7 +121,7 @@ func checkLogAccess(cfg endpointconfig.Config, ingest localingest.Deliverer) Che
if marked {
return Check{Name: name, Target: path, Status: StatusWarn, Severity: SeverityMedium,
Message: "the log is marked restricted but the endpoint config says shared, so hooks cannot append to it",
- Evidence: "log_access_mismatch", Action: repairSystemAction + " --log-access shared"}
+ Evidence: "log_access_mismatch", Action: repairSystemWith("--log-access shared")}
}
if pending, err := ingest.Pending(path); err == nil && pending > 0 {
// Left from a time the log was restricted, or refused this account; the account's
@@ -97,7 +137,7 @@ func checkLogAccess(cfg endpointconfig.Config, ingest localingest.Deliverer) Che
if markerReadable && !marked {
return Check{Name: name, Target: path, Status: StatusFail, Severity: SeverityHigh,
- Message: "the endpoint config says restricted but the log is not marked, so the collector will make it world-writable again at its next write",
+ Message: "the endpoint config says restricted but the log is not marked, so the collector will make it writable by every account again at its next write",
Evidence: "log_access_marker_missing", Action: repairSystemAction}
}
// A probe, not a look at the socket file: a collector that was killed leaves its socket behind,
@@ -126,9 +166,9 @@ func checkLogAccess(cfg endpointconfig.Config, ingest localingest.Deliverer) Che
Message: fmt.Sprintf("restricted; %d events from this account are waiting in its spool and go to the collector with the next event", pending),
Evidence: "ingest_spool_pending"}
}
- message := fmt.Sprintf("restricted: only the collector writes the log; root and the %s group read it", loggroup.Name)
+ message := fmt.Sprintf("restricted: only the collector writes the log; %s and the %s group read it", privilegedWriters(), loggroup.Name)
if !markerReadable {
- message += " (run doctor with sudo to inspect the log itself)"
+ message += " (run doctor " + elevated() + " to inspect the log itself)"
}
return Check{Name: name, Target: path, Status: StatusOK, Severity: SeverityInfo, Message: message, Evidence: "log_access_restricted"}
}
@@ -139,3 +179,30 @@ func ingestSocketPath(ingest localingest.Deliverer) string {
}
return localingest.DefaultSocketPath
}
+
+// checkRestrictedLogACL is checkRestrictedLogPermissions on Windows, where file modes say nothing:
+// the directory and every file of the log family must grant nobody but SYSTEM, Administrators and
+// the readers group (who may only read) anything at all. Run unelevated it cannot open the
+// directory, which is the restricted mode working.
+func checkRestrictedLogACL(path string) Check {
+ dir := filepath.Dir(path)
+ problems, err := restrictedLogProblems(path)
+ switch {
+ case errors.Is(err, fs.ErrPermission):
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusOK, Severity: SeverityInfo,
+ Message: "this account cannot open the restricted log, as intended; run doctor " + elevated() + " to inspect it",
+ Evidence: "restricted_log_not_readable_by_caller"}
+ case errors.Is(err, fs.ErrNotExist):
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusFail, Severity: SeverityMedium,
+ Message: "the log directory is missing: " + err.Error(), Evidence: "log_dir_missing", Action: repairSystemAction}
+ case err != nil:
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusWarn, Severity: SeverityLow,
+ Message: "could not read the restricted log's ACL: " + err.Error(), Evidence: "acl_unreadable"}
+ case len(problems) > 0:
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusFail, Severity: SeverityHigh,
+ Message: "the restricted log lets accounts outside SYSTEM, Administrators and the " + loggroup.Name + " group reach it: " + strings.Join(problems, "; "),
+ Evidence: "restricted_log_too_open", Action: repairSystemAction}
+ }
+ return Check{Name: "runtime_log_permissions", Target: dir, Status: StatusOK, Severity: SeverityInfo,
+ Message: "restricted: only SYSTEM, Administrators and the " + loggroup.Name + " group can reach the log", Evidence: "restricted_acl"}
+}
diff --git a/cli/beacon/internal/endpoint/diagnostics/logaccess_acl_test.go b/cli/beacon/internal/endpoint/diagnostics/logaccess_acl_test.go
new file mode 100644
index 00000000..c26e82cc
--- /dev/null
+++ b/cli/beacon/internal/endpoint/diagnostics/logaccess_acl_test.go
@@ -0,0 +1,39 @@
+package diagnostics
+
+import (
+ "errors"
+ "io/fs"
+ "testing"
+)
+
+// checkRestrictedLogACL is doctor's question about a restricted log on Windows, answered here from
+// a stand-in for the ACL reader so every outcome is checked on every platform.
+func TestCheckRestrictedLogACL(t *testing.T) {
+ cases := []struct {
+ name string
+ problems []string
+ err error
+ status string
+ evidence string
+ }{
+ {"as install leaves it", nil, nil, StatusOK, "restricted_acl"},
+ {"a leftover grant", []string{`runtime.jsonl: grants S-1-5-32-545 access (0x1200a9)`}, nil, StatusFail, "restricted_log_too_open"},
+ {"run without elevation", nil, &fs.PathError{Op: "open", Path: "logs", Err: fs.ErrPermission}, StatusOK, "restricted_log_not_readable_by_caller"},
+ {"no directory", nil, &fs.PathError{Op: "open", Path: "logs", Err: fs.ErrNotExist}, StatusFail, "log_dir_missing"},
+ {"the readers group is gone", nil, errors.New("the beacon-log group does not exist"), StatusWarn, "acl_unreadable"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ prev := restrictedLogProblems
+ restrictedLogProblems = func(string) ([]string, error) { return tc.problems, tc.err }
+ t.Cleanup(func() { restrictedLogProblems = prev })
+ c := checkRestrictedLogACL(`C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl`)
+ if c.Status != tc.status || c.Evidence != tc.evidence {
+ t.Fatalf("check = %+v, want %s/%s", c, tc.status, tc.evidence)
+ }
+ if c.Status == StatusFail && c.Action == "" {
+ t.Fatal("a failing check names no repair")
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/endpoint/lifecycle/logaccess.go b/cli/beacon/internal/endpoint/lifecycle/logaccess.go
index b2a45185..434ce3ec 100644
--- a/cli/beacon/internal/endpoint/lifecycle/logaccess.go
+++ b/cli/beacon/internal/endpoint/lifecycle/logaccess.go
@@ -2,7 +2,6 @@ package lifecycle
import (
"fmt"
- "runtime"
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/loggroup"
@@ -33,9 +32,6 @@ func validateLogAccess(cfg endpointconfig.Config) error {
if cfg.UserMode {
return fmt.Errorf("--log-access %s applies to a system install; a user-mode log is already private to its user", mode)
}
- if runtime.GOOS == "windows" {
- return fmt.Errorf("--log-access %s is not available on Windows yet; the system log keeps its shared access", mode)
- }
return nil
}
diff --git a/cli/beacon/internal/endpoint/lifecycle/logaccess_test.go b/cli/beacon/internal/endpoint/lifecycle/logaccess_test.go
index 031ef5b5..baa0a020 100644
--- a/cli/beacon/internal/endpoint/lifecycle/logaccess_test.go
+++ b/cli/beacon/internal/endpoint/lifecycle/logaccess_test.go
@@ -3,7 +3,6 @@ package lifecycle
import (
"errors"
"path/filepath"
- "runtime"
"strings"
"testing"
@@ -70,12 +69,7 @@ func TestValidateLogAccess(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "system install") {
t.Errorf("restricted in user mode = %v, want a refusal naming the system install", err)
}
- err = validateLogAccess(system("restricted"))
- if runtime.GOOS == "windows" {
- if err == nil {
- t.Error("restricted was accepted on Windows")
- }
- } else if err != nil {
+ if err := validateLogAccess(system("restricted")); err != nil {
t.Errorf("restricted on a system install = %v", err)
}
}
@@ -111,9 +105,6 @@ func fakeLogAccess(t *testing.T, gid int, created bool, ensureErr, restrictErr e
}
func TestPrepareSystemLogRestricts(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no restricted mode on Windows")
- }
calls := fakeLogAccess(t, 4242, true, nil, nil)
created, err := prepareSystemLog(endpointconfig.Config{LogPath: "/var/log/beacon-agent/runtime.jsonl", LogAccess: "restricted"})
if err != nil || !created {
@@ -138,9 +129,6 @@ func TestPrepareSystemLogShares(t *testing.T) {
}
func TestPrepareSystemLogStopsWhenTheGroupCannotBeMade(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no restricted mode on Windows")
- }
calls := fakeLogAccess(t, 0, false, errors.New("groupadd: permission denied"), nil)
_, err := prepareSystemLog(endpointconfig.Config{LogPath: "/var/log/beacon-agent/runtime.jsonl", LogAccess: "restricted"})
if err == nil || !strings.Contains(err.Error(), loggroup.Name) {
@@ -158,17 +146,12 @@ func TestLogAccessOf(t *testing.T) {
if got := logAccessOf(endpointconfig.Config{}); got != "shared" {
t.Fatalf("system default = %q", got)
}
- if runtime.GOOS != "windows" {
- if got := logAccessOf(endpointconfig.Config{LogAccess: "restricted"}); got != "restricted" {
- t.Fatalf("restricted = %q", got)
- }
+ if got := logAccessOf(endpointconfig.Config{LogAccess: "restricted"}); got != "restricted" {
+ t.Fatalf("restricted = %q", got)
}
}
func TestLogAccessRestorerPutsBackWhatAFailedInstallChanged(t *testing.T) {
- if runtime.GOOS == "windows" {
- t.Skip("no restricted mode on Windows")
- }
restricted := false
prev := logIsRestricted
logIsRestricted = func(string) bool { return restricted }
diff --git a/cli/beacon/internal/endpoint/writer/logaccess_other.go b/cli/beacon/internal/endpoint/writer/logaccess_other.go
index e4249b00..34ddcae0 100644
--- a/cli/beacon/internal/endpoint/writer/logaccess_other.go
+++ b/cli/beacon/internal/endpoint/writer/logaccess_other.go
@@ -12,3 +12,6 @@ func RestrictSystemLog(string, int) error {
// ShareSystemLog is EnsureSystemLogWritable here, where the log is always shared.
func ShareSystemLog(path string) error { return EnsureSystemLogWritable(path) }
+
+// CheckRestrictedSystemLogACL has nothing to read here.
+func CheckRestrictedSystemLogACL(string) ([]string, error) { return nil, nil }
diff --git a/cli/beacon/internal/endpoint/writer/logaccess_unix.go b/cli/beacon/internal/endpoint/writer/logaccess_unix.go
index 4f58b1cc..af5f8968 100644
--- a/cli/beacon/internal/endpoint/writer/logaccess_unix.go
+++ b/cli/beacon/internal/endpoint/writer/logaccess_unix.go
@@ -250,3 +250,7 @@ func settleOne(path string, fn func(*os.File) error) error {
}
return fn(f)
}
+
+// CheckRestrictedSystemLogACL has nothing to read on Unix, where a restricted log's access is its
+// file modes, which doctor reads itself.
+func CheckRestrictedSystemLogACL(string) ([]string, error) { return nil, nil }
diff --git a/cli/beacon/internal/endpoint/writer/logaccess_windows.go b/cli/beacon/internal/endpoint/writer/logaccess_windows.go
index b3fc4943..a5523361 100644
--- a/cli/beacon/internal/endpoint/writer/logaccess_windows.go
+++ b/cli/beacon/internal/endpoint/writer/logaccess_windows.go
@@ -193,3 +193,15 @@ func ShareSystemLog(path string) error {
}
return EnsureSystemLogWritable(path)
}
+
+// CheckRestrictedSystemLogACL lists every way the restricted log at path, its directory, its
+// archives or its lock let an account other than SYSTEM, Administrators and the readers group
+// reach it (sysacl.RestrictedProblems), for doctor. An ordinary user cannot open the directory, and
+// gets that error back.
+func CheckRestrictedSystemLogACL(path string) ([]string, error) {
+ readers, err := logReadersSID()
+ if err != nil {
+ return nil, err
+ }
+ return sysacl.InspectRestrictedLogDir(filepath.Dir(path), filepath.Base(path), readers)
+}
diff --git a/cli/beacon/internal/endpoint/writer/writer.go b/cli/beacon/internal/endpoint/writer/writer.go
index 71df04ad..3972bbd3 100644
--- a/cli/beacon/internal/endpoint/writer/writer.go
+++ b/cli/beacon/internal/endpoint/writer/writer.go
@@ -9,6 +9,7 @@ import (
"os"
"path/filepath"
"reflect"
+ "runtime"
"strconv"
"strings"
"testing"
@@ -157,8 +158,12 @@ func defaultIngest() localingest.Deliverer {
return localingest.Deliverer{}
}
dir := filepath.Join(os.TempDir(), fmt.Sprintf("beacon-writer-test-%d", os.Getpid()))
+ socket := filepath.Join(dir, "no-collector.sock")
+ if runtime.GOOS == "windows" {
+ socket = fmt.Sprintf(`\\.\pipe\beacon-writer-test-%d-none`, os.Getpid())
+ }
return localingest.Deliverer{
- Client: localingest.Client{SocketPath: filepath.Join(dir, "no-collector.sock")},
+ Client: localingest.Client{SocketPath: socket},
Spool: localingest.Spool{Dir: filepath.Join(dir, "spool")},
}
}
diff --git a/packaging/windows/install-endpoint.ps1 b/packaging/windows/install-endpoint.ps1
index 6b0baa04..d8c54a85 100644
--- a/packaging/windows/install-endpoint.ps1
+++ b/packaging/windows/install-endpoint.ps1
@@ -35,6 +35,11 @@ $httpPort = Get-EnvOrDefault 'BEACON_OTLP_HTTP_PORT' '4318'
$collector = Get-EnvOrDefault 'BEACON_COLLECTOR' ''
$service = Get-EnvOrDefault 'BEACON_SERVICE' ''
$noStart = Get-EnvOrDefault 'BEACON_NO_START' '0'
+# shared or restricted; empty keeps whatever the endpoint already has, so an upgrade never changes
+# the mode. Restricted makes the SYSTEM collector the only writer of the runtime log: hooks send their
+# events to it over a local named pipe, and only SYSTEM, Administrators and the beacon-log group can
+# read the log. The same variable the Linux and macOS install scripts read.
+$logAccess = Get-EnvOrDefault 'BEACON_LOG_ACCESS' ''
# Auto-detected rather than required, so a manual invocation without BEACON_COLLECTOR still works.
# DiscoverBinary would find this on its own -- it is passed explicitly so that a failure says which
@@ -55,6 +60,7 @@ if (-not [string]::IsNullOrWhiteSpace($collector)) { $installArgs += @('--collec
# install. Passing it explicitly is for a fleet that wants the supervised fallback instead.
if (-not [string]::IsNullOrWhiteSpace($service)) { $installArgs += @('--service', $service) }
if ($noStart -eq '1') { $installArgs += '--no-start' }
+if (-not [string]::IsNullOrWhiteSpace($logAccess)) { $installArgs += @('--log-access', $logAccess) }
# The access control on %ProgramData%\Beacon is applied by the install itself, not here, so a fleet
# that runs `beacon endpoint install --system` directly gets the same result as the MSI. It resets the
@@ -62,7 +68,8 @@ if ($noStart -eq '1') { $installArgs += '--no-start' }
# found there may belong to someone else -- to Administrators ownership with inheritance disabled:
# SYSTEM and Administrators full control, Users read and execute. The log directory adds only an
# inherit-only grant letting INTERACTIVE append to the runtime log files; ordinary users cannot add,
-# delete or rename anything in it. Do not add an icacls grant here: a second, broader grant is how
+# delete or rename anything in it. In the restricted log access mode the log directory grants
+# ordinary users nothing at all. Do not add an icacls grant here: a second, broader grant is how
# the log directory once became writable enough to redirect the collector's writes.
Write-Output "beacon: installing the system endpoint"
& $beaconBin @installArgs
diff --git a/packaging/windows/smoke-restricted-log.ps1 b/packaging/windows/smoke-restricted-log.ps1
new file mode 100644
index 00000000..d75d32bb
--- /dev/null
+++ b/packaging/windows/smoke-restricted-log.ps1
@@ -0,0 +1,182 @@
+# End-to-end check of the restricted log access mode on an installed Windows endpoint.
+#
+# Runs after the MSI is installed and its BeaconCollector service is running. It needs an elevated
+# shell, which the CI runner is, because it switches the endpoint's mode and creates a local account.
+#
+# What it proves, with a real ordinary account rather than the elevated runner's own:
+# - `beacon endpoint repair --system --log-access restricted` restricts the log, and status and
+# doctor agree that it is.
+# - That account's hook reaches the log through the collector's pipe, under the account's own SID
+# and name whatever the event claimed, and the account cannot read or append to the log itself.
+# - While the collector is stopped the hook spools its event instead of losing it, and the event
+# arrives with the next one once the collector is back.
+# - `--log-access shared` puts it back: the hook appends directly again and doctor is satisfied.
+[CmdletBinding()]
+param()
+
+$ErrorActionPreference = 'Stop'
+
+$beacon = Join-Path $env:ProgramFiles 'Beacon\bin\beacon.exe'
+$hooks = Join-Path $env:ProgramFiles 'Beacon\bin\beacon-hooks.exe'
+$log = Join-Path $env:ProgramData 'Beacon\Endpoint\logs\runtime.jsonl'
+$config = Join-Path $env:ProgramData 'Beacon\Endpoint\config.json'
+$pipe = '\\.\pipe\beacon-agent-ingest'
+$work = Join-Path $env:SystemDrive 'BeaconSmoke'
+$account = 'beaconsmoke'
+
+function Invoke-Beacon {
+ param([string[]]$Arguments)
+ $out = & $beacon @Arguments 2>&1 | Out-String
+ if ($LASTEXITCODE -ne 0) {
+ Write-Output $out
+ throw "beacon $($Arguments -join ' ') exited $LASTEXITCODE"
+ }
+ return $out
+}
+
+function Get-Status {
+ return (Invoke-Beacon @('endpoint', 'status', '--system', '--json')) | ConvertFrom-Json
+}
+
+function Get-Check {
+ param($Status, [string]$Name)
+ return $Status.diagnostics | Where-Object { $_.name -eq $Name } | Select-Object -First 1
+}
+
+function Test-Pipe {
+ return [System.IO.Directory]::GetFiles('\\.\pipe\') -contains $pipe
+}
+
+function Wait-Pipe {
+ param([bool]$Present)
+ $deadline = (Get-Date).AddSeconds(60)
+ while ((Test-Pipe) -ne $Present) {
+ if ((Get-Date) -gt $deadline) { throw "the ingest pipe never became $(if ($Present) { 'available' } else { 'absent' })" }
+ Start-Sleep -Milliseconds 500
+ }
+}
+
+# Every log line holding the marker, parsed. Read as this elevated account, which may read the log in
+# either mode.
+function Get-LogEvents {
+ param([string]$Marker)
+ if (-not (Test-Path -LiteralPath $log)) { return @() }
+ return @(Get-Content -LiteralPath $log | Where-Object { $_.Contains($Marker) } | ForEach-Object { $_ | ConvertFrom-Json })
+}
+
+$password = 'Bs1!' + [Guid]::NewGuid().ToString('N')
+$credential = [System.Management.Automation.PSCredential]::new(
+ $account, (ConvertTo-SecureString $password -AsPlainText -Force))
+
+# Runs a batch file as the ordinary account and returns its exit code. A batch file because the
+# environment a hook gets from its runtime is set inline there, and Start-Process cannot give a
+# process started under other credentials an environment of the caller's choosing.
+function Invoke-AsAccount {
+ param([string]$Tag, [string[]]$Lines)
+ $script = Join-Path $work "$Tag.cmd"
+ Set-Content -LiteralPath $script -Encoding ascii -Value (@('@echo off') + $Lines + @('exit /b %ERRORLEVEL%'))
+ $p = Start-Process -FilePath (Join-Path $env:SystemRoot 'System32\cmd.exe') -ArgumentList @('/d', '/c', "`"$script`"") `
+ -Credential $credential -LoadUserProfile -WorkingDirectory $work -Wait -PassThru
+ return $p.ExitCode
+}
+
+# Runs the Claude Code SessionStart hook as the ordinary account, the way Claude Code would. USER is
+# set to an account it is not, which a shared-mode hook would write into user.name as it stands.
+function Invoke-Hook {
+ param([string]$Session)
+ $payload = Join-Path $work "$Session.json"
+ @{ session_id = $Session; hook_event_name = 'SessionStart'; source = 'startup'; cwd = $work } |
+ ConvertTo-Json | Set-Content -LiteralPath $payload -Encoding utf8
+ $code = Invoke-AsAccount $Session @(
+ 'set "BEACON_ENDPOINT_MODE=1"',
+ "set `"BEACON_ENDPOINT_LOG=$log`"",
+ "set `"BEACON_ENDPOINT_CONFIG=$config`"",
+ 'set "USER=Administrator"',
+ "`"$hooks`" --platform claude session-start < `"$payload`" > `"$work\$Session.out`" 2> `"$work\$Session.err`""
+ )
+ if ($code -ne 0) {
+ Get-Content -LiteralPath "$work\$Session.err" -ErrorAction SilentlyContinue | Write-Output
+ throw "the hook for $Session exited $code"
+ }
+}
+
+New-Item -ItemType Directory -Force -Path $work | Out-Null
+& net.exe user $account $password /add | Out-Null
+if ($LASTEXITCODE -ne 0) { throw "could not create the local account $account" }
+try {
+ & icacls.exe $work /grant "${account}:(OI)(CI)M" | Out-Null
+ $sid = ([System.Security.Principal.NTAccount]"$env:COMPUTERNAME\$account").Translate(
+ [System.Security.Principal.SecurityIdentifier]).Value
+ Write-Output "ordinary account: $account ($sid)"
+
+ # --- Restricted ----------------------------------------------------------------------------
+ Invoke-Beacon @('endpoint', 'repair', '--system', '--log-access', 'restricted') | Write-Output
+ Wait-Pipe $true
+ $status = Get-Status
+ if ($status.log_access -ne 'restricted') { throw "status reports log_access '$($status.log_access)' after restricting" }
+ foreach ($name in @('runtime_log_access', 'runtime_log_permissions')) {
+ $check = Get-Check $status $name
+ if (-not $check -or $check.status -ne 'ok') {
+ $status.diagnostics | ConvertTo-Json -Depth 5 | Write-Output
+ throw "doctor's $name is not ok on the restricted endpoint"
+ }
+ }
+
+ $sessionA = 'smoke-a-' + [Guid]::NewGuid().ToString('N')
+ Invoke-Hook $sessionA
+ $events = Get-LogEvents $sessionA
+ if ($events.Count -lt 1) { throw "the ordinary account's event never reached the restricted log" }
+ foreach ($e in $events) {
+ if ($e.user.uid -ne $sid) { throw "user.uid is '$($e.user.uid)'; the collector must stamp the sender's SID $sid" }
+ if ($e.user.name -notlike "*\$account") { throw "user.name is '$($e.user.name)'; the event claimed Administrator and must carry $account" }
+ }
+ Write-Output "ok: the hook's event reached the log through the pipe as $($events[0].user.name)"
+
+ if ((Invoke-AsAccount 'read' @("type `"$log`" > nul 2>&1")) -eq 0) { throw "an ordinary account can read the restricted log" }
+ $forged = 'forged-' + [Guid]::NewGuid().ToString('N')
+ if ((Invoke-AsAccount 'append' @("echo $forged>> `"$log`" 2>nul")) -eq 0 -or (Get-LogEvents $forged).Count -gt 0) {
+ throw "an ordinary account can append to the restricted log"
+ }
+ Write-Output "ok: the ordinary account can neither read nor append to the log"
+
+ # Collector down: the event waits in the account's spool, and arrives with the next one.
+ Stop-Service -Name BeaconCollector
+ Wait-Pipe $false
+ $sessionB = 'smoke-b-' + [Guid]::NewGuid().ToString('N')
+ Invoke-Hook $sessionB
+ if ((Get-LogEvents $sessionB).Count -gt 0) { throw "an event reached the restricted log with the collector stopped" }
+ $spool = Join-Path $env:SystemDrive "Users\$account\.beacon\endpoint\spool"
+ if (-not (Get-ChildItem -LiteralPath $spool -Recurse -File -ErrorAction SilentlyContinue | Select-String -SimpleMatch $sessionB -Quiet)) {
+ throw "the event sent while the collector was stopped is not in the account's spool ($spool)"
+ }
+ Start-Service -Name BeaconCollector
+ Wait-Pipe $true
+ $sessionC = 'smoke-c-' + [Guid]::NewGuid().ToString('N')
+ Invoke-Hook $sessionC
+ foreach ($session in @($sessionB, $sessionC)) {
+ if ((Get-LogEvents $session).Count -lt 1) { throw "$session did not reach the log once the collector was back" }
+ }
+ Write-Output "ok: an event spooled while the collector was stopped arrived once it was back"
+
+ # --- Shared again -----------------------------------------------------------------------------
+ Invoke-Beacon @('endpoint', 'repair', '--system', '--log-access', 'shared') | Write-Output
+ Wait-Pipe $false
+ $status = Get-Status
+ if ($status.log_access -ne 'shared') { throw "status reports log_access '$($status.log_access)' after sharing" }
+ $permissions = Get-Check $status 'runtime_log_permissions'
+ if (-not $permissions -or $permissions.status -ne 'ok') {
+ $status.diagnostics | ConvertTo-Json -Depth 5 | Write-Output
+ throw "doctor's runtime_log_permissions is not ok once the log is shared again"
+ }
+ $sessionD = 'smoke-d-' + [Guid]::NewGuid().ToString('N')
+ Invoke-Hook $sessionD
+ if ((Get-LogEvents $sessionD).Count -lt 1) { throw "the hook could not append to the log once it was shared again" }
+ Write-Output "ok: shared again, the hook appends directly"
+} catch {
+ Write-Output "--- runtime log (tail) ---"
+ Get-Content -LiteralPath $log -Tail 20 -ErrorAction SilentlyContinue | Write-Output
+ throw
+} finally {
+ & net.exe user $account /delete | Out-Null
+ $global:LASTEXITCODE = 0
+}
diff --git a/packaging/windows/test-endpoint-scripts.ps1 b/packaging/windows/test-endpoint-scripts.ps1
index bf3245ae..76ad6f8a 100644
--- a/packaging/windows/test-endpoint-scripts.ps1
+++ b/packaging/windows/test-endpoint-scripts.ps1
@@ -20,7 +20,7 @@ function Fail {
$script:failures++
}
-$scripts = @('install-endpoint.ps1', 'uninstall-endpoint.ps1', 'build-msi.ps1')
+$scripts = @('install-endpoint.ps1', 'uninstall-endpoint.ps1', 'build-msi.ps1', 'smoke-restricted-log.ps1')
foreach ($name in $scripts) {
$path = Join-Path $scriptDir $name
if (-not (Test-Path -LiteralPath $path)) {
@@ -47,6 +47,10 @@ foreach ($needle in @('endpoint', 'install', '--system', 'user-config', 'repair-
Fail "install-endpoint.ps1 no longer references '$needle'"
}
}
+# BEACON_LOG_ACCESS is the one contract for the log access mode across all three platforms' scripts.
+if ($install -notmatch "BEACON_LOG_ACCESS" -or $install -notmatch [regex]::Escape("'--log-access'")) {
+ Fail "install-endpoint.ps1 no longer passes BEACON_LOG_ACCESS on as --log-access"
+}
# The step whose absence made the Linux package produce a healthy collector that captured nothing.
if ($install -notmatch 'repair-installed') {
Fail "install-endpoint.ps1 must configure the interactive user's runtime, or the endpoint captures nothing"
diff --git a/pkg/asymptoteobserve/localingest/deliver.go b/pkg/asymptoteobserve/localingest/deliver.go
index 2ad19a5c..690fc453 100644
--- a/pkg/asymptoteobserve/localingest/deliver.go
+++ b/pkg/asymptoteobserve/localingest/deliver.go
@@ -8,7 +8,6 @@ import (
"io/fs"
"os"
"path/filepath"
- "runtime"
"sync/atomic"
"time"
@@ -44,27 +43,28 @@ type Deliverer struct {
// Spool holds lines that could not be written. An empty Dir means DefaultSpoolDir. Each log
// has its own spool beneath it, so a line is only ever written to the log it was meant for.
Spool Spool
- // Euid reports the process's effective uid; nil means os.Geteuid. Tests replace it.
+ // Euid stands in for the process's privilege in tests: 0 is a privileged writer, anything else
+ // is not. Nil asks the operating system (processPrivileged).
Euid func() int
// FailureBackoff is how long, after a failed send, this account goes straight to the direct
// append without trying the socket. Zero means 10s; negative turns it off.
FailureBackoff time.Duration
}
-// Applies reports whether a write to logPath goes through Write's socket path at all. Root writes
-// the log directly: it owns the file in every mode, and the events it writes -- a backfill of the
-// console user's sessions, the collector's own -- name their account themselves, which the ingest
-// server would replace with root. A per-user log is private to its account and always written
-// directly. Windows has no ingest socket.
+// Applies reports whether a write to logPath goes through Write's socket path at all. A privileged
+// writer -- root, or on Windows SYSTEM or an elevated administrator -- writes the log directly: it
+// may write the log in every mode, and the events it writes -- a backfill of the console user's
+// sessions, the collector's own -- name their account themselves, which the ingest server would
+// replace with its own. A per-user log is private to its account and always written directly.
func (d Deliverer) Applies(logPath string) bool {
- if runtime.GOOS == "windows" {
- return false
- }
- euid := os.Geteuid()
+ return !d.privileged() && !asymptoteobserve.RuntimeLogIsPrivate(logPath)
+}
+
+func (d Deliverer) privileged() bool {
if d.Euid != nil {
- euid = d.Euid()
+ return d.Euid() == 0
}
- return euid != 0 && !asymptoteobserve.RuntimeLogIsPrivate(logPath)
+ return processPrivileged()
}
// Outcome is where Write put a line.
diff --git a/pkg/asymptoteobserve/localingest/deliver_windows_test.go b/pkg/asymptoteobserve/localingest/deliver_windows_test.go
new file mode 100644
index 00000000..3b90e3e0
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/deliver_windows_test.go
@@ -0,0 +1,152 @@
+//go:build windows
+
+package localingest
+
+import (
+ "errors"
+ "io/fs"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/windows"
+)
+
+// systemLog is the log the Windows deliverer tests write; the pipe servers accept any.
+const systemLog = `C:\ProgramData\Beacon\Endpoint\logs\runtime.jsonl`
+
+// winLog stands in for the writer's own append: it records lines, or refuses them as a restricted
+// log's ACL refuses an ordinary account.
+type winLog struct {
+ mu sync.Mutex
+ lines []string
+ refuse bool
+}
+
+func (l *winLog) append(line []byte) error {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.refuse {
+ return &fs.PathError{Op: "open", Path: systemLog, Err: windows.ERROR_ACCESS_DENIED}
+ }
+ l.lines = append(l.lines, string(line))
+ return nil
+}
+
+func (l *winLog) count() int {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ return len(l.lines)
+}
+
+// pipeDeliverer writes as an ordinary account to the pipe at path.
+func pipeDeliverer(t *testing.T, path string) Deliverer {
+ t.Helper()
+ lastSendFailure.Store(0)
+ t.Cleanup(func() { lastSendFailure.Store(0) })
+ return Deliverer{
+ Client: Client{SocketPath: path, TrustedSID: currentSID(t), Timeout: 5 * time.Second},
+ Spool: Spool{Dir: filepath.Join(t.TempDir(), "spool")},
+ Euid: func() int { return 1000 },
+ FailureBackoff: -1,
+ }
+}
+
+func TestWindowsWriteGoesThroughThePipe(t *testing.T) {
+ h := startPipeServer(t, nil)
+ d := pipeDeliverer(t, h.path)
+ log := &winLog{}
+ outcome, err := d.WriteOutcome(systemLog, lines(t, 1)[0], log.append)
+ if err != nil || outcome != Sent {
+ t.Fatalf("WriteOutcome = %v, %v", outcome, err)
+ }
+ if h.rec.count() != 1 || log.count() != 0 {
+ t.Fatalf("collector %d, direct %d", h.rec.count(), log.count())
+ }
+ if uid := decode(t, h.rec.lines[0])["user"].(map[string]interface{})["uid"]; uid != currentSID(t) {
+ t.Fatalf("stamped uid = %v", uid)
+ }
+}
+
+func TestWindowsWriteWithoutAPipeAppendsDirectly(t *testing.T) {
+ d := pipeDeliverer(t, testPipe(t))
+ log := &winLog{}
+ outcome, err := d.WriteOutcome(systemLog, lines(t, 1)[0], log.append)
+ if err != nil || outcome != Appended || log.count() != 1 {
+ t.Fatalf("WriteOutcome = %v, %v; direct %d", outcome, err, log.count())
+ }
+}
+
+// A restricted log refuses the direct append while the collector is down: the event is spooled,
+// and reaches the collector with the next event once it is back.
+func TestWindowsWriteSpoolsWhileTheCollectorIsDownAndDrainsAfter(t *testing.T) {
+ path := testPipe(t)
+ d := pipeDeliverer(t, path)
+ log := &winLog{refuse: true}
+ outcome, err := d.WriteOutcome(systemLog, lines(t, 1)[0], log.append)
+ if err != nil || outcome != Spooled {
+ t.Fatalf("WriteOutcome = %v, %v; want it spooled", outcome, err)
+ }
+ if n, _ := d.Pending(systemLog); n != 1 {
+ t.Fatalf("Pending = %d", n)
+ }
+ l, err := Listen(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := &recorder{}
+ s := &Server{Append: rec.append}
+ go func() { _ = s.Serve(l) }()
+ t.Cleanup(func() { _ = s.Close() })
+ if err := d.Write(systemLog, lines(t, 1)[0], log.append); err != nil {
+ t.Fatal(err)
+ }
+ if rec.count() != 2 {
+ t.Fatalf("collector received %d lines, want the new one and the spooled one", rec.count())
+ }
+ if n, _ := d.Pending(systemLog); n != 0 {
+ t.Fatalf("Pending after recovery = %d", n)
+ }
+}
+
+// What a restricted log's ACL actually returns to an ordinary account must read as a refusal for
+// permission, which is the one error that spools.
+func TestARealAccessDeniedIsAPermissionRefusal(t *testing.T) {
+ file := filepath.Join(t.TempDir(), "runtime.jsonl")
+ if err := os.WriteFile(file, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if out, err := exec.Command("icacls", file, "/deny", "*"+currentSID(t)+":(W)").CombinedOutput(); err != nil {
+ t.Fatalf("icacls: %v: %s", err, strings.TrimSpace(string(out)))
+ }
+ t.Cleanup(func() { _ = exec.Command("icacls", file, "/reset").Run() })
+ f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY, 0)
+ if err == nil {
+ _ = f.Close()
+ t.Fatal("opened a file this account is denied writing")
+ }
+ if !errors.Is(err, fs.ErrPermission) {
+ t.Fatalf("open = %v; want it to read as fs.ErrPermission", err)
+ }
+}
+
+// SYSTEM and elevated administrators write the restricted log directly; everyone else goes through
+// the pipe.
+func TestWindowsPrivilegeDecidesTheRoute(t *testing.T) {
+ token, err := windows.OpenCurrentProcessToken()
+ if err != nil {
+ t.Fatal(err)
+ }
+ elevated := token.IsElevated()
+ token.Close()
+ if elevated && !processPrivileged() {
+ t.Fatal("an elevated process is not treated as privileged")
+ }
+ if (Deliverer{}).Applies(systemLog) == processPrivileged() {
+ t.Fatalf("Applies = %v while processPrivileged = %v", (Deliverer{}).Applies(systemLog), processPrivileged())
+ }
+}
diff --git a/pkg/asymptoteobserve/localingest/privilege_unix.go b/pkg/asymptoteobserve/localingest/privilege_unix.go
new file mode 100644
index 00000000..999bc9ca
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/privilege_unix.go
@@ -0,0 +1,8 @@
+//go:build unix
+
+package localingest
+
+import "os"
+
+// processPrivileged reports whether this process is root.
+func processPrivileged() bool { return os.Geteuid() == 0 }
diff --git a/pkg/asymptoteobserve/localingest/privilege_windows.go b/pkg/asymptoteobserve/localingest/privilege_windows.go
new file mode 100644
index 00000000..ccbc2a7d
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/privilege_windows.go
@@ -0,0 +1,17 @@
+//go:build windows
+
+package localingest
+
+import "golang.org/x/sys/windows"
+
+// processPrivileged reports whether this process runs as SYSTEM or with an elevated token: either
+// may write the restricted log, whose ACL gives SYSTEM and Administrators full control, and neither
+// may be stamped as anyone else.
+func processPrivileged() bool {
+ token := windows.GetCurrentProcessToken()
+ if token.IsElevated() {
+ return true
+ }
+ user, err := token.GetTokenUser()
+ return err == nil && user.User.Sid.IsWellKnown(windows.WinLocalSystemSid)
+}
diff --git a/pkg/asymptoteobserve/localingest/transport_other.go b/pkg/asymptoteobserve/localingest/transport_other.go
index 6136b841..2373cae9 100644
--- a/pkg/asymptoteobserve/localingest/transport_other.go
+++ b/pkg/asymptoteobserve/localingest/transport_other.go
@@ -33,3 +33,6 @@ func identify(net.Conn) (Peer, error) { return Peer{}, errors.ErrUnsupported }
const peerCredentialsSupported = false
func temporaryAcceptError(error) bool { return false }
+
+// processPrivileged is never true here, where there is no ingest channel to bypass.
+func processPrivileged() bool { return false }