Skip to content

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

Attribute OTLP exports to their sender on macOS and Windows

Claudeb77cc18da4d0
diff --git a/CLAUDE.md b/CLAUDE.md
index cdb2eea6..88d7ca1f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -28,7 +28,7 @@ Do not recreate or depend on removed `asymptote` mirror trees. Keep new work foc
- Beacon is visibility-first endpoint telemetry for local AI agent runtimes, not a hosted policy service or general endpoint protection product.
- Preserve the local-only default. The public Beacon build must not require a hosted account, remote policy fetch, hosted dashboard, or external network dependency during normal hook execution, and hooks themselves never touch the network.
- `beacon login` is the account-identity channel for interactive users and is required by the interactive `beacon endpoint install` wizard. It uses browser PKCE against beacon.sh and stores the scoped CLI token only in `~/.beacon/auth/session.json` (0600 under a 0700 directory). Signing in alone never starts forwarding. User-mode `beacon endpoint connect` may send that token once to `POST /api/cli/enroll/account` to authorize minting a separate device ingest key, and `beacon mcp token create` may send it to `POST /api/cli/mcp/tokens` (scope `mcp:token:create`, listed on the sign-in page) to mint a personal MCP token that is printed once to stdout and never written to a file, and `beacon share` may send it (scope `traces:write`, also on the sign-in page) to `PUT /v1/traces/{external_id}`, `POST /v1/traces/{external_id}/events/batch` and `GET /v1/traces/{external_id}` on the Beacon API host (`https://api.beacon.sh` for a beacon.sh sign-in, other hosts unchanged, `BEACON_API_URL` overrides) to upload a shared trace the person chose to publish, as a `beacon.trace.v1` summary and its events (`cli/beacon/internal/account/share.go`; a `bcn_api_` API key from `--key` or `BEACON_API_KEY` may stand in for it, precedence `--key`, then a current sign-in carrying the scope, then the environment). These are explicit, user-initiated requests with redirects refused. Hooks, plugins and background jobs never make them, with one exception: the git pre-push hook, only when the person opted in with `beacon git setup --share-sessions` (public needs confirmation), may make the three share requests during a push the person started, within the hook's budget and never failing the push. Never copy the account token into endpoint config, Vector, hook environments, logs, or command output. System/root/package/MDM/CI/piped-stdin/dry-run installs stay noninteractive and account-free.
-- System log access (`beacon endpoint install|repair --system --log-access shared|restricted`; docs in `docs/cli/endpoint-install.mdx#restricted-log-access`). Shared, the default, is the system log as it always was: hooks append to `/var/log/beacon-agent/runtime.jsonl` directly, so it is `0666`. Restricted is opt-in and makes the root collector the only writer: its `beacon_ingest` extension (`collector-builder/exporter/beaconjsonexporter/beaconingestextension`, appending through the exporter's own `internal/runtimelog`) serves `/var/run/beacon-agent/ingest.sock`, and the hook adapter and the CLI writer, as any account but root writing the system log, hand finished lines to it through `pkg/asymptoteobserve/localingest` (`Deliverer`). The protocol is one batch per connection (`BEACON-INGEST/1`, a header naming the log, one event per line, one JSON reply saying how far it got); the server refuses a batch for any log but its own, identifies the sender only by kernel peer credentials (`SO_PEERCRED`, `LOCAL_PEERCRED`), overwrites the event's `user` with that uid and its resolved name and always derives `event.id` itself (`StampLine` re-encodes, so a sender cannot split or forge lines or reuse another event's id), and bounds connections overall and per uid, batch size, each account's bytes per second, and its own time per connection (shorter than the client's, so it reports how far it got instead of being resent). The client sends only to a socket that root owns in a directory nobody else can write (group-writable ancestors only for gid 0/1, which macOS's `/private/var/run` needs). `Deliverer.Write` sends through the socket when it answers and otherwise appends directly as before; only a direct append refused for permission (a restricted log whose collector is down) spools the line, to the account's private spool for that log (`~/.beacon/endpoint/spool/<log digest>`, 0600 under 0700), and the next line that gets through either way drains it. Root writers and per-user logs always write directly. The mode is `config.json` `log_access`, carried through repair and package upgrades (`BEACON_LOG_ACCESS` in the install scripts); install creates the `beacon-log` group (`internal/endpoint/loggroup`, getent/groupadd, dscl/dseditgroup) and `writer.RestrictSystemLog` makes the directory `root:beacon-log 02750`, the log and archives `0640` and the lock root-only `0600`, after writing the root-owned `.beacon-log-access` marker beside the log; a shared log is not narrowed in place but copied to fresh root-created files and renamed over, under its lock (bounded wait), because a descriptor opened while it was 0666 survives any chmod. A failed install restores the previous mode in its rollback, and a shared install removes a dead socket. The marker is what tells every root writer (`asymptoteobserve.RuntimeLogModes`) to keep the restricted modes. The OTLP receivers on loopback are not covered by the socket: any local process can still send OTLP. On Linux those events are attributed to the account that owns the sending socket (peer attribution, below), which names the sender but does not stop an account sending what it likes under its own name; elsewhere they are unattributed, so never claim more than that. Doctor's `runtime_log_access` covers the marker, the socket and pending spool. Unix sockets are local IPC, not a network channel, so the hooks-never-touch-the-network rule holds. On Windows the same mode runs over the named pipe `\\.\pipe\beacon-agent-ingest` (`localingest` `transport_windows.go`, go-winio): the collector creates it as the first instance, and when the name is taken (any account may create one) it reports a recoverable error and retries every few seconds rather than failing, so the rest of the collector stays up; it rejects remote clients and its DACL denies NETWORK and withholds `FILE_CREATE_PIPE_INSTANCE` from ordinary accounts, so it is not a network channel either; a client connects at identification level and sends only to a pipe owned by SYSTEM or Administrators; the server counts a connection against its account from the client process's token before reading and stamps the SID it reads by `ImpersonateNamedPipeClient` after the preamble (they must agree), with `Peer.UID` a string (decimal uid on Unix, SID on Windows) and the name from `LookupAccountSid`, bounded. Privileged writers there are SYSTEM and tokens with Administrators enabled (`CheckTokenMembership`; elevation for another group is not enough). The directory gets `sysacl.RestrictedLogDirDACL` (protected: SYSTEM and Administrators full, `beacon-log` local group read, nothing else; the lock SYSTEM and Administrators only) and everything below it is reset, because every account may bypass traverse checking; `writer.RestrictSystemLog` replaces every file directly in the directory (the log family under the lock; files outside it with another hard link are skipped) with a copy created with its final owner and DACL (`sysacl.CreateRestrictedFile`) and a POSIX-semantics rename, fails naming any file held open without sharing delete and then puts a log that was shared back to shared, and writes the marker last (on Windows it decides nothing for root writers, so a failed or killed run is not mistaken for a finished one). The marker counts there when SYSTEM or Administrators own it and no other account can write it. `loggroup` creates the local group with `net.exe` and looks it up qualified with the computer name. Doctor reads the restricted ACL (`writer.CheckRestrictedSystemLogACL`). `packaging/windows/smoke-restricted-log.ps1` runs in `windows-package-smoke` against the installed MSI with a real ordinary account. Hook and writer tests point `logging.EndpointIngest`/`writer.Ingest` at sockets of their own.
+- System log access (`beacon endpoint install|repair --system --log-access shared|restricted`; docs in `docs/cli/endpoint-install.mdx#restricted-log-access`). Shared, the default, is the system log as it always was: hooks append to `/var/log/beacon-agent/runtime.jsonl` directly, so it is `0666`. Restricted is opt-in and makes the root collector the only writer: its `beacon_ingest` extension (`collector-builder/exporter/beaconjsonexporter/beaconingestextension`, appending through the exporter's own `internal/runtimelog`) serves `/var/run/beacon-agent/ingest.sock`, and the hook adapter and the CLI writer, as any account but root writing the system log, hand finished lines to it through `pkg/asymptoteobserve/localingest` (`Deliverer`). The protocol is one batch per connection (`BEACON-INGEST/1`, a header naming the log, one event per line, one JSON reply saying how far it got); the server refuses a batch for any log but its own, identifies the sender only by kernel peer credentials (`SO_PEERCRED`, `LOCAL_PEERCRED`), overwrites the event's `user` with that uid and its resolved name and always derives `event.id` itself (`StampLine` re-encodes, so a sender cannot split or forge lines or reuse another event's id), and bounds connections overall and per uid, batch size, each account's bytes per second, and its own time per connection (shorter than the client's, so it reports how far it got instead of being resent). The client sends only to a socket that root owns in a directory nobody else can write (group-writable ancestors only for gid 0/1, which macOS's `/private/var/run` needs). `Deliverer.Write` sends through the socket when it answers and otherwise appends directly as before; only a direct append refused for permission (a restricted log whose collector is down) spools the line, to the account's private spool for that log (`~/.beacon/endpoint/spool/<log digest>`, 0600 under 0700), and the next line that gets through either way drains it. Root writers and per-user logs always write directly. The mode is `config.json` `log_access`, carried through repair and package upgrades (`BEACON_LOG_ACCESS` in the install scripts); install creates the `beacon-log` group (`internal/endpoint/loggroup`, getent/groupadd, dscl/dseditgroup) and `writer.RestrictSystemLog` makes the directory `root:beacon-log 02750`, the log and archives `0640` and the lock root-only `0600`, after writing the root-owned `.beacon-log-access` marker beside the log; a shared log is not narrowed in place but copied to fresh root-created files and renamed over, under its lock (bounded wait), because a descriptor opened while it was 0666 survives any chmod. A failed install restores the previous mode in its rollback, and a shared install removes a dead socket. The marker is what tells every root writer (`asymptoteobserve.RuntimeLogModes`) to keep the restricted modes. The OTLP receivers on loopback are not covered by the socket: any local process can still send OTLP. On Linux, macOS and Windows those events are attributed to the account that owns the sending socket (peer attribution, below), which names the sender but does not stop an account sending what it likes under its own name, so never claim more than that. Doctor's `runtime_log_access` covers the marker, the socket and pending spool. Unix sockets are local IPC, not a network channel, so the hooks-never-touch-the-network rule holds. On Windows the same mode runs over the named pipe `\\.\pipe\beacon-agent-ingest` (`localingest` `transport_windows.go`, go-winio): the collector creates it as the first instance, and when the name is taken (any account may create one) it reports a recoverable error and retries every few seconds rather than failing, so the rest of the collector stays up; it rejects remote clients and its DACL denies NETWORK and withholds `FILE_CREATE_PIPE_INSTANCE` from ordinary accounts, so it is not a network channel either; a client connects at identification level and sends only to a pipe owned by SYSTEM or Administrators; the server counts a connection against its account from the client process's token before reading and stamps the SID it reads by `ImpersonateNamedPipeClient` after the preamble (they must agree), with `Peer.UID` a string (decimal uid on Unix, SID on Windows) and the name from `LookupAccountSid`, bounded. Privileged writers there are SYSTEM and tokens with Administrators enabled (`CheckTokenMembership`; elevation for another group is not enough). The directory gets `sysacl.RestrictedLogDirDACL` (protected: SYSTEM and Administrators full, `beacon-log` local group read, nothing else; the lock SYSTEM and Administrators only) and everything below it is reset, because every account may bypass traverse checking; `writer.RestrictSystemLog` replaces every file directly in the directory (the log family under the lock; files outside it with another hard link are skipped) with a copy created with its final owner and DACL (`sysacl.CreateRestrictedFile`) and a POSIX-semantics rename, fails naming any file held open without sharing delete and then puts a log that was shared back to shared, and writes the marker last (on Windows it decides nothing for root writers, so a failed or killed run is not mistaken for a finished one). The marker counts there when SYSTEM or Administrators own it and no other account can write it. `loggroup` creates the local group with `net.exe` and looks it up qualified with the computer name. Doctor reads the restricted ACL (`writer.CheckRestrictedSystemLogACL`). `packaging/windows/smoke-restricted-log.ps1` runs in `windows-package-smoke` against the installed MSI with a real ordinary account. Hook and writer tests point `logging.EndpointIngest`/`writer.Ingest` at sockets of their own.
- Beacon Cloud forwarding (`cli/beacon/internal/endpoint/asymptote`, `beacon endpoint connect`, `beacon endpoint asymptote`) is Vector-shaped: Beacon writes local JSONL, Vector ships runtime lines only from the connection point forward and reads inventory from the beginning to establish the endpoint's current baseline, plus the one bounded exception of the session backfill (below), and the `bcn_device_*` key stays only in `<BaseDir>/asymptote/vector-secrets.json` via Vector's secret backend. The onboarding wizard preselects Beacon Cloud, and confirming it connects this endpoint in the same command once the local install has succeeded; an endpoint that is already enrolled is never re-enrolled, because enrollment rotates the device key. Standard mode ships locally sanitized retained content; metadata-only uses local Vector transforms to remove prompts, responses, reasoning, tool arguments/results, tool descriptions/definitions, retrieval queries/documents, evaluation explanations, agent descriptions, stop sequences, approval/policy reasons, command output, raw fields, diffs, inventory content, and MCP definitions before buffering/upload. Every text-shaped event field must be classified in `metadata_fields_test.go` (`metadataOnlyRemoved`, each with its own `del()` in `pack/metadata-transforms.toml`, or `metadataOnlyKept`); a new field fails that test until it is, and `BEACON_TEST_VECTOR_BIN` runs the transform on an event with every field set. `vector.toml` is not rendered only at connect: `asymptote.ReconcileForwarder` re-renders it in place for a connected endpoint from the current pack with the enrollment's ingest URL and recorded privacy mode, validates it with the forwarder's own Vector exactly as connect does, atomically replaces it, and, when run from install, repair, the package upgrade or the hidden reconcile the macOS postinstall runs (`ReconcileOptions.Restart`), restarts a running forwarder even when nothing changed (after `vector validate` of the current config with the forwarder's own Vector, and never after a warning, so a refused config or a missing Vector leaves the running forwarder alone), as the Sentinel reconcile does: switching to restricted log access replaces the runtime log with a copy, and Vector, which recognizes a file by its first line, keeps tailing the replaced one until it restarts; an upgrade may also have installed a new Vector. A stopped one is never started and reads the new config when it next starts. The `beacon_runtime` source reads `runtime.jsonl.1` too, as the Sentinel pack does, so lines written to a replaced log before a restart are found again at the next rotation instead of lost. It never enrolls, reads or rewrites the secrets file, makes a network request, or touches `vector-data/` (checkpoints stay, so pack changes must keep source ids and fingerprinting stable), and a rejected config is a warning that keeps the old one; it is a no-op when not connected, after an incomplete connect, without an installed unit, or where `ForwarderManager` is unsupported (supervised mode). `lifecycle.Install` runs it last when services are started (so install, repair and the Linux package upgrade), repair's teardown keeps the forwarder (`UninstallOptions.KeepManagedIngest`) instead of disconnecting it, and the macOS postinstall, which installs with `--no-start`, runs the hidden `beacon endpoint asymptote reconcile --system`. Keep the ingest URL `https://`, the wire contract aligned with `beacon-ingest` (`/v1/ingest/{runtime,inventory}` and `/v1/ingest/health`), and do not add another endpoint network channel. The cloud-sandbox shuttle is the bounded exception: only with `BEACON_ORIGIN=cloud`, it can upload new runtime lines to GCS, S3, or the same Beacon ingest contract because no Vector/service manager/browser/persistent disk exists there.
- Session backfill (`cli/beacon/cmd/endpoint_backfill.go`; docs in `docs/cli/endpoint-install.mdx#session-backfill` and `docs/cli/endpoint-connect.mdx#session-backfill`): after every successful install (user or system mode), every session-store collector runs once with `CollectOptions.Since` (30 days; `sessionwindow.Recent` keeps those sessions, newest first, and never touches the cursors of the rest) and a shared `writer.Budget` (24 MiB, at most 12 MiB per runtime through `Budget.Sub`; a refused append returns `writer.ErrBudgetSpent`, the collector stops with cursors past only what was written, and a manual sync reads the rest). A new session-store collector takes both fields, reads its store only through `internal/sessionfs` (a test parses every collector package to enforce it), and joins `endpointBackfillRunners` and that test's list. Every connect, first or re-connect, user or system, runs the same sweep before enrollment (skipped when install just ran it) and, before the forwarder starts, `asymptote.StageBackfill` copies the window's `harness.collection_method=poll` lines into `cloud-backfill.jsonl` beside the runtime log, which the `beacon_backfill` Vector source (fingerprinted `device_and_inode`, so each atomically restaged copy is a new file) reads from the beginning into the runtime sink through the same privacy transform. Live hook/OTLP/plugin history before the connection point stays local. Re-connects restage, so a resend of already-shipped lines is expected and rests on the deterministic `event.id`; a privacy-mode change clears the checkpoints and the restage renames the new-mode copy over the old one (kept until then so the copy is always a new inode; deleted instead when nothing restages), and `disconnect` removes it. System mode runs the collectors under `withUserHome` for the active console user (`activeConsoleUser`), with cursors under the system base directory, and reports a skip when nobody is logged in; root is reading a home the console user controls, so the sweep runs under `sessionfs.Confine` (an `os.Root` on that home, files owned by the home's owner only, non-blocking opens that refuse FIFOs/devices, SQLite read from a private snapshot under `<SystemBaseDir>/state/backfill-snapshots`, retried until the database size/change counter and WAL header are unchanged across the copy, and refused past `sessionfs.MaxSnapshotBytes` (512 MiB with its WAL) with the runtime's sync command named in the report), and refused paths read as absent and are listed in the report. User-mode sync and backfill stay unconfined. The wizard's confirm screen names the upload (`WizardOptions.BackfillDays`). Dry-run, `--no-backfill` and `BEACON_BACKFILL=0` skip all of it; the cmd tests run with `BEACON_BACKFILL=0` set in `TestMain`.
- `beacon endpoint install` has a full-screen onboarding wizard on interactive user TTYs. It signs in, preselects Beacon Cloud, requires an explicit choice to opt out to Local, and asks Managed users to choose Standard or Metadata-only privacy. Signing in alone still moves no telemetry. Confirming Beacon Cloud does: the confirm screen states that it installs Beacon and starts forwarding, and names what the selected privacy mode sends, so that screen is the consent point. The managed destination is recorded only after enrollment succeeds, so a failed enrollment leaves a working local install, prints `beacon endpoint connect` as the retry, and re-offers the question on the next install. The onboarding record is written only after `lifecycle.Install` returns, because a profile written first left a failed install looking onboarded and silently skipped the wizard on the retry. Explicit `install --connect` is unchanged. The wizard is skipped for system/root/CI/piped-stdin/dry-run or `BEACON_ONBOARDING=0`; those unattended paths must never gain an account or browser dependency. Legacy `BEACON_ONBOARDING_EMAIL`/`USAGE` submissions remain only for fleet compatibility. After the destination, the wizard shows an agent tools screen; every row is preselected (opt-out, space toggles). Beacon Cloud MCP is offered only with Beacon Cloud and runs the `beacon mcp connect` flow (`connectCloudMCP` with `yes`, OAuth, detected harnesses) only after the endpoint is connected (or already was), via `finishCloudSetup`; a failed enrollment skips it and names the retry. The Beacon Agent Skills are offered for either destination and installed user-wide into `~/.agents/skills` and, when Claude Code is set up, `~/.claude/skills` (`cli/beacon/internal/agentskills`, `beacon skills install|uninstall`; a `.beacon-managed` marker decides what Beacon may replace or remove; install and repair refresh only copies Beacon already wrote). Both run after `lifecycle.Install` returns and warn rather than fail. The answers are recorded as `onboarding.cloud_mcp`/`agent_skills`. Implementation lives in `cli/beacon/internal/onboarding`, `cli/beacon/cmd/endpoint_onboarding.go`, `cli/beacon/cmd/endpoint_install.go` and `cli/beacon/cmd/agent_tools.go`; keep `docs/cli/endpoint-onboarding.mdx` and `docs/cli/skills.mdx` in sync.
@@ -59,7 +59,7 @@ Supported runtime surfaces today:
- DeepSeek Harness (`dsh`) is installed through two user-level files: `$DSH_HOME/beacon-endpoint-hooks.json` and a row in `$DSH_HOME/cordis.patch.yml`; there is no project scope. The `@deepseek-ai/dsh-hooks-claude-code` bridge that row mounts is not shipped with the CLI (dev dependency only) and must be installed per profile with `@deepseek-ai/dsh-hook-protocol` at exactly the dsh version; a mount dsh cannot load is skipped at boot with only a warning. So `InstallDsh` first runs `hooks.InspectDshBridge` (`internal/endpoint/hooks/dsh_bridge.go`, read-only: the installation found from the `dsh` launcher on PATH, each `$DSH_HOME/profiles/*` resolved Node-style, and rows in any patch layer that mount a bridge by absolute path at Beacon's hooks file) and returns `*DshBridgeUnavailableError` without writing anything when nothing loads a matching bridge; explicit `--harness dsh` fails, `--all` and endpoint install skip with a warning. A healthy by-path mount (how Nix installs it; it must also resolve its declared dsh peers from its own location, because dsh's host-package interception applies only to profile plugins, else `peers_missing`) counts as installed and Beacon writes no row of its own (removing one it wrote earlier) so hooks never run twice. Beacon never installs the packages. `DshStatus.Active`/`Bridge`, discovery (misconfigured when inactive), doctor `dsh_hook_bridge`, and inventory (each profile's patch layer) surface it; tests build on-disk fixtures with `internal/endpoint/hooks/dshtest`. It also installs a Beacon-owned local skill at `$DSH_HOME/skills/beacon-endpoint/SKILL.md` and supports native session backfill from `$DSH_HOME/sessions` through `beacon endpoint dsh sync`, which fills assistant text/reasoning, tool failures, and token usage that the hook bridge does not expose. It rides the Claude-shaped envelope on the hook path, but `run_code` remains `tool.invoked` because nested commands fire their own hooks.
- fx (vercel-labs/fx) telemetry read from the session store fx commits under `~/.fx/sessions/`, covering session start, prompts, tool calls, commands with exit codes and output, file reads/creates/edits with diffs, MCP tool calls, agent messages, history compaction, and per-turn token usage plus reported cost. fx exposes no third-party hook, plugin, or OTLP surface -- its lifecycle hooks are compiled into the binary -- so collection is a read of fx's own records, run by `beacon endpoint fx sync`. Every event carries `harness.collection_method=poll`; approvals are not synthesized (fx persists permission feedback text, not a per-call decision, matching the Cline and Pi posture) and no session-end event is invented, since fx sessions are resumable. Implementation lives in `cli/beacon/internal/fxsession` and `cli/beacon/cmd/endpoint_fx.go`.
- Harness² (google-research/harness2) rollouts, read from the executor event streams Harness² records under its runs directory (`$HARNESS2_RUNS_DIR`, `~/harness2/runs`, or a `--runs-dir` an earlier sync was given and the cursor file remembers): OpenCode `run --format json` and Codex `exec --json`, recognized by their first event rather than by file name. Harness² runs Codex under its own `CODEX_HOME` with `--ephemeral` and OpenCode from a source checkout, so Beacon's Codex/OpenCode integrations do not record these sessions. Events carry `harness.name=harness2`, `harness.collection_method=poll`, the executor's own session id, and the rollout's benchmark/task/label/run/trial/attempt/harness fingerprint under `raw.harness2`. Codex `turn.completed` usage is the thread's running total and is differenced per turn; Codex exec lines carry no times, so they take the file's mtime. No prompts (an argv argument, absent from both streams) and no approvals are recorded or synthesized. `testdata/recorded` holds streams recorded from the exact OpenCode and Codex releases Harness² pins; re-record them when it bumps either. Implementation lives in `cli/beacon/internal/harness2session` and `cli/beacon/cmd/endpoint_harness2.go`.
-- Attribution of OTLP events: every account on a machine exports to the same loopback collector, and the exporter's base `user` is the collector process's own account (`asymptoteobserve.NewEvent` reads `$USER`/`$USERNAME`). On Linux the collector replaces it with the account that owns the sending socket (peer attribution): `collector.ConfigYAML` renders, only where `collector.PeerAttribution` (`runtime.GOOS == "linux"`), the `beacon_otlp_http` receiver (`collector-builder/exporter/beaconjsonexporter/otlphttpreceiver`, the upstream OTLP/HTTP protocol rebuilt on confighttp so `client.Info.Addr` keeps the client port that upstream drops; it replaces `otlp.protocols.http` on the same port and carries the same `include_metadata` and `loopback_host` authenticator, so non-loopback Host headers are refused there too) and the `beacon_peer` processor (`peerprocessor`, right after `memory_limiter` and before `batch`, which loses the connection) on Beacon's own pipelines, never the OTLP forward's, plus `peer_user: true` on beaconjson. `beacon_peer` removes `beacon.peer.uid`/`beacon.peer.user` wherever a sender put them (resource, scope, record, span, span event and link, every datapoint type), then asks `internal/peercred` for the owner of the client socket of exactly this connection: the client address from `client.Info.Addr` and the collector's end from the gRPC peer's `LocalAddr` or net/http's `LocalAddrContextKey` (no server address, no lookup). `peercred` first asks the kernel with one `NETLINK_SOCK_DIAG` exact four-tuple lookup (`diag_linux.go`, constant cost per export) and scans `/proc/net/tcp{,6}` for the same four-tuple when sock_diag itself is unavailable or, until sock_diag has once answered with a socket, when it says ENOENT (the kernel says that for a missing `tcp_diag` handler too; a socket `/proc` finds then marks sock_diag blind for good); inode 0 (TIME_WAIT/orphan, uid printed 0), no match, or two owners are unknown, never guessed, and an unrelated TIME_WAIT on the same port is skipped. The name comes from `internal/accountname` (shared with `beacon_ingest`). The converter reads the peer attributes from the resource only (`mergeSignalAttrs`), and `applyPeerUser` copies them into `user` only with `Options.PeerUser`, and with it every `claude_cowork` event, log, span or datapoint, has an empty `user` (`applyPeerUser`, which every signal passes through, and `normalizeClaudeCoworkContext` for logs; Cowork reaches a Linux collector only through a relay such as `beacon endpoint cowork --ngrok`, so the kernel names the relay's account, and the cloud identity is the sender's own claim; both stay in raw attributes; without `PeerUser` the cloud identity still replaces the collector's account); the `falcon_hec` exporter gets `peer_user: true` too, so LogScale matches the log; with `PeerUser` an unidentified sender gets an empty `user`, never the collector's root, so a recorded root always means root sent it. `CheckComponentsFor` refuses a collector without both where they are rendered. macOS and Windows have no lookup and keep the collector's account (root, or `COMPUTERNAME$` under LocalSystem). Hook and plugin events carry the person's uid or SID from `os/user.Current()` (verified by the OS in restricted mode). The person is also on the session's hook and plugin events, joined by `session.id`; the Sentinel guide carries the KQL. Never describe OTLP events on macOS or Windows as carrying the person who ran the agent.
+- Attribution of OTLP events: every account on a machine exports to the same loopback collector, and the exporter's base `user` is the collector process's own account (`asymptoteobserve.NewEvent` reads `$USER`/`$USERNAME`). On Linux, macOS and Windows the collector replaces it with the account that owns the sending socket (peer attribution): `collector.ConfigYAML` renders, only where `collector.PeerAttribution` (`runtime.GOOS` is `linux`, `darwin` or `windows`), the `beacon_otlp_http` receiver (`collector-builder/exporter/beaconjsonexporter/otlphttpreceiver`, the upstream OTLP/HTTP protocol rebuilt on confighttp so `client.Info.Addr` keeps the client port that upstream drops; it replaces `otlp.protocols.http` on the same port and carries the same `include_metadata` and `loopback_host` authenticator, so non-loopback Host headers are refused there too) and the `beacon_peer` processor (`peerprocessor`, right after `memory_limiter` and before `batch`, which loses the connection) on Beacon's own pipelines, never the OTLP forward's, plus `peer_user: true` on beaconjson. `beacon_peer` removes `beacon.peer.uid`/`beacon.peer.user` wherever a sender put them (resource, scope, record, span, span event and link, every datapoint type), then asks `internal/peercred` for the owner of the client socket of exactly this connection: the client address from `client.Info.Addr` and the collector's end from the gRPC peer's `LocalAddr` or net/http's `LocalAddrContextKey` (no server address, no lookup). On Linux `peercred` first asks the kernel with one `NETLINK_SOCK_DIAG` exact four-tuple lookup (`diag_linux.go`, constant cost per export) and scans `/proc/net/tcp{,6}` for the same four-tuple when sock_diag itself is unavailable or, until sock_diag has once answered with a socket, when it says ENOENT (the kernel says that for a missing `tcp_diag` handler too; a socket `/proc` finds then marks sock_diag blind for good); inode 0 (TIME_WAIT/orphan, uid printed 0), no match, or two owners are unknown, never guessed, and an unrelated TIME_WAIT on the same port is skipped. On macOS (`peercred_darwin.go`, parser `pcblist.go`, no cgo) it reads the whole `net.inet.tcp.pcblist_n` sysctl table netstat reads (one read per export, proportional to the machine's TCP sockets) and takes `so_uid` from the `xsocket_n` of the pcb whose `xinpcb_n` is exactly the client four-tuple (IPv4 in the last four address bytes, IPv6 and v4-mapped in all sixteen; offsets from xnu's `#pragma pack(4)` structs, records walked by length and kind and padded to 8, a table without its closing `xinpgen` refused); a pcb with no socket, `SS_NOFDREF` (closed by its owner), or `t_state` CLOSED/LISTEN/TIME_WAIT is passed over even though xnu keeps the creator's uid there. On Windows (`peercred_windows.go`, parser `tcptable.go`) `GetExtendedTcpTable` (`TCP_TABLE_OWNER_PID_ALL`, AF_INET and, for an IPv4 pair too, AF_INET6 for v4-mapped rows; ports in network byte order) gives the owning PID of exactly the four-tuple, skipping PID 0/4 and CLOSED/LISTEN/TIME_WAIT/DELETE_TCB rows; the process is opened (`PROCESS_QUERY_LIMITED_INFORMATION`), the table is read again and must still name that PID (a PID is not reused while a handle is open), and the answer is its token's `TokenUser` SID. A user-mode Windows collector can open only its own account's processes, so other accounts' exports are unknown there. Byte-fixture tests for both parsers run on every OS; the live-socket tests (`peercred_live_test.go`) run only on macOS and Windows CI. The name comes from `internal/accountname` (shared with `beacon_ingest`). The converter reads the peer attributes from the resource only (`mergeSignalAttrs`), and `applyPeerUser` copies them into `user` only with `Options.PeerUser`, and with it every `claude_cowork` event, log, span or datapoint, has an empty `user` (`applyPeerUser`, which every signal passes through, and `normalizeClaudeCoworkContext` for logs; Cowork reaches a collector only through a relay such as `beacon endpoint cowork --ngrok`, so the kernel names the relay's account, and the cloud identity is the sender's own claim; both stay in raw attributes; without `PeerUser` the cloud identity still replaces the collector's account); the `falcon_hec` exporter gets `peer_user: true` too, so LogScale matches the log; with `PeerUser` an unidentified sender gets an empty `user`, never the collector's root, so a recorded root always means root sent it. `CheckComponentsFor` refuses a collector without both where they are rendered. A platform without a lookup (anything but these three) keeps the collector's account, as did macOS and Windows collectors before this (root, or `COMPUTERNAME$` under LocalSystem). Hook and plugin events carry the person's uid or SID from `os/user.Current()` (verified by the OS in restricted mode). The person is also on the session's hook and plugin events, joined by `session.id`; the Sentinel guide carries the KQL. Peer attribution names the account that owns the sending socket, not necessarily the person who ran the agent (a relay, a shared service account, a process that inherited a socket), so never describe it as more than that.
- Claude Cowork admin-configured OpenTelemetry setup guidance and local validation.
- OpenClaw Gateway uses a Beacon-managed plugin directory plus OpenClaw's own diagnostics OTLP guidance (`beacon endpoint integrations openclaw`). The plugin's `before_tool_call` hook is fail-closed, so the handler dispatches synchronously and returns without awaiting. Conversation hooks, including `llm_output`, require `plugins.entries.beacon-endpoint.hooks.allowConversationAccess`; without it, token and agent-message coverage is partial. Beacon reads OpenClaw JSON/JSON5 config for advice but does not rewrite it.
- GitHub Copilot CLI uses MDM/customer-managed OTLP HTTP for live spans and approval-like activity, plus `beacon endpoint copilot sync` to backfill local session records from `~/.copilot/session-state`. Poll events carry assistant text, complete tool results, command/file details, and token usage with `harness.collection_method=poll`, plus the shutdown's session-wide `totalNanoAiu` differenced into `gen_ai.usage.cost_usd` once per shutdown (10^9 nano-AIU = one AI credit = US$0.01), only for sessions started on or after the 2026-06-01 AI-credit cutover (`cli/beacon/internal/copilotsession/cost.go`); approvals still come only from the live OTLP path and are not synthesized from persisted records.
diff --git a/cli/beacon/internal/endpoint/collector/collector.go b/cli/beacon/internal/endpoint/collector/collector.go
index 3b8282f7..6fac7677 100644
--- a/cli/beacon/internal/endpoint/collector/collector.go
+++ b/cli/beacon/internal/endpoint/collector/collector.go
@@ -162,10 +162,12 @@ const (
OTLPHTTPReceiver = "beacon_otlp_http"
)
-// PeerAttribution reports whether ConfigYAML renders peer attribution. Only Linux: the processor's
-// lookup reads /proc/net/tcp, and elsewhere it would name nobody, so the upstream HTTP receiver
-// stays as it was. A var so tests on any platform can render either form.
-var PeerAttribution = runtime.GOOS == "linux"
+// PeerAttribution reports whether ConfigYAML renders peer attribution: on the platforms where the
+// processor can ask the kernel who owns a loopback client socket (Linux: sock_diag or /proc/net/tcp;
+// macOS: the net.inet.tcp.pcblist_n table; Windows: GetExtendedTcpTable and the owning process's
+// token). Elsewhere it would name nobody, so the upstream HTTP receiver stays as it was. A var so
+// tests on any platform can render either form.
+var PeerAttribution = runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows"
func ConfigYAML(cfg endpointconfig.Config) string {
endpointconfig.NormalizeDestinations(&cfg)
diff --git a/cli/beacon/internal/endpoint/collector/peer_test.go b/cli/beacon/internal/endpoint/collector/peer_test.go
index 53112838..954140ea 100644
--- a/cli/beacon/internal/endpoint/collector/peer_test.go
+++ b/cli/beacon/internal/endpoint/collector/peer_test.go
@@ -2,6 +2,7 @@ package collector
import (
"os"
+ "runtime"
"strings"
"testing"
@@ -9,8 +10,12 @@ import (
"gopkg.in/yaml.v3"
)
-// The other tests in this package pin the config every platform but Linux renders; the tests below
-// set PeerAttribution themselves.
+// shippedPeerAttribution is PeerAttribution as the package sets it for this platform, read before
+// TestMain changes it.
+var shippedPeerAttribution = PeerAttribution
+
+// The other tests in this package pin the config rendered without peer attribution (a platform with
+// no lookup); the tests below set PeerAttribution themselves.
func TestMain(m *testing.M) {
PeerAttribution = false
os.Exit(m.Run())
@@ -44,7 +49,7 @@ func render(t *testing.T, cfg endpointconfig.Config) renderedConfig {
return out
}
-// On Linux, OTLP/HTTP is served by beacon_otlp_http on the same port (so every runtime keeps
+// With peer attribution (Linux, macOS and Windows), OTLP/HTTP is served by beacon_otlp_http on the same port (so every runtime keeps
// exporting where it did), every Beacon pipeline runs beacon_peer before batch, and beaconjson
// trusts what it wrote.
func TestConfigYAMLRendersPeerAttribution(t *testing.T) {
@@ -137,7 +142,15 @@ func TestPeerAttributionStaysOutOfTheOTLPForward(t *testing.T) {
}
}
-// Everywhere else the config is what it always was.
+// Peer attribution is rendered on every platform the collector's lookup supports, and nowhere else.
+func TestPeerAttributionIsOnWhereTheLookupExists(t *testing.T) {
+ want := runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows"
+ if shippedPeerAttribution != want {
+ t.Fatalf("PeerAttribution on %s = %v, want %v", runtime.GOOS, shippedPeerAttribution, want)
+ }
+}
+
+// Without peer attribution the config is what it always was.
func TestConfigYAMLWithoutPeerAttributionIsUnchanged(t *testing.T) {
cfg := testConfig(t)
text := ConfigYAML(cfg)
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go
index da0fb4e9..782538fb 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go
@@ -94,7 +94,7 @@ func TestCoworkEventHasNoUserUnderThePeer(t *testing.T) {
}
}
-// Without beacon_peer (macOS, Windows), Claude Cowork's cloud identity replaces the collector's own
+// Without beacon_peer (a collector config that does not render it), Claude Cowork's cloud identity replaces the collector's own
// account, as it always has.
func TestCoworkIdentityWinsWithoutThePeer(t *testing.T) {
resource, record := peerLog("claude-cowork")
@@ -218,7 +218,7 @@ func TestCoworkSpansAndMetricsHaveNoUserUnderThePeer(t *testing.T) {
}
}
- // Without the processor (macOS, Windows) nothing changes for these signals.
+ // Without the processor nothing changes for these signals.
if got := NewConverter(Options{}).EventFromSpan(resource, span).User; got == (UserInfo{}) {
t.Fatal("span user empty without peer_user; want the collector's account as before")
}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/pcblist.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/pcblist.go
new file mode 100644
index 00000000..f40805df
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/pcblist.go
@@ -0,0 +1,189 @@
+package peercred
+
+import (
+ "encoding/binary"
+ "errors"
+ "fmt"
+ "net"
+ "strconv"
+)
+
+// The macOS lookup reads the kernel's TCP socket table from the net.inet.tcp.pcblist_n sysctl, the
+// one netstat(1) reads. It is parsed here, apart from the sysctl itself, so the parser is tested on
+// every platform with byte fixtures.
+//
+// The table is a struct xinpgen, then for each TCP protocol control block a run of records, each a
+// length and a kind followed by the record and padded to 8 bytes (ROUNDUP64), then a closing
+// xinpgen. The records come from xnu's bsd/netinet/in_pcblist.c (get_pcblist_n), in this order:
+//
+// xinpcb_n (XSO_INPCB) addresses and ports
+// xsocket_n (XSO_SOCKET) the socket, with so_uid: the account whose credential created it
+// xsockbuf_n x2 receive and send buffers
+// xsockstat_n (XSO_STATS)
+// xtcpcb_n (XSO_TCPCB) t_state
+//
+// The layouts are xnu's bsd/netinet/in_pcb.h, bsd/sys/socketvar.h and bsd/netinet/tcp_var.h, all
+// declared under #pragma pack(4), so a u_int64_t can sit at a 4-byte offset. Only the fields below
+// are read, each at its fixed offset in the record, and a record shorter than what is read from it
+// is not used. Lengths, kinds, uids and states are in host byte order, which is little-endian on
+// every Mac; ports are in network byte order, as in the kernel's pcb.
+const (
+ xsoSocket = 0x001 // XSO_SOCKET
+ xsoInpcb = 0x010 // XSO_INPCB
+ xsoTcpcb = 0x020 // XSO_TCPCB
+
+ // sizeof(struct xinpgen): xig_len, xig_count, xig_gen, xig_sogen. A record no longer than this
+ // is the closing xinpgen, which has no kind (netstat stops on the same test).
+ xinpgenLen = 24
+
+ // struct xinpcb_n.
+ xinpcbFPort = 16 // u_short inp_fport, network order
+ xinpcbLPort = 18 // u_short inp_lport, network order
+ xinpcbVFlag = 44 // u_char inp_vflag
+ xinpcbFAddr = 48 // inp_dependfaddr: in6_addr, or in_addr_4in6 with the IPv4 address last
+ xinpcbLAddr = 64 // inp_dependladdr, the same
+ xinpcbMinLen = 80
+
+ // struct xsocket_n.
+ xsocketState = 26 // short so_state
+ xsocketFamily = 40 // int xso_family; 0 when the pcb has no socket
+ xsocketUID = 64 // uid_t so_uid
+ xsocketMinLen = 68
+
+ // struct xtcpcb_n.
+ xtcpcbState = 36 // int t_state
+ xtcpcbMinLen = 40
+
+ inpIPv4 = 0x1 // INP_IPV4
+ inpIPv6 = 0x2 // INP_IPV6
+
+ ssNoFDRef = 0x0001 // SS_NOFDREF: no file descriptor refers to the socket any more
+
+ tcpsClosed = 0 // TCPS_CLOSED
+ tcpsListen = 1 // TCPS_LISTEN
+ tcpsTimeWait = 10 // TCPS_TIME_WAIT
+)
+
+// errMalformed is a table that does not parse: an answer about nothing, never a guess.
+var errMalformed = errors.New("malformed socket table")
+
+// pcbListUID finds, in a net.inet.tcp.pcblist_n table, the socket whose local end is client and whose
+// remote end is server, and returns the uid that owns it.
+//
+// A socket nobody holds any more is passed over, as on Linux: one in TIME_WAIT or CLOSED, one whose
+// last descriptor has been closed (SS_NOFDREF, which a FIN_WAIT socket left behind by close(2) has),
+// and a pcb without a socket. Unlike Linux, xnu keeps the creator's uid on such a socket, so it
+// would name the right account; it is still refused, because the sender has gone and a client that
+// can close before the lookup could otherwise pick the moment its export is read.
+func pcbListUID(buf []byte, client, server *net.TCPAddr) (string, error) {
+ le := binary.LittleEndian
+ if len(buf) < 8 {
+ return "", errMalformed
+ }
+ first := int(le.Uint32(buf))
+ if first < 8 || first > len(buf) {
+ return "", fmt.Errorf("%w: header length %d", errMalformed, first)
+ }
+ if first == xinpgenLen && le.Uint32(buf[4:]) == 0 && roundup8(first) >= len(buf) {
+ // xig_count 0: get_pcblist_n writes the opening xinpgen alone, with no closing one.
+ return "", ErrNotFound
+ }
+ var inpcb, socket, tcpcb []byte
+ found := ""
+ flush := func() error {
+ defer func() { inpcb, socket, tcpcb = nil, nil, nil }()
+ uid, ok := pcbOwner(inpcb, socket, tcpcb, client, server)
+ if !ok {
+ return nil
+ }
+ if found != "" && found != uid {
+ return ErrAmbiguous
+ }
+ found = uid
+ return nil
+ }
+ closed := false
+ for off := roundup8(first); off+8 <= len(buf); {
+ n := int(le.Uint32(buf[off:]))
+ if n <= xinpgenLen {
+ // The closing xinpgen. A table cut short before it, or inside it, is not trusted.
+ closed = n == xinpgenLen && off+xinpgenLen <= len(buf)
+ break
+ }
+ if n > len(buf)-off {
+ return "", fmt.Errorf("%w: record of %d bytes at %d overruns the table", errMalformed, n, off)
+ }
+ rec := buf[off : off+n]
+ switch le.Uint32(rec[4:]) {
+ case xsoInpcb:
+ if err := flush(); err != nil {
+ return "", err
+ }
+ inpcb = rec
+ case xsoSocket:
+ socket = rec
+ case xsoTcpcb:
+ tcpcb = rec
+ }
+ next := off + roundup8(n)
+ if next <= off {
+ return "", errMalformed
+ }
+ off = next
+ }
+ if !closed {
+ return "", fmt.Errorf("%w: no closing record", errMalformed)
+ }
+ if err := flush(); err != nil {
+ return "", err
+ }
+ if found == "" {
+ return "", ErrNotFound
+ }
+ return found, nil
+}
+
+// pcbOwner is the uid of one pcb's socket when that pcb is the client end of client -> server and
+// someone still holds it.
+func pcbOwner(inpcb, socket, tcpcb []byte, client, server *net.TCPAddr) (string, bool) {
+ le := binary.LittleEndian
+ if len(inpcb) < xinpcbMinLen || len(socket) < xsocketMinLen || len(tcpcb) < xtcpcbMinLen {
+ return "", false
+ }
+ if int(binary.BigEndian.Uint16(inpcb[xinpcbLPort:])) != client.Port ||
+ int(binary.BigEndian.Uint16(inpcb[xinpcbFPort:])) != server.Port {
+ return "", false
+ }
+ vflag := inpcb[xinpcbVFlag]
+ if !pcbAddrIs(inpcb[xinpcbLAddr:xinpcbLAddr+16], vflag, client.IP) ||
+ !pcbAddrIs(inpcb[xinpcbFAddr:xinpcbFAddr+16], vflag, server.IP) {
+ return "", false
+ }
+ if le.Uint32(socket[xsocketFamily:]) == 0 {
+ // sotoxsocket_n leaves the record zeroed when the pcb has no socket.
+ return "", false
+ }
+ if le.Uint16(socket[xsocketState:])&ssNoFDRef != 0 {
+ return "", false
+ }
+ switch int32(le.Uint32(tcpcb[xtcpcbState:])) {
+ case tcpsClosed, tcpsListen, tcpsTimeWait:
+ return "", false
+ }
+ return strconv.FormatUint(uint64(le.Uint32(socket[xsocketUID:])), 10), true
+}
+
+// pcbAddrIs reports whether a pcb address field holds ip. An IPv4 pcb keeps its address in the last
+// four bytes (in_addr_4in6); an IPv6 one uses all sixteen, and net.IP.Equal matches an IPv4-mapped
+// IPv6 address with its IPv4 form. A dual-stack socket connected to an IPv4 address is switched to
+// INP_IPV4 by the kernel and stored the IPv4 way.
+func pcbAddrIs(field []byte, vflag byte, ip net.IP) bool {
+ if vflag&inpIPv4 != 0 && net.IP(field[12:16]).Equal(ip) {
+ return true
+ }
+ return vflag&inpIPv6 != 0 && net.IP(field[:16]).Equal(ip)
+}
+
+func roundup8(n int) int {
+ return (n + 7) &^ 7
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/pcblist_test.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/pcblist_test.go
new file mode 100644
index 00000000..152ae746
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/pcblist_test.go
@@ -0,0 +1,286 @@
+package peercred
+
+import (
+ "encoding/binary"
+ "errors"
+ "net"
+ "testing"
+)
+
+// Fixtures for the macOS net.inet.tcp.pcblist_n table, laid out as xnu writes it: the record sizes
+// are the real sizeof() of each pack(4) struct, each record padded to 8 bytes.
+const (
+ fixtureXinpcbLen = 104 // sizeof(struct xinpcb_n)
+ fixtureXsocketLen = 104 // sizeof(struct xsocket_n)
+ fixtureXsockbufLen = 32 // sizeof(struct xsockbuf_n)
+ fixtureXsockstat = 136 // sizeof(struct xsockstat_n)
+ fixtureXtcpcbLen = 204 // sizeof(struct xtcpcb_n)
+
+ xsoRcvbuf = 0x002
+ xsoSndbuf = 0x004
+ xsoStats = 0x008
+
+ tcpsEstablished = 4
+ tcpsFinWait1 = 6
+ afInet = 2
+ afInet6 = 30
+)
+
+type fixturePCB struct {
+ local, foreign *net.TCPAddr
+ ipv6 bool // an AF_INET6 pcb (INP_IPV6); otherwise INP_IPV4
+ uid uint32
+ state int32
+ soState uint16
+ noSocket bool // the pcb has no socket: sotoxsocket_n leaves the record zeroed
+ skipTCPCB bool
+}
+
+func appendRecord(buf []byte, length int, kind uint32, fill func(rec []byte)) []byte {
+ rec := make([]byte, roundup8(length))
+ binary.LittleEndian.PutUint32(rec[0:], uint32(length))
+ binary.LittleEndian.PutUint32(rec[4:], kind)
+ if fill != nil {
+ fill(rec[:length])
+ }
+ return append(buf, rec...)
+}
+
+func putPCBAddr(field []byte, ip net.IP, ipv6 bool) {
+ if ipv6 {
+ copy(field[:16], ip.To16())
+ return
+ }
+ copy(field[12:16], ip.To4())
+}
+
+func pcbListFixture(pcbs ...fixturePCB) []byte {
+ xinpgen := func(buf []byte, count int) []byte {
+ rec := make([]byte, xinpgenLen)
+ binary.LittleEndian.PutUint32(rec[0:], xinpgenLen)
+ binary.LittleEndian.PutUint32(rec[4:], uint32(count)) // xig_count, not a kind
+ binary.LittleEndian.PutUint64(rec[8:], 77)
+ binary.LittleEndian.PutUint64(rec[16:], 88)
+ return append(buf, rec...)
+ }
+ buf := xinpgen(nil, len(pcbs))
+ for _, p := range pcbs {
+ buf = appendRecord(buf, fixtureXinpcbLen, xsoInpcb, func(r []byte) {
+ binary.LittleEndian.PutUint64(r[8:], 0xfeedface) // xi_inpp
+ binary.BigEndian.PutUint16(r[xinpcbFPort:], uint16(p.foreign.Port))
+ binary.BigEndian.PutUint16(r[xinpcbLPort:], uint16(p.local.Port))
+ binary.LittleEndian.PutUint64(r[20:], 0xcafef00d) // inp_ppcb, at a 4-byte offset
+ vflag := byte(inpIPv4)
+ if p.ipv6 {
+ vflag = inpIPv6
+ }
+ r[xinpcbVFlag] = vflag
+ r[46] = 6 // inp_ip_p
+ putPCBAddr(r[xinpcbFAddr:xinpcbFAddr+16], p.foreign.IP, p.ipv6)
+ putPCBAddr(r[xinpcbLAddr:xinpcbLAddr+16], p.local.IP, p.ipv6)
+ })
+ buf = appendRecord(buf, fixtureXsocketLen, xsoSocket, func(r []byte) {
+ if p.noSocket {
+ return
+ }
+ binary.LittleEndian.PutUint64(r[8:], 0xabad1dea) // xso_so
+ binary.LittleEndian.PutUint16(r[16:], 1) // so_type SOCK_STREAM
+ binary.LittleEndian.PutUint16(r[xsocketState:], p.soState)
+ binary.LittleEndian.PutUint32(r[36:], 6) // xso_protocol
+ family := uint32(afInet)
+ if p.ipv6 {
+ family = afInet6
+ }
+ binary.LittleEndian.PutUint32(r[xsocketFamily:], family)
+ binary.LittleEndian.PutUint32(r[xsocketUID:], p.uid)
+ binary.LittleEndian.PutUint32(r[68:], 4242) // so_last_pid
+ })
+ buf = appendRecord(buf, fixtureXsockbufLen, xsoRcvbuf, nil)
+ buf = appendRecord(buf, fixtureXsockbufLen, xsoSndbuf, nil)
+ buf = appendRecord(buf, fixtureXsockstat, xsoStats, nil)
+ if !p.skipTCPCB {
+ buf = appendRecord(buf, fixtureXtcpcbLen, xsoTcpcb, func(r []byte) {
+ binary.LittleEndian.PutUint32(r[xtcpcbState:], uint32(p.state))
+ })
+ }
+ }
+ return xinpgen(buf, len(pcbs))
+}
+
+func TestPCBListFixtures(t *testing.T) {
+ lo := net.IPv4(127, 0, 0, 1)
+ client := &net.TCPAddr{IP: lo, Port: 50123}
+ server := &net.TCPAddr{IP: lo, Port: 4318}
+ other := &net.TCPAddr{IP: lo, Port: 8080}
+ established := func(local, foreign *net.TCPAddr, uid uint32) fixturePCB {
+ return fixturePCB{local: local, foreign: foreign, uid: uid, state: tcpsEstablished}
+ }
+ listener := fixturePCB{local: server, foreign: &net.TCPAddr{IP: net.IPv4zero, Port: 0}, uid: 0, state: tcpsListen}
+
+ cases := []struct {
+ name string
+ client, server *net.TCPAddr
+ pcbs []fixturePCB
+ want string
+ err error
+ }{
+ {
+ name: "the client end among the listener and the collector's own end",
+ pcbs: []fixturePCB{listener, established(server, client, 0), established(client, server, 501)},
+ want: "501",
+ },
+ {
+ name: "the collector's end of the same connection is not the client",
+ pcbs: []fixturePCB{listener, established(server, client, 0)},
+ err: ErrNotFound,
+ },
+ {
+ name: "a socket in TIME_WAIT is gone, though xnu still knows its creator",
+ pcbs: []fixturePCB{{local: client, foreign: server, uid: 501, state: tcpsTimeWait, soState: ssNoFDRef}},
+ err: ErrNotFound,
+ },
+ {
+ name: "TIME_WAIT is refused on its own",
+ pcbs: []fixturePCB{{local: client, foreign: server, uid: 501, state: tcpsTimeWait}},
+ err: ErrNotFound,
+ },
+ {
+ name: "a socket closed by its owner and left in FIN_WAIT is not an answer",
+ pcbs: []fixturePCB{{local: client, foreign: server, uid: 501, state: tcpsFinWait1, soState: ssNoFDRef}},
+ err: ErrNotFound,
+ },
+ {
+ name: "a half-closed socket its owner still holds is",
+ pcbs: []fixturePCB{{local: client, foreign: server, uid: 501, state: tcpsFinWait1}},
+ want: "501",
+ },
+ {
+ name: "a pcb without a socket reads uid 0 and is not root",
+ pcbs: []fixturePCB{{local: client, foreign: server, state: tcpsEstablished, noSocket: true}},
+ err: ErrNotFound,
+ },
+ {
+ name: "a pcb whose tcpcb is missing is not used",
+ pcbs: []fixturePCB{{local: client, foreign: server, uid: 501, state: tcpsEstablished, skipTCPCB: true}},
+ err: ErrNotFound,
+ },
+ {
+ name: "an unrelated TIME_WAIT on the same port does not stop the lookup",
+ pcbs: []fixturePCB{
+ {local: client, foreign: other, uid: 0, state: tcpsTimeWait, soState: ssNoFDRef},
+ established(client, server, 501),
+ },
+ want: "501",
+ },
+ {
+ name: "another account's socket on the same port to another service is not this client",
+ pcbs: []fixturePCB{established(client, other, 502), established(client, server, 501)},
+ want: "501",
+ },
+ {
+ name: "and when this client has gone, that socket is still not named",
+ pcbs: []fixturePCB{established(client, other, 502)},
+ err: ErrNotFound,
+ },
+ {
+ name: "two owners of the same connection is ambiguous",
+ pcbs: []fixturePCB{established(client, server, 501), established(client, server, 502)},
+ err: ErrAmbiguous,
+ },
+ {
+ name: "the same owner twice is still that owner",
+ pcbs: []fixturePCB{established(client, server, 501), established(client, server, 501)},
+ want: "501",
+ },
+ {
+ name: "another port is not this client",
+ pcbs: []fixturePCB{established(&net.TCPAddr{IP: lo, Port: client.Port + 1}, server, 501)},
+ err: ErrNotFound,
+ },
+ {
+ name: "another address is not this client",
+ pcbs: []fixturePCB{established(&net.TCPAddr{IP: net.IPv4(127, 0, 0, 2), Port: client.Port}, server, 501)},
+ err: ErrNotFound,
+ },
+ {
+ name: "an IPv6 loopback connection",
+ client: &net.TCPAddr{IP: net.IPv6loopback, Port: 50123},
+ server: &net.TCPAddr{IP: net.IPv6loopback, Port: 4318},
+ pcbs: []fixturePCB{{
+ local: &net.TCPAddr{IP: net.IPv6loopback, Port: 50123}, foreign: &net.TCPAddr{IP: net.IPv6loopback, Port: 4318},
+ ipv6: true, uid: 503, state: tcpsEstablished,
+ }},
+ want: "503",
+ },
+ {
+ name: "an IPv4 client seen by a dual-stack listener as IPv4-mapped",
+ pcbs: []fixturePCB{{
+ local: &net.TCPAddr{IP: mapped(lo.To4()), Port: client.Port}, foreign: &net.TCPAddr{IP: mapped(lo.To4()), Port: server.Port},
+ ipv6: true, uid: 504, state: tcpsEstablished,
+ }},
+ want: "504",
+ },
+ {
+ name: "an IPv4 pcb's padding is not read as an IPv6 address",
+ client: &net.TCPAddr{IP: net.ParseIP("::127.0.0.1"), Port: 50123},
+ pcbs: []fixturePCB{established(client, server, 501)},
+ err: ErrNotFound,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ c, s := client, server
+ if tc.client != nil {
+ c = tc.client
+ }
+ if tc.server != nil {
+ s = tc.server
+ }
+ uid, err := pcbListUID(pcbListFixture(tc.pcbs...), c, s)
+ if tc.err != nil {
+ if !errors.Is(err, tc.err) {
+ t.Fatalf("pcbListUID = %q, %v; want %v", uid, err, tc.err)
+ }
+ return
+ }
+ if err != nil || uid != tc.want {
+ t.Fatalf("pcbListUID = %q, %v; want %s", uid, err, tc.want)
+ }
+ })
+ }
+}
+
+// A table that does not parse is an error, never an answer, and never reads past its end.
+func TestPCBListRefusesMalformedTables(t *testing.T) {
+ client := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 50123}
+ server := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 4318}
+ good := pcbListFixture(fixturePCB{local: client, foreign: server, uid: 501, state: tcpsEstablished})
+
+ if _, err := pcbListUID(nil, client, server); !errors.Is(err, errMalformed) {
+ t.Fatalf("empty table err = %v, want errMalformed", err)
+ }
+ header := append([]byte(nil), good...)
+ binary.LittleEndian.PutUint32(header, uint32(len(good)+1))
+ if _, err := pcbListUID(header, client, server); !errors.Is(err, errMalformed) {
+ t.Fatalf("oversized header err = %v, want errMalformed", err)
+ }
+ overrun := append([]byte(nil), good...)
+ binary.LittleEndian.PutUint32(overrun[xinpgenLen:], uint32(len(good)))
+ if _, err := pcbListUID(overrun, client, server); !errors.Is(err, errMalformed) {
+ t.Fatalf("overrunning record err = %v, want errMalformed", err)
+ }
+ // Every truncation either errors or finds nothing; none panics or names an account it cut off.
+ for n := 0; n < len(good); n++ {
+ if uid, err := pcbListUID(good[:n], client, server); err == nil {
+ t.Fatalf("truncated to %d bytes: %q, want no answer", n, uid)
+ }
+ }
+ // A table with no pcbs at all is the opening xinpgen alone, with xig_count 0.
+ if _, err := pcbListUID(pcbListFixture()[:xinpgenLen], client, server); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("zero-count table err = %v, want ErrNotFound", err)
+ }
+ // An empty table (two xinpgens and nothing between) names nobody.
+ if _, err := pcbListUID(pcbListFixture(), client, server); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("empty table err = %v, want ErrNotFound", err)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go
index 0c8df646..8371ee49 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go
@@ -9,6 +9,18 @@
// It is only an answer for connections the collector can see from its own network namespace, over
// loopback, while they are open. Anything else (another host, a connection already closed, a
// platform without a lookup) is reported as unknown, never guessed.
+//
+// Each platform reads the kernel's own record of exactly this connection's client socket:
+//
+// - Linux: one NETLINK_SOCK_DIAG lookup of the four-tuple, or /proc/net/tcp{,6} (peercred_linux.go,
+// diag_linux.go). The answer is the socket's uid.
+// - macOS: the net.inet.tcp.pcblist_n table netstat reads, which carries each socket's so_uid
+// (peercred_darwin.go, pcblist.go). The answer is the uid.
+// - Windows: GetExtendedTcpTable's owning PID for the four-tuple, then that process's token user
+// (peercred_windows.go, tcptable.go). The answer is the SID.
+//
+// The answer is a string: a decimal uid on Unix, a SID on Windows, as the ingest extension's peer
+// identity is.
package peercred
import (
@@ -30,11 +42,12 @@ var (
ErrNotLoopback = errors.New("not a loopback address")
)
-// UID returns the account id, as a decimal string, that owns the client end of the connection from
-// client to server: the remote and local addresses of a connection the collector accepted.
+// UID returns the account that owns the client end of the connection from client to server (the
+// remote and local addresses of a connection the collector accepted): a decimal uid on Linux and
+// macOS, a SID on Windows.
//
-// Both ends are matched, never the client's address alone. Linux lets connections to different
-// destinations share one source port, so 127.0.0.1:P can at the same time be this client and an
+// Both ends are matched, never the client's address alone. Linux (and any stack with SO_REUSEADDR
+// or SO_REUSEPORT) lets connections to different destinations share one source port, so 127.0.0.1:P can at the same time be this client and an
// unrelated socket another account opened to some other service; matching only P would then name
// that account, or give up on a stray TIME_WAIT entry, instead of finding this connection.
func UID(client, server *net.TCPAddr) (string, error) {
@@ -49,3 +62,8 @@ func UID(client, server *net.TCPAddr) (string, error) {
}
return lookupUID(client, server)
}
+
+// mapped is the IPv4-mapped IPv6 form of an IPv4 address, as a dual-stack socket records it.
+func mapped(ip4 net.IP) net.IP {
+ return append(net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}, ip4...)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_darwin.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_darwin.go
new file mode 100644
index 00000000..f13db841
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_darwin.go
@@ -0,0 +1,49 @@
+//go:build darwin
+
+package peercred
+
+import (
+ "errors"
+ "fmt"
+ "net"
+
+ "golang.org/x/sys/unix"
+)
+
+// pcbListSysctl is the TCP socket table netstat(1) reads. It covers IPv4 and IPv6 pcbs alike (xnu
+// keeps one tcbinfo for both), carries the owning uid of each socket (so_uid, from the credential
+// that created it), and is readable without privileges, so it serves the root collector and a
+// user-mode one the same way. It needs no cgo, which the collector is built without.
+const pcbListSysctl = "net.inet.tcp.pcblist_n"
+
+// readPCBList is the sysctl read; a var so tests could stand in for it.
+var readPCBList = func() ([]byte, error) {
+ var err error
+ // The kernel sizes the first call with room for an eighth more pcbs; a table that grew past
+ // that between the two calls answers ENOMEM, and asking again sizes it afresh.
+ for attempt := 0; attempt < 3; attempt++ {
+ var buf []byte
+ buf, err = unix.SysctlRaw(pcbListSysctl)
+ if err == nil {
+ return buf, nil
+ }
+ if !errors.Is(err, unix.ENOMEM) {
+ break
+ }
+ }
+ return nil, err
+}
+
+// lookupUID reads the whole TCP table and picks out exactly the connection client -> server.
+//
+// macOS has no exact lookup by four-tuple like Linux's sock_diag, so this costs one table read per
+// export, proportional to the number of TCP sockets on the machine. The table is a snapshot taken
+// under the kernel's pcb lock, and the connection this export arrived on is open while the
+// processor runs, so it is in it.
+func lookupUID(client, server *net.TCPAddr) (string, error) {
+ buf, err := readPCBList()
+ if err != nil {
+ return "", fmt.Errorf("read %s: %w", pcbListSysctl, err)
+ }
+ return pcbListUID(buf, client, server)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_darwin_test.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_darwin_test.go
new file mode 100644
index 00000000..8e5d7094
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_darwin_test.go
@@ -0,0 +1,30 @@
+//go:build darwin
+
+package peercred
+
+import (
+ "errors"
+ "net"
+ "os"
+ "strconv"
+ "testing"
+)
+
+// so_uid is the effective uid of the credential that created the socket.
+func currentOwner(t *testing.T) string {
+ t.Helper()
+ return strconv.Itoa(os.Geteuid())
+}
+
+// The live table parses as a whole: whatever the running kernel writes, the parser reaches the
+// closing record without calling it malformed.
+func TestLivePCBListParses(t *testing.T) {
+ buf, err := readPCBList()
+ if err != nil {
+ t.Fatalf("read %s: %v", pcbListSysctl, err)
+ }
+ nowhere := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 1}
+ if _, err := pcbListUID(buf, nowhere, nowhere); err != nil && !errors.Is(err, ErrNotFound) {
+ t.Fatalf("live table: %v", err)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go
index 9a18ab5c..901661bc 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go
@@ -145,10 +145,6 @@ func scanTable(r io.Reader, want map[[2]string]bool) (string, error) {
return found, nil
}
-func mapped(ip4 net.IP) net.IP {
- return append(net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}, ip4...)
-}
-
// procAddr4 is how the kernel prints an IPv4 socket address: the address as one 32-bit word in host
// byte order, then the port, both in upper-case hex.
func procAddr4(ip net.IP, port int) string {
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_live_test.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_live_test.go
new file mode 100644
index 00000000..691831ef
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_live_test.go
@@ -0,0 +1,78 @@
+//go:build darwin || windows
+
+package peercred
+
+import (
+ "net"
+ "testing"
+)
+
+// The real thing on macOS and Windows, as peercred_linux_test.go does on Linux: the server end of a
+// loopback connection sees the client's address as remote, and the socket at that address belongs
+// to this process's account. currentOwner is per platform.
+func TestUIDNamesTheOwnerOfARealLoopbackConnection(t *testing.T) {
+ want := currentOwner(t)
+ for _, network := range []string{"tcp4", "tcp6"} {
+ t.Run(network, func(t *testing.T) {
+ addr := "127.0.0.1:0"
+ if network == "tcp6" {
+ addr = "[::1]:0"
+ }
+ ln, err := net.Listen(network, addr)
+ if err != nil {
+ t.Skipf("no %s loopback: %v", network, err)
+ }
+ defer ln.Close()
+ accepted := make(chan net.Conn, 1)
+ go func() {
+ c, _ := ln.Accept()
+ accepted <- c
+ }()
+ client, err := net.Dial(network, ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer client.Close()
+ server := <-accepted
+ defer server.Close()
+
+ remote, local := server.RemoteAddr().(*net.TCPAddr), server.LocalAddr().(*net.TCPAddr)
+ if uid, err := UID(remote, local); err != nil || uid != want {
+ t.Fatalf("UID(%s -> %s) = %q, %v; want this process's %s", remote, local, uid, err, want)
+ }
+ // The same client address paired with another destination is another connection.
+ other := &net.TCPAddr{IP: local.IP, Port: local.Port + 1}
+ if uid, err := UID(remote, other); err == nil {
+ t.Fatalf("UID matched a connection to %s that does not exist: %s", other, uid)
+ }
+ })
+ }
+}
+
+// Once the client has closed and its socket is gone (or left in TIME_WAIT), there is nobody to name.
+func TestUIDOfAClosedClientIsUnknown(t *testing.T) {
+ ln, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ client, err := net.Dial("tcp4", ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ server, err := ln.Accept()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer server.Close()
+ remote, local := server.RemoteAddr().(*net.TCPAddr), server.LocalAddr().(*net.TCPAddr)
+ if uid, err := UID(remote, local); err != nil {
+ t.Fatalf("UID while open = %q, %v", uid, err)
+ }
+ // Reset the client so its end leaves the table rather than lingering in FIN_WAIT.
+ _ = client.(*net.TCPConn).SetLinger(0)
+ _ = client.Close()
+ if uid, err := UID(remote, local); err == nil {
+ t.Fatalf("UID of a closed client = %s, want unknown", uid)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go
index 529f70b8..d476c82c 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go
@@ -1,4 +1,4 @@
-//go:build !linux
+//go:build !linux && !darwin && !windows
package peercred
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_windows.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_windows.go
new file mode 100644
index 00000000..31292e85
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_windows.go
@@ -0,0 +1,128 @@
+//go:build windows
+
+package peercred
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+var procGetExtendedTcpTable = windows.NewLazySystemDLL("iphlpapi.dll").NewProc("GetExtendedTcpTable")
+
+const tcpTableOwnerPIDAll = 5 // TCP_TABLE_OWNER_PID_ALL
+
+// extendedTCPTable returns GetExtendedTcpTable's TCP_TABLE_OWNER_PID_ALL table for one address
+// family; a var so tests could stand in for it.
+var extendedTCPTable = func(family uint32) ([]byte, error) {
+ if err := procGetExtendedTcpTable.Find(); err != nil {
+ return nil, err
+ }
+ size := uint32(16 << 10)
+ for attempt := 0; attempt < 8; attempt++ {
+ buf := make([]byte, size)
+ r, _, _ := procGetExtendedTcpTable.Call(
+ uintptr(unsafe.Pointer(&buf[0])),
+ uintptr(unsafe.Pointer(&size)),
+ 0, // unsorted
+ uintptr(family),
+ tcpTableOwnerPIDAll,
+ 0,
+ )
+ switch windows.Errno(r) {
+ case 0:
+ return buf, nil
+ case windows.ERROR_INSUFFICIENT_BUFFER:
+ // size now holds what the table needs; leave room for connections opened meanwhile.
+ size += size/8 + 1024
+ default:
+ return nil, windows.Errno(r)
+ }
+ }
+ return nil, windows.ERROR_INSUFFICIENT_BUFFER
+}
+
+// connectionOwner is the PID that owns the client end of client -> server, read from the IPv4 table
+// and, for an IPv4 pair, also from the IPv6 table, where a dual-stack socket appears with
+// IPv4-mapped addresses.
+func connectionOwner(client, server *net.TCPAddr) (uint32, error) {
+ var rows []tcpOwnerRow
+ ipv4 := client.IP.To4() != nil && server.IP.To4() != nil
+ if ipv4 {
+ buf, err := extendedTCPTable(windows.AF_INET)
+ if err != nil {
+ return 0, fmt.Errorf("read the IPv4 TCP table: %w", err)
+ }
+ r, err := tcpTable4Rows(buf)
+ if err != nil {
+ return 0, err
+ }
+ rows = append(rows, r...)
+ }
+ buf, err := extendedTCPTable(windows.AF_INET6)
+ switch {
+ case err != nil && ipv4:
+ // IPv6 may be off; the IPv4 table is the answer then.
+ case err != nil:
+ return 0, fmt.Errorf("read the IPv6 TCP table: %w", err)
+ default:
+ r, err := tcpTable6Rows(buf)
+ if err != nil {
+ return 0, err
+ }
+ rows = append(rows, r...)
+ }
+ return ownerPID(rows, client, server)
+}
+
+// lookupUID names the SID of the account whose process owns the client end of client -> server.
+//
+// The TCP table gives a PID, and a PID is only a name for a process while that process exists: one
+// that exits can have its PID handed to another. So the process is opened first, and then the
+// table is read again and must still name the same PID for the connection. Windows does not reuse
+// a PID while a handle to its process is open, so if the connection still belongs to that PID once
+// the handle is held, the handle is the process that owns it, and its token is the sender's. A
+// process that exits before that closes its sockets, and the second read no longer names it.
+//
+// The SID is TokenUser of the process's primary token, the account it runs as. The collector runs
+// as LocalSystem, which may open any process for PROCESS_QUERY_LIMITED_INFORMATION and query its
+// token; a user-mode collector can open only its own account's processes, so another account's
+// export is unknown there rather than misattributed.
+func lookupUID(client, server *net.TCPAddr) (string, error) {
+ pid, err := connectionOwner(client, server)
+ if err != nil {
+ return "", err
+ }
+ process, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid)
+ if err != nil {
+ if errors.Is(err, windows.ERROR_INVALID_PARAMETER) {
+ // No such process: it exited after the table was read.
+ return "", ErrNotFound
+ }
+ return "", fmt.Errorf("open process %d: %w", pid, err)
+ }
+ defer windows.CloseHandle(process)
+ again, err := connectionOwner(client, server)
+ if err != nil {
+ return "", err
+ }
+ if again != pid {
+ return "", ErrNotFound
+ }
+ var token windows.Token
+ if err := windows.OpenProcessToken(process, windows.TOKEN_QUERY, &token); err != nil {
+ return "", fmt.Errorf("open the token of process %d: %w", pid, err)
+ }
+ defer token.Close()
+ user, err := token.GetTokenUser()
+ if err != nil {
+ return "", fmt.Errorf("read the token user of process %d: %w", pid, err)
+ }
+ if user.User.Sid == nil || !user.User.Sid.IsValid() {
+ return "", ErrNotFound
+ }
+ return user.User.Sid.String(), nil
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_windows_test.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_windows_test.go
new file mode 100644
index 00000000..2b472f9c
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_windows_test.go
@@ -0,0 +1,35 @@
+//go:build windows
+
+package peercred
+
+import (
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+// TokenUser of this process's own token.
+func currentOwner(t *testing.T) string {
+ t.Helper()
+ user, err := windows.GetCurrentProcessToken().GetTokenUser()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return user.User.Sid.String()
+}
+
+// The live tables parse: whatever the running system returns fits the row layouts.
+func TestLiveTCPTablesParse(t *testing.T) {
+ buf, err := extendedTCPTable(windows.AF_INET)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tcpTable4Rows(buf); err != nil {
+ t.Fatalf("IPv4 table: %v", err)
+ }
+ if buf, err := extendedTCPTable(windows.AF_INET6); err == nil {
+ if _, err := tcpTable6Rows(buf); err != nil {
+ t.Fatalf("IPv6 table: %v", err)
+ }
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/tcptable.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/tcptable.go
new file mode 100644
index 00000000..353403cd
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/tcptable.go
@@ -0,0 +1,124 @@
+package peercred
+
+import (
+ "encoding/binary"
+ "fmt"
+ "net"
+)
+
+// The Windows lookup reads the TCP tables GetExtendedTcpTable returns with TCP_TABLE_OWNER_PID_ALL:
+// a MIB_TCPTABLE_OWNER_PID (AF_INET) or MIB_TCP6TABLE_OWNER_PID (AF_INET6), each a DWORD count
+// followed by that many rows. They are parsed here, apart from the call, so the parser is tested on
+// every platform with byte fixtures.
+//
+// MIB_TCPROW_OWNER_PID, 24 bytes:
+//
+// 0 dwState
+// 4 dwLocalAddr the address in network byte order
+// 8 dwLocalPort the port in network byte order in the low 16 bits (the first two bytes)
+// 12 dwRemoteAddr
+// 16 dwRemotePort
+// 20 dwOwningPid
+//
+// MIB_TCP6ROW_OWNER_PID, 56 bytes:
+//
+// 0 ucLocalAddr[16]
+// 16 dwLocalScopeId
+// 20 dwLocalPort
+// 24 ucRemoteAddr[16]
+// 40 dwRemoteScopeId
+// 44 dwRemotePort
+// 48 dwState
+// 52 dwOwningPid
+//
+// DWORDs other than addresses and ports are little-endian, as on every Windows Beacon supports.
+const (
+ tcpRow4Size = 24
+ tcpRow6Size = 56
+
+ mibTCPStateClosed = 1 // MIB_TCP_STATE_CLOSED
+ mibTCPStateListen = 2 // MIB_TCP_STATE_LISTEN
+ mibTCPStateTimeWait = 11 // MIB_TCP_STATE_TIME_WAIT
+ mibTCPStateDeleteTCB = 12 // MIB_TCP_STATE_DELETE_TCB
+
+ pidSystemIdle = 0
+ pidSystem = 4
+)
+
+// tcpOwnerRow is one row of either table.
+type tcpOwnerRow struct {
+ local, remote net.TCPAddr
+ state uint32
+ pid uint32
+}
+
+func tcpTableRows(buf []byte, rowSize int, parse func([]byte) tcpOwnerRow) ([]tcpOwnerRow, error) {
+ if len(buf) < 4 {
+ return nil, errMalformed
+ }
+ n := int(binary.LittleEndian.Uint32(buf))
+ if n < 0 || n > (len(buf)-4)/rowSize {
+ return nil, fmt.Errorf("%w: %d rows do not fit in %d bytes", errMalformed, n, len(buf))
+ }
+ rows := make([]tcpOwnerRow, 0, n)
+ for i := 0; i < n; i++ {
+ off := 4 + i*rowSize
+ rows = append(rows, parse(buf[off:off+rowSize]))
+ }
+ return rows, nil
+}
+
+// tcpTable4Rows parses a MIB_TCPTABLE_OWNER_PID.
+func tcpTable4Rows(buf []byte) ([]tcpOwnerRow, error) {
+ return tcpTableRows(buf, tcpRow4Size, func(r []byte) tcpOwnerRow {
+ return tcpOwnerRow{
+ state: binary.LittleEndian.Uint32(r[0:]),
+ local: net.TCPAddr{IP: net.IP(append([]byte(nil), r[4:8]...)), Port: int(binary.BigEndian.Uint16(r[8:]))},
+ remote: net.TCPAddr{IP: net.IP(append([]byte(nil), r[12:16]...)), Port: int(binary.BigEndian.Uint16(r[16:]))},
+ pid: binary.LittleEndian.Uint32(r[20:]),
+ }
+ })
+}
+
+// tcpTable6Rows parses a MIB_TCP6TABLE_OWNER_PID.
+func tcpTable6Rows(buf []byte) ([]tcpOwnerRow, error) {
+ return tcpTableRows(buf, tcpRow6Size, func(r []byte) tcpOwnerRow {
+ return tcpOwnerRow{
+ local: net.TCPAddr{IP: net.IP(append([]byte(nil), r[0:16]...)), Port: int(binary.BigEndian.Uint16(r[20:]))},
+ remote: net.TCPAddr{IP: net.IP(append([]byte(nil), r[24:40]...)), Port: int(binary.BigEndian.Uint16(r[44:]))},
+ state: binary.LittleEndian.Uint32(r[48:]),
+ pid: binary.LittleEndian.Uint32(r[52:]),
+ }
+ })
+}
+
+// ownerPID finds the process that owns the client end of client -> server among rows: the row whose
+// local end is client and remote end is server. Rows nobody owns any more are passed over (TIME_WAIT
+// and the like report PID 0), as is one owned by the System process (PID 4), whose token names
+// SYSTEM rather than whoever caused the connection. Two rows with different owners are ambiguous;
+// none is not found.
+func ownerPID(rows []tcpOwnerRow, client, server *net.TCPAddr) (uint32, error) {
+ var found uint32
+ have := false
+ for _, row := range rows {
+ if row.local.Port != client.Port || row.remote.Port != server.Port ||
+ !row.local.IP.Equal(client.IP) || !row.remote.IP.Equal(server.IP) {
+ continue
+ }
+ switch row.state {
+ case mibTCPStateClosed, mibTCPStateListen, mibTCPStateTimeWait, mibTCPStateDeleteTCB:
+ continue
+ }
+ if row.pid == pidSystemIdle || row.pid == pidSystem {
+ continue
+ }
+ if have && found != row.pid {
+ return 0, ErrAmbiguous
+ }
+ found, have = row.pid, true
+ }
+ if !have {
+ return 0, ErrNotFound
+ }
+ return found, nil
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/tcptable_test.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/tcptable_test.go
new file mode 100644
index 00000000..08e49313
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/tcptable_test.go
@@ -0,0 +1,221 @@
+package peercred
+
+import (
+ "encoding/binary"
+ "errors"
+ "net"
+ "testing"
+)
+
+// Fixtures for GetExtendedTcpTable's TCP_TABLE_OWNER_PID_ALL tables, byte for byte: addresses as
+// the bytes on the wire, ports in network byte order in the low two bytes of their DWORD, every
+// other DWORD little-endian.
+type fixtureRow struct {
+ local, remote *net.TCPAddr
+ state, pid uint32
+}
+
+func tcpTable4Fixture(rows ...fixtureRow) []byte {
+ buf := make([]byte, 4+len(rows)*tcpRow4Size)
+ binary.LittleEndian.PutUint32(buf, uint32(len(rows)))
+ for i, r := range rows {
+ row := buf[4+i*tcpRow4Size:]
+ binary.LittleEndian.PutUint32(row[0:], r.state)
+ copy(row[4:8], r.local.IP.To4())
+ binary.BigEndian.PutUint16(row[8:], uint16(r.local.Port))
+ copy(row[12:16], r.remote.IP.To4())
+ binary.BigEndian.PutUint16(row[16:], uint16(r.remote.Port))
+ binary.LittleEndian.PutUint32(row[20:], r.pid)
+ }
+ return buf
+}
+
+func tcpTable6Fixture(rows ...fixtureRow) []byte {
+ buf := make([]byte, 4+len(rows)*tcpRow6Size)
+ binary.LittleEndian.PutUint32(buf, uint32(len(rows)))
+ for i, r := range rows {
+ row := buf[4+i*tcpRow6Size:]
+ copy(row[0:16], r.local.IP.To16())
+ binary.BigEndian.PutUint16(row[20:], uint16(r.local.Port))
+ copy(row[24:40], r.remote.IP.To16())
+ binary.BigEndian.PutUint16(row[44:], uint16(r.remote.Port))
+ binary.LittleEndian.PutUint32(row[48:], r.state)
+ binary.LittleEndian.PutUint32(row[52:], r.pid)
+ }
+ return buf
+}
+
+// The byte order is the point of these fixtures: port 50123 is 0xC3CB, so the row holds CB C3 if
+// it was ever written little-endian.
+func TestTCPTable4RowByteOrder(t *testing.T) {
+ raw := []byte{
+ 1, 0, 0, 0, // one row
+ 5, 0, 0, 0, // MIB_TCP_STATE_ESTAB
+ 127, 0, 0, 1, // local 127.0.0.1
+ 0xC3, 0xCB, 0, 0, // local port 50123
+ 127, 0, 0, 1, // remote 127.0.0.1
+ 0x10, 0xDE, 0, 0, // remote port 4318
+ 0x39, 0x30, 0, 0, // PID 12345
+ }
+ rows, err := tcpTable4Rows(raw)
+ if err != nil || len(rows) != 1 {
+ t.Fatalf("rows = %v, %v", rows, err)
+ }
+ r := rows[0]
+ if !r.local.IP.Equal(net.IPv4(127, 0, 0, 1)) || r.local.Port != 50123 || r.remote.Port != 4318 || r.state != 5 || r.pid != 12345 {
+ t.Fatalf("row = %+v", r)
+ }
+}
+
+func TestTCPTable6RowByteOrder(t *testing.T) {
+ raw := make([]byte, 4+tcpRow6Size)
+ raw[0] = 1
+ row := raw[4:]
+ row[15] = 1 // ::1
+ row[20], row[21] = 0xC3, 0xCB // local port 50123
+ row[39] = 1 // ::1
+ row[44], row[45] = 0x10, 0xDE // remote port 4318
+ row[48] = 5 // ESTAB
+ row[52], row[53] = 0x39, 0x30 // PID 12345
+ rows, err := tcpTable6Rows(raw)
+ if err != nil || len(rows) != 1 {
+ t.Fatalf("rows = %v, %v", rows, err)
+ }
+ r := rows[0]
+ if !r.local.IP.Equal(net.IPv6loopback) || r.local.Port != 50123 || !r.remote.IP.Equal(net.IPv6loopback) || r.remote.Port != 4318 || r.state != 5 || r.pid != 12345 {
+ t.Fatalf("row = %+v", r)
+ }
+}
+
+func TestOwnerPIDFixtures(t *testing.T) {
+ const estab = 5
+ lo := net.IPv4(127, 0, 0, 1)
+ client := &net.TCPAddr{IP: lo, Port: 50123}
+ server := &net.TCPAddr{IP: lo, Port: 4318}
+ other := &net.TCPAddr{IP: lo, Port: 8080}
+ any4 := &net.TCPAddr{IP: net.IPv4zero}
+ cases := []struct {
+ name string
+ rows4 []fixtureRow
+ rows6 []fixtureRow
+ want uint32
+ err error
+ }{
+ {
+ name: "the client end among the listener and the collector's own end",
+ rows4: []fixtureRow{
+ {local: server, remote: any4, state: mibTCPStateListen, pid: 900},
+ {local: server, remote: client, state: estab, pid: 900},
+ {local: client, remote: server, state: estab, pid: 1234},
+ },
+ want: 1234,
+ },
+ {
+ name: "the collector's end alone is not the client",
+ rows4: []fixtureRow{{local: server, remote: client, state: estab, pid: 900}},
+ err: ErrNotFound,
+ },
+ {
+ name: "TIME_WAIT is gone",
+ rows4: []fixtureRow{{local: client, remote: server, state: mibTCPStateTimeWait, pid: 0}},
+ err: ErrNotFound,
+ },
+ {
+ name: "TIME_WAIT is refused even if a PID is reported",
+ rows4: []fixtureRow{{local: client, remote: server, state: mibTCPStateTimeWait, pid: 1234}},
+ err: ErrNotFound,
+ },
+ {
+ name: "PID 0 is nobody",
+ rows4: []fixtureRow{{local: client, remote: server, state: estab, pid: 0}},
+ err: ErrNotFound,
+ },
+ {
+ name: "PID 4 is the System process, not a sender",
+ rows4: []fixtureRow{{local: client, remote: server, state: estab, pid: 4}},
+ err: ErrNotFound,
+ },
+ {
+ name: "an unrelated TIME_WAIT on the same port does not stop the lookup",
+ rows4: []fixtureRow{
+ {local: client, remote: other, state: mibTCPStateTimeWait},
+ {local: client, remote: server, state: estab, pid: 1234},
+ },
+ want: 1234,
+ },
+ {
+ name: "another process's socket on the same port to another service is not this client",
+ rows4: []fixtureRow{{local: client, remote: other, state: estab, pid: 77}},
+ err: ErrNotFound,
+ },
+ {
+ name: "two owners of the same connection is ambiguous",
+ rows4: []fixtureRow{
+ {local: client, remote: server, state: estab, pid: 1234},
+ {local: client, remote: server, state: estab, pid: 5678},
+ },
+ err: ErrAmbiguous,
+ },
+ {
+ name: "a dual-stack socket appears in the IPv6 table as IPv4-mapped",
+ rows6: []fixtureRow{{local: &net.TCPAddr{IP: mapped(lo.To4()), Port: client.Port}, remote: &net.TCPAddr{IP: mapped(lo.To4()), Port: server.Port}, state: estab, pid: 2222}},
+ want: 2222,
+ },
+ {
+ name: "disagreeing tables are ambiguous",
+ rows4: []fixtureRow{{local: client, remote: server, state: estab, pid: 1234}},
+ rows6: []fixtureRow{{local: &net.TCPAddr{IP: mapped(lo.To4()), Port: client.Port}, remote: &net.TCPAddr{IP: mapped(lo.To4()), Port: server.Port}, state: estab, pid: 2222}},
+ err: ErrAmbiguous,
+ },
+ {
+ name: "another port is not this client",
+ rows4: []fixtureRow{{local: &net.TCPAddr{IP: lo, Port: client.Port + 1}, remote: server, state: estab, pid: 1234}},
+ err: ErrNotFound,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ r4, err := tcpTable4Rows(tcpTable4Fixture(tc.rows4...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ r6, err := tcpTable6Rows(tcpTable6Fixture(tc.rows6...))
+ if err != nil {
+ t.Fatal(err)
+ }
+ pid, err := ownerPID(append(r4, r6...), client, server)
+ if tc.err != nil {
+ if !errors.Is(err, tc.err) {
+ t.Fatalf("ownerPID = %d, %v; want %v", pid, err, tc.err)
+ }
+ return
+ }
+ if err != nil || pid != tc.want {
+ t.Fatalf("ownerPID = %d, %v; want %d", pid, err, tc.want)
+ }
+ })
+ }
+ v6c := &net.TCPAddr{IP: net.IPv6loopback, Port: 50123}
+ v6s := &net.TCPAddr{IP: net.IPv6loopback, Port: 4318}
+ r6, _ := tcpTable6Rows(tcpTable6Fixture(fixtureRow{local: v6c, remote: v6s, state: estab, pid: 3333}))
+ if pid, err := ownerPID(r6, v6c, v6s); err != nil || pid != 3333 {
+ t.Fatalf("IPv6 loopback: %d, %v; want 3333", pid, err)
+ }
+}
+
+func TestTCPTableRefusesMalformedTables(t *testing.T) {
+ if _, err := tcpTable4Rows([]byte{1, 0}); !errors.Is(err, errMalformed) {
+ t.Fatalf("short table err = %v", err)
+ }
+ // A count the buffer cannot hold is refused rather than read past the end.
+ raw := tcpTable4Fixture(fixtureRow{local: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}, remote: &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}})
+ binary.LittleEndian.PutUint32(raw, 2)
+ if _, err := tcpTable4Rows(raw); !errors.Is(err, errMalformed) {
+ t.Fatalf("overcounted IPv4 table err = %v", err)
+ }
+ raw6 := tcpTable6Fixture()
+ binary.LittleEndian.PutUint32(raw6, 0xFFFFFFFF)
+ if _, err := tcpTable6Rows(raw6); !errors.Is(err, errMalformed) {
+ t.Fatalf("overcounted IPv6 table err = %v", err)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_owner_unix_test.go b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_owner_unix_test.go
new file mode 100644
index 00000000..6819aa56
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_owner_unix_test.go
@@ -0,0 +1,15 @@
+//go:build linux || darwin
+
+package otlphttpreceiver
+
+import (
+ "os"
+ "strconv"
+ "testing"
+)
+
+// currentOwner is how peercred names this process's account: its effective uid.
+func currentOwner(t *testing.T) string {
+ t.Helper()
+ return strconv.Itoa(os.Geteuid())
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_owner_windows_test.go b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_owner_windows_test.go
new file mode 100644
index 00000000..6dc288c3
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_owner_windows_test.go
@@ -0,0 +1,19 @@
+//go:build windows
+
+package otlphttpreceiver
+
+import (
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+// currentOwner is how peercred names this process's account: the SID of its token's user.
+func currentOwner(t *testing.T) string {
+ t.Helper()
+ user, err := windows.GetCurrentProcessToken().GetTokenUser()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return user.User.Sid.String()
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_linux_test.go b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_test.go
similarity index 95%
rename from collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_linux_test.go
rename to collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_test.go
index cd9c2c59..baecb825 100644
--- a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_linux_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_test.go
@@ -1,12 +1,10 @@
-//go:build linux
+//go:build linux || darwin || windows
package otlphttpreceiver
import (
"context"
"net/http"
- "os"
- "strconv"
"testing"
"go.opentelemetry.io/collector/component/componenttest"
@@ -54,7 +52,7 @@ func TestAnHTTPExportIsAttributedToTheSendingAccount(t *testing.T) {
if !ok {
t.Fatal("no peer uid recorded")
}
- if want := strconv.Itoa(os.Geteuid()); uid.AsString() != want {
+ if want := currentOwner(t); uid.AsString() != want {
t.Fatalf("peer uid = %s, want this process's %s rather than the claimed 4242", uid.AsString(), want)
}
}
diff --git a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver.go b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver.go
index 7f07c061..60f1165f 100644
--- a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver.go
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver.go
@@ -7,7 +7,8 @@
// (confighttp's parseIP), and the port is what tells one loopback connection from another. This one
// records the full address, so the beacon_peer processor can ask the kernel which account owns the
// sending socket, as it already can for gRPC. Beacon renders it in place of the upstream HTTP
-// protocol only where that lookup exists (Linux), so everywhere else nothing changes.
+// protocol only where that lookup exists (Linux, macOS and Windows), so everywhere else nothing
+// changes.
package otlphttpreceiver
import (
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index 141c044e..d2c999e3 100644
--- a/docs/changelog/cli.mdx
+++ b/docs/changelog/cli.mdx
@@ -11,6 +11,7 @@ Stay up to date with the latest changes to the Agent Beacon CLI.
## Unreleased
+- **OpenTelemetry events name the person who sent them on macOS and Windows too** · The collector on macOS and Windows now records each OpenTelemetry export (Claude Code's and Codex's spans, logs and token usage, the browser extension's chats) under the account that owns the connection it arrived on, as Linux already did, instead of the collector's own account (`root`, or the machine account `COMPUTERNAME$` on Windows). macOS reads the owner of the sending socket from the kernel's TCP table (the one `netstat` reads); Windows finds the process that owns the connection and reads the account from its token. A sender's own claim to an account is ignored, an export whose sender cannot be identified (it disconnected before the collector looked) carries no `user` at all, and Claude Cowork events carry no `user` on every platform, with the cloud account Cowork reports and the relaying account kept in their raw attributes. A user-mode collector on Windows can identify only its own account's exports; others carry no `user`. A Falcon LogScale HEC destination records the same account as `runtime.jsonl`, and Beacon's OTLP forward to another backend is unchanged. Run `beacon endpoint repair --system` (package upgrades do this) to render the new collector config; the collector from the same release is required.
- **OpenTelemetry events name the person who sent them on Linux** · On a system install every account exports to the same local collector, so prompts and token usage from Claude Code, Codex and the browser extension were recorded, and forwarded to SIEMs such as Microsoft Sentinel, under the collector's account, `root`, whoever typed them. The Linux collector now records each OpenTelemetry export under the account that owns the connection it arrived on, as the kernel reports it, over gRPC and HTTP alike, and ignores any account a sender names for itself, on the resource or on a record, span or datapoint. Claude Cowork events on Linux carry no `user`: they reach the collector through a relay such as `beacon endpoint cowork --ngrok`, so the kernel names the relay's account rather than the person, and the cloud account Cowork reports is the sender's own claim. Both stay in the event's raw attributes. An export whose sender cannot be identified (it disconnected before the collector looked) carries no `user` at all, rather than the collector's `root`, so a recorded `root` always means root sent it. A Falcon LogScale HEC destination records the same account as `runtime.jsonl`. Beacon's OTLP forward to another backend is unchanged. macOS and Windows are unchanged. Run `beacon endpoint repair --system` (package upgrades do this) to render the new collector config; the collector from the same release is required.
- **Root and fleet installs configure everyone logged in, and say who** · A system install by root with no `sudo` user, such as Salt's `pkg.installed` or an Ansible `apt` task, configured the agent runtime of only the first logged-in session it found, and printed nothing about it; the only hook lines in the output were root's own. `beacon endpoint user-config repair-installed --system`, which the Linux package runs after installing, now configures the `sudo` user and every account with a live logind session, each as themselves, carries on when one of them fails, and prints `Configured <user> (<home>): …` for each, or that nobody was logged in and what to run. `--json` adds a `users` array; the existing fields still describe the first person.
- **Windows gets the right advice for elevation** · `beacon endpoint connect`, `disconnect` and `uninstall --system` from a shell without privileges told Windows users to rerun with `sudo`, a command Windows does not have. They now say to run from an elevated shell, the same as `beacon endpoint install --system` already did.
diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdx
index d9c5ac88..1e475c48 100644
--- a/docs/cli/endpoint-install.mdx
+++ b/docs/cli/endpoint-install.mdx
@@ -316,7 +316,7 @@ What this does and does not change:
- Local accounts can no longer alter or delete events already in the log, or read other users' sessions.
- Every event that arrives over the socket records the account that sent it, as the operating system reports it. A user still controls their own agent, so they can still send events of their own choosing, including ones that name another session's id, but always under their own account.
-- The collector's OTLP ports on `127.0.0.1` still accept telemetry from any local process, as they do in the shared mode. Agents that export over OTLP, such as Claude Code and Codex, and the browser extension use them. On Linux, events that arrive that way are recorded under the account that owns the sending connection, as the kernel reports it, in either mode (with no `user` when the sender disconnected before the collector could look); on macOS and Windows they carry the collector's own account.
+- The collector's OTLP ports on `127.0.0.1` still accept telemetry from any local process, as they do in the shared mode. Agents that export over OTLP, such as Claude Code and Codex, and the browser extension use them. Events that arrive that way are recorded under the account that owns the sending connection, as the operating system reports it, in either mode and on Linux, macOS and Windows (with no `user` when the sender disconnected before the collector could look). That names the sender; it does not stop an account sending whatever it likes under its own name.
While the endpoint is restricted, commands that read the system log as the person running them (`beacon endpoint dashboard`, `beacon scan`, `beacon traces`, and the session lookups in `beacon share`, `beacon handoff` and `beacon git` commit linking) see it only when run as root or by a `beacon-log` member. [`beacon endpoint doctor`](/cli/endpoint-doctor#runtime_log_access) connects to the socket and reports a collector that is not answering on it, including one that was killed and left its socket behind, and any events waiting in the caller's spool. On Windows the mode works the same way with Windows mechanisms: hooks send to the named pipe `\\.\pipe\beacon-agent-ingest`, the log directory's ACL gives SYSTEM and Administrators full control, the `beacon-log` local group read and nobody else anything, events record the sender's SID and account name, and the commands run from an elevated shell (see [On Windows](/security/restricted-log-access#on-windows)). For how the mode fits with log shippers such as Microsoft Sentinel, and what it does and does not protect, see [Restricted log access](/security/restricted-log-access).
diff --git a/docs/guides/workspace-one-sentinel-mdm.mdx b/docs/guides/workspace-one-sentinel-mdm.mdx
index 0d309c8c..58f04340 100644
--- a/docs/guides/workspace-one-sentinel-mdm.mdx
+++ b/docs/guides/workspace-one-sentinel-mdm.mdx
@@ -194,7 +194,7 @@ BeaconRuntime_CL
| where Message has "Beacon endpoint Sentinel validation event"
```
-Then have someone run Claude Code and check whose sessions arrived. Hook events carry the person's account. Claude Code's and Codex's own OpenTelemetry events (token usage, cost, API requests) carry the collector's own account, the machine account `COMPUTERNAME$`, because every account sends to the same local port, but they share the session's id, so the join below names the person behind every event:
+Then have someone run Claude Code and check whose sessions arrived. Hook events carry the person's account. Claude Code's and Codex's own OpenTelemetry events (token usage, cost, API requests) carry the account that sent them too, as Windows reports the owner of the connection they arrived on; one whose sender disconnected before the collector could look has no `user`. They share the session's id, so the join below names the person behind every event, including those:
```kql
let owners = BeaconRuntime_CL
@@ -222,7 +222,7 @@ See [Who ran each session](/log-forwarding/microsoft-sentinel#who-ran-each-sessi
| The forwarder script fails with "PKCS12 parsing failed" | The PFX password is wrong. Check `BEACON_SENTINEL_PFX_PASSWORD`. |
| `status` reports `Retrying after response` with 403 | The role assignment has not applied yet. Wait up to 30 minutes; nothing is lost meanwhile. |
| `status` reports an `AADSTS` error | Entra ID refused the credential: a wrong tenant or client ID, or a certificate that was not uploaded to the app, has expired or was removed. Vector drops what it cannot send while this lasts, so renew certificates before they expire and rerun the forwarder script with the new one. |
-| Events arrive under the machine account (`COMPUTERNAME$`) | Agents' own OpenTelemetry events always do; attribute them with the join in step 3. If a session has no hook events at all, the person's agent-tools script has not run yet (check its Login trigger). |
+| Events arrive under the machine account (`COMPUTERNAME$`) | Agents' own OpenTelemetry events did with collectors from earlier releases; repair the endpoint (`beacon endpoint repair --system`) so the collector config names the sender, and attribute older events with the join in step 3. If a session has no hook events at all, the person's agent-tools script has not run yet (check its Login trigger). |
| An app, script or hook is blocked | AppLocker or WDAC; allow everything listed under the app above. |
## Related
diff --git a/docs/log-forwarding/microsoft-sentinel.mdx b/docs/log-forwarding/microsoft-sentinel.mdx
index 1a456f29..0b244a8f 100644
--- a/docs/log-forwarding/microsoft-sentinel.mdx
+++ b/docs/log-forwarding/microsoft-sentinel.mdx
@@ -232,7 +232,7 @@ One case is not retried. When Microsoft Entra ID refuses the credential itself,
### Who ran each session
-On a machine several people use, the person behind an event is in `RawData.user`: `uid` is the account's uid, or its SID on Windows, and `name` its name. Hook and plugin events carry it, because each hook and plugin runs as the person who ran the agent; with [restricted log access](/security/restricted-log-access) the operating system vouches for it. On Linux, events from an agent's own OpenTelemetry export, such as Claude Code's token usage and cost or the browser extension's chats, carry the account that sent them too, as the kernel reports it; one whose sender disconnected before the collector could look has no `user`. On macOS and Windows they carry the collector's own account instead (such as `root`, or the machine account `COMPUTERNAME$` on Windows), because every account sends to the same local port and nothing there identifies the sender. On macOS and Windows, Claude Cowork is the exception: its events name the cloud account it reports. On Linux, Cowork events have no `user`: they arrive through a relay such as `beacon endpoint cowork --ngrok`, so the account the kernel reports is the relay's, not the person's. The cloud account Cowork reports is in `RawData.raw.attributes` (`user.email`, `user.account_uuid`), unverified, beside the relaying account (`beacon.peer.uid`, `beacon.peer.user`). Both kinds share the session's id, so take the person from the hook and plugin events, and keep an event's own user where its session has none:
+On a machine several people use, the person behind an event is in `RawData.user`: `uid` is the account's uid, or its SID on Windows, and `name` its name. Hook and plugin events carry it, because each hook and plugin runs as the person who ran the agent; with [restricted log access](/security/restricted-log-access) the operating system vouches for it. Events from an agent's own OpenTelemetry export, such as Claude Code's token usage and cost or the browser extension's chats, carry the account that sent them too, as the operating system reports the owner of the connection they arrived on (Linux, macOS and Windows); one whose sender disconnected before the collector could look has no `user`, and on Windows a user-mode collector names only its own account's exports. Claude Cowork events have no `user`: they arrive through a relay such as `beacon endpoint cowork --ngrok`, so the account the operating system reports is the relay's, not the person's. Collectors from releases before OpenTelemetry attribution reached macOS and Windows record the collector's own account there (such as `root`, or the machine account `COMPUTERNAME$` on Windows). The cloud account Cowork reports is in `RawData.raw.attributes` (`user.email`, `user.account_uuid`), unverified, beside the relaying account (`beacon.peer.uid`, `beacon.peer.user`). Both kinds share the session's id, so take the person from the hook and plugin events, and keep an event's own user where its session has none:
```kql title="Attribute every event to the person who ran its session"
let owners = BeaconRuntime_CL
diff --git a/docs/security/restricted-log-access.mdx b/docs/security/restricted-log-access.mdx
index 2c062328..4c7e5b1f 100644
--- a/docs/security/restricted-log-access.mdx
+++ b/docs/security/restricted-log-access.mdx
@@ -177,7 +177,7 @@ Restricted mode protects the **log**: what has been recorded cannot be altered o
- **A user still controls their own agent.** They can still send events of their own choosing through the socket, including ones that name another session's id, but every event is recorded under their own account, as the operating system reports it. They cannot write an event that claims to be someone else's.
- **A user can still change their own agent settings.** The hooks and OpenTelemetry settings that send an agent's activity to Beacon live in each user's home (for example `~/.claude/settings.json`), and that user can edit them, which stops capture of their future sessions. Restricted mode does not change this. Run [`beacon endpoint doctor --system`](/cli/endpoint-doctor#console_user_configured) from your MDM to catch it: `console_user_configured` fails when the logged-in user's agents no longer point at the collector, and `sudo beacon endpoint user-config repair-installed --system` puts the settings back.
-- **The OTLP ports are open to every account.** The collector's OTLP receivers on `127.0.0.1:4317` and `4318` still accept telemetry from any local process, as in the shared mode. Agents that export over OTLP, such as Claude Code and Codex, and the browser extension use them. On Linux the collector records each such event under the account that owns the connection it arrived on, as the kernel reports it, and ignores any account the sender names itself; an event whose sender had already disconnected when the collector looked carries no `user` at all, so it is never mistaken for root's. On macOS and Windows these events carry the collector's own account (such as `root`, or the machine account `COMPUTERNAME$` on Windows), not the person who ran the agent: every account on the machine sends to the same port, and nothing there identifies the sender. There, Claude Cowork's events name the cloud account it reports instead, which no one checks either; on Linux they carry no `user`, because they arrive through a relay whose account is not the person's, and keep the cloud account and the relaying account only in their raw attributes. The person is on the same session's hook and plugin events, which share the OTLP events' `session.id` and which restricted mode does attribute; see [Microsoft Sentinel forwarding](/log-forwarding/microsoft-sentinel#who-ran-each-session) for the join.
+- **The OTLP ports are open to every account.** The collector's OTLP receivers on `127.0.0.1:4317` and `4318` still accept telemetry from any local process, as in the shared mode. Agents that export over OTLP, such as Claude Code and Codex, and the browser extension use them. On Linux, macOS and Windows the collector records each such event under the account that owns the connection it arrived on, as the operating system reports it, and ignores any account the sender names itself; an event whose sender had already disconnected when the collector looked carries no `user` at all, so it is never mistaken for root's. That names the sender but does not stop an account sending whatever it likes under its own name. Claude Cowork's events carry no `user`, because they arrive through a relay whose account is not the person's, and keep the cloud account and the relaying account only in their raw attributes. The person is on the same session's hook and plugin events, which share the OTLP events' `session.id` and which restricted mode does attribute; see [Microsoft Sentinel forwarding](/log-forwarding/microsoft-sentinel#who-ran-each-session) for the join.
- **Root is trusted.** An administrator can read and change the log in either mode. On Windows that is SYSTEM and any elevated administrator.
## Verify