Skip to content

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

collector: beacon_ingest extension serves the local ingest socket

Claudee46639b0598b
diff --git a/collector-builder/builder.yaml b/collector-builder/builder.yaml
index 42b3acfb..f93c2835 100644
--- a/collector-builder/builder.yaml
+++ b/collector-builder/builder.yaml
@@ -26,6 +26,9 @@ exporters:
extensions:
- gomod: github.com/open-telemetry/opentelemetry-collector-contrib/extension/healthcheckextension v0.121.0
+ - gomod: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter v0.0.0
+ import: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/beaconingestextension
+ path: ./exporter/beaconjsonexporter
replaces:
- github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../../pkg/asymptoteobserve
diff --git a/collector-builder/exporter/beaconjsonexporter/README.md b/collector-builder/exporter/beaconjsonexporter/README.md
index 1232cfda..a07b7d34 100644
--- a/collector-builder/exporter/beaconjsonexporter/README.md
+++ b/collector-builder/exporter/beaconjsonexporter/README.md
@@ -84,3 +84,30 @@ Noise controls:
The production implementation should live here and be included by
`collector-builder/builder.yaml`.
+
+## beacon_ingest extension
+
+`beaconingestextension` (component type `beacon_ingest`) is the collector side of the restricted
+log access mode for system-mode endpoints. With it, the collector is the only writer of
+`/var/log/beacon-agent/runtime.jsonl`, which can then be `0640 root:beacon-log` instead of
+world-writable:
+
+- It listens on a Unix socket (`/var/run/beacon-agent/ingest.sock` by default) that hooks send
+ their events to (`pkg/asymptoteobserve/localingest`).
+- Each event's `user` is replaced with the sender's kernel-verified uid and account name, so a
+ user can describe their own sessions but cannot write an event under someone else's account.
+- Events are appended through `internal/runtimelog`, the same lock, rotation and file-mode handling
+ the exporter uses, so both writers can share one log.
+- Shutdown removes the socket; hooks then spool their events privately until the collector is back.
+
+```yaml
+extensions:
+ beacon_ingest:
+ log_path: /var/log/beacon-agent/runtime.jsonl
+ rotate_bytes: 10485760
+ rotate_archives: 5
+service:
+ extensions: [health_check, beacon_ingest]
+```
+
+`beacon endpoint install --system --log-access restricted` renders this; nothing else enables it.
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/config.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/config.go
new file mode 100644
index 00000000..ecd7025f
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/config.go
@@ -0,0 +1,52 @@
+package beaconingestextension
+
+import (
+ "errors"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+)
+
+const (
+ defaultRotateBytes = 10 * 1024 * 1024
+ defaultRotateArchives = 5
+)
+
+// Config is the beacon_ingest extension's configuration. Install renders it only for a system-mode
+// endpoint in the restricted log access mode, with the same log path and rotation the beaconjson
+// exporter uses.
+type Config struct {
+ // SocketPath is where hooks connect. Empty means localingest.DefaultSocketPath.
+ SocketPath string `mapstructure:"socket_path"`
+ // LogPath is the runtime log the events are appended to.
+ LogPath string `mapstructure:"log_path"`
+ RotateBytes int64 `mapstructure:"rotate_bytes"`
+ RotateArchives int `mapstructure:"rotate_archives"`
+ // MaxConnections bounds concurrent connections; zero is the localingest default.
+ MaxConnections int `mapstructure:"max_connections"`
+ // MaxConnectionsPerUID bounds one account's concurrent connections; zero is the localingest
+ // default.
+ MaxConnectionsPerUID int `mapstructure:"max_connections_per_uid"`
+ // RateBytesPerSecond and RateBurstBytes bound the bytes each account can write; zero is the
+ // localingest default and a negative rate turns the bound off.
+ RateBytesPerSecond float64 `mapstructure:"rate_bytes_per_second"`
+ RateBurstBytes float64 `mapstructure:"rate_burst_bytes"`
+}
+
+func createDefaultConfig() *Config {
+ return &Config{
+ SocketPath: localingest.DefaultSocketPath,
+ RotateBytes: defaultRotateBytes,
+ RotateArchives: defaultRotateArchives,
+ }
+}
+
+// Validate checks the configuration.
+func (c *Config) Validate() error {
+ if c.LogPath == "" {
+ return errors.New("log_path is required")
+ }
+ if c.RotateBytes < 0 || c.RotateArchives < 0 || c.MaxConnections < 0 || c.MaxConnectionsPerUID < 0 || c.RateBurstBytes < 0 {
+ return errors.New("rotate_bytes, rotate_archives, max_connections, max_connections_per_uid and rate_burst_bytes must not be negative")
+ }
+ return nil
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go
new file mode 100644
index 00000000..55eb3e56
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go
@@ -0,0 +1,123 @@
+// Package beaconingestextension is the collector side of the restricted log access mode: it
+// listens on the local ingest socket and appends the events hooks send there to the runtime log,
+// so a system-mode endpoint can keep that log 0640 root:beacon-log instead of world-writable.
+//
+// Each event is stamped with the sender's kernel-verified account (localingest.StampLine) and
+// written through the same lock, rotation and file-mode handling as the beaconjson exporter
+// (internal/runtimelog), so the two writers stay interchangeable on one log.
+package beaconingestextension
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "sync"
+
+ "go.opentelemetry.io/collector/component"
+ "go.uber.org/zap"
+
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/runtimelog"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+)
+
+type ingest struct {
+ cfg *Config
+ logger *zap.Logger
+ names *nameCache
+
+ // listen and appendLine are the seams tests replace.
+ listen func(path string) (*net.UnixListener, error)
+ appendLine func(path string, line []byte, rotateBytes int64, rotateArchives int) error
+
+ mu sync.Mutex
+ server *localingest.Server
+ done chan error
+}
+
+func newIngest(cfg *Config, logger *zap.Logger) *ingest {
+ if logger == nil {
+ logger = zap.NewNop()
+ }
+ return &ingest{
+ cfg: cfg,
+ logger: logger,
+ names: newNameCache(),
+ listen: localingest.Listen,
+ appendLine: runtimelog.Append,
+ }
+}
+
+// Start creates the socket and serves it in the background. A socket another running collector
+// still answers on, or a non-socket at the path, fails the start: two writers serving one log, or
+// a path someone put something else at, is a configuration problem to surface, not to work around.
+func (e *ingest) Start(context.Context, component.Host) error {
+ if !asymptoteobserve.RuntimeLogAccessRestricted(e.cfg.LogPath) {
+ // Harmless -- the log is simply also writable directly -- but not what install sets up,
+ // so it is worth a line in the collector's log.
+ e.logger.Warn("beacon_ingest is serving a runtime log that is not in the restricted access mode",
+ zap.String("log_path", e.cfg.LogPath))
+ }
+ l, err := e.listen(e.socketPath())
+ if err != nil {
+ return fmt.Errorf("beacon_ingest: listen on %s: %w", e.socketPath(), err)
+ }
+ server := &localingest.Server{
+ Append: e.append,
+ LogPath: e.cfg.LogPath,
+ LookupName: e.names.lookup,
+ MaxConns: e.cfg.MaxConnections,
+ MaxConnsPerUID: e.cfg.MaxConnectionsPerUID,
+ RateBytesPerSecond: e.cfg.RateBytesPerSecond,
+ RateBurstBytes: e.cfg.RateBurstBytes,
+ Logf: func(format string, args ...interface{}) {
+ e.logger.Warn(fmt.Sprintf(format, args...))
+ },
+ }
+ done := make(chan error, 1)
+ go func() { done <- server.Serve(l) }()
+ e.mu.Lock()
+ e.server, e.done = server, done
+ e.mu.Unlock()
+ e.logger.Info("beacon_ingest listening", zap.String("socket", e.socketPath()), zap.String("log_path", e.cfg.LogPath))
+ return nil
+}
+
+// Shutdown stops serving, waits for connections in progress to finish their writes, and removes
+// the socket, so hooks find no socket and spool until the collector is back.
+func (e *ingest) Shutdown(context.Context) error {
+ e.mu.Lock()
+ server, done := e.server, e.done
+ e.server, e.done = nil, nil
+ e.mu.Unlock()
+ if server == nil {
+ return nil
+ }
+ err := server.Close()
+ if serveErr := <-done; serveErr != nil && !errors.Is(serveErr, localingest.ErrServerClosed) && err == nil {
+ err = serveErr
+ }
+ return err
+}
+
+func (e *ingest) socketPath() string {
+ if e.cfg.SocketPath == "" {
+ return localingest.DefaultSocketPath
+ }
+ return e.cfg.SocketPath
+}
+
+func (e *ingest) append(line []byte) error {
+ rotateBytes := e.cfg.RotateBytes
+ if rotateBytes <= 0 {
+ rotateBytes = defaultRotateBytes
+ }
+ archives := e.cfg.RotateArchives
+ if archives <= 0 {
+ archives = defaultRotateArchives
+ }
+ out := make([]byte, 0, len(line)+1)
+ out = append(append(out, line...), '\n')
+ return e.appendLine(e.cfg.LogPath, out, rotateBytes, archives)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go
new file mode 100644
index 00000000..689db613
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go
@@ -0,0 +1,326 @@
+//go:build linux || darwin
+
+package beaconingestextension
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "go.opentelemetry.io/collector/component"
+ "go.opentelemetry.io/collector/extension"
+ "go.uber.org/zap"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/localingest"
+)
+
+func shortDir(t *testing.T) string {
+ t.Helper()
+ dir, err := os.MkdirTemp("", "bi")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = os.RemoveAll(dir) })
+ if err := os.Chmod(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ return dir
+}
+
+type fixture struct {
+ ext *ingest
+ client localingest.Client
+ log string
+}
+
+func start(t *testing.T, mutate func(*Config)) *fixture {
+ t.Helper()
+ dir := shortDir(t)
+ cfg := createDefaultConfig()
+ cfg.SocketPath = filepath.Join(dir, "run", "ingest.sock")
+ cfg.LogPath = filepath.Join(dir, "log", "runtime.jsonl")
+ if mutate != nil {
+ mutate(cfg)
+ }
+ if err := os.MkdirAll(filepath.Dir(cfg.LogPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ ext := newIngest(cfg, zap.NewNop())
+ if err := ext.Start(context.Background(), nil); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = ext.Shutdown(context.Background()) })
+ return &fixture{
+ ext: ext,
+ log: cfg.LogPath,
+ client: localingest.Client{SocketPath: cfg.SocketPath, TrustedOwner: os.Geteuid(), LogPath: cfg.LogPath},
+ }
+}
+
+func event(t *testing.T, i int, claimedUser string) []byte {
+ t.Helper()
+ data, err := json.Marshal(map[string]interface{}{
+ "timestamp": fmt.Sprintf("2026-10-29T09:03:%02d.000000000Z", i%60),
+ "vendor": asymptoteobserve.Vendor,
+ "product": asymptoteobserve.Product,
+ "schema_version": asymptoteobserve.SchemaVersion,
+ "event": map[string]interface{}{"action": "command.executed", "category": "command", "id": fmt.Sprintf("evt-%d", i)},
+ "session": map[string]interface{}{"id": fmt.Sprintf("s-%d", i)},
+ "user": map[string]interface{}{"name": claimedUser, "uid": "0"},
+ "message": fmt.Sprintf("event %d", i),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
+
+func readLog(t *testing.T, path string) []map[string]interface{} {
+ t.Helper()
+ f, err := os.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ var out []map[string]interface{}
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 1<<20), 1<<20)
+ for scanner.Scan() {
+ var e map[string]interface{}
+ if err := json.Unmarshal(scanner.Bytes(), &e); err != nil {
+ t.Fatalf("log line is not one JSON object: %q", scanner.Text())
+ }
+ out = append(out, e)
+ }
+ return out
+}
+
+func TestEventsSentToTheSocketLandInTheLogUnderTheSendersAccount(t *testing.T) {
+ f := start(t, nil)
+ batch := [][]byte{event(t, 1, "root"), event(t, 2, "someone-else")}
+ resp, err := f.client.Send(batch)
+ if err != nil || resp.Accepted != 2 {
+ t.Fatalf("Send = %+v, %v", resp, err)
+ }
+ lines := readLog(t, f.log)
+ if len(lines) != 2 {
+ t.Fatalf("log has %d lines, want 2", len(lines))
+ }
+ uid := fmt.Sprint(os.Geteuid())
+ want := resolveName(uint32(os.Geteuid()))
+ for i, line := range lines {
+ user := line["user"].(map[string]interface{})
+ if user["uid"] != uid {
+ t.Fatalf("line %d uid = %v, want the sender's %s", i, user["uid"], uid)
+ }
+ if want != "" && user["name"] != want {
+ t.Fatalf("line %d name = %v, want %q", i, user["name"], want)
+ }
+ if line["message"] != fmt.Sprintf("event %d", i+1) {
+ t.Fatalf("line %d out of order: %v", i, line["message"])
+ }
+ }
+ if _, err := os.Stat(f.log + ".lock"); err != nil {
+ t.Fatalf("the shared lock file was not used: %v", err)
+ }
+}
+
+func TestRejectedEventsNeverReachTheLog(t *testing.T) {
+ f := start(t, nil)
+ resp, err := f.client.Send([][]byte{
+ []byte(`{"vendor":"beacon","product":"endpoint-agent"}`),
+ []byte(`{"evil":"` + strings.Repeat("x", 100) + `"}`),
+ event(t, 1, "x"),
+ })
+ if err != nil || resp.Rejected != 2 || resp.Accepted != 1 {
+ t.Fatalf("Send = %+v, %v", resp, err)
+ }
+ if got := len(readLog(t, f.log)); got != 1 {
+ t.Fatalf("log has %d lines, want only the valid event", got)
+ }
+}
+
+func TestLogRotatesThroughTheSharedWriter(t *testing.T) {
+ f := start(t, func(c *Config) {
+ c.RotateBytes = 600
+ c.RotateArchives = 2
+ c.RateBytesPerSecond = -1
+ })
+ for i := 0; i < 20; i++ {
+ if _, err := f.client.Send([][]byte{event(t, i, "x")}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, archive := range []string{f.log + ".1", f.log + ".2"} {
+ if _, err := os.Stat(archive); err != nil {
+ t.Fatalf("expected archive %s: %v", filepath.Base(archive), err)
+ }
+ }
+ if _, err := os.Stat(f.log + ".3"); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("kept more archives than configured")
+ }
+}
+
+func TestAWriteFailureIsReportedSoTheClientKeepsTheEvents(t *testing.T) {
+ f := start(t, nil)
+ var calls atomic.Int32
+ f.ext.appendLine = func(string, []byte, int64, int) error {
+ calls.Add(1)
+ return errors.New("read-only file system")
+ }
+ resp, err := f.client.Send([][]byte{event(t, 1, "x"), event(t, 2, "x")})
+ if err == nil || resp.Processed != 0 {
+ t.Fatalf("Send = %+v, %v; want nothing processed", resp, err)
+ }
+ if calls.Load() != 1 {
+ t.Fatalf("append called %d times; the batch must stop at the first failure", calls.Load())
+ }
+}
+
+func TestEventsForAnotherLogAreRefused(t *testing.T) {
+ f := start(t, nil)
+ c := f.client
+ c.LogPath = filepath.Join(t.TempDir(), "runtime.jsonl")
+ if _, err := c.Send([][]byte{event(t, 1, "x")}); !errors.Is(err, localingest.ErrLogMismatch) {
+ t.Fatalf("Send for another log = %v, want ErrLogMismatch", err)
+ }
+ if _, err := os.Stat(f.log); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("the collector wrote an event meant for another log")
+ }
+}
+
+func TestShutdownRemovesTheSocket(t *testing.T) {
+ f := start(t, nil)
+ if err := f.ext.Shutdown(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.ext.Shutdown(context.Background()); err != nil {
+ t.Fatalf("a second Shutdown: %v", err)
+ }
+ if _, err := os.Lstat(f.ext.socketPath()); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("socket left after Shutdown: %v", err)
+ }
+ if _, err := f.client.Send([][]byte{event(t, 1, "x")}); !errors.Is(err, localingest.ErrNoSocket) {
+ t.Fatalf("Send after Shutdown = %v, want ErrNoSocket so hooks spool", err)
+ }
+}
+
+func TestShutdownWithoutStart(t *testing.T) {
+ cfg := createDefaultConfig()
+ cfg.LogPath = "/nonexistent/runtime.jsonl"
+ if err := newIngest(cfg, nil).Shutdown(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestASecondCollectorOnTheSameSocketFailsToStart(t *testing.T) {
+ f := start(t, nil)
+ cfg := *f.ext.cfg
+ second := newIngest(&cfg, zap.NewNop())
+ err := second.Start(context.Background(), nil)
+ if err == nil {
+ _ = second.Shutdown(context.Background())
+ t.Fatal("two collectors served one socket")
+ }
+ // The first is untouched.
+ if _, err := f.client.Send([][]byte{event(t, 1, "x")}); err != nil {
+ t.Fatalf("the running collector stopped answering: %v", err)
+ }
+}
+
+func TestStartReplacesAStaleSocket(t *testing.T) {
+ dir := shortDir(t)
+ sock := filepath.Join(dir, "run", "ingest.sock")
+ if err := os.MkdirAll(filepath.Dir(sock), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ stale, err := net.ListenUnix("unix", &net.UnixAddr{Name: sock, Net: "unix"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ stale.SetUnlinkOnClose(false)
+ _ = stale.Close()
+ f := start(t, func(c *Config) { c.SocketPath = sock })
+ if _, err := f.client.Send([][]byte{event(t, 1, "x")}); err != nil {
+ t.Fatalf("Send after replacing a stale socket: %v", err)
+ }
+}
+
+// As root, with the log marked restricted, the files the extension creates take the restricted mode.
+func TestRestrictedLogFilesAreNotWorldAccessible(t *testing.T) {
+ if os.Geteuid() != 0 {
+ t.Skip("the restricted marker is trusted only when root owns it")
+ }
+ dir := shortDir(t)
+ logPath := filepath.Join(dir, "log", "runtime.jsonl")
+ if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := asymptoteobserve.SetRuntimeLogAccess(logPath, asymptoteobserve.LogAccessRestricted); err != nil {
+ t.Fatal(err)
+ }
+ f := start(t, func(c *Config) { c.LogPath = logPath; c.SocketPath = filepath.Join(dir, "run", "ingest.sock") })
+ if _, err := f.client.Send([][]byte{event(t, 1, "x")}); err != nil {
+ t.Fatal(err)
+ }
+ for path, want := range map[string]os.FileMode{
+ logPath: asymptoteobserve.RestrictedRuntimeLogFileMode,
+ logPath + ".lock": asymptoteobserve.RestrictedRuntimeLogLockMode,
+ } {
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != want {
+ t.Fatalf("%s mode = %o, want %o", filepath.Base(path), info.Mode().Perm(), want)
+ }
+ }
+}
+
+func TestFactory(t *testing.T) {
+ factory := NewFactory()
+ if factory.Type().String() != "beacon_ingest" {
+ t.Fatalf("type = %s", factory.Type())
+ }
+ cfg := factory.CreateDefaultConfig().(*Config)
+ if cfg.SocketPath != localingest.DefaultSocketPath || cfg.RotateBytes <= 0 || cfg.RotateArchives <= 0 {
+ t.Fatalf("default config = %+v", cfg)
+ }
+ set := extension.Settings{ID: component.NewID(factory.Type()), TelemetrySettings: component.TelemetrySettings{Logger: zap.NewNop()}}
+ if _, err := factory.Create(context.Background(), set, cfg); err == nil {
+ t.Fatal("created an extension without a log path")
+ }
+ cfg.LogPath = "/var/log/beacon-agent/runtime.jsonl"
+ ext, err := factory.Create(context.Background(), set, cfg)
+ if err != nil || ext == nil {
+ t.Fatalf("Create = %v, %v", ext, err)
+ }
+}
+
+func TestConfigValidate(t *testing.T) {
+ for name, cfg := range map[string]Config{
+ "negative rotate": {LogPath: "x", RotateBytes: -1},
+ "negative archives": {LogPath: "x", RotateArchives: -1},
+ "negative conns": {LogPath: "x", MaxConnections: -1},
+ "negative burst": {LogPath: "x", RateBurstBytes: -1},
+ "negative per uid": {LogPath: "x", MaxConnectionsPerUID: -1},
+ "no log path": {},
+ } {
+ if err := cfg.Validate(); err == nil {
+ t.Errorf("%s: Validate accepted %+v", name, cfg)
+ }
+ }
+ ok := Config{LogPath: "x", RateBytesPerSecond: -1}
+ if err := ok.Validate(); err != nil {
+ t.Errorf("a negative rate turns the bound off and must validate: %v", err)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/factory.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/factory.go
new file mode 100644
index 00000000..b6062a12
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/factory.go
@@ -0,0 +1,32 @@
+package beaconingestextension
+
+import (
+ "context"
+ "fmt"
+
+ "go.opentelemetry.io/collector/component"
+ "go.opentelemetry.io/collector/extension"
+)
+
+var componentType = component.MustNewType("beacon_ingest")
+
+// NewFactory creates the factory for the beacon_ingest extension.
+func NewFactory() extension.Factory {
+ return extension.NewFactory(
+ componentType,
+ func() component.Config { return createDefaultConfig() },
+ create,
+ component.StabilityLevelBeta,
+ )
+}
+
+func create(_ context.Context, set extension.Settings, raw component.Config) (extension.Extension, error) {
+ cfg, ok := raw.(*Config)
+ if !ok {
+ return nil, fmt.Errorf("unexpected config type %T", raw)
+ }
+ if err := cfg.Validate(); err != nil {
+ return nil, err
+ }
+ return newIngest(cfg, set.Logger), nil
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go
new file mode 100644
index 00000000..b3eb4cbd
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go
@@ -0,0 +1,96 @@
+package beaconingestextension
+
+import (
+ "context"
+ "os/exec"
+ "os/user"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ // nameLookupTimeout bounds one id(1) call. The name is resolved once per connection, inside the
+ // server's budget for it, so a directory service that does not answer costs one connection
+ // half a second and leaves the event named by uid only.
+ nameLookupTimeout = 500 * time.Millisecond
+ // nameCacheTTL bounds how long a uid's name is reused. Accounts are renamed rarely; a miss is
+ // retried after the same interval, so a directory service that was briefly unreachable does
+ // not leave an account unnamed until the collector restarts.
+ nameCacheTTL = 10 * time.Minute
+)
+
+// nameCache resolves the account name stamped on each event from the peer's uid.
+//
+// The collector is built with CGO_ENABLED=0, whose os/user reads /etc/passwd and never asks NSS
+// or Directory Services, so accounts from LDAP, SSSD, AD or macOS's own directory would come back
+// unnamed. `id -nu <uid>` asks the system's own resolver on both Linux and macOS and is the
+// fallback.
+type nameCache struct {
+ mu sync.Mutex
+ entries map[uint32]nameEntry
+ now func() time.Time
+ lookup1 func(uid uint32) string
+}
+
+type nameEntry struct {
+ name string
+ expires time.Time
+}
+
+func newNameCache() *nameCache {
+ return &nameCache{entries: map[uint32]nameEntry{}, now: time.Now, lookup1: resolveName}
+}
+
+func (c *nameCache) lookup(uid uint32) string {
+ now := c.now()
+ c.mu.Lock()
+ entry, ok := c.entries[uid]
+ c.mu.Unlock()
+ if ok && now.Before(entry.expires) {
+ return entry.name
+ }
+ name := c.lookup1(uid)
+ c.mu.Lock()
+ c.entries[uid] = nameEntry{name: name, expires: now.Add(nameCacheTTL)}
+ c.mu.Unlock()
+ return name
+}
+
+// idCommands are the absolute paths tried for id(1). The collector runs as root, so PATH is not
+// consulted.
+var idCommands = []string{"/usr/bin/id", "/bin/id"}
+
+func resolveName(uid uint32) string {
+ id := strconv.FormatUint(uint64(uid), 10)
+ if u, err := user.LookupId(id); err == nil && validName(u.Username) {
+ return u.Username
+ }
+ for _, path := range idCommands {
+ ctx, cancel := context.WithTimeout(context.Background(), nameLookupTimeout)
+ out, err := exec.CommandContext(ctx, path, "-nu", id).Output()
+ cancel()
+ if err != nil {
+ continue
+ }
+ if name := strings.TrimSpace(string(out)); validName(name) {
+ return name
+ }
+ }
+ return ""
+}
+
+// validName accepts what an account name can be and nothing that could disturb a log line or a
+// reader: no control characters or whitespace, bounded length.
+func validName(name string) bool {
+ if name == "" || len(name) > 256 {
+ return false
+ }
+ for _, r := range name {
+ if r <= ' ' || r == 0x7f {
+ return false
+ }
+ }
+ return true
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go
new file mode 100644
index 00000000..489f006a
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go
@@ -0,0 +1,82 @@
+package beaconingestextension
+
+import (
+ "os"
+ "os/user"
+ "runtime"
+ "testing"
+ "time"
+)
+
+func TestNameCacheReusesAndExpires(t *testing.T) {
+ now := time.Unix(0, 0)
+ calls := 0
+ c := newNameCache()
+ c.now = func() time.Time { return now }
+ c.lookup1 = func(uid uint32) string { calls++; return "alice" }
+
+ for i := 0; i < 5; i++ {
+ if got := c.lookup(501); got != "alice" {
+ t.Fatalf("lookup = %q", got)
+ }
+ }
+ if calls != 1 {
+ t.Fatalf("resolved %d times within the TTL, want 1", calls)
+ }
+ now = now.Add(nameCacheTTL + time.Second)
+ _ = c.lookup(501)
+ if calls != 2 {
+ t.Fatalf("resolved %d times after the TTL, want 2", calls)
+ }
+}
+
+func TestNameCacheRetriesAMissAfterTheTTL(t *testing.T) {
+ now := time.Unix(0, 0)
+ answer := ""
+ c := newNameCache()
+ c.now = func() time.Time { return now }
+ c.lookup1 = func(uint32) string { return answer }
+ if got := c.lookup(7); got != "" {
+ t.Fatalf("lookup = %q", got)
+ }
+ answer = "bob"
+ if got := c.lookup(7); got != "" {
+ t.Fatalf("a miss was retried within the TTL: %q", got)
+ }
+ now = now.Add(nameCacheTTL + time.Second)
+ if got := c.lookup(7); got != "bob" {
+ t.Fatalf("a miss was not retried after the TTL: %q", got)
+ }
+}
+
+func TestResolveNameFindsTheCurrentAccount(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("uids are a Unix concept")
+ }
+ me, err := user.Current()
+ if err != nil {
+ t.Skip(err)
+ }
+ if got := resolveName(uint32(os.Geteuid())); got != me.Username {
+ t.Fatalf("resolveName = %q, want %q", got, me.Username)
+ }
+}
+
+func TestResolveNameOfAnUnknownUID(t *testing.T) {
+ if got := resolveName(4294967000); got != "" {
+ t.Fatalf("resolveName of an unused uid = %q, want empty", got)
+ }
+}
+
+func TestValidName(t *testing.T) {
+ for _, ok := range []string{"alice", "j.doe", "DOMAIN\\bob", "[email protected]", "_svc"} {
+ if !validName(ok) {
+ t.Errorf("validName(%q) = false", ok)
+ }
+ }
+ for _, bad := range []string{"", "a b", "tab\there", "nl\nx", "esc\x1b[31m", "del\x7f", string(make([]byte, 257))} {
+ if validName(bad) {
+ t.Errorf("validName(%q) = true", bad)
+ }
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/go.mod b/collector-builder/exporter/beaconjsonexporter/go.mod
index 4ccc7dc3..b3a53e5c 100644
--- a/collector-builder/exporter/beaconjsonexporter/go.mod
+++ b/collector-builder/exporter/beaconjsonexporter/go.mod
@@ -11,6 +11,7 @@ require (
go.opentelemetry.io/collector/consumer v1.27.0
go.opentelemetry.io/collector/consumer/consumertest v0.121.0
go.opentelemetry.io/collector/exporter v0.121.0
+ go.opentelemetry.io/collector/extension v1.27.0
go.opentelemetry.io/collector/pdata v1.27.0
go.opentelemetry.io/collector/processor v0.121.0
go.opentelemetry.io/collector/processor/processortest v0.121.0
@@ -45,7 +46,6 @@ require (
go.opentelemetry.io/collector/confmap v1.27.0 // indirect
go.opentelemetry.io/collector/consumer/consumererror v0.121.0 // indirect
go.opentelemetry.io/collector/consumer/xconsumer v0.121.0 // indirect
- go.opentelemetry.io/collector/extension v1.27.0 // indirect
go.opentelemetry.io/collector/extension/xextension v0.121.0 // indirect
go.opentelemetry.io/collector/featuregate v1.27.0 // indirect
go.opentelemetry.io/collector/pdata/pprofile v0.121.0 // indirect
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/runtimelog/runtimelog.go b/collector-builder/exporter/beaconjsonexporter/internal/runtimelog/runtimelog.go
new file mode 100644
index 00000000..4a05a380
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/runtimelog/runtimelog.go
@@ -0,0 +1,125 @@
+// Package runtimelog appends lines to the endpoint runtime log for the collector's components: the
+// beaconjson exporter and the beacon_ingest extension, which must take the same lock, rotate the
+// same way and settle the same file modes.
+package runtimelog
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
+)
+
+// DefaultRotateArchives is how many archives a log keeps when the caller passes none.
+const DefaultRotateArchives = 5
+
+// Append writes one line to the runtime log at path under its lock, rotating first when the line
+// would take the log past rotateBytes and dropping a line that duplicates a recent one.
+//
+// Keep this rotation and file-mode contract mirrored with the endpoint CLI and hook writer.
+func Append(path string, line []byte, rotateBytes int64, rotateArchives int) error {
+ _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)
+ if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {
+ return err
+ }
+ lock, err := openRuntimeFileAs(path+".lock", path, os.O_CREATE|os.O_RDWR)
+ if err != nil {
+ return err
+ }
+ held, err := filelock.Exclusive(lock)
+ if err != nil {
+ _ = lock.Close()
+ return err
+ }
+ // Unlock before closing: LIFO defer ordering means the close listed first runs last.
+ defer lock.Close()
+ defer held.Release()
+ if asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {
+ return nil
+ }
+ if err := rotateIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil {
+ return err
+ }
+ f, err := openRuntimeFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ _, err = f.Write(line)
+ return err
+}
+
+func openRuntimeFile(path string, flag int) (*os.File, error) {
+ return openRuntimeFileAs(path, path, flag)
+}
+
+// openRuntimeFileAs opens path (the log or its lock) with the mode logPath calls for, and settles
+// its mode through asymptoteobserve.OpenRuntimeLogFile: a new file gets that mode whatever the
+// umask, an existing one is only ever narrowed toward it, by its owner, and root never follows a
+// symlink or opens anything but a regular file there.
+func openRuntimeFileAs(path, logPath string, flag int) (*os.File, error) {
+ return asymptoteobserve.OpenRuntimeLogFile(path, logPath, flag)
+}
+
+func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int64) error {
+ if maxSize <= 0 {
+ return nil
+ }
+ if archives < 1 {
+ archives = DefaultRotateArchives
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return err
+ }
+ if info.Size() == 0 || info.Size()+nextWriteBytes <= maxSize {
+ return nil
+ }
+ if err := removeOverflowArchives(path, archives); err != nil {
+ return err
+ }
+ for i := archives - 1; i >= 1; i-- {
+ from := path + fmt.Sprintf(".%d", i)
+ to := path + fmt.Sprintf(".%d", i+1)
+ if err := os.Rename(from, to); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ if err := os.Rename(path, path+".1"); err != nil {
+ return err
+ }
+ asymptoteobserve.TightenRuntimeLogArchives(path, archives)
+ return nil
+}
+
+func removeOverflowArchives(path string, archives int) error {
+ dir := filepath.Dir(path)
+ base := filepath.Base(path)
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ return err
+ }
+ prefix := base + "."
+ for _, entry := range entries {
+ name := entry.Name()
+ suffix, ok := strings.CutPrefix(name, prefix)
+ if !ok {
+ continue
+ }
+ index, err := strconv.Atoi(suffix)
+ if err != nil || index < archives {
+ continue
+ }
+ if err := os.Remove(filepath.Join(dir, name)); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/writer.go b/collector-builder/exporter/beaconjsonexporter/writer.go
index aadc0b2f..f12eda67 100644
--- a/collector-builder/exporter/beaconjsonexporter/writer.go
+++ b/collector-builder/exporter/beaconjsonexporter/writer.go
@@ -5,12 +5,10 @@ import (
"fmt"
"os"
"path/filepath"
- "strconv"
- "strings"
"github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/beaconevent"
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/runtimelog"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
- "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
type jsonlWriter struct {
@@ -208,106 +206,9 @@ func sanitizeTyped[T any](input *T, sanitize func(map[string]interface{}) map[st
// identically in all three writers.
const runtimeFileMode = asymptoteobserve.SharedRuntimeLogFileMode
-// Keep this rotation and file-mode contract mirrored with the endpoint CLI and hook writer.
+// Keep this rotation and file-mode contract mirrored with the endpoint CLI and hook writer. The
+// implementation lives in internal/runtimelog so the beacon_ingest extension appends through the
+// same lock, rotation and file-mode handling as the exporter.
func appendJSONL(path string, line []byte, rotateBytes int64, rotateArchives int) error {
- _, dirMode, _ := asymptoteobserve.RuntimeLogModes(path)
- if err := os.MkdirAll(filepath.Dir(path), dirMode); err != nil {
- return err
- }
- lock, err := openRuntimeFileAs(path+".lock", path, os.O_CREATE|os.O_RDWR)
- if err != nil {
- return err
- }
- held, err := filelock.Exclusive(lock)
- if err != nil {
- _ = lock.Close()
- return err
- }
- // Unlock before closing: LIFO defer ordering means the close listed first runs last.
- defer lock.Close()
- defer held.Release()
- if asymptoteobserve.IsDuplicateEndpointEvent(path, line, asymptoteobserve.EndpointDuplicateWindow) {
- return nil
- }
- if err := rotateIfNeeded(path, rotateBytes, rotateArchives, int64(len(line))); err != nil {
- return err
- }
- f, err := openRuntimeFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY)
- if err != nil {
- return err
- }
- defer f.Close()
- _, err = f.Write(line)
- return err
-}
-
-func openRuntimeFile(path string, flag int) (*os.File, error) {
- return openRuntimeFileAs(path, path, flag)
-}
-
-// openRuntimeFileAs opens path (the log or its lock) with the mode logPath calls for, and settles
-// its mode through asymptoteobserve.OpenRuntimeLogFile: a new file gets that mode whatever the
-// umask, an existing one is only ever narrowed toward it, by its owner, and root never follows a
-// symlink or opens anything but a regular file there.
-func openRuntimeFileAs(path, logPath string, flag int) (*os.File, error) {
- return asymptoteobserve.OpenRuntimeLogFile(path, logPath, flag)
-}
-
-func rotateIfNeeded(path string, maxSize int64, archives int, nextWriteBytes int64) error {
- if maxSize <= 0 {
- return nil
- }
- if archives < 1 {
- archives = defaultRotateArchives
- }
- info, err := os.Stat(path)
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- if info.Size() == 0 || info.Size()+nextWriteBytes <= maxSize {
- return nil
- }
- if err := removeOverflowArchives(path, archives); err != nil {
- return err
- }
- for i := archives - 1; i >= 1; i-- {
- from := path + fmt.Sprintf(".%d", i)
- to := path + fmt.Sprintf(".%d", i+1)
- if err := os.Rename(from, to); err != nil && !os.IsNotExist(err) {
- return err
- }
- }
- if err := os.Rename(path, path+".1"); err != nil {
- return err
- }
- asymptoteobserve.TightenRuntimeLogArchives(path, archives)
- return nil
-}
-
-func removeOverflowArchives(path string, archives int) error {
- dir := filepath.Dir(path)
- base := filepath.Base(path)
- entries, err := os.ReadDir(dir)
- if err != nil {
- return err
- }
- prefix := base + "."
- for _, entry := range entries {
- name := entry.Name()
- suffix, ok := strings.CutPrefix(name, prefix)
- if !ok {
- continue
- }
- index, err := strconv.Atoi(suffix)
- if err != nil || index < archives {
- continue
- }
- if err := os.Remove(filepath.Join(dir, name)); err != nil && !os.IsNotExist(err) {
- return err
- }
- }
- return nil
+ return runtimelog.Append(path, line, rotateBytes, rotateArchives)
}