Skip to content

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

localingest: local socket channel from hooks to the system collector

Claude32f389cae404
diff --git a/pkg/asymptoteobserve/localingest/client.go b/pkg/asymptoteobserve/localingest/client.go
new file mode 100644
index 00000000..d45873b5
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/client.go
@@ -0,0 +1,154 @@
+package localingest
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "time"
+)
+
+// DefaultClientTimeout bounds one batch exchange. Hooks run inline with the agent, so a collector
+// that does not answer promptly costs the agent this long once, after which the events are spooled.
+// It is longer than the server's own budget for a connection (1.5s plus time to reply), so a
+// busy server reports how far it got rather than leaving the client to resend lines it wrote.
+const DefaultClientTimeout = 3 * time.Second
+
+// Client sends batches to a collector's ingest socket.
+type Client struct {
+ // SocketPath is the socket to send to. Empty means DefaultSocketPath.
+ SocketPath string
+ // Timeout bounds each connection, from dial to reply. Zero means DefaultClientTimeout.
+ Timeout time.Duration
+ // TrustedOwner is the uid the socket and its directory must belong to. Zero, the default, is
+ // root; tests set their own uid.
+ TrustedOwner int
+ // LogPath is the runtime log the lines are meant for, sent in the header. The collector refuses
+ // them, with ErrLogMismatch, if it writes another log.
+ LogPath string
+}
+
+func (c Client) path() string {
+ if c.SocketPath == "" {
+ return DefaultSocketPath
+ }
+ return c.SocketPath
+}
+
+// Available reports whether a trusted ingest socket exists, without connecting to it. It is how a
+// writer decides whether the endpoint is in the restricted mode at all; ErrNoSocket means it is
+// not.
+func (c Client) Available() error {
+ return checkSocket(c.path(), c.TrustedOwner)
+}
+
+// Send delivers lines in batches of at most MaxLinesPerConn and returns how far it got: lines
+// [0, Processed) were each written or rejected for good, and the caller keeps the rest. It stops at
+// the first batch that does not finish, and returns the reason.
+//
+// Each line must be one complete event with no newline inside it; a trailing newline is dropped.
+// ErrNoSocket means the endpoint has no ingest socket, so nothing was sent.
+func (c Client) Send(lines [][]byte) (Response, error) {
+ cleaned := make([][]byte, len(lines))
+ for i, line := range lines {
+ line = bytes.TrimSuffix(line, []byte{'\n'})
+ if bytes.IndexByte(line, '\n') >= 0 {
+ return Response{}, fmt.Errorf("line %d contains a newline", i)
+ }
+ cleaned[i] = line
+ }
+ if err := checkSocket(c.path(), c.TrustedOwner); err != nil {
+ return Response{}, err
+ }
+ var total Response
+ for start := 0; start < len(cleaned); start += MaxLinesPerConn {
+ end := start + MaxLinesPerConn
+ if end > len(cleaned) {
+ end = len(cleaned)
+ }
+ resp, err := c.sendBatch(cleaned[start:end])
+ total.Accepted += resp.Accepted
+ total.Rejected += resp.Rejected
+ total.Processed += resp.Processed
+ if err != nil {
+ total.Error = resp.Error
+ return total, err
+ }
+ }
+ return total, nil
+}
+
+func (c Client) sendBatch(lines [][]byte) (Response, error) {
+ timeout := c.Timeout
+ if timeout <= 0 {
+ timeout = DefaultClientTimeout
+ }
+ conn, err := net.DialTimeout("unix", c.path(), timeout)
+ if err != nil {
+ return Response{}, fmt.Errorf("connect to %s: %w", c.path(), err)
+ }
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(timeout))
+
+ header, err := json.Marshal(Header{Log: c.LogPath})
+ if err != nil {
+ return Response{}, err
+ }
+ w := bufio.NewWriter(conn)
+ _, writeErr := w.WriteString(Preamble + "\n" + string(header) + "\n")
+ for _, line := range lines {
+ if writeErr != nil {
+ break
+ }
+ if _, writeErr = w.Write(line); writeErr == nil {
+ writeErr = w.WriteByte('\n')
+ }
+ }
+ if writeErr == nil {
+ writeErr = w.Flush()
+ }
+ if writeErr == nil {
+ if uc, ok := conn.(*net.UnixConn); ok {
+ writeErr = uc.CloseWrite()
+ }
+ }
+
+ // Read the reply even after a failed write: a server that stopped reading early (a full batch,
+ // a refused preamble) still says how far it got before closing.
+ reply, readErr := bufio.NewReader(io.LimitReader(conn, maxResponseBytes)).ReadBytes('\n')
+ if readErr != nil && len(reply) == 0 {
+ if writeErr != nil {
+ return Response{}, fmt.Errorf("send to %s: %w", c.path(), writeErr)
+ }
+ return Response{}, fmt.Errorf("read reply from %s: %w", c.path(), readErr)
+ }
+ var resp Response
+ if err := json.Unmarshal(bytes.TrimSpace(reply), &resp); err != nil {
+ return Response{}, fmt.Errorf("malformed reply from %s: %w", c.path(), err)
+ }
+ if resp.Processed < 0 || resp.Processed > len(lines) || resp.Accepted < 0 || resp.Rejected < 0 ||
+ resp.Accepted+resp.Rejected != resp.Processed {
+ return Response{}, fmt.Errorf("inconsistent reply from %s: %+v for %d lines", c.path(), resp, len(lines))
+ }
+ if resp.Error == errLogMismatch {
+ return resp, fmt.Errorf("%w: sent for %s", ErrLogMismatch, c.LogPath)
+ }
+ if resp.Error != "" {
+ return resp, fmt.Errorf("collector stopped after %d of %d events: %s", resp.Processed, len(lines), resp.Error)
+ }
+ if resp.Processed != len(lines) {
+ if writeErr != nil {
+ return resp, fmt.Errorf("send to %s: %w", c.path(), writeErr)
+ }
+ return resp, fmt.Errorf("collector handled %d of %d events", resp.Processed, len(lines))
+ }
+ return resp, nil
+}
+
+// ErrUntrustedSocket is returned when something exists at the socket path but could have been put
+// there by someone other than root. A writer that sees it does not send there, because a socket a
+// user planted would receive every other user's events.
+var ErrUntrustedSocket = errors.New("untrusted ingest socket")
diff --git a/pkg/asymptoteobserve/localingest/localingest.go b/pkg/asymptoteobserve/localingest/localingest.go
new file mode 100644
index 00000000..9f4eaa37
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/localingest.go
@@ -0,0 +1,211 @@
+// Package localingest is the local channel through which processes that are not root hand runtime
+// log events to the privileged collector on a system-mode endpoint, instead of appending to the
+// shared log themselves.
+//
+// # Why it exists
+//
+// A system-mode endpoint has one runtime log, /var/log/beacon-agent/runtime.jsonl, written by the
+// root collector and by every logged-in user's hooks. For hooks to append to it, the file has to be
+// writable by everyone (0666), and so anyone on the machine can also truncate or rewrite it and read
+// every other user's prompts, command output and diffs. The restricted log access mode closes that:
+// the collector becomes the only writer, the log becomes 0640 root:beacon-log, and hooks send their
+// events here instead.
+//
+// # The channel
+//
+// The collector listens on a Unix domain socket (DefaultSocketPath) in a root-owned directory. A
+// connection carries one batch:
+//
+// client: "BEACON-INGEST/1\n", a Header line, one event per line, then half-closes its write side
+// server: one JSON Response line, after it has handled every line it read
+//
+// The header names the log the client means to write. A server refuses a batch meant for another
+// log, so an event a writer aimed at some other file -- a test's, a custom path -- is written there
+// directly rather than landing in the system log.
+//
+// The server learns who is on the other end from the kernel (SO_PEERCRED on Linux, LOCAL_PEERCRED
+// on macOS), never from the event, and StampLine overwrites the event's user with that identity.
+// So a user can still describe their own sessions however they like -- their agent runs under their
+// control -- but cannot erase, rewrite or read anything already in the log, and cannot write an
+// event that claims to be someone else's.
+//
+// Nothing here touches the network: a Unix socket is a local file, and the client refuses to
+// connect to one that is not in a directory only root could have created it in, because a socket a
+// user planted there would receive every other user's events.
+package localingest
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strconv"
+ "strings"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+const (
+ // DefaultSocketPath is where a system-mode collector in the restricted log access mode listens.
+ // /var/run is root-owned on Linux (a link to /run) and macOS (a link to /private/var/run), so
+ // only root can create the directory the socket lives in.
+ DefaultSocketPath = "/var/run/beacon-agent/ingest.sock"
+
+ // Preamble opens every connection. It names the protocol version, so a later version can be
+ // told apart, and keeps a stray client that happened to connect from having its bytes taken
+ // for events.
+ Preamble = "BEACON-INGEST/1"
+
+ // MaxLineBytes is the largest event the server accepts, without its newline. It is the runtime
+ // log's own per-event limit, which every writer already enforces before an event gets here.
+ MaxLineBytes = 64 * 1024
+
+ // MaxLinesPerConn bounds one batch. A client with more sends another connection.
+ MaxLinesPerConn = 256
+
+ // maxResponseBytes bounds what a client reads back.
+ maxResponseBytes = 4096
+ // maxHeaderBytes bounds the header line.
+ maxHeaderBytes = 4096
+
+ // errLogMismatch is the Response.Error a server gives for a batch meant for another log.
+ errLogMismatch = "log mismatch"
+)
+
+// Header follows the preamble.
+type Header struct {
+ // Log is the runtime log the client means to write.
+ Log string `json:"log"`
+}
+
+// ErrLogMismatch is returned by Send when the collector writes a different log from the one the
+// client named: the caller writes its own log directly.
+var ErrLogMismatch = errors.New("the collector writes a different runtime log")
+
+// ErrRejected marks a line the server will never accept, however often it is sent: malformed,
+// too large, or not a Beacon endpoint event. A client drops such lines rather than spooling them.
+var ErrRejected = errors.New("event rejected")
+
+// ErrNoSocket is returned by Send when nothing is listening at the socket path because no socket
+// exists there: the endpoint is not in the restricted mode, so the caller writes the log as before.
+var ErrNoSocket = errors.New("no ingest socket")
+
+// Peer is who the kernel says is on the other end of a connection.
+type Peer struct {
+ UID uint32
+ GID uint32
+ // PID is the sending process, or 0 where the platform does not report one.
+ PID int32
+}
+
+// Response is the server's one reply to a batch.
+//
+// Lines are handled in order. Processed is how many were handled, each either accepted (written)
+// or rejected (dropped for good). A server that hits an error it might not hit next time -- the log
+// could not be written, the sender is over its rate -- stops there and reports it in Error, so the
+// client keeps lines[Processed:] and tries them again later.
+type Response struct {
+ Accepted int `json:"accepted"`
+ Rejected int `json:"rejected"`
+ Processed int `json:"processed"`
+ Error string `json:"error,omitempty"`
+}
+
+// StampLine validates one line a peer sent and returns the line to append to the runtime log, with
+// the event's user replaced by the peer's verified identity. An error wrapping ErrRejected means the
+// line is not acceptable at all.
+//
+// The returned line is re-encoded, so whatever bytes the peer sent, exactly one JSON object on one
+// line reaches the log: nothing the sender writes can break the log into extra lines or forge a
+// second event inside the first. Numbers are kept exactly as sent. event.id is always derived
+// from the stamped line, never taken from the sender.
+//
+// lookupName resolves a uid to an account name and may be nil; a name it cannot resolve is left
+// out rather than taken from the event, which the sender wrote.
+func StampLine(line []byte, peer Peer, lookupName func(uid uint32) string) ([]byte, error) {
+ line = bytes.TrimSuffix(line, []byte{'\r'})
+ if len(line) == 0 {
+ return nil, fmt.Errorf("%w: empty line", ErrRejected)
+ }
+ if len(line) > MaxLineBytes {
+ return nil, fmt.Errorf("%w: %d bytes is over the %d byte limit", ErrRejected, len(line), MaxLineBytes)
+ }
+ event, err := decodeObject(line)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrRejected, err)
+ }
+ if err := checkEnvelope(event); err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrRejected, err)
+ }
+
+ user := map[string]interface{}{"uid": strconv.FormatUint(uint64(peer.UID), 10)}
+ if lookupName != nil {
+ if name := strings.TrimSpace(lookupName(peer.UID)); name != "" {
+ user["name"] = name
+ }
+ }
+ event["user"] = user
+
+ // The id is derived here, from the line as it will be written, never taken from the sender:
+ // otherwise one account could reuse another's event.id, and consumers that deduplicate by id
+ // would drop the real event as a repeat. Deterministic, so a resent line keeps its id.
+ info := event["event"].(map[string]interface{})
+ delete(info, "id")
+ unstamped, err := marshalLine(event)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrRejected, err)
+ }
+ info["id"] = asymptoteobserve.EventIDForLine(unstamped)
+ out, err := marshalLine(event)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %v", ErrRejected, err)
+ }
+ if len(out) > MaxLineBytes {
+ return nil, fmt.Errorf("%w: %d bytes after stamping is over the %d byte limit", ErrRejected, len(out), MaxLineBytes)
+ }
+ return out, nil
+}
+
+func decodeObject(line []byte) (map[string]interface{}, error) {
+ dec := json.NewDecoder(bytes.NewReader(line))
+ dec.UseNumber()
+ var event map[string]interface{}
+ if err := dec.Decode(&event); err != nil {
+ return nil, fmt.Errorf("not a JSON object: %v", err)
+ }
+ if event == nil {
+ return nil, errors.New("not a JSON object")
+ }
+ if dec.More() {
+ return nil, errors.New("more than one JSON value on the line")
+ }
+ var trailing json.RawMessage
+ if err := dec.Decode(&trailing); err == nil {
+ return nil, errors.New("more than one JSON value on the line")
+ }
+ return event, nil
+}
+
+func checkEnvelope(event map[string]interface{}) error {
+ if v, _ := event["vendor"].(string); v != asymptoteobserve.Vendor {
+ return fmt.Errorf("vendor must be %q", asymptoteobserve.Vendor)
+ }
+ if p, _ := event["product"].(string); p != asymptoteobserve.Product {
+ return fmt.Errorf("product must be %q", asymptoteobserve.Product)
+ }
+ if s, _ := event["schema_version"].(string); strings.TrimSpace(s) == "" {
+ return errors.New("schema_version is required")
+ }
+ info, ok := event["event"].(map[string]interface{})
+ if !ok {
+ return errors.New("event must be an object")
+ }
+ if action, _ := info["action"].(string); strings.TrimSpace(action) == "" {
+ return errors.New("event.action is required")
+ }
+ return nil
+}
+
+func marshalLine(event map[string]interface{}) ([]byte, error) {
+ return json.Marshal(event)
+}
diff --git a/pkg/asymptoteobserve/localingest/localingest_test.go b/pkg/asymptoteobserve/localingest/localingest_test.go
new file mode 100644
index 00000000..3789f75a
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/localingest_test.go
@@ -0,0 +1,227 @@
+package localingest
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
+)
+
+func validLine(t *testing.T, mutate func(map[string]interface{})) []byte {
+ t.Helper()
+ event := map[string]interface{}{
+ "timestamp": "2026-10-29T09:03:00.123456789Z",
+ "sequence": json.Number("18446744073709551615"),
+ "vendor": asymptoteobserve.Vendor,
+ "product": asymptoteobserve.Product,
+ "schema_version": asymptoteobserve.SchemaVersion,
+ "event": map[string]interface{}{"action": "tool.invoked", "category": "tool", "id": "fixed-id"},
+ "user": map[string]interface{}{"name": "alice", "uid": "501"},
+ "harness": map[string]interface{}{"name": "claude_code", "collection_method": "hook"},
+ "gen_ai": map[string]interface{}{"usage": map[string]interface{}{"cost_usd": json.Number("0.10")}},
+ "message": "line one\nline two",
+ }
+ if mutate != nil {
+ mutate(event)
+ }
+ data, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
+
+func decode(t *testing.T, line []byte) map[string]interface{} {
+ t.Helper()
+ dec := json.NewDecoder(bytes.NewReader(line))
+ dec.UseNumber()
+ var out map[string]interface{}
+ if err := dec.Decode(&out); err != nil {
+ t.Fatalf("decode %s: %v", line, err)
+ }
+ return out
+}
+
+func TestStampLineReplacesTheClaimedUserWithThePeer(t *testing.T) {
+ line := validLine(t, nil)
+ out, err := StampLine(line, Peer{UID: 1002, GID: 20, PID: 77}, func(uid uint32) string {
+ if uid != 1002 {
+ t.Fatalf("lookup asked for uid %d", uid)
+ }
+ return "mallory"
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ got := decode(t, out)
+ user := got["user"].(map[string]interface{})
+ if user["uid"] != "1002" || user["name"] != "mallory" || len(user) != 2 {
+ t.Fatalf("user = %#v, want the peer's uid and resolved name only", user)
+ }
+}
+
+func TestStampLineLeavesOutANameItCannotResolve(t *testing.T) {
+ for name, lookup := range map[string]func(uint32) string{
+ "nil lookup": nil,
+ "empty result": func(uint32) string { return " " },
+ } {
+ t.Run(name, func(t *testing.T) {
+ out, err := StampLine(validLine(t, nil), Peer{UID: 42}, lookup)
+ if err != nil {
+ t.Fatal(err)
+ }
+ user := decode(t, out)["user"].(map[string]interface{})
+ if _, ok := user["name"]; ok {
+ t.Fatalf("user = %#v: a name the kernel did not vouch for must not be kept", user)
+ }
+ if user["uid"] != "42" {
+ t.Fatalf("uid = %v, want 42", user["uid"])
+ }
+ })
+ }
+}
+
+func TestStampLineAddsAUserToAnEventWithout(t *testing.T) {
+ line := validLine(t, func(e map[string]interface{}) { delete(e, "user") })
+ out, err := StampLine(line, Peer{UID: 0}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if user := decode(t, out)["user"].(map[string]interface{}); user["uid"] != "0" {
+ t.Fatalf("user = %#v", user)
+ }
+}
+
+func TestStampLineKeepsEverythingElseExactly(t *testing.T) {
+ line := validLine(t, nil)
+ out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The sender claimed exactly what the kernel reports, so apart from the id, which is always
+ // derived here, the line must come back byte for byte: numbers keep their spelling and
+ // nothing is reordered or re-escaped.
+ withoutID := func(b []byte) []byte {
+ e := decode(t, b)
+ delete(e["event"].(map[string]interface{}), "id")
+ out, _ := json.Marshal(e)
+ return out
+ }
+ if !bytes.Equal(withoutID(out), withoutID(line)) {
+ t.Fatalf("line changed:\n in: %s\nout: %s", line, out)
+ }
+ if bytes.IndexByte(out, '\n') >= 0 {
+ t.Fatal("stamped line contains a raw newline")
+ }
+ got := decode(t, out)
+ if got["sequence"].(json.Number).String() != "18446744073709551615" {
+ t.Fatalf("sequence = %v, lost precision", got["sequence"])
+ }
+}
+
+func TestStampLineNamesAnEventThatArrivesWithoutAnID(t *testing.T) {
+ line := validLine(t, func(e map[string]interface{}) {
+ delete(e["event"].(map[string]interface{}), "id")
+ })
+ first, err := StampLine(line, Peer{UID: 501}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := StampLine(line, Peer{UID: 501}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(first, second) {
+ t.Fatal("the derived id is not deterministic")
+ }
+ got := decode(t, first)
+ id, _ := got["event"].(map[string]interface{})["id"].(string)
+ if id == "" {
+ t.Fatal("no event.id was derived")
+ }
+ // The id is derived from the stamped line without its id, exactly as the writers derive it.
+ delete(got["event"].(map[string]interface{}), "id")
+ unstamped, _ := json.Marshal(got)
+ if want := asymptoteobserve.EventIDForLine(unstamped); id != want {
+ t.Fatalf("event.id = %q, want %q", id, want)
+ }
+ // A different account sending the same bytes is a different event.
+ other, err := StampLine(line, Peer{UID: 502}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if decode(t, other)["event"].(map[string]interface{})["id"] == id {
+ t.Fatal("two accounts' events share an id")
+ }
+}
+
+func TestStampLineRejects(t *testing.T) {
+ cases := map[string][]byte{
+ "empty": nil,
+ "not json": []byte("hello"),
+ "array": []byte(`[1,2]`),
+ "null": []byte(`null`),
+ "string": []byte(`"x"`),
+ "two objects": append(validLine(t, nil), validLine(t, nil)...),
+ "trailing garbage": append(validLine(t, nil), []byte(" x")...),
+ "truncated": validLine(t, nil)[:40],
+ "wrong vendor": validLine(t, func(e map[string]interface{}) { e["vendor"] = "evil" }),
+ "wrong product": validLine(t, func(e map[string]interface{}) { e["product"] = "other" }),
+ "no schema version": validLine(t, func(e map[string]interface{}) { delete(e, "schema_version") }),
+ "event not an object": validLine(t, func(e map[string]interface{}) { e["event"] = "tool.invoked" }),
+ "no action": validLine(t, func(e map[string]interface{}) { delete(e["event"].(map[string]interface{}), "action") }),
+ "blank action": validLine(t, func(e map[string]interface{}) { e["event"].(map[string]interface{})["action"] = " " }),
+ "too long": validLine(t, func(e map[string]interface{}) { e["message"] = strings.Repeat("a", MaxLineBytes) }),
+ }
+ for name, line := range cases {
+ t.Run(name, func(t *testing.T) {
+ out, err := StampLine(line, Peer{UID: 1}, nil)
+ if !errors.Is(err, ErrRejected) {
+ t.Fatalf("err = %v, out = %s; want ErrRejected", err, out)
+ }
+ })
+ }
+}
+
+func TestStampLineRejectsALineThatOutgrowsTheLimitWhenStamped(t *testing.T) {
+ base := validLine(t, func(e map[string]interface{}) { delete(e, "user") })
+ pad := MaxLineBytes - len(base) - 10
+ line := validLine(t, func(e map[string]interface{}) {
+ delete(e, "user")
+ e["message"] = strings.Repeat("a", pad+len("line one\nline two"))
+ })
+ if len(line) > MaxLineBytes {
+ t.Fatalf("fixture is %d bytes, want it under the limit before stamping", len(line))
+ }
+ _, err := StampLine(line, Peer{UID: 1}, func(uint32) string { return strings.Repeat("n", 64) })
+ if !errors.Is(err, ErrRejected) {
+ t.Fatalf("err = %v, want ErrRejected for a line over the limit once stamped", err)
+ }
+}
+
+func TestStampLineAcceptsATrailingCarriageReturn(t *testing.T) {
+ line := append(validLine(t, nil), '\r')
+ out, err := StampLine(line, Peer{UID: 501}, func(uint32) string { return "alice" })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if bytes.HasSuffix(out, []byte{'\r'}) {
+ t.Fatal("carriage return kept")
+ }
+}
+
+func TestStampLineNeverKeepsTheSendersEventID(t *testing.T) {
+ line := validLine(t, func(e map[string]interface{}) {
+ e["event"].(map[string]interface{})["id"] = "someone-elses-event-id"
+ })
+ out, err := StampLine(line, Peer{UID: 501}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if id := decode(t, out)["event"].(map[string]interface{})["id"]; id == "someone-elses-event-id" || id == "" {
+ t.Fatalf("event.id = %v; a sender must not choose it", id)
+ }
+}
diff --git a/pkg/asymptoteobserve/localingest/peercred_darwin.go b/pkg/asymptoteobserve/localingest/peercred_darwin.go
new file mode 100644
index 00000000..4b5eee4f
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/peercred_darwin.go
@@ -0,0 +1,40 @@
+//go:build darwin
+
+package localingest
+
+import (
+ "fmt"
+ "net"
+
+ "golang.org/x/sys/unix"
+)
+
+// peerCredentials asks the kernel who opened the other end of conn. LOCAL_PEERCRED reports the
+// effective credentials the peer had when it connected; LOCAL_PEERPID adds its pid, best effort.
+func peerCredentials(conn *net.UnixConn) (Peer, error) {
+ raw, err := conn.SyscallConn()
+ if err != nil {
+ return Peer{}, err
+ }
+ var cred *unix.Xucred
+ var pid int
+ var credErr error
+ if err := raw.Control(func(fd uintptr) {
+ cred, credErr = unix.GetsockoptXucred(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERCRED)
+ if credErr == nil {
+ pid, _ = unix.GetsockoptInt(int(fd), unix.SOL_LOCAL, unix.LOCAL_PEERPID)
+ }
+ }); err != nil {
+ return Peer{}, err
+ }
+ if credErr != nil {
+ return Peer{}, fmt.Errorf("read peer credentials: %w", credErr)
+ }
+ peer := Peer{UID: cred.Uid, PID: int32(pid)}
+ if cred.Ngroups > 0 {
+ peer.GID = cred.Groups[0]
+ }
+ return peer, nil
+}
+
+const peerCredentialsSupported = true
diff --git a/pkg/asymptoteobserve/localingest/peercred_linux.go b/pkg/asymptoteobserve/localingest/peercred_linux.go
new file mode 100644
index 00000000..b663b288
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/peercred_linux.go
@@ -0,0 +1,33 @@
+//go:build linux
+
+package localingest
+
+import (
+ "fmt"
+ "net"
+
+ "golang.org/x/sys/unix"
+)
+
+// peerCredentials asks the kernel who opened the other end of conn. SO_PEERCRED reports the
+// credentials the peer had when it called connect, which is what matters: a process cannot change
+// them afterwards by dropping or gaining privilege.
+func peerCredentials(conn *net.UnixConn) (Peer, error) {
+ raw, err := conn.SyscallConn()
+ if err != nil {
+ return Peer{}, err
+ }
+ var cred *unix.Ucred
+ var credErr error
+ if err := raw.Control(func(fd uintptr) {
+ cred, credErr = unix.GetsockoptUcred(int(fd), unix.SOL_SOCKET, unix.SO_PEERCRED)
+ }); err != nil {
+ return Peer{}, err
+ }
+ if credErr != nil {
+ return Peer{}, fmt.Errorf("read peer credentials: %w", credErr)
+ }
+ return Peer{UID: cred.Uid, GID: cred.Gid, PID: cred.Pid}, nil
+}
+
+const peerCredentialsSupported = true
diff --git a/pkg/asymptoteobserve/localingest/peercred_other.go b/pkg/asymptoteobserve/localingest/peercred_other.go
new file mode 100644
index 00000000..32402704
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/peercred_other.go
@@ -0,0 +1,16 @@
+//go:build !linux && !darwin
+
+package localingest
+
+import (
+ "errors"
+ "net"
+)
+
+// peerCredentials is unsupported here. The server refuses to start rather than accept events it
+// cannot attribute, because attributing them is the point of the channel.
+func peerCredentials(*net.UnixConn) (Peer, error) {
+ return Peer{}, errors.ErrUnsupported
+}
+
+const peerCredentialsSupported = false
diff --git a/pkg/asymptoteobserve/localingest/server.go b/pkg/asymptoteobserve/localingest/server.go
new file mode 100644
index 00000000..e58f840a
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/server.go
@@ -0,0 +1,439 @@
+package localingest
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "path/filepath"
+ "sync"
+ "time"
+)
+
+const (
+ defaultMaxConns = 64
+ // defaultMaxConnsPerUID keeps one account from holding every connection slot, which would
+ // leave every other account's hooks spooling. It leaves room for an agent running many tool
+ // calls at once; a hook refused here spools its event rather than losing it.
+ defaultMaxConnsPerUID = 16
+ // defaultConnTimeout is the server's whole budget for one connection: reading, writing the log
+ // and replying. It is shorter than DefaultClientTimeout, so a busy server stops and says how
+ // far it got before the client gives up -- a client that gave up resends the whole batch, and
+ // the lines the server did write would then be written twice.
+ defaultConnTimeout = 1500 * time.Millisecond
+ // replyGrace is the time past the budget the server allows itself to drain what the client is
+ // still sending and write the reply.
+ replyGrace = 500 * time.Millisecond
+ // defaultRateBytesPerSecond and defaultRateBurstBytes bound how many bytes one account can push
+ // into the log. Bytes, not events: the log rotates by size, so a flood of maximum-size events
+ // counted as events would rotate everyone else's history out in seconds. An honest hook writes
+ // a few kilobytes per tool call; the burst covers a full spool drain.
+ defaultRateBytesPerSecond = 256 * 1024
+ defaultRateBurstBytes = 16 * 1024 * 1024
+)
+
+// Server accepts batches on a listener and hands each verified, stamped line to Append.
+type Server struct {
+ // Append writes one line, already stamped by StampLine, to the runtime log. An error wrapping
+ // ErrRejected drops that line for good; any other error stops the batch, and the client keeps
+ // the rest to send again.
+ Append func(line []byte) error
+ // LookupName resolves a peer's uid to its account name for the stamped user. Optional.
+ LookupName func(uid uint32) string
+ // LogPath is the runtime log Append writes. A batch whose header names another log is refused
+ // without being read into the log. Empty accepts any header; only tests leave it empty.
+ LogPath string
+ // Logf reports refused connections and rejected lines. Optional.
+ Logf func(format string, args ...interface{})
+
+ // MaxConns bounds concurrent connections; further ones are closed at once, and their clients
+ // spool. Zero means 64.
+ MaxConns int
+ // MaxConnsPerUID bounds one account's concurrent connections. Zero means 16.
+ MaxConnsPerUID int
+ // ConnTimeout bounds the work on one connection. Zero means 1.5s.
+ ConnTimeout time.Duration
+ // RateBytesPerSecond and RateBurstBytes bound the bytes each account can write. Zero means
+ // the defaults; a negative rate turns the bound off.
+ RateBytesPerSecond float64
+ RateBurstBytes float64
+
+ // now is the clock the rate limiter reads; tests replace it.
+ now func() time.Time
+
+ mu sync.Mutex
+ listeners map[net.Listener]struct{}
+ conns map[net.Conn]struct{}
+ slots chan struct{}
+ closed bool
+ wg sync.WaitGroup
+ buckets map[uint32]*bucket
+ perUID map[uint32]int
+}
+
+// ErrServerClosed is returned by Serve after Close.
+var ErrServerClosed = errors.New("localingest: server closed")
+
+// Serve accepts connections on l until Close is called or l fails. It refuses to run where the
+// kernel cannot say who a peer is, because then nothing it wrote could be attributed.
+func (s *Server) Serve(l net.Listener) error {
+ if s.Append == nil {
+ return errors.New("localingest: Server.Append is required")
+ }
+ if !peerCredentialsSupported {
+ return fmt.Errorf("localingest: peer credentials are not available on this platform: %w", errors.ErrUnsupported)
+ }
+ if !s.track(l) {
+ _ = l.Close()
+ return ErrServerClosed
+ }
+ defer s.untrack(l)
+ for {
+ conn, err := l.Accept()
+ if err != nil {
+ if s.isClosed() {
+ return ErrServerClosed
+ }
+ var ne net.Error
+ if errors.As(err, &ne) && ne.Timeout() {
+ continue
+ }
+ return err
+ }
+ select {
+ case s.slots <- struct{}{}:
+ default:
+ s.logf("refusing connection: %d already open", cap(s.slots))
+ _ = conn.Close()
+ continue
+ }
+ if !s.trackConn(conn) {
+ <-s.slots
+ _ = conn.Close()
+ return ErrServerClosed
+ }
+ s.wg.Add(1)
+ go func() {
+ defer s.wg.Done()
+ defer func() { <-s.slots }()
+ defer s.untrackConn(conn)
+ s.handle(conn)
+ }()
+ }
+}
+
+// Close stops every Serve call, closes open connections, and waits for their handlers.
+func (s *Server) Close() error {
+ s.mu.Lock()
+ s.closed = true
+ var err error
+ for l := range s.listeners {
+ if cerr := l.Close(); cerr != nil && err == nil {
+ err = cerr
+ }
+ }
+ for c := range s.conns {
+ _ = c.Close()
+ }
+ s.mu.Unlock()
+ s.wg.Wait()
+ return err
+}
+
+func (s *Server) init() {
+ if s.listeners == nil {
+ s.listeners = map[net.Listener]struct{}{}
+ s.conns = map[net.Conn]struct{}{}
+ s.buckets = map[uint32]*bucket{}
+ s.perUID = map[uint32]int{}
+ n := s.MaxConns
+ if n <= 0 {
+ n = defaultMaxConns
+ }
+ s.slots = make(chan struct{}, n)
+ }
+}
+
+func (s *Server) track(l net.Listener) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return false
+ }
+ s.init()
+ s.listeners[l] = struct{}{}
+ return true
+}
+
+func (s *Server) untrack(l net.Listener) {
+ s.mu.Lock()
+ delete(s.listeners, l)
+ s.mu.Unlock()
+}
+
+func (s *Server) trackConn(c net.Conn) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return false
+ }
+ s.conns[c] = struct{}{}
+ return true
+}
+
+func (s *Server) untrackConn(c net.Conn) {
+ s.mu.Lock()
+ delete(s.conns, c)
+ s.mu.Unlock()
+ _ = c.Close()
+}
+
+func (s *Server) isClosed() bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.closed
+}
+
+func (s *Server) logf(format string, args ...interface{}) {
+ if s.Logf != nil {
+ s.Logf(format, args...)
+ }
+}
+
+func (s *Server) handle(conn net.Conn) {
+ timeout := s.ConnTimeout
+ if timeout <= 0 {
+ timeout = defaultConnTimeout
+ }
+ budget := time.Now().Add(timeout)
+ _ = conn.SetDeadline(budget)
+
+ unixConn, ok := conn.(*net.UnixConn)
+ if !ok {
+ s.logf("refusing connection: not a Unix socket")
+ return
+ }
+ peer, err := peerCredentials(unixConn)
+ if err != nil {
+ s.logf("refusing connection: %v", err)
+ return
+ }
+ if !s.acquireUID(peer.UID) {
+ s.logf("refusing connection from uid %d: it already has the most connections one account may hold", peer.UID)
+ return
+ }
+ defer s.releaseUID(peer.UID)
+ // The name is resolved once per connection, before any line, so a slow directory service is
+ // paid for once and never between writes.
+ var lookup func(uint32) string
+ if s.LookupName != nil {
+ name := s.LookupName(peer.UID)
+ lookup = func(uint32) string { return name }
+ }
+
+ r := bufio.NewReaderSize(conn, MaxLineBytes+2)
+ preamble, tooLong, err := readLine(r, len(Preamble)+1)
+ if err != nil && !errors.Is(err, io.EOF) || tooLong || string(preamble) != Preamble {
+ s.logf("refusing connection from uid %d: no %s preamble", peer.UID, Preamble)
+ writeResponse(conn, Response{Error: "expected " + Preamble})
+ return
+ }
+
+ var resp Response
+ stopped := false
+ headerLine, tooLong, err := readLine(r, maxHeaderBytes)
+ var header Header
+ switch {
+ case err != nil && !errors.Is(err, io.EOF), tooLong, json.Unmarshal(headerLine, &header) != nil:
+ s.logf("refusing connection from uid %d: no valid header", peer.UID)
+ writeResponse(conn, Response{Error: "expected a header"})
+ return
+ case s.LogPath != "" && !sameLog(header.Log, s.LogPath):
+ // Read and drop the rest, so the client can finish writing and read why.
+ resp.Error = errLogMismatch
+ stopped = true
+ }
+ lines := 0
+ for {
+ line, tooLong, err := readLine(r, MaxLineBytes)
+ if err != nil && !errors.Is(err, io.EOF) {
+ // A read that failed part way (a timeout, a reset) may have cut the last line short, so
+ // it is not handled, and the client gets no reply: it keeps the whole batch and sends it
+ // again. A line written before the failure may then appear twice, under the same
+ // deterministic event.id, which is the trade the log already makes on any retried write.
+ s.logf("connection from uid %d ended early: %v", peer.UID, err)
+ return
+ }
+ if len(line) == 0 && !tooLong {
+ if err != nil {
+ break
+ }
+ continue // a blank line carries nothing
+ }
+ if stopped {
+ if err != nil {
+ break
+ }
+ continue // drain, so the client can finish writing and read the reply
+ }
+ lines++
+ switch {
+ case time.Now().After(budget):
+ // Out of time: stop writing and say how far this got, while the client still waits.
+ resp.Error = "busy"
+ stopped = true
+ _ = conn.SetDeadline(time.Now().Add(replyGrace))
+ case lines > MaxLinesPerConn:
+ resp.Error = fmt.Sprintf("batch is over %d lines", MaxLinesPerConn)
+ stopped = true
+ case tooLong:
+ resp.Rejected++
+ s.logf("rejected an event from uid %d: over %d bytes", peer.UID, MaxLineBytes)
+ case !s.allow(peer.UID, len(line)):
+ resp.Error = "rate limited"
+ stopped = true
+ default:
+ stamped, stampErr := StampLine(line, peer, lookup)
+ if stampErr != nil {
+ resp.Rejected++
+ s.logf("rejected an event from uid %d: %v", peer.UID, stampErr)
+ break
+ }
+ if appendErr := s.Append(stamped); appendErr != nil {
+ if errors.Is(appendErr, ErrRejected) {
+ resp.Rejected++
+ break
+ }
+ resp.Error = "write failed"
+ s.logf("could not write an event from uid %d: %v", peer.UID, appendErr)
+ stopped = true
+ break
+ }
+ resp.Accepted++
+ }
+ if err != nil {
+ break
+ }
+ }
+ resp.Processed = resp.Accepted + resp.Rejected
+ if time.Now().After(budget) {
+ _ = conn.SetWriteDeadline(time.Now().Add(replyGrace))
+ }
+ writeResponse(conn, resp)
+}
+
+func (s *Server) acquireUID(uid uint32) bool {
+ limit := s.MaxConnsPerUID
+ if limit <= 0 {
+ limit = defaultMaxConnsPerUID
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.perUID[uid] >= limit {
+ return false
+ }
+ s.perUID[uid]++
+ return true
+}
+
+func (s *Server) releaseUID(uid uint32) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.perUID[uid] <= 1 {
+ delete(s.perUID, uid)
+ return
+ }
+ s.perUID[uid]--
+}
+
+func sameLog(a, b string) bool {
+ if a == "" || b == "" {
+ return false
+ }
+ return filepath.Clean(a) == filepath.Clean(b)
+}
+
+func writeResponse(w io.Writer, resp Response) {
+ data, err := json.Marshal(resp)
+ if err != nil {
+ return
+ }
+ _, _ = w.Write(append(data, '\n'))
+}
+
+// readLine reads up to the next newline. A line longer than max is consumed to its end and
+// reported as tooLong with no content. err is the read error that ended the line, if any; a final
+// line with no newline before EOF is returned with io.EOF.
+func readLine(r *bufio.Reader, max int) (line []byte, tooLong bool, err error) {
+ var buf []byte
+ for {
+ chunk, readErr := r.ReadSlice('\n')
+ if !tooLong {
+ if len(buf)+len(chunk) > max+1 {
+ tooLong = true
+ buf = nil
+ } else {
+ buf = append(buf, chunk...)
+ }
+ }
+ if readErr == bufio.ErrBufferFull {
+ continue
+ }
+ if tooLong {
+ return nil, true, readErr
+ }
+ buf = bytes.TrimSuffix(buf, []byte{'\n'})
+ if len(buf) > max {
+ return nil, true, readErr
+ }
+ return buf, false, readErr
+ }
+}
+
+// bucket is a token bucket for one account.
+type bucket struct {
+ tokens float64
+ last time.Time
+}
+
+// allow charges size bytes to uid's bucket.
+func (s *Server) allow(uid uint32, size int) bool {
+ rate := s.RateBytesPerSecond
+ if rate < 0 {
+ return true
+ }
+ if rate == 0 {
+ rate = defaultRateBytesPerSecond
+ }
+ burst := s.RateBurstBytes
+ if burst <= 0 {
+ burst = defaultRateBurstBytes
+ }
+ now := time.Now()
+ if s.now != nil {
+ now = s.now()
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ b := s.buckets[uid]
+ if b == nil {
+ b = &bucket{tokens: burst, last: now}
+ s.buckets[uid] = b
+ }
+ if elapsed := now.Sub(b.last).Seconds(); elapsed > 0 {
+ b.tokens += elapsed * rate
+ if b.tokens > burst {
+ b.tokens = burst
+ }
+ b.last = now
+ }
+ cost := float64(size + 1)
+ if b.tokens < cost {
+ return false
+ }
+ b.tokens -= cost
+ return true
+}
diff --git a/pkg/asymptoteobserve/localingest/server_unix_test.go b/pkg/asymptoteobserve/localingest/server_unix_test.go
new file mode 100644
index 00000000..e513a2bb
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/server_unix_test.go
@@ -0,0 +1,858 @@
+//go:build linux || darwin
+
+package localingest
+
+import (
+ "bufio"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// shortTempDir returns a directory with a path short enough for a Unix socket name, which macOS
+// caps at 104 bytes; t.TempDir() under /var/folders can exceed that.
+func shortTempDir(t *testing.T) string {
+ t.Helper()
+ dir, err := os.MkdirTemp("", "li")
+ 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 recorder struct {
+ mu sync.Mutex
+ lines [][]byte
+ fail func(n int, line []byte) error
+}
+
+func (r *recorder) append(line []byte) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.fail != nil {
+ if err := r.fail(len(r.lines), line); err != nil {
+ return err
+ }
+ }
+ r.lines = append(r.lines, append([]byte(nil), line...))
+ return nil
+}
+
+func (r *recorder) setFail(fail func(n int, line []byte) error) {
+ r.mu.Lock()
+ r.fail = fail
+ r.mu.Unlock()
+}
+
+func (r *recorder) count() int {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ return len(r.lines)
+}
+
+type harness struct {
+ server *Server
+ rec *recorder
+ client Client
+ path string
+ done chan error
+}
+
+func startServer(t *testing.T, configure func(*Server)) *harness {
+ t.Helper()
+ dir := filepath.Join(shortTempDir(t), "run")
+ path := filepath.Join(dir, "ingest.sock")
+ l, err := Listen(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := &recorder{}
+ s := &Server{
+ Append: rec.append,
+ LookupName: func(uid uint32) string { return fmt.Sprintf("user%d", uid) },
+ }
+ if configure != nil {
+ configure(s)
+ }
+ done := make(chan error, 1)
+ go func() { done <- s.Serve(l) }()
+ h := &harness{server: s, rec: rec, path: path, done: done,
+ client: Client{SocketPath: path, TrustedOwner: os.Geteuid(), Timeout: 2 * time.Second}}
+ t.Cleanup(func() { _ = s.Close() })
+ return h
+}
+
+func lines(t *testing.T, n int) [][]byte {
+ t.Helper()
+ out := make([][]byte, n)
+ for i := range out {
+ i := i
+ out[i] = validLine(t, func(e map[string]interface{}) {
+ e["event"].(map[string]interface{})["id"] = fmt.Sprintf("id-%d", i)
+ e["message"] = fmt.Sprintf("m-%d", i)
+ e["user"] = map[string]interface{}{"name": "root", "uid": "0"}
+ })
+ }
+ return out
+}
+
+// opening is the preamble and a header naming no log, which a server without a LogPath accepts.
+const opening = Preamble + "\n" + `{"log":""}` + "\n"
+
+// rawExchange speaks the protocol by hand, for what a well-behaved Client never sends.
+func rawExchange(t *testing.T, path string, payload string) (Response, error) {
+ t.Helper()
+ conn, err := net.Dial("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ _ = conn.SetDeadline(time.Now().Add(5 * time.Second))
+ if _, err := conn.Write([]byte(payload)); err != nil {
+ return Response{}, err
+ }
+ _ = conn.(*net.UnixConn).CloseWrite()
+ reply, err := bufio.NewReader(conn).ReadBytes('\n')
+ if err != nil {
+ return Response{}, err
+ }
+ var resp Response
+ if err := json.Unmarshal(reply, &resp); err != nil {
+ t.Fatalf("reply %q: %v", reply, err)
+ }
+ return resp, nil
+}
+
+func TestRoundTripStampsTheSendersKernelIdentity(t *testing.T) {
+ h := startServer(t, nil)
+ resp, err := h.client.Send(lines(t, 3))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Accepted != 3 || resp.Processed != 3 || resp.Rejected != 0 {
+ t.Fatalf("resp = %+v", resp)
+ }
+ if h.rec.count() != 3 {
+ t.Fatalf("wrote %d lines, want 3", h.rec.count())
+ }
+ uid := fmt.Sprint(os.Geteuid())
+ for i, line := range h.rec.lines {
+ user := decode(t, line)["user"].(map[string]interface{})
+ // Every line claimed root; the kernel says otherwise.
+ if user["uid"] != uid || user["name"] != "user"+uid {
+ t.Fatalf("line %d user = %#v, want uid %s", i, user, uid)
+ }
+ if m := decode(t, line)["message"]; m != fmt.Sprintf("m-%d", i) {
+ t.Fatalf("line %d arrived out of order: %v", i, m)
+ }
+ }
+}
+
+func TestPeerCredentialsMatchTheConnectingProcess(t *testing.T) {
+ dir := shortTempDir(t)
+ path := filepath.Join(dir, "p.sock")
+ l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ got := make(chan Peer, 1)
+ go func() {
+ conn, err := l.AcceptUnix()
+ if err != nil {
+ return
+ }
+ defer conn.Close()
+ peer, err := peerCredentials(conn)
+ if err != nil {
+ t.Error(err)
+ }
+ got <- peer
+ }()
+ conn, err := net.Dial("unix", path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ peer := <-got
+ if int(peer.UID) != os.Geteuid() || int(peer.GID) != os.Getegid() {
+ t.Fatalf("peer = %+v, want uid %d gid %d", peer, os.Geteuid(), os.Getegid())
+ }
+ if peer.PID != int32(os.Getpid()) {
+ t.Fatalf("peer pid = %d, want %d", peer.PID, os.Getpid())
+ }
+}
+
+func TestMixedBatchCountsRejectedLinesAndKeepsGoing(t *testing.T) {
+ h := startServer(t, nil)
+ batch := lines(t, 3)
+ batch = append(batch[:1], append([][]byte{[]byte(`{"vendor":"evil"}`), []byte(`not json`)}, batch[1:]...)...)
+ resp, err := h.client.Send(batch)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Accepted != 3 || resp.Rejected != 2 || resp.Processed != 5 {
+ t.Fatalf("resp = %+v", resp)
+ }
+}
+
+func TestAWriteFailureStopsTheBatchAndReportsHowFarItGot(t *testing.T) {
+ h := startServer(t, nil)
+ h.rec.setFail(func(n int, _ []byte) error {
+ if n == 1 {
+ return errors.New("disk full")
+ }
+ return nil
+ })
+ resp, err := h.client.Send(lines(t, 4))
+ if err == nil {
+ t.Fatal("Send succeeded past a write failure")
+ }
+ if resp.Processed != 1 || resp.Accepted != 1 || resp.Error != "write failed" {
+ t.Fatalf("resp = %+v, want one processed and the failure reported", resp)
+ }
+ if h.rec.count() != 1 {
+ t.Fatalf("wrote %d lines after the failure", h.rec.count())
+ }
+ // The reply must not leak the server-side error text to the client.
+ if strings.Contains(err.Error(), "disk full") {
+ t.Fatalf("error %q exposes the server's internal error", err)
+ }
+}
+
+func TestAnAppendRejectionDropsOnlyThatLine(t *testing.T) {
+ h := startServer(t, nil)
+ h.rec.setFail(func(n int, _ []byte) error {
+ if n == 0 {
+ h.rec.fail = nil // runs under h.rec.mu
+ return fmt.Errorf("refused: %w", ErrRejected)
+ }
+ return nil
+ })
+ resp, err := h.client.Send(lines(t, 3))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Rejected != 1 || resp.Accepted != 2 || resp.Processed != 3 {
+ t.Fatalf("resp = %+v", resp)
+ }
+}
+
+func TestClientSplitsLargeBatches(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.RateBytesPerSecond = -1 })
+ n := MaxLinesPerConn*2 + 17
+ resp, err := h.client.Send(lines(t, n))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Accepted != n || h.rec.count() != n {
+ t.Fatalf("resp = %+v, wrote %d, want %d", resp, h.rec.count(), n)
+ }
+}
+
+func TestServerStopsABatchOverTheLineLimit(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.RateBytesPerSecond = -1 })
+ var b strings.Builder
+ b.WriteString(opening)
+ for _, line := range lines(t, MaxLinesPerConn+5) {
+ b.Write(line)
+ b.WriteByte('\n')
+ }
+ resp, err := rawExchange(t, h.path, b.String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Processed != MaxLinesPerConn || resp.Error == "" {
+ t.Fatalf("resp = %+v, want the batch cut at %d", resp, MaxLinesPerConn)
+ }
+ if h.rec.count() != MaxLinesPerConn {
+ t.Fatalf("wrote %d", h.rec.count())
+ }
+}
+
+func TestServerRefusesAConnectionWithoutThePreamble(t *testing.T) {
+ h := startServer(t, nil)
+ resp, err := rawExchange(t, h.path, string(lines(t, 1)[0])+"\n")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Error == "" || resp.Processed != 0 {
+ t.Fatalf("resp = %+v", resp)
+ }
+ if h.rec.count() != 0 {
+ t.Fatal("an event without the preamble was written")
+ }
+}
+
+func TestServerSkipsAnOversizedLineAndReadsTheNext(t *testing.T) {
+ h := startServer(t, nil)
+ good := lines(t, 1)[0]
+ payload := opening + strings.Repeat("x", MaxLineBytes*3) + "\n" + string(good) + "\n"
+ resp, err := rawExchange(t, h.path, payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Rejected != 1 || resp.Accepted != 1 || resp.Processed != 2 {
+ t.Fatalf("resp = %+v", resp)
+ }
+}
+
+const uuidSized = "00000000-0000-0000-0000-000000000000"
+
+func TestServerAcceptsALineAtExactlyTheLimit(t *testing.T) {
+ h := startServer(t, nil)
+ base := validLine(t, func(e map[string]interface{}) {
+ e["message"] = ""
+ e["user"] = map[string]interface{}{"uid": fmt.Sprint(os.Geteuid()), "name": fmt.Sprintf("user%d", os.Geteuid())}
+ e["event"].(map[string]interface{})["id"] = uuidSized
+ })
+ line := validLine(t, func(e map[string]interface{}) {
+ e["message"] = strings.Repeat("m", MaxLineBytes-len(base))
+ e["user"] = map[string]interface{}{"uid": fmt.Sprint(os.Geteuid()), "name": fmt.Sprintf("user%d", os.Geteuid())}
+ // The server replaces the id with one it derives, which is a UUID: the same length.
+ e["event"].(map[string]interface{})["id"] = uuidSized
+ })
+ if len(line) != MaxLineBytes {
+ t.Fatalf("fixture is %d bytes, want %d", len(line), MaxLineBytes)
+ }
+ resp, err := h.client.Send([][]byte{line})
+ if err != nil || resp.Accepted != 1 {
+ t.Fatalf("resp = %+v, err = %v", resp, err)
+ }
+}
+
+func TestServerTakesAFinalLineWithoutANewline(t *testing.T) {
+ h := startServer(t, nil)
+ resp, err := rawExchange(t, h.path, opening+"\n"+string(lines(t, 1)[0]))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Accepted != 1 || resp.Processed != 1 {
+ t.Fatalf("resp = %+v", resp)
+ }
+}
+
+func TestServerDropsAConnectionThatStalls(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.ConnTimeout = 150 * time.Millisecond })
+ conn, err := net.Dial("unix", h.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ line := lines(t, 1)[0]
+ // A whole line, then half of the next, then nothing.
+ if _, err := conn.Write([]byte(opening + string(line) + "\n" + string(line[:20]))); err != nil {
+ t.Fatal(err)
+ }
+ _ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
+ reply, err := bufio.NewReader(conn).ReadBytes('\n')
+ if err == nil {
+ t.Fatalf("got reply %q from a stalled connection; want it closed without one", reply)
+ }
+ if h.rec.count() != 1 {
+ t.Fatalf("wrote %d lines, want only the complete one", h.rec.count())
+ }
+}
+
+func TestRateLimitStopsAFloodingAccount(t *testing.T) {
+ now := time.Unix(1000, 0)
+ h := startServer(t, func(s *Server) {
+ size := float64(len(lines(t, 1)[0]) + 1)
+ s.RateBytesPerSecond = size
+ s.RateBurstBytes = 2*size + 1
+ s.now = func() time.Time { return now }
+ })
+ resp, err := h.client.Send(lines(t, 5))
+ if err == nil || resp.Processed != 2 || resp.Error != "rate limited" {
+ t.Fatalf("resp = %+v, err = %v; want two through and the rest refused", resp, err)
+ }
+ now = now.Add(3 * time.Second)
+ resp, err = h.client.Send(lines(t, 2))
+ if err != nil || resp.Accepted != 2 {
+ t.Fatalf("after refill resp = %+v, err = %v", resp, err)
+ }
+}
+
+func TestServerClosesConnectionsOverTheLimit(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.MaxConns = 1 })
+ held, err := net.Dial("unix", h.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Wait until the server has taken the held connection's slot.
+ deadline := time.Now().Add(2 * time.Second)
+ for openConns(h.server) == 0 && time.Now().Before(deadline) {
+ time.Sleep(5 * time.Millisecond)
+ }
+ if _, err := h.client.Send(lines(t, 1)); err == nil {
+ t.Fatal("Send succeeded over the connection limit")
+ }
+ if h.rec.count() != 0 {
+ t.Fatal("an event over the connection limit was written")
+ }
+ _ = held.Close()
+ deadline = time.Now().Add(2 * time.Second)
+ for {
+ if _, err := h.client.Send(lines(t, 1)); err == nil {
+ break
+ } else if time.Now().After(deadline) {
+ t.Fatalf("Send still failing after the slot freed: %v", err)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func TestConcurrentSendersEachLandWhole(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.RateBytesPerSecond = -1; s.MaxConnsPerUID = 64 })
+ const senders, per = 16, 40
+ var wg sync.WaitGroup
+ errs := make(chan error, senders)
+ for i := 0; i < senders; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ if _, err := h.client.Send(lines(t, per)); err != nil {
+ errs <- err
+ }
+ }()
+ }
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ t.Error(err)
+ }
+ if h.rec.count() != senders*per {
+ t.Fatalf("wrote %d, want %d", h.rec.count(), senders*per)
+ }
+ for _, line := range h.rec.lines {
+ _ = decode(t, line)
+ }
+}
+
+func TestCloseStopsServeAndRemovesTheSocket(t *testing.T) {
+ h := startServer(t, nil)
+ if err := h.server.Close(); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case err := <-h.done:
+ if !errors.Is(err, ErrServerClosed) {
+ t.Fatalf("Serve returned %v", err)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("Serve did not return after Close")
+ }
+ if _, err := os.Lstat(h.path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("socket still present after Close: %v", err)
+ }
+ if _, err := h.client.Send(lines(t, 1)); !errors.Is(err, ErrNoSocket) {
+ t.Fatalf("Send after Close = %v, want ErrNoSocket", err)
+ }
+}
+
+func TestServeRequiresAppend(t *testing.T) {
+ l, err := Listen(filepath.Join(shortTempDir(t), "run", "s.sock"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ if err := (&Server{}).Serve(l); err == nil {
+ t.Fatal("Serve ran without Append")
+ }
+}
+
+func TestClientRefusesALineWithAnEmbeddedNewline(t *testing.T) {
+ h := startServer(t, nil)
+ _, err := h.client.Send([][]byte{[]byte("{\"a\":1}\n{\"b\":2}")})
+ if err == nil || errors.Is(err, ErrNoSocket) {
+ t.Fatalf("err = %v, want a refusal before sending", err)
+ }
+ if h.rec.count() != 0 {
+ t.Fatal("wrote a line")
+ }
+}
+
+func TestClientWithoutASocket(t *testing.T) {
+ c := Client{SocketPath: filepath.Join(shortTempDir(t), "missing.sock"), TrustedOwner: os.Geteuid()}
+ if err := c.Available(); !errors.Is(err, ErrNoSocket) {
+ t.Fatalf("Available = %v, want ErrNoSocket", err)
+ }
+ if _, err := c.Send(lines(t, 1)); !errors.Is(err, ErrNoSocket) {
+ t.Fatalf("Send = %v, want ErrNoSocket", err)
+ }
+}
+
+func TestClientRefusesUntrustedSockets(t *testing.T) {
+ t.Run("not a socket", func(t *testing.T) {
+ dir := shortTempDir(t)
+ path := filepath.Join(dir, "ingest.sock")
+ if err := os.WriteFile(path, nil, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ c := Client{SocketPath: path, TrustedOwner: os.Geteuid()}
+ if _, err := c.Send(lines(t, 1)); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("err = %v", err)
+ }
+ })
+ t.Run("owned by another account", func(t *testing.T) {
+ h := startServer(t, nil)
+ c := h.client
+ c.TrustedOwner = os.Geteuid() + 1
+ if _, err := c.Send(lines(t, 1)); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("err = %v", err)
+ }
+ if h.rec.count() != 0 {
+ t.Fatal("sent to an untrusted socket")
+ }
+ })
+ t.Run("directory writable by others", func(t *testing.T) {
+ h := startServer(t, nil)
+ if err := os.Chmod(filepath.Dir(h.path), 0o777); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.client.Available(); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("Available = %v", err)
+ }
+ if _, err := h.client.Send(lines(t, 1)); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("err = %v", err)
+ }
+ })
+ t.Run("ancestor writable by others without the sticky bit", func(t *testing.T) {
+ h := startServer(t, nil)
+ ancestor := filepath.Dir(filepath.Dir(h.path))
+ if err := os.Chmod(ancestor, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.client.Available(); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("Available = %v", err)
+ }
+ if err := os.Chmod(ancestor, 0o777|os.ModeSticky); err != nil {
+ t.Fatal(err)
+ }
+ if err := h.client.Available(); err != nil {
+ t.Fatalf("a sticky ancestor (like /tmp) should be trusted: %v", err)
+ }
+ })
+ t.Run("ancestor writable by an ordinary group", func(t *testing.T) {
+ h := startServer(t, nil)
+ ancestor := filepath.Dir(filepath.Dir(h.path))
+ if err := os.Chmod(ancestor, 0o775); err != nil {
+ t.Fatal(err)
+ }
+ gid := os.Getegid()
+ if systemGroups[gid] {
+ // Running as root's group: stand in an ordinary group by distrusting it here.
+ prev := systemGroups
+ systemGroups = map[int]bool{}
+ t.Cleanup(func() { systemGroups = prev })
+ }
+ if err := h.client.Available(); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("Available = %v, want a group-writable ancestor refused", err)
+ }
+ })
+ t.Run("ancestor writable by a system group, as /private/var/run is on macOS", func(t *testing.T) {
+ h := startServer(t, nil)
+ ancestor := filepath.Dir(filepath.Dir(h.path))
+ if err := os.Chmod(ancestor, 0o775); err != nil {
+ t.Fatal(err)
+ }
+ prev := systemGroups
+ systemGroups = map[int]bool{os.Getegid(): true}
+ t.Cleanup(func() { systemGroups = prev })
+ if err := h.client.Available(); err != nil {
+ t.Fatalf("Available = %v, want a system group's write trusted", err)
+ }
+ })
+ t.Run("symlink in place of the socket", func(t *testing.T) {
+ h := startServer(t, nil)
+ link := filepath.Join(filepath.Dir(h.path), "link.sock")
+ if err := os.Symlink(h.path, link); err != nil {
+ t.Fatal(err)
+ }
+ c := h.client
+ c.SocketPath = link
+ if err := c.Available(); !errors.Is(err, ErrUntrustedSocket) {
+ t.Fatalf("Available = %v, want a link refused", err)
+ }
+ })
+}
+
+func TestListenSetsModesWhateverTheUmask(t *testing.T) {
+ old := syscall.Umask(0o077)
+ defer syscall.Umask(old)
+ dir := filepath.Join(shortTempDir(t), "run")
+ path := filepath.Join(dir, "ingest.sock")
+ l, err := Listen(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ info, err := os.Stat(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode().Perm() != SocketDirMode {
+ t.Fatalf("dir mode = %v, want %v", info.Mode().Perm(), SocketDirMode)
+ }
+ info, err = os.Lstat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if info.Mode()&os.ModeSocket == 0 || info.Mode().Perm() != SocketMode {
+ t.Fatalf("socket mode = %v, want a socket with %v", info.Mode(), SocketMode)
+ }
+}
+
+func TestListenNarrowsAnExistingDirectory(t *testing.T) {
+ dir := filepath.Join(shortTempDir(t), "run")
+ if err := os.Mkdir(dir, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(dir, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ l, err := Listen(filepath.Join(dir, "ingest.sock"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer l.Close()
+ if info, _ := os.Stat(dir); info.Mode().Perm() != SocketDirMode {
+ t.Fatalf("dir mode = %v", info.Mode().Perm())
+ }
+}
+
+func TestListenReplacesAStaleSocketOnly(t *testing.T) {
+ dir := filepath.Join(shortTempDir(t), "run")
+ path := filepath.Join(dir, "ingest.sock")
+
+ stale, err := Listen(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stale.SetUnlinkOnClose(false)
+ _ = stale.Close()
+ if _, err := os.Lstat(path); err != nil {
+ t.Fatalf("fixture: stale socket missing: %v", err)
+ }
+ live, err := Listen(path)
+ if err != nil {
+ t.Fatalf("Listen over a stale socket: %v", err)
+ }
+ defer live.Close()
+ go func() {
+ for {
+ c, err := live.Accept()
+ if err != nil {
+ return
+ }
+ _ = c.Close()
+ }
+ }()
+ if _, err := Listen(path); err == nil || !strings.Contains(err.Error(), "already listening") {
+ t.Fatalf("Listen over a live socket = %v, want a refusal", err)
+ }
+}
+
+func TestListenRefusesToRemoveANonSocket(t *testing.T) {
+ dir := filepath.Join(shortTempDir(t), "run")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ path := filepath.Join(dir, "ingest.sock")
+ if err := os.WriteFile(path, []byte("keep me"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := Listen(path); err == nil {
+ t.Fatal("Listen replaced a regular file")
+ }
+ if data, _ := os.ReadFile(path); string(data) != "keep me" {
+ t.Fatal("the file was changed")
+ }
+}
+
+func TestPeerCredentialsAreSupportedHere(t *testing.T) {
+ if !peerCredentialsSupported {
+ t.Fatalf("peer credentials unsupported on %s", runtime.GOOS)
+ }
+}
+
+func openConns(s *Server) int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.conns)
+}
+
+func TestServerRefusesABatchForAnotherLog(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.LogPath = "/var/log/beacon-agent/runtime.jsonl" })
+ c := h.client
+ c.LogPath = "/tmp/some-test/runtime.jsonl"
+ resp, err := c.Send(lines(t, 3))
+ if !errors.Is(err, ErrLogMismatch) {
+ t.Fatalf("Send = %+v, %v; want ErrLogMismatch", resp, err)
+ }
+ if resp.Processed != 0 || h.rec.count() != 0 {
+ t.Fatalf("a batch for another log was written: %+v", resp)
+ }
+ c.LogPath = "/var/log/beacon-agent/../beacon-agent/runtime.jsonl"
+ if resp, err := c.Send(lines(t, 1)); err != nil || resp.Accepted != 1 {
+ t.Fatalf("Send for the same log, spelled differently = %+v, %v", resp, err)
+ }
+}
+
+func TestServerWithALogPathRefusesAHeaderWithoutOne(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.LogPath = "/var/log/beacon-agent/runtime.jsonl" })
+ resp, err := h.client.Send(lines(t, 1))
+ if !errors.Is(err, ErrLogMismatch) || h.rec.count() != 0 {
+ t.Fatalf("Send = %+v, %v", resp, err)
+ }
+}
+
+func TestServerRefusesAMalformedHeader(t *testing.T) {
+ h := startServer(t, nil)
+ for _, header := range []string{"not json", strings.Repeat("x", maxHeaderBytes+10)} {
+ resp, err := rawExchange(t, h.path, Preamble+"\n"+header+"\n"+string(lines(t, 1)[0])+"\n")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.Error == "" || resp.Processed != 0 {
+ t.Fatalf("header %.20q: resp = %+v", header, resp)
+ }
+ }
+ if h.rec.count() != 0 {
+ t.Fatal("an event behind a malformed header was written")
+ }
+}
+
+// The real default path must pass the trust walk wherever the platform's own directories sit, or
+// restricted mode records nothing there. Only the ancestors are checked: the socket itself exists
+// only on an installed endpoint.
+func TestDefaultSocketDirectoryAncestorsAreTrusted(t *testing.T) {
+ dir, err := filepath.EvalSymlinks(filepath.Dir(filepath.Dir(DefaultSocketPath)))
+ if err != nil {
+ t.Skipf("no %s here: %v", filepath.Dir(filepath.Dir(DefaultSocketPath)), err)
+ }
+ for {
+ info, err := os.Lstat(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ uid, _ := fileOwner(info)
+ if uid != 0 || !ancestorWriteSafe(info) {
+ t.Fatalf("%s (%v, uid %d) would make the client refuse %s", dir, info.Mode(), uid, DefaultSocketPath)
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ return
+ }
+ dir = parent
+ }
+}
+
+func TestOneAccountCannotHoldEveryConnection(t *testing.T) {
+ h := startServer(t, func(s *Server) { s.MaxConnsPerUID = 2 })
+ var held []net.Conn
+ for i := 0; i < 2; i++ {
+ c, err := net.Dial("unix", h.path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ held = append(held, c)
+ }
+ deadline := time.Now().Add(2 * time.Second)
+ for openConns(h.server) < 2 && time.Now().Before(deadline) {
+ time.Sleep(5 * time.Millisecond)
+ }
+ // Wait for both to be counted against the account.
+ for time.Now().Before(deadline) {
+ h.server.mu.Lock()
+ n := h.server.perUID[uint32(os.Geteuid())]
+ h.server.mu.Unlock()
+ if n == 2 {
+ break
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ if _, err := h.client.Send(lines(t, 1)); err == nil {
+ t.Fatal("a third connection from the same account was served")
+ }
+ for _, c := range held {
+ _ = c.Close()
+ }
+ deadline = time.Now().Add(2 * time.Second)
+ for {
+ if _, err := h.client.Send(lines(t, 1)); err == nil {
+ break
+ } else if time.Now().After(deadline) {
+ t.Fatalf("still refused after the account's connections closed: %v", err)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+func TestABusyServerReportsHowFarItGotBeforeTheClientGivesUp(t *testing.T) {
+ h := startServer(t, func(s *Server) {
+ s.ConnTimeout = 200 * time.Millisecond
+ s.RateBytesPerSecond = -1
+ })
+ h.rec.setFail(func(int, []byte) error {
+ time.Sleep(80 * time.Millisecond) // a slow log: lock contention, a slow disk
+ return nil
+ })
+ c := h.client
+ c.Timeout = 3 * time.Second
+ resp, err := c.Send(lines(t, 10))
+ if err == nil || resp.Error != "busy" {
+ t.Fatalf("Send = %+v, %v; want the server to stop and report", resp, err)
+ }
+ if resp.Processed == 0 || resp.Processed >= 10 || resp.Processed != h.rec.count() {
+ t.Fatalf("processed %d, wrote %d; the reply must match what was written", resp.Processed, h.rec.count())
+ }
+}
+
+func TestRemoveStale(t *testing.T) {
+ dir := filepath.Join(shortTempDir(t), "run")
+ sock := filepath.Join(dir, "ingest.sock")
+ stale, err := Listen(sock)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stale.SetUnlinkOnClose(false)
+ _ = stale.Close()
+ if err := RemoveStale(sock); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(sock); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("a stale socket was left")
+ }
+ h := startServer(t, nil)
+ if err := RemoveStale(h.path); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(h.path); err != nil {
+ t.Fatal("a live socket was removed")
+ }
+ file := filepath.Join(dir, "not-a-socket")
+ _ = os.WriteFile(file, nil, 0o600)
+ if err := RemoveStale(file); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Lstat(file); err != nil {
+ t.Fatal("a regular file was removed")
+ }
+ if err := RemoveStale(filepath.Join(dir, "absent")); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/pkg/asymptoteobserve/localingest/spool.go b/pkg/asymptoteobserve/localingest/spool.go
new file mode 100644
index 00000000..22d7c38d
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/spool.go
@@ -0,0 +1,256 @@
+package localingest
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
+)
+
+const (
+ // DefaultSpoolMaxBytes caps a spool. Events past it are dropped and counted, so a collector
+ // that stays down cannot fill the user's disk.
+ DefaultSpoolMaxBytes int64 = 8 * 1024 * 1024
+ defaultSpoolLockWait = 250 * time.Millisecond
+
+ spoolFileName = "pending.jsonl"
+ spoolLockName = "pending.lock"
+ // spoolDrainLockName is held for a whole drain, so two writers never send the same events.
+ spoolDrainLockName = "drain.lock"
+
+ // SpoolDirMode and SpoolFileMode keep a spool private: it holds the same content as the log.
+ SpoolDirMode os.FileMode = 0o700
+ SpoolFileMode os.FileMode = 0o600
+)
+
+// Spool holds events a writer could not hand to the collector, in a directory only the writer's
+// own account can read, until a later writer drains them. It is the restricted mode's answer to a
+// collector that is stopped or restarting: the event is late rather than lost, and the agent is
+// never held up waiting.
+type Spool struct {
+ Dir string
+ // MaxBytes caps the spool; zero means DefaultSpoolMaxBytes.
+ MaxBytes int64
+ // LockWait bounds how long Append waits for another writer's lock; zero means 250ms.
+ LockWait time.Duration
+}
+
+func (s Spool) maxBytes() int64 {
+ if s.MaxBytes <= 0 {
+ return DefaultSpoolMaxBytes
+ }
+ return s.MaxBytes
+}
+
+func (s Spool) filePath() string { return filepath.Join(s.Dir, spoolFileName) }
+
+func (s Spool) openLock() (*os.File, error) { return s.openNamedLock(spoolLockName) }
+
+func (s Spool) openNamedLock(name string) (*os.File, error) {
+ if s.Dir == "" {
+ return nil, errors.New("localingest: spool directory is not set")
+ }
+ if err := os.MkdirAll(s.Dir, SpoolDirMode); err != nil {
+ return nil, err
+ }
+ // MkdirAll leaves an existing directory's mode alone and is masked by the umask.
+ _ = os.Chmod(s.Dir, SpoolDirMode)
+ return os.OpenFile(filepath.Join(s.Dir, name), os.O_CREATE|os.O_RDWR, SpoolFileMode)
+}
+
+// Append adds lines to the spool and returns how many were dropped because the spool is full or
+// a line could never be sent. On an error, assume none were spooled.
+func (s Spool) Append(lines [][]byte) (dropped int, err error) {
+ if len(lines) == 0 {
+ return 0, nil
+ }
+ err = s.withLock(func() error {
+ f, err := os.OpenFile(s.filePath(), os.O_APPEND|os.O_CREATE|os.O_WRONLY, SpoolFileMode)
+ if err != nil {
+ return err
+ }
+ defer f.Close()
+ info, err := f.Stat()
+ if err != nil {
+ return err
+ }
+ _ = f.Chmod(SpoolFileMode)
+ size := info.Size()
+ var buf bytes.Buffer
+ for _, line := range lines {
+ line = bytes.TrimSuffix(line, []byte{'\n'})
+ if len(line) == 0 || bytes.IndexByte(line, '\n') >= 0 || len(line) > MaxLineBytes {
+ dropped++
+ continue
+ }
+ if size+int64(buf.Len()+len(line)+1) > s.maxBytes() {
+ dropped++
+ continue
+ }
+ buf.Write(line)
+ buf.WriteByte('\n')
+ }
+ if buf.Len() == 0 {
+ return nil
+ }
+ _, err = f.Write(buf.Bytes())
+ return err
+ })
+ if err != nil {
+ return len(lines), err
+ }
+ return dropped, nil
+}
+
+// Drain sends up to maxLines of the oldest spooled events through send and removes the ones send
+// reports processed. send returns how many lines, from the start, it handled for good (written or
+// rejected), and an error if it stopped short.
+//
+// Only one writer drains at a time; another that finds a drain under way skips it and returns zero,
+// so concurrent hooks never wait on each other here. The spool itself is locked only to read the
+// batch and to remove what was sent, not while sending, so a hook spooling an event meanwhile is
+// not held up by a slow collector: appends only ever add to the end, and only the drainer removes
+// from the start.
+func (s Spool) Drain(maxLines int, send func(lines [][]byte) (int, error)) (int, error) {
+ if maxLines <= 0 {
+ return 0, nil
+ }
+ if _, err := os.Stat(s.filePath()); errors.Is(err, os.ErrNotExist) {
+ return 0, nil
+ }
+ drainFile, err := s.openNamedLock(spoolDrainLockName)
+ if err != nil {
+ return 0, err
+ }
+ defer drainFile.Close()
+ draining, err := filelock.TryExclusive(drainFile)
+ if err != nil {
+ return 0, nil
+ }
+ defer draining.Release()
+
+ var batch [][]byte
+ if err := s.withLock(func() error {
+ data, err := os.ReadFile(s.filePath())
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return err
+ }
+ batch = splitLines(data)
+ if len(batch) > maxLines {
+ batch = batch[:maxLines]
+ }
+ return nil
+ }); err != nil {
+ return 0, err
+ }
+ if len(batch) == 0 {
+ return 0, nil
+ }
+ processed, sendErr := send(batch)
+ if processed < 0 {
+ processed = 0
+ }
+ if processed > len(batch) {
+ processed = len(batch)
+ }
+ if processed == 0 {
+ return 0, sendErr
+ }
+ if err := s.withLock(func() error {
+ data, err := os.ReadFile(s.filePath())
+ if err != nil {
+ return err
+ }
+ lines := splitLines(data)
+ if processed > len(lines) {
+ processed = len(lines)
+ }
+ return s.rewrite(lines[processed:])
+ }); err != nil {
+ return processed, err
+ }
+ return processed, sendErr
+}
+
+func (s Spool) withLock(fn func() error) error {
+ lockFile, err := s.openLock()
+ if err != nil {
+ return err
+ }
+ defer lockFile.Close()
+ wait := s.LockWait
+ if wait <= 0 {
+ wait = defaultSpoolLockWait
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), wait)
+ defer cancel()
+ held, err := filelock.ExclusiveContext(ctx, lockFile)
+ if err != nil {
+ return fmt.Errorf("lock the spool: %w", err)
+ }
+ defer held.Release()
+ return fn()
+}
+
+// Pending reports how many events are spooled and their size.
+func (s Spool) Pending() (lines int, size int64, err error) {
+ data, err := os.ReadFile(s.filePath())
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return 0, 0, nil
+ }
+ return 0, 0, err
+ }
+ return len(splitLines(data)), int64(len(data)), nil
+}
+
+// rewrite replaces the spool with remaining, through a rename so a crash leaves either the old
+// spool or the new one and never half of each. Called with the lock held.
+func (s Spool) rewrite(remaining [][]byte) error {
+ if len(remaining) == 0 {
+ if err := os.Remove(s.filePath()); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return nil
+ }
+ tmp, err := os.CreateTemp(s.Dir, spoolFileName+".*")
+ if err != nil {
+ return err
+ }
+ tmpName := tmp.Name()
+ defer os.Remove(tmpName)
+ _ = tmp.Chmod(SpoolFileMode)
+ w := bufio.NewWriter(tmp)
+ for _, line := range remaining {
+ _, _ = w.Write(line)
+ _ = w.WriteByte('\n')
+ }
+ if err := w.Flush(); err != nil {
+ _ = tmp.Close()
+ return err
+ }
+ if err := tmp.Close(); err != nil {
+ return err
+ }
+ return os.Rename(tmpName, s.filePath())
+}
+
+func splitLines(data []byte) [][]byte {
+ var out [][]byte
+ for _, line := range bytes.Split(data, []byte{'\n'}) {
+ if len(bytes.TrimSpace(line)) == 0 {
+ continue
+ }
+ out = append(out, line)
+ }
+ return out
+}
diff --git a/pkg/asymptoteobserve/localingest/spool_test.go b/pkg/asymptoteobserve/localingest/spool_test.go
new file mode 100644
index 00000000..736315e3
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/spool_test.go
@@ -0,0 +1,240 @@
+package localingest
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+func spoolLines(prefix string, n int) [][]byte {
+ out := make([][]byte, n)
+ for i := range out {
+ out[i] = []byte(fmt.Sprintf(`{"n":"%s-%d"}`, prefix, i))
+ }
+ return out
+}
+
+func readSpool(t *testing.T, s Spool) []string {
+ t.Helper()
+ data, err := os.ReadFile(s.filePath())
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ var out []string
+ for _, line := range splitLines(data) {
+ out = append(out, string(line))
+ }
+ return out
+}
+
+func acceptAll(sent *[][]byte) func([][]byte) (int, error) {
+ return func(lines [][]byte) (int, error) {
+ for _, l := range lines {
+ *sent = append(*sent, append([]byte(nil), l...))
+ }
+ return len(lines), nil
+ }
+}
+
+func TestSpoolAppendThenDrainEverything(t *testing.T) {
+ s := Spool{Dir: filepath.Join(t.TempDir(), "spool")}
+ if dropped, err := s.Append(spoolLines("a", 3)); err != nil || dropped != 0 {
+ t.Fatalf("Append = %d, %v", dropped, err)
+ }
+ if n, size, err := s.Pending(); err != nil || n != 3 || size == 0 {
+ t.Fatalf("Pending = %d, %d, %v", n, size, err)
+ }
+ var sent [][]byte
+ n, err := s.Drain(100, acceptAll(&sent))
+ if err != nil || n != 3 {
+ t.Fatalf("Drain = %d, %v", n, err)
+ }
+ for i, line := range sent {
+ if string(line) != fmt.Sprintf(`{"n":"a-%d"}`, i) {
+ t.Fatalf("sent[%d] = %s, out of order", i, line)
+ }
+ }
+ if _, err := os.Stat(s.filePath()); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("spool file left behind after a full drain: %v", err)
+ }
+ if n, _, _ := s.Pending(); n != 0 {
+ t.Fatalf("Pending after drain = %d", n)
+ }
+}
+
+func TestSpoolDrainKeepsWhatWasNotProcessed(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ _, _ = s.Append(spoolLines("a", 5))
+ n, err := s.Drain(100, func(lines [][]byte) (int, error) {
+ return 2, errors.New("collector stopped")
+ })
+ if n != 2 || err == nil {
+ t.Fatalf("Drain = %d, %v", n, err)
+ }
+ if got := readSpool(t, s); strings.Join(got, ",") != `{"n":"a-2"},{"n":"a-3"},{"n":"a-4"}` {
+ t.Fatalf("spool = %v", got)
+ }
+}
+
+func TestSpoolDrainThatSendsNothingRemovesNothing(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ _, _ = s.Append(spoolLines("a", 2))
+ n, err := s.Drain(100, func([][]byte) (int, error) { return 0, errors.New("down") })
+ if n != 0 || err == nil {
+ t.Fatalf("Drain = %d, %v", n, err)
+ }
+ if got := readSpool(t, s); len(got) != 2 {
+ t.Fatalf("spool = %v", got)
+ }
+}
+
+func TestSpoolDrainClampsANonsenseCount(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ _, _ = s.Append(spoolLines("a", 2))
+ n, _ := s.Drain(100, func([][]byte) (int, error) { return 99, nil })
+ if n != 2 {
+ t.Fatalf("Drain = %d, want it clamped to the batch", n)
+ }
+ n, _ = s.Drain(100, func([][]byte) (int, error) { return -1, nil })
+ if n != 0 {
+ t.Fatalf("Drain = %d", n)
+ }
+}
+
+func TestSpoolDrainHonorsMaxLines(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ _, _ = s.Append(spoolLines("a", 10))
+ var sent [][]byte
+ n, err := s.Drain(4, acceptAll(&sent))
+ if err != nil || n != 4 || len(sent) != 4 {
+ t.Fatalf("Drain = %d, %v, sent %d", n, err, len(sent))
+ }
+ if got := readSpool(t, s); len(got) != 6 || got[0] != `{"n":"a-4"}` {
+ t.Fatalf("spool = %v", got)
+ }
+ if n, _ := s.Drain(0, acceptAll(&sent)); n != 0 {
+ t.Fatal("Drain(0) sent something")
+ }
+}
+
+func TestSpoolDrainOfNothing(t *testing.T) {
+ s := Spool{Dir: filepath.Join(t.TempDir(), "never-created")}
+ called := false
+ n, err := s.Drain(10, func([][]byte) (int, error) { called = true; return 0, nil })
+ if n != 0 || err != nil || called {
+ t.Fatalf("Drain = %d, %v, called %v", n, err, called)
+ }
+ if _, err := os.Stat(s.Dir); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("Drain created the spool directory")
+ }
+}
+
+func TestSpoolDropsPastItsCap(t *testing.T) {
+ s := Spool{Dir: t.TempDir(), MaxBytes: 30}
+ // Each line is 12 bytes plus a newline: two fit in 30, the third does not.
+ dropped, err := s.Append(spoolLines("x", 3))
+ if err != nil || dropped != 1 {
+ t.Fatalf("Append = %d, %v", dropped, err)
+ }
+ dropped, err = s.Append(spoolLines("y", 1))
+ if err != nil || dropped != 1 {
+ t.Fatalf("Append into a full spool = %d, %v", dropped, err)
+ }
+ if got := readSpool(t, s); len(got) != 2 {
+ t.Fatalf("spool = %v", got)
+ }
+}
+
+func TestSpoolDropsLinesThatCouldNeverBeSent(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ dropped, err := s.Append([][]byte{
+ []byte(""),
+ []byte("{\"a\":1}\n{\"b\":2}"),
+ []byte(strings.Repeat("x", MaxLineBytes+1)),
+ []byte("{\"ok\":1}\n"),
+ })
+ if err != nil || dropped != 3 {
+ t.Fatalf("Append = %d, %v", dropped, err)
+ }
+ if got := readSpool(t, s); len(got) != 1 || got[0] != `{"ok":1}` {
+ t.Fatalf("spool = %v", got)
+ }
+}
+
+func TestSpoolIsPrivate(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("file modes do not decide access on Windows")
+ }
+ parent := t.TempDir()
+ s := Spool{Dir: filepath.Join(parent, "spool")}
+ if err := os.MkdirAll(s.Dir, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Chmod(s.Dir, 0o777); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.Append(spoolLines("a", 2)); err != nil {
+ t.Fatal(err)
+ }
+ if info, _ := os.Stat(s.Dir); info.Mode().Perm() != SpoolDirMode {
+ t.Fatalf("dir mode = %v", info.Mode().Perm())
+ }
+ if info, _ := os.Stat(s.filePath()); info.Mode().Perm() != SpoolFileMode {
+ t.Fatalf("file mode = %v", info.Mode().Perm())
+ }
+ _, _ = s.Drain(1, func([][]byte) (int, error) { return 1, nil })
+ if info, _ := os.Stat(s.filePath()); info.Mode().Perm() != SpoolFileMode {
+ t.Fatalf("rewritten file mode = %v", info.Mode().Perm())
+ }
+}
+
+func TestSpoolAppendIsNotHeldUpByASlowDrain(t *testing.T) {
+ s := Spool{Dir: t.TempDir()}
+ _, _ = s.Append(spoolLines("old", 3))
+ inSend := make(chan struct{})
+ release := make(chan struct{})
+ result := make(chan int, 1)
+ go func() {
+ n, _ := s.Drain(2, func(lines [][]byte) (int, error) {
+ close(inSend)
+ <-release
+ return len(lines), nil
+ })
+ result <- n
+ }()
+ <-inSend
+
+ start := time.Now()
+ if _, err := s.Append(spoolLines("new", 1)); err != nil {
+ t.Fatalf("Append during a drain: %v", err)
+ }
+ if elapsed := time.Since(start); elapsed > 200*time.Millisecond {
+ t.Fatalf("Append waited %v on a drain that was sending", elapsed)
+ }
+ // A second drain finds one under way and steps aside.
+ if n, err := s.Drain(10, func([][]byte) (int, error) { t.Error("a second drain sent"); return 0, nil }); n != 0 || err != nil {
+ t.Fatalf("concurrent Drain = %d, %v", n, err)
+ }
+ close(release)
+ if n := <-result; n != 2 {
+ t.Fatalf("Drain = %d", n)
+ }
+ got := strings.Join(readSpool(t, s), ",")
+ if got != `{"n":"old-2"},{"n":"new-0"}` {
+ t.Fatalf("spool = %s; the event appended mid-drain must survive and the sent ones must go", got)
+ }
+}
+
+func TestSpoolWithoutADirectory(t *testing.T) {
+ if _, err := (Spool{}).Append(spoolLines("a", 1)); err == nil {
+ t.Fatal("Append with no directory succeeded")
+ }
+}
diff --git a/pkg/asymptoteobserve/localingest/trust_other.go b/pkg/asymptoteobserve/localingest/trust_other.go
new file mode 100644
index 00000000..22a42c1b
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/trust_other.go
@@ -0,0 +1,18 @@
+//go:build !unix
+
+package localingest
+
+import (
+ "errors"
+ "net"
+)
+
+// checkSocket always reports no socket off Unix: the restricted log access mode is not available
+// there, so writers keep appending to the log as before.
+func checkSocket(string, int) error { return ErrNoSocket }
+
+// RemoveStale has nothing to remove off Unix.
+func RemoveStale(string) error { return nil }
+
+// Listen is unsupported off Unix.
+func Listen(string) (*net.UnixListener, error) { return nil, errors.ErrUnsupported }
diff --git a/pkg/asymptoteobserve/localingest/trust_unix.go b/pkg/asymptoteobserve/localingest/trust_unix.go
new file mode 100644
index 00000000..d2a0745b
--- /dev/null
+++ b/pkg/asymptoteobserve/localingest/trust_unix.go
@@ -0,0 +1,190 @@
+//go:build unix
+
+package localingest
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "syscall"
+ "time"
+)
+
+// SocketDirMode is the mode of the directory the socket lives in: root may create entries, nobody
+// else may.
+const SocketDirMode os.FileMode = 0o755
+
+// SocketMode lets every account connect. Connecting to a Unix socket needs write permission on it;
+// what a connection may do is decided by the server, from the peer's kernel credentials.
+const SocketMode os.FileMode = 0o666
+
+// checkSocket decides whether a writer may send to path. The socket must be owned by owner, and so
+// must its directory, which nobody else may write; every directory above it must belong to root or
+// owner and be writable by nobody else unless it is sticky (as /tmp is), so the directory holding
+// the socket cannot be swapped for another.
+func checkSocket(path string, owner int) error {
+ info, err := os.Lstat(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return ErrNoSocket
+ }
+ return fmt.Errorf("%w: %v", ErrUntrustedSocket, err)
+ }
+ if info.Mode()&os.ModeSocket == 0 {
+ return fmt.Errorf("%w: %s is not a socket", ErrUntrustedSocket, path)
+ }
+ if uid, ok := fileOwner(info); !ok || uid != owner {
+ return fmt.Errorf("%w: %s is not owned by uid %d", ErrUntrustedSocket, path, owner)
+ }
+ dir, err := filepath.EvalSymlinks(filepath.Dir(path))
+ if err != nil {
+ return fmt.Errorf("%w: %v", ErrUntrustedSocket, err)
+ }
+ for first := true; ; first = false {
+ info, err := os.Lstat(dir)
+ if err != nil {
+ return fmt.Errorf("%w: %v", ErrUntrustedSocket, err)
+ }
+ if !info.IsDir() {
+ return fmt.Errorf("%w: %s is not a directory", ErrUntrustedSocket, dir)
+ }
+ uid, ok := fileOwner(info)
+ if !ok {
+ return fmt.Errorf("%w: cannot read the owner of %s", ErrUntrustedSocket, dir)
+ }
+ writableByOthers := info.Mode().Perm()&0o022 != 0
+ if first {
+ if uid != owner || writableByOthers {
+ return fmt.Errorf("%w: %s must be owned by uid %d and writable by nobody else", ErrUntrustedSocket, dir, owner)
+ }
+ } else if (uid != 0 && uid != owner) || !ancestorWriteSafe(info) {
+ return fmt.Errorf("%w: %s is writable by other accounts", ErrUntrustedSocket, dir)
+ }
+ parent := filepath.Dir(dir)
+ if parent == dir {
+ return nil
+ }
+ dir = parent
+ }
+}
+
+// ancestorWriteSafe reports whether a directory above the socket's own is closed to ordinary
+// accounts. Writable by others is safe only with the sticky bit (as /tmp is), which stops them
+// renaming or removing what root put there. Writable by its group is safe when that group is a
+// system group no person is in: macOS ships /private/var/run, where /var/run points, as
+// root:daemon 0775, so refusing every group-writable ancestor would refuse the default socket path
+// on every Mac.
+func ancestorWriteSafe(info os.FileInfo) bool {
+ perm := info.Mode().Perm()
+ if perm&0o002 != 0 && info.Mode()&os.ModeSticky == 0 {
+ return false
+ }
+ if perm&0o020 != 0 && info.Mode()&os.ModeSticky == 0 {
+ gid, ok := fileGroup(info)
+ if !ok || !systemGroups[gid] {
+ return false
+ }
+ }
+ return true
+}
+
+// systemGroups are the groups trusted to write an ancestor of the socket directory: root's own
+// (root on Linux, wheel on macOS) and daemon, which owns /private/var/run on macOS. Neither has
+// people in it on a managed machine; admins on macOS are in admin (80), which is not trusted.
+var systemGroups = map[int]bool{0: true, 1: true}
+
+func fileGroup(info os.FileInfo) (int, bool) {
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, false
+ }
+ return int(stat.Gid), true
+}
+
+func fileOwner(info os.FileInfo) (int, bool) {
+ stat, ok := info.Sys().(*syscall.Stat_t)
+ if !ok {
+ return 0, false
+ }
+ return int(stat.Uid), true
+}
+
+// RemoveStale removes a socket at path that nothing answers on: one a collector left behind when it
+// was killed. It leaves a live socket, and anything that is not a socket, alone.
+func RemoveStale(path string) error {
+ if path == "" {
+ path = DefaultSocketPath
+ }
+ info, err := os.Lstat(path)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ return err
+ }
+ if info.Mode()&os.ModeSocket == 0 {
+ return nil
+ }
+ if conn, err := net.DialTimeout("unix", path, 500*time.Millisecond); err == nil {
+ _ = conn.Close()
+ return nil
+ }
+ if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return nil
+}
+
+// Listen creates the socket at path for a Server to serve, replacing a stale one a previous
+// collector left behind, and makes it connectable by every account. The directory is created if it
+// is missing and must end up owned by this process and writable by nobody else; a non-socket at
+// path, or a socket another server still answers on, is refused rather than removed.
+func Listen(path string) (*net.UnixListener, error) {
+ if path == "" {
+ path = DefaultSocketPath
+ }
+ dir := filepath.Dir(path)
+ if err := os.MkdirAll(dir, SocketDirMode); err != nil {
+ return nil, fmt.Errorf("create %s: %w", dir, err)
+ }
+ info, err := os.Lstat(dir)
+ if err != nil {
+ return nil, err
+ }
+ if !info.IsDir() {
+ return nil, fmt.Errorf("%s is not a directory", dir)
+ }
+ if uid, ok := fileOwner(info); !ok || uid != os.Geteuid() {
+ return nil, fmt.Errorf("%s is not owned by this process (uid %d)", dir, os.Geteuid())
+ }
+ // MkdirAll's mode is masked by the umask, and an existing directory keeps whatever it had.
+ if err := os.Chmod(dir, SocketDirMode); err != nil {
+ return nil, fmt.Errorf("set the mode of %s: %w", dir, err)
+ }
+ if existing, err := os.Lstat(path); err == nil {
+ if existing.Mode()&os.ModeSocket == 0 {
+ return nil, fmt.Errorf("%s exists and is not a socket", path)
+ }
+ if conn, err := net.DialTimeout("unix", path, 500*time.Millisecond); err == nil {
+ _ = conn.Close()
+ return nil, fmt.Errorf("another collector is already listening on %s", path)
+ }
+ if err := os.Remove(path); err != nil {
+ return nil, fmt.Errorf("remove the stale socket %s: %w", path, err)
+ }
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ l, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
+ if err != nil {
+ return nil, err
+ }
+ l.SetUnlinkOnClose(true)
+ if err := os.Chmod(path, SocketMode); err != nil {
+ _ = l.Close()
+ return nil, fmt.Errorf("set the mode of %s: %w", path, err)
+ }
+ return l, nil
+}