Skip to content

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

Attribute OTLP events to the account that sent them on Linux

Claude690295166bbf
diff --git a/CLAUDE.md b/CLAUDE.md
index 0a3ad686..4ce1c661 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: any local process can still send OTLP, unattributed, so never claim more than the hook channel guarantees. 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 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.
- 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 restarts the forwarder only when the content changed and the forwarder is running (a stopped one reads the new config when it next starts). 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 `user` is the collector process's own account (`asymptoteobserve.NewEvent` reads `$USER`/`$USERNAME`), so on a system install OTLP events show the service's account (root, or the machine account `COMPUTERNAME$` under LocalSystem on Windows) rather than the person (Claude Cowork's excepted: `normalizeClaudeCoworkContext` uses the cloud identity it reports); hook and plugin events carry the person's uid or SID from `os/user.Current()`. The person is on the session's hook and plugin events (verified by the OS in restricted mode), joined by `session.id`; the Sentinel guide carries the KQL. Never describe OTLP events 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 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 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 any `beacon.peer.uid`/`beacon.peer.user` resource attribute a sender wrote, then asks `internal/peercred` (`/proc/net/tcp{,6}`: the line whose local address is the client's; inode 0 (TIME_WAIT/orphan, uid printed 0), no match, or two owners are unknown, never guessed) and names the uid through `internal/accountname` (shared with `beacon_ingest`); the converter's `applyPeerUser` copies them into `user` only with `Options.PeerUser`, before `normalizeClaudeCoworkContext`, whose cloud identity still wins. `CheckComponentsFor` refuses a collector without both where they are rendered. An unidentified sender keeps the collector's account; macOS and Windows have no lookup and keep it too (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.
- 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 201b247c..331984ad 100644
--- a/cli/beacon/internal/endpoint/collector/collector.go
+++ b/cli/beacon/internal/endpoint/collector/collector.go
@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "runtime"
"sort"
"strings"
"time"
@@ -152,6 +153,20 @@ func WriteConfig(cfg endpointconfig.Config) error {
// log access mode.
const IngestExtension = "beacon_ingest"
+// PeerProcessor and OTLPHTTPReceiver are the collector components that record which local account
+// sent each OTLP export: the receiver serves OTLP/HTTP keeping the client's port, which the upstream
+// one drops, and the processor asks the kernel who owns that client socket (gRPC already carries
+// the port). See collector-builder/exporter/beaconjsonexporter/peerprocessor.
+const (
+ PeerProcessor = "beacon_peer"
+ 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"
+
func ConfigYAML(cfg endpointconfig.Config) string {
endpointconfig.NormalizeDestinations(&cfg)
exporterNames := []string{"beaconjson"}
@@ -223,6 +238,22 @@ func ConfigYAML(cfg endpointconfig.Config) string {
// The restricted log access mode makes the collector the only writer of the system log: hooks
// send their events to beacon_ingest over a local socket instead of appending, so the log can
// be 0640 root:beacon-log. Its rotation matches beaconjson's, since both append to one log.
+ // Peer attribution. Without it every OTLP event records the collector's own account (root, on
+ // a system install), whoever sent it. beacon_peer goes right after memory_limiter and before
+ // batch, which would drop the connection details it reads; beaconjson is told to trust what it
+ // writes, and only then. The OTLP forward's pipelines do not run it, so Beacon's attribution
+ // never reaches that backend.
+ receivers, httpReceiverYAML, otlpHTTPYAML, peerYAML, peerStep, peerExporterYAML := "[otlp]", "", "", "", "", ""
+ if PeerAttribution {
+ receivers = "[otlp, " + OTLPHTTPReceiver + "]"
+ httpReceiverYAML = fmt.Sprintf(" %s:\n endpoint: 127.0.0.1:%d\n", OTLPHTTPReceiver, cfg.Collector.HTTPPort)
+ peerYAML = " " + PeerProcessor + ": {}\n"
+ peerStep = PeerProcessor + ", "
+ peerExporterYAML = " peer_user: true\n"
+ } else {
+ otlpHTTPYAML = fmt.Sprintf(" http:\n endpoint: 127.0.0.1:%d\n", cfg.Collector.HTTPPort)
+ }
+ forwardPipelines = strings.ReplaceAll(forwardPipelines, "receivers: [otlp]", "receivers: "+receivers)
ingestYAML, extensions := "", "[health_check]"
if cfg.RestrictedLogAccess() {
ingestYAML = fmt.Sprintf(" %s:\n log_path: %q\n rotate_bytes: 10485760\n rotate_archives: 5\n", IngestExtension, cfg.LogPath)
@@ -233,9 +264,7 @@ func ConfigYAML(cfg endpointconfig.Config) string {
protocols:
grpc:
endpoint: 127.0.0.1:%d
-%s http:
- endpoint: 127.0.0.1:%d
-
+%s%s%s
processors:
memory_limiter:
check_interval: 1s
@@ -245,7 +274,7 @@ processors:
send_batch_size: 128
claude_api_body:
%s
-%sexporters:
+%s%sexporters:
beaconjson:
path: %q
max_event_bytes: 65536
@@ -264,18 +293,24 @@ service:
extensions: %s
pipelines:
logs:
- receivers: [otlp]
- processors: [memory_limiter, claude_api_body, %sbatch]
+ receivers: %s
+ processors: [memory_limiter, %sclaude_api_body, %sbatch]
exporters: %s
traces:
- receivers: [otlp]
- processors: [memory_limiter, %sbatch]
+ receivers: %s
+ processors: [memory_limiter, %s%sbatch]
exporters: %s
metrics:
- receivers: [otlp]
- processors: [memory_limiter, %sbatch]
+ receivers: %s
+ processors: [memory_limiter, %s%sbatch]
exporters: %s
-%s`, cfg.Collector.GRPCPort, grpcLimitYAML, cfg.Collector.HTTPPort, modelContextYAML, privacyYAML, cfg.LogPath, runtimeMetricsYAML+codexSpansYAML+modelContextYAML+splunkExporter+falconExporter+forwardExporter, endpointconfig.HealthCheckPort(cfg.Collector), ingestYAML, extensions, privacyStep, exporters, privacyStep, exporters, privacyStep, exporters, forwardPipelines)
+%s`, cfg.Collector.GRPCPort, grpcLimitYAML, otlpHTTPYAML, httpReceiverYAML, modelContextYAML, privacyYAML, peerYAML, cfg.LogPath,
+ runtimeMetricsYAML+codexSpansYAML+modelContextYAML+peerExporterYAML+splunkExporter+falconExporter+forwardExporter,
+ endpointconfig.HealthCheckPort(cfg.Collector), ingestYAML, extensions,
+ receivers, peerStep, privacyStep, exporters,
+ receivers, peerStep, privacyStep, exporters,
+ receivers, peerStep, privacyStep, exporters,
+ forwardPipelines)
}
// ForwardFilterProcessor keeps an OTLP forward to the runtimes it is meant to carry.
diff --git a/cli/beacon/internal/endpoint/collector/components.go b/cli/beacon/internal/endpoint/collector/components.go
index fc671520..f4fafda5 100644
--- a/cli/beacon/internal/endpoint/collector/components.go
+++ b/cli/beacon/internal/endpoint/collector/components.go
@@ -37,8 +37,14 @@ func CheckComponents(binary string, extensions ...string) error {
}
// CheckComponentsFor is CheckComponents with the processors and exporters the config will use
-// beyond Beacon's own -- the OTLP forward's -- refused the same way.
+// beyond Beacon's own -- the OTLP forward's -- refused the same way. Where ConfigYAML renders peer
+// attribution, its receiver and processor are required too.
func CheckComponentsFor(binary string, extensions, processors, exporters []string) error {
+ var receivers []string
+ if PeerAttribution {
+ processors = append(append([]string{}, processors...), PeerProcessor)
+ receivers = append(receivers, OTLPHTTPReceiver)
+ }
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
out, err := listComponents(ctx, binary)
@@ -46,6 +52,9 @@ func CheckComponentsFor(binary string, extensions, processors, exporters []strin
return nil
}
var listed struct {
+ Receivers []struct {
+ Name string `yaml:"name"`
+ } `yaml:"receivers"`
Processors []struct {
Name string `yaml:"name"`
} `yaml:"processors"`
@@ -69,6 +78,16 @@ func CheckComponentsFor(binary string, extensions, processors, exporters []strin
"use the %s from the same Beacon release, or pass --collector with one", binary, name, BinaryName)
}
}
+ haveReceiver := map[string]bool{}
+ for _, receiver := range listed.Receivers {
+ haveReceiver[receiver.Name] = true
+ }
+ for _, name := range receivers {
+ if !haveReceiver[name] {
+ return fmt.Errorf("collector %s is older than this beacon CLI: it has no %q receiver, which the collector config needs; "+
+ "use the %s from the same Beacon release, or pass --collector with one", binary, name, BinaryName)
+ }
+ }
haveExtension := map[string]bool{}
for _, extension := range listed.Extensions {
haveExtension[extension.Name] = true
diff --git a/cli/beacon/internal/endpoint/collector/peer_test.go b/cli/beacon/internal/endpoint/collector/peer_test.go
new file mode 100644
index 00000000..1bc77802
--- /dev/null
+++ b/cli/beacon/internal/endpoint/collector/peer_test.go
@@ -0,0 +1,159 @@
+package collector
+
+import (
+ "os"
+ "strings"
+ "testing"
+
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "gopkg.in/yaml.v3"
+)
+
+// The other tests in this package pin the config every platform but Linux renders; the tests below
+// set PeerAttribution themselves.
+func TestMain(m *testing.M) {
+ PeerAttribution = false
+ os.Exit(m.Run())
+}
+
+func withPeerAttribution(t *testing.T) {
+ t.Helper()
+ PeerAttribution = true
+ t.Cleanup(func() { PeerAttribution = false })
+}
+
+type renderedConfig struct {
+ Receivers map[string]any `yaml:"receivers"`
+ Processors map[string]any `yaml:"processors"`
+ Exporters map[string]any `yaml:"exporters"`
+ Service struct {
+ Pipelines map[string]struct {
+ Receivers []string `yaml:"receivers"`
+ Processors []string `yaml:"processors"`
+ Exporters []string `yaml:"exporters"`
+ } `yaml:"pipelines"`
+ } `yaml:"service"`
+}
+
+func render(t *testing.T, cfg endpointconfig.Config) renderedConfig {
+ t.Helper()
+ var out renderedConfig
+ if err := yaml.Unmarshal([]byte(ConfigYAML(cfg)), &out); err != nil {
+ t.Fatalf("ConfigYAML is not YAML: %v\n%s", err, ConfigYAML(cfg))
+ }
+ return out
+}
+
+// On Linux, 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) {
+ withPeerAttribution(t)
+ cfg := testConfig(t)
+ text := ConfigYAML(cfg)
+ out := render(t, cfg)
+
+ otlp := out.Receivers["otlp"].(map[string]any)["protocols"].(map[string]any)
+ if _, ok := otlp["http"]; ok {
+ t.Fatalf("otlp still serves HTTP; the port belongs to %s:\n%s", OTLPHTTPReceiver, text)
+ }
+ if _, ok := otlp["grpc"]; !ok {
+ t.Fatalf("otlp lost gRPC:\n%s", text)
+ }
+ if got := out.Receivers[OTLPHTTPReceiver].(map[string]any)["endpoint"]; got != "127.0.0.1:14318" {
+ t.Fatalf("%s endpoint = %v, want the configured HTTP port on loopback", OTLPHTTPReceiver, got)
+ }
+ if _, ok := out.Processors[PeerProcessor]; !ok {
+ t.Fatalf("no %s processor:\n%s", PeerProcessor, text)
+ }
+ if got := out.Exporters["beaconjson"].(map[string]any)["peer_user"]; got != true {
+ t.Fatalf("beaconjson peer_user = %v, want true", got)
+ }
+ for _, signal := range []string{"logs", "traces", "metrics"} {
+ p := out.Service.Pipelines[signal]
+ if strings.Join(p.Receivers, ",") != "otlp,"+OTLPHTTPReceiver {
+ t.Errorf("%s receivers = %v", signal, p.Receivers)
+ }
+ if len(p.Processors) < 2 || p.Processors[0] != "memory_limiter" || p.Processors[1] != PeerProcessor || p.Processors[len(p.Processors)-1] != "batch" {
+ t.Errorf("%s processors = %v, want memory_limiter, %s first and batch last", signal, p.Processors, PeerProcessor)
+ }
+ }
+}
+
+// The OTLP forward hears HTTP exports too, but never runs beacon_peer: Beacon's attribution of
+// local accounts stays on this machine.
+func TestPeerAttributionStaysOutOfTheOTLPForward(t *testing.T) {
+ withPeerAttribution(t)
+ cfg := testConfig(t)
+ cfg.Destinations = &endpointconfig.Destinations{OTLPForward: &endpointconfig.OTLPForward{
+ Endpoint: "https://otel.backend.example",
+ Protocol: endpointconfig.OTLPForwardProtocolHTTP,
+ }}
+ endpointconfig.NormalizeDestinations(&cfg)
+ out := render(t, cfg)
+ for _, signal := range []string{"logs/forward", "traces/forward", "metrics/forward"} {
+ p, ok := out.Service.Pipelines[signal]
+ if !ok {
+ t.Fatalf("no %s pipeline", signal)
+ }
+ if strings.Join(p.Receivers, ",") != "otlp,"+OTLPHTTPReceiver {
+ t.Errorf("%s receivers = %v, want both, so HTTP exports are still forwarded", signal, p.Receivers)
+ }
+ for _, proc := range p.Processors {
+ if proc == PeerProcessor {
+ t.Errorf("%s runs %s: %v", signal, PeerProcessor, p.Processors)
+ }
+ }
+ }
+}
+
+// Everywhere else the config is what it always was.
+func TestConfigYAMLWithoutPeerAttributionIsUnchanged(t *testing.T) {
+ cfg := testConfig(t)
+ text := ConfigYAML(cfg)
+ for _, absent := range []string{OTLPHTTPReceiver, PeerProcessor, "peer_user"} {
+ if strings.Contains(text, absent) {
+ t.Fatalf("config names %s without peer attribution:\n%s", absent, text)
+ }
+ }
+ if !strings.Contains(text, " http:\n endpoint: 127.0.0.1:14318\n") {
+ t.Fatalf("otlp lost its HTTP protocol:\n%s", text)
+ }
+}
+
+const peerComponents = `buildinfo:
+ command: beacon-otelcol
+receivers:
+ - name: otlp
+ - name: beacon_otlp_http
+processors:
+ - name: batch
+ - name: memory_limiter
+ - name: claude_api_body
+ - name: beacon_privacy
+ - name: beacon_peer
+`
+
+// A collector from before peer attribution would refuse the whole config at start; install says so
+// first, as it does for every other component.
+func TestCheckComponentsRequiresPeerAttributionWhereItIsRendered(t *testing.T) {
+ withPeerAttribution(t)
+ stubComponents(t, peerComponents, nil)
+ if err := CheckComponents("/opt/beacon/bin/beacon-otelcol"); err != nil {
+ t.Fatalf("CheckComponents = %v, want a current collector accepted", err)
+ }
+ stubComponents(t, strings.Replace(peerComponents, " - name: beacon_otlp_http\n", "", 1), nil)
+ if err := CheckComponents("/opt/beacon/bin/beacon-otelcol"); err == nil || !strings.Contains(err.Error(), `"beacon_otlp_http" receiver`) {
+ t.Fatalf("CheckComponents = %v, want the missing receiver named", err)
+ }
+ stubComponents(t, strings.Replace(peerComponents, " - name: beacon_peer\n", "", 1), nil)
+ if err := CheckComponents("/opt/beacon/bin/beacon-otelcol"); err == nil || !strings.Contains(err.Error(), `"beacon_peer" processor`) {
+ t.Fatalf("CheckComponents = %v, want the missing processor named", err)
+ }
+
+ PeerAttribution = false
+ stubComponents(t, strings.Replace(strings.Replace(peerComponents, " - name: beacon_peer\n", "", 1), " - name: beacon_otlp_http\n", "", 1), nil)
+ if err := CheckComponents("/opt/beacon/bin/beacon-otelcol"); err != nil {
+ t.Fatalf("CheckComponents = %v; without peer attribution neither is needed", err)
+ }
+}
diff --git a/collector-builder/builder.yaml b/collector-builder/builder.yaml
index 891d6114..b4cf9899 100644
--- a/collector-builder/builder.yaml
+++ b/collector-builder/builder.yaml
@@ -5,6 +5,10 @@ dist:
receivers:
- gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.121.0
+ # OTLP/HTTP that keeps the client's port, so beacon_peer can name the sending account (Linux).
+ - gomod: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter v0.0.0
+ import: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver
+ path: ./exporter/beaconjsonexporter
processors:
- gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.121.0
@@ -18,6 +22,9 @@ processors:
- gomod: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter v0.0.0
import: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/forwardfilterprocessor
path: ./exporter/beaconjsonexporter
+ - gomod: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter v0.0.0
+ import: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/peerprocessor
+ path: ./exporter/beaconjsonexporter
exporters:
- gomod: github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter v0.0.0
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go
index ed256e9d..d95165e4 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension.go
@@ -13,6 +13,7 @@ import (
"context"
"errors"
"fmt"
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/accountname"
"net"
"sync"
"time"
@@ -29,7 +30,7 @@ import (
type ingest struct {
cfg *Config
logger *zap.Logger
- names *nameCache
+ names *accountname.Cache
// listen, serveListener and appendLine are the seams tests replace.
listen func(path string) (localingest.Listener, error)
@@ -51,7 +52,7 @@ func newIngest(cfg *Config, logger *zap.Logger) *ingest {
return &ingest{
cfg: cfg,
logger: logger,
- names: newNameCache(),
+ names: accountname.NewCache(),
listen: localingest.Listen,
appendLine: runtimelog.Append,
}
@@ -135,7 +136,7 @@ func (e *ingest) serve(host component.Host, l localingest.Listener) {
server := &localingest.Server{
Append: e.append,
LogPath: e.cfg.LogPath,
- LookupName: e.names.lookup,
+ LookupName: e.names.Lookup,
MaxConns: e.cfg.MaxConnections,
MaxConnsPerUID: e.cfg.MaxConnectionsPerUID,
RateBytesPerSecond: e.cfg.RateBytesPerSecond,
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go
index 52cc037e..b5e17ee4 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_unix_test.go
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/accountname"
"net"
"os"
"path/filepath"
@@ -120,7 +121,7 @@ func TestEventsSentToTheSocketLandInTheLogUnderTheSendersAccount(t *testing.T) {
t.Fatalf("log has %d lines, want 2", len(lines))
}
uid := fmt.Sprint(os.Geteuid())
- want := resolveName(strconv.Itoa(os.Geteuid()))
+ want := accountname.Resolve(strconv.Itoa(os.Geteuid()))
for i, line := range lines {
user := line["user"].(map[string]interface{})
if user["uid"] != uid {
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_windows_test.go b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_windows_test.go
index 2d7ccfcc..f902e363 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_windows_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/beaconingestextension/extension_windows_test.go
@@ -185,43 +185,6 @@ func TestShutdownLeavesNoPipe(t *testing.T) {
}
}
-func TestResolveNameNamesTheCurrentAccount(t *testing.T) {
- me, err := user.Current()
- if err != nil {
- t.Skip(err)
- }
- if got := resolveName(currentSID(t)); got != me.Username {
- t.Fatalf("resolveName = %q, want %q", got, me.Username)
- }
- if got := resolveName("S-1-5-21-1-2-3-999999"); got != "" {
- t.Fatalf("resolveName of an unknown SID = %q", got)
- }
-}
-
-// Accounts that are not SidTypeUser are named too. os/user refused them, which would have left
-// events from SYSTEM, a service's virtual account or an Entra ID account without a name.
-func TestResolveNameNamesAccountsThatAreNotLocalUsers(t *testing.T) {
- if got := resolveName("S-1-5-18"); got != `NT AUTHORITY\SYSTEM` {
- t.Fatalf("resolveName(SYSTEM) = %q", got)
- }
- if got := resolveName("not a sid"); got != "" {
- t.Fatalf("resolveName of a malformed SID = %q", got)
- }
-}
-
-func TestValidWindowsName(t *testing.T) {
- for _, ok := range []string{`CONTOSO\Jane Doe`, `DESKTOP-1\runneradmin`, `NT AUTHORITY\SYSTEM`} {
- if !validWindowsName(ok) {
- t.Errorf("validWindowsName(%q) = false", ok)
- }
- }
- for _, bad := range []string{"", " lead", "trail ", "nl\nx", "esc\x1b[31m", "del\x7f", string(make([]byte, 257))} {
- if validWindowsName(bad) {
- t.Errorf("validWindowsName(%q) = true", bad)
- }
- }
-}
-
// Only a taken name is waited out. A socket_path that can never be a pipe fails the start loudly,
// as it did before, instead of a collector that looks healthy and never serves.
func TestAListenErrorThatCannotClearStillFailsTheStart(t *testing.T) {
diff --git a/collector-builder/exporter/beaconjsonexporter/config.go b/collector-builder/exporter/beaconjsonexporter/config.go
index 9ac0d952..3a9d447d 100644
--- a/collector-builder/exporter/beaconjsonexporter/config.go
+++ b/collector-builder/exporter/beaconjsonexporter/config.go
@@ -21,6 +21,9 @@ type Config struct {
// CaptureModelContext is the --claude-capture-model-context opt-in, the same setting the
// claude_api_body processor reads; see beaconevent.Options.
CaptureModelContext bool `mapstructure:"capture_model_context"`
+ // PeerUser records each event under the account the beacon_peer processor resolved; set only
+ // together with that processor in the pipeline. See beaconevent.Options.PeerUser.
+ PeerUser bool `mapstructure:"peer_user"`
}
func createDefaultConfig() *Config {
diff --git a/collector-builder/exporter/beaconjsonexporter/exporter.go b/collector-builder/exporter/beaconjsonexporter/exporter.go
index fd51463f..5ab6acb7 100644
--- a/collector-builder/exporter/beaconjsonexporter/exporter.go
+++ b/collector-builder/exporter/beaconjsonexporter/exporter.go
@@ -86,6 +86,7 @@ func newExporter(raw component.Config, set exporter.Settings) (*beaconExporter,
IncludeRuntimeMetrics: cfg.IncludeRuntimeMetrics,
IncludeCodexSpans: cfg.IncludeCodexSpans,
CaptureModelContext: cfg.CaptureModelContext,
+ PeerUser: cfg.PeerUser,
CodexSurfaces: codexSurfaces,
}),
}, nil
@@ -234,6 +235,7 @@ func (e *beaconExporter) eventConverter() beaconevent.Converter {
IncludeRuntimeMetrics: e.cfg.IncludeRuntimeMetrics,
IncludeCodexSpans: e.cfg.IncludeCodexSpans,
CaptureModelContext: e.cfg.CaptureModelContext,
+ PeerUser: e.cfg.PeerUser,
CodexSurfaces: e.codexSurfaces,
})
}
diff --git a/collector-builder/exporter/beaconjsonexporter/go.mod b/collector-builder/exporter/beaconjsonexporter/go.mod
index d47d3397..6df606b7 100644
--- a/collector-builder/exporter/beaconjsonexporter/go.mod
+++ b/collector-builder/exporter/beaconjsonexporter/go.mod
@@ -6,17 +6,26 @@ toolchain go1.27.3
require (
github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve v0.0.0
+ go.opentelemetry.io/collector/client v1.27.0
go.opentelemetry.io/collector/component v1.27.0
go.opentelemetry.io/collector/component/componentstatus v0.121.0
+ go.opentelemetry.io/collector/component/componenttest v0.121.0
+ go.opentelemetry.io/collector/config/confighttp v0.121.0
go.opentelemetry.io/collector/config/configretry v1.27.0
go.opentelemetry.io/collector/consumer v1.27.0
+ go.opentelemetry.io/collector/consumer/consumererror v0.121.0
go.opentelemetry.io/collector/consumer/consumertest v0.121.0
go.opentelemetry.io/collector/exporter v0.121.0
go.opentelemetry.io/collector/extension v1.27.0
go.opentelemetry.io/collector/pdata v1.27.0
go.opentelemetry.io/collector/processor v0.121.0
go.opentelemetry.io/collector/processor/processortest v0.121.0
+ go.opentelemetry.io/collector/receiver v0.121.0
+ go.opentelemetry.io/collector/receiver/receivertest v0.121.0
go.uber.org/zap v1.27.0
+ golang.org/x/sys v0.49.0
+ google.golang.org/grpc v1.83.2
+ google.golang.org/protobuf v1.36.11
)
replace github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve => ../../../pkg/asymptoteobserve
@@ -26,13 +35,17 @@ require (
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
+ github.com/felixge/httpsnoop v1.0.4 // indirect
+ github.com/fsnotify/fsnotify v1.8.0 // indirect
github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
+ github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/go-version v1.7.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
+ github.com/klauspost/compress v1.18.0 // indirect
github.com/knadh/koanf/maps v0.1.1 // indirect
github.com/knadh/koanf/providers/confmap v0.1.0 // indirect
github.com/knadh/koanf/v2 v2.1.2 // indirect
@@ -40,19 +53,26 @@ require (
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
+ github.com/pierrec/lz4/v4 v4.1.22 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
+ github.com/rs/cors v1.11.1 // indirect
github.com/stretchr/testify v1.11.1 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
- go.opentelemetry.io/collector/component/componenttest v0.121.0 // indirect
+ go.opentelemetry.io/collector/config/configauth v0.121.0 // indirect
+ go.opentelemetry.io/collector/config/configcompression v1.27.0 // indirect
+ go.opentelemetry.io/collector/config/configopaque v1.27.0 // indirect
+ go.opentelemetry.io/collector/config/configtls v1.27.0 // indirect
go.opentelemetry.io/collector/confmap v1.27.0 // indirect
- go.opentelemetry.io/collector/consumer/consumererror v0.121.0 // indirect
go.opentelemetry.io/collector/consumer/xconsumer v0.121.0 // indirect
+ go.opentelemetry.io/collector/extension/extensionauth v0.121.0 // indirect
go.opentelemetry.io/collector/extension/xextension v0.121.0 // indirect
go.opentelemetry.io/collector/featuregate v1.27.0 // indirect
go.opentelemetry.io/collector/pdata/pprofile v0.121.0 // indirect
go.opentelemetry.io/collector/pdata/testdata v0.121.0 // indirect
go.opentelemetry.io/collector/pipeline v0.121.0 // indirect
go.opentelemetry.io/collector/processor/xprocessor v0.121.0 // indirect
+ go.opentelemetry.io/collector/receiver/xreceiver v0.121.0 // indirect
+ go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect
go.opentelemetry.io/otel v1.45.0 // indirect
go.opentelemetry.io/otel/metric v1.45.0 // indirect
go.opentelemetry.io/otel/sdk v1.45.0 // indirect
@@ -60,10 +80,7 @@ require (
go.opentelemetry.io/otel/trace v1.45.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/net v0.61.0 // indirect
- golang.org/x/sys v0.49.0 // indirect
golang.org/x/text v0.43.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
- google.golang.org/grpc v1.83.2 // indirect
- google.golang.org/protobuf v1.36.11 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
diff --git a/collector-builder/exporter/beaconjsonexporter/go.sum b/collector-builder/exporter/beaconjsonexporter/go.sum
index f19aadf6..74f59c3f 100644
--- a/collector-builder/exporter/beaconjsonexporter/go.sum
+++ b/collector-builder/exporter/beaconjsonexporter/go.sum
@@ -1,5 +1,9 @@
+cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs=
+cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
+github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ=
+github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
@@ -7,6 +11,10 @@ github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XL
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
+github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
+github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
+github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
@@ -18,6 +26,10 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
+github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
+github.com/google/cel-go v0.30.0 h1:ll54AkzKunWkBn9wSoiUXbFZXYZTkdJGNXTBXUoolGo=
+github.com/google/cel-go v0.30.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
@@ -29,6 +41,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
+github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
+github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
github.com/knadh/koanf/maps v0.1.1 h1:G5TjmUh2D7G2YWf5SQQqSiHRJEjaicvU0KpypqB3NIs=
github.com/knadh/koanf/maps v0.1.1/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=
github.com/knadh/koanf/providers/confmap v0.1.0 h1:gOkxhHkemwG4LezxxN8DMOFopOPghxRVp7JbIvdvqzU=
@@ -48,10 +62,14 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIU=
+github.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
+github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
+github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
@@ -60,14 +78,26 @@ github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/collector/client v1.27.0 h1:ClA1mY+/hoESIWdsd0aU383okG8weAluTzQEr3rolCg=
+go.opentelemetry.io/collector/client v1.27.0/go.mod h1:u8bkisWvtwsicvYh+7pXr2rmBWoa3rZFziKu2x2yXq4=
go.opentelemetry.io/collector/component v1.27.0 h1:6wk0K23YT9lSprX8BH9x5w8ssAORE109ekH/ix2S614=
go.opentelemetry.io/collector/component v1.27.0/go.mod h1:fIyBHoa7vDyZL3Pcidgy45cx24tBe7iHWne097blGgo=
go.opentelemetry.io/collector/component/componentstatus v0.121.0 h1:G4KqBUuAqnQ1kB3fUxXPwspjwnhGZzdArlO7vc343og=
go.opentelemetry.io/collector/component/componentstatus v0.121.0/go.mod h1:ufRv8q15XNdbr9nNzdepMHlLl2aC3NHQgecCzp5VRns=
go.opentelemetry.io/collector/component/componenttest v0.121.0 h1:4q1/7WnP9LPKaY4HAd8/OkzhllZpRACKAOlWsqbrzqc=
go.opentelemetry.io/collector/component/componenttest v0.121.0/go.mod h1:H7bEXDPMYNeWcHal0xyKlVfRPByVxale7hCJ+Myjq3Q=
+go.opentelemetry.io/collector/config/configauth v0.121.0 h1:96+mrHCNnTiAyZI+hvp4Rn8JOgQusO5sYd5/ED78LP4=
+go.opentelemetry.io/collector/config/configauth v0.121.0/go.mod h1:jUjtq1xolk/w+J3fzbvPEak2sr07ZLFdLn0miJ5ACP4=
+go.opentelemetry.io/collector/config/configcompression v1.27.0 h1:IlLCId4T3ADrj3bM1H7BTB26qwYEYV/5wLIWh71Zpqs=
+go.opentelemetry.io/collector/config/configcompression v1.27.0/go.mod h1:QwbNpaOl6Me+wd0EdFuEJg0Cc+WR42HNjJtdq4TwE6w=
+go.opentelemetry.io/collector/config/confighttp v0.121.0 h1:EgauuACOHrygbaosC/W9unKrlG3gOxiif2yA18W5ChM=
+go.opentelemetry.io/collector/config/confighttp v0.121.0/go.mod h1:SFv+5S9KFNDSe++ZFsJnyerXpcd0AAZ1FtOV/7mDdZU=
+go.opentelemetry.io/collector/config/configopaque v1.27.0 h1:MuUKdcmB3vbxXnzi++G18eLkJq3AtzKBrfIPGhmfwl4=
+go.opentelemetry.io/collector/config/configopaque v1.27.0/go.mod h1:GYQiC8IejBcwE8z0O4DwbBR/Hf6U7d8DTf+cszyqwFs=
go.opentelemetry.io/collector/config/configretry v1.27.0 h1:mM0X/7eiWRVmYTZJ5QTtly10uJWHnctIFuYST6tc/zU=
go.opentelemetry.io/collector/config/configretry v1.27.0/go.mod h1:8gzFQ0qzKLYvzP2sNPwsB9gwzKSEls649yANmt/d6yE=
+go.opentelemetry.io/collector/config/configtls v1.27.0 h1:NqU91J5yRIs5hwUEZBDTmG7XnsLZGS6JpedxgY00srg=
+go.opentelemetry.io/collector/config/configtls v1.27.0/go.mod h1:i6kX7oboR1sO+J+hDImtKH4GnNCFiwcTAr2fzGRP0kI=
go.opentelemetry.io/collector/confmap v1.27.0 h1:OIjPcjij1NxkVQsQVmHro4+t1eYNFiUGib9+J9YBZhM=
go.opentelemetry.io/collector/confmap v1.27.0/go.mod h1:tmOa6iw3FJsEgfBHKALqvcdfRtf71JZGor0wSM5MoH8=
go.opentelemetry.io/collector/consumer v1.27.0 h1:JoXdoCeFDJG3d9TYrKHvTT4eBhzKXDVTkWW5mDfnLiY=
@@ -86,6 +116,10 @@ go.opentelemetry.io/collector/exporter/xexporter v0.121.0 h1:e5QIl51EutJrH8X4tfn
go.opentelemetry.io/collector/exporter/xexporter v0.121.0/go.mod h1:PGrW5pOQkNpaz8xqtkITCNEkcJVxOHSptg2chVTtv+o=
go.opentelemetry.io/collector/extension v1.27.0 h1:7F+O8/+bcwo3Zk3B/+H8A75cz9dhqXUrbeiyiFajoy4=
go.opentelemetry.io/collector/extension v1.27.0/go.mod h1:Fe0nUGMcr0c6IIBD3QEa3XmdUYpfmm5wCjc3PYho8DM=
+go.opentelemetry.io/collector/extension/extensionauth v0.121.0 h1:LmPwZI7+OSpE4/ojGqqTU9Onxvn7Nd4JEN+YxBE5BJg=
+go.opentelemetry.io/collector/extension/extensionauth v0.121.0/go.mod h1:sINEH4b4YPSQJtvc/qcYTQdNRglDoKK0BUJqR+EHn94=
+go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest v0.121.0 h1:ghfRACcBN0NaTdLOTa25d+sEOsIgvP5flzqEQcfLBYM=
+go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest v0.121.0/go.mod h1:5jAEucvzRjZ4MurcznqdaNh467KeXti0+ldkPLZmw8Y=
go.opentelemetry.io/collector/extension/extensiontest v0.121.0 h1:ce3IEWXBDOOSljd0niVbwHs7AhC8hOjC2RXGIoMOXog=
go.opentelemetry.io/collector/extension/extensiontest v0.121.0/go.mod h1:yrZhZhf2a3aD0/17drjHnzSTlr0XnNREVrOLYBlcP1o=
go.opentelemetry.io/collector/extension/xextension v0.121.0 h1:RIhFXwm9+2sc6H2PsM9asGfEBlIDBrK+dyyFMx257bs=
@@ -112,6 +146,8 @@ go.opentelemetry.io/collector/receiver/receivertest v0.121.0 h1:kdwV0tkaawRwKoZ1
go.opentelemetry.io/collector/receiver/receivertest v0.121.0/go.mod h1:H7N4CLG4J8Do3NWeo9gj7VmJCtDstDeeCffPBgHu1WQ=
go.opentelemetry.io/collector/receiver/xreceiver v0.121.0 h1:F6IVdEArgicLVtDtZ2Ovmjv8o6+3AyxYaC3HdNIbakM=
go.opentelemetry.io/collector/receiver/xreceiver v0.121.0/go.mod h1:ZsI1dzGq9J8y0f8h8MYYnoyC8SRJ5u1OqVRX2EwdZwo=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus=
+go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q=
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
@@ -130,9 +166,13 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA=
+golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
@@ -163,6 +203,8 @@ golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8T
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
+google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8=
+google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU=
@@ -176,3 +218,5 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
+mvdan.cc/sh/v3 v3.14.1 h1:bXkhQWNHCs0KZEChF8hYS6FC+T2N9mUZLbQv9blditI=
+mvdan.cc/sh/v3 v3.14.1/go.mod h1:syYCoFET8w9tvevxiXUtY8/ICrU+l26jHmhJDra3Vwo=
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names.go
similarity index 82%
rename from collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go
rename to collector-builder/exporter/beaconjsonexporter/internal/accountname/names.go
index 97017e5a..8eb3adcd 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names.go
@@ -1,4 +1,4 @@
-package beaconingestextension
+package accountname
import (
"sync"
@@ -17,12 +17,12 @@ const (
nameCacheTTL = 10 * time.Minute
)
-// nameCache resolves the account name stamped on each event from the peer's account: a uid on
-// Unix, a SID on Windows (see resolveName for each). At most one lookup per account runs at a time:
+// Cache resolves the account name stamped on each event from the peer's account: a uid on
+// Unix, a SID on Windows (see Resolve for each). At most one lookup per account runs at a time:
// connections that arrive while it runs wait on that one, and one that outlasts the wait still
// fills the cache when it returns, so a slow directory service leaves the account unnamed only
// until it answers rather than for nameCacheTTL.
-type nameCache struct {
+type Cache struct {
mu sync.Mutex
entries map[string]nameEntry
pending map[string]chan struct{}
@@ -36,17 +36,17 @@ type nameEntry struct {
expires time.Time
}
-func newNameCache() *nameCache {
- return &nameCache{
+func NewCache() *Cache {
+ return &Cache{
entries: map[string]nameEntry{},
pending: map[string]chan struct{}{},
now: time.Now,
wait: nameLookupTimeout,
- lookup1: resolveName,
+ lookup1: Resolve,
}
}
-func (c *nameCache) lookup(uid string) string {
+func (c *Cache) Lookup(uid string) string {
c.mu.Lock()
if entry, ok := c.entries[uid]; ok && c.now().Before(entry.expires) {
c.mu.Unlock()
@@ -79,9 +79,9 @@ func (c *nameCache) lookup(uid string) string {
return c.entries[uid].name
}
-// validName accepts what an account name can be and nothing that could disturb a log line or a
+// ValidName accepts what an account name can be and nothing that could disturb a log line or a
// reader: no control characters or whitespace, bounded length.
-func validName(name string) bool {
+func ValidName(name string) bool {
if name == "" || len(name) > 256 {
return false
}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_test.go
similarity index 75%
rename from collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go
rename to collector-builder/exporter/beaconjsonexporter/internal/accountname/names_test.go
index f0b40d31..e040d818 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_test.go
@@ -1,4 +1,4 @@
-package beaconingestextension
+package accountname
import (
"os"
@@ -12,12 +12,12 @@ import (
func TestNameCacheReusesAndExpires(t *testing.T) {
now := time.Unix(0, 0)
calls := 0
- c := newNameCache()
+ c := NewCache()
c.now = func() time.Time { return now }
c.lookup1 = func(uid string) string { calls++; return "alice" }
for i := 0; i < 5; i++ {
- if got := c.lookup("501"); got != "alice" {
+ if got := c.Lookup("501"); got != "alice" {
t.Fatalf("lookup = %q", got)
}
}
@@ -25,7 +25,7 @@ func TestNameCacheReusesAndExpires(t *testing.T) {
t.Fatalf("resolved %d times within the TTL, want 1", calls)
}
now = now.Add(nameCacheTTL + time.Second)
- _ = c.lookup("501")
+ _ = c.Lookup("501")
if calls != 2 {
t.Fatalf("resolved %d times after the TTL, want 2", calls)
}
@@ -34,18 +34,18 @@ func TestNameCacheReusesAndExpires(t *testing.T) {
func TestNameCacheRetriesAMissAfterTheTTL(t *testing.T) {
now := time.Unix(0, 0)
answer := ""
- c := newNameCache()
+ c := NewCache()
c.now = func() time.Time { return now }
c.lookup1 = func(string) string { return answer }
- if got := c.lookup("7"); got != "" {
+ if got := c.Lookup("7"); got != "" {
t.Fatalf("lookup = %q", got)
}
answer = "bob"
- if got := c.lookup("7"); got != "" {
+ if got := c.Lookup("7"); got != "" {
t.Fatalf("a miss was retried within the TTL: %q", got)
}
now = now.Add(nameCacheTTL + time.Second)
- if got := c.lookup("7"); got != "bob" {
+ if got := c.Lookup("7"); got != "bob" {
t.Fatalf("a miss was not retried after the TTL: %q", got)
}
}
@@ -56,18 +56,18 @@ func TestNameCacheRetriesAMissAfterTheTTL(t *testing.T) {
func TestNameCacheKeepsALateAnswer(t *testing.T) {
release := make(chan struct{})
calls := 0
- c := newNameCache()
+ c := NewCache()
c.wait = 20 * time.Millisecond
c.lookup1 = func(string) string { calls++; <-release; return `CONTOSO\late` }
for i := 0; i < 3; i++ {
- if got := c.lookup("S-1-5-21-1"); got != "" {
+ if got := c.Lookup("S-1-5-21-1"); got != "" {
t.Fatalf("lookup %d = %q before the directory answered", i, got)
}
}
close(release)
deadline := time.Now().Add(5 * time.Second)
for {
- if got := c.lookup("S-1-5-21-1"); got == `CONTOSO\late` {
+ if got := c.Lookup("S-1-5-21-1"); got == `CONTOSO\late` {
break
}
if time.Now().After(deadline) {
@@ -88,26 +88,26 @@ func TestResolveNameFindsTheCurrentAccount(t *testing.T) {
if err != nil {
t.Skip(err)
}
- if got := resolveName(strconv.Itoa(os.Geteuid())); got != me.Username {
- t.Fatalf("resolveName = %q, want %q", got, me.Username)
+ if got := Resolve(strconv.Itoa(os.Geteuid())); got != me.Username {
+ t.Fatalf("Resolve = %q, want %q", got, me.Username)
}
}
func TestResolveNameOfAnUnknownUID(t *testing.T) {
- if got := resolveName("4294967000"); got != "" {
- t.Fatalf("resolveName of an unused uid = %q, want empty", got)
+ if got := Resolve("4294967000"); got != "" {
+ t.Fatalf("Resolve of an unused uid = %q, want empty", got)
}
}
func TestValidName(t *testing.T) {
for _, ok := range []string{"alice", "j.doe", "DOMAIN\\bob", "[email protected]", "_svc"} {
- if !validName(ok) {
- t.Errorf("validName(%q) = false", ok)
+ if !ValidName(ok) {
+ t.Errorf("ValidName(%q) = false", ok)
}
}
for _, bad := range []string{"", "a b", "tab\there", "nl\nx", "esc\x1b[31m", "del\x7f", string(make([]byte, 257))} {
- if validName(bad) {
- t.Errorf("validName(%q) = true", bad)
+ if ValidName(bad) {
+ t.Errorf("ValidName(%q) = true", bad)
}
}
}
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_unix.go b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_unix.go
similarity index 79%
rename from collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_unix.go
rename to collector-builder/exporter/beaconjsonexporter/internal/accountname/names_unix.go
index 4e13050d..d71d146f 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_unix.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_unix.go
@@ -1,6 +1,6 @@
//go:build !windows
-package beaconingestextension
+package accountname
import (
"context"
@@ -10,7 +10,7 @@ import (
"strings"
)
-// resolveName names a uid. The collector is built with CGO_ENABLED=0, whose os/user reads /etc/passwd and never asks NSS or
+// Resolve names a uid. The collector is built with CGO_ENABLED=0, whose os/user reads /etc/passwd and never asks NSS or
// Directory Services, so accounts from LDAP, SSSD, AD or macOS's own directory would come back
// unnamed. `id -nu <uid>` asks the system's own resolver on both Linux and macOS and is the
// fallback.
@@ -29,8 +29,8 @@ func firstExecutable(paths []string) string {
return ""
}
-func resolveName(id string) string {
- if u, err := user.LookupId(id); err == nil && validName(u.Username) {
+func Resolve(id string) string {
+ if u, err := user.LookupId(id); err == nil && ValidName(u.Username) {
return u.Username
}
// id(1) is tried once: on merged-/usr systems both paths are the same binary, and running it
@@ -45,7 +45,7 @@ func resolveName(id string) string {
if err != nil {
return ""
}
- if name := strings.TrimSpace(string(out)); validName(name) {
+ if name := strings.TrimSpace(string(out)); ValidName(name) {
return name
}
return ""
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_unix_test.go b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_unix_test.go
similarity index 94%
rename from collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_unix_test.go
rename to collector-builder/exporter/beaconjsonexporter/internal/accountname/names_unix_test.go
index 5aec5bc3..3bedce5f 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_unix_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_unix_test.go
@@ -1,6 +1,6 @@
//go:build !windows
-package beaconingestextension
+package accountname
import (
"os"
diff --git a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_windows.go b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_windows.go
similarity index 80%
rename from collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_windows.go
rename to collector-builder/exporter/beaconjsonexporter/internal/accountname/names_windows.go
index 69998594..46971701 100644
--- a/collector-builder/exporter/beaconjsonexporter/beaconingestextension/names_windows.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_windows.go
@@ -1,6 +1,6 @@
//go:build windows
-package beaconingestextension
+package accountname
import (
"strings"
@@ -8,11 +8,11 @@ import (
"golang.org/x/sys/windows"
)
-// resolveName names a SID: DOMAIN\user, the form Windows hooks write to user.name. It asks
+// Resolve names a SID: DOMAIN\user, the form Windows hooks write to user.name. It asks
// LookupAccountSid, which consults a domain controller on a domain-joined machine and can wait on
-// one that does not answer; nameCache bounds how long a connection waits for it. Windows has no
+// one that does not answer; Cache bounds how long a connection waits for it. Windows has no
// id(1) to fall back to.
-func resolveName(sid string) string {
+func Resolve(sid string) string {
name, err := lookupAccount(sid)
if err != nil || !validWindowsName(name) {
return ""
@@ -39,7 +39,7 @@ var lookupAccount = func(sid string) (string, error) {
return domain + `\` + account, nil
}
-// validWindowsName is validName with spaces allowed inside the name, as Windows account names
+// validWindowsName is ValidName with spaces allowed inside the name, as Windows account names
// allow them ("CONTOSO\Jane Doe"); still no control characters, nothing at either end, bounded.
func validWindowsName(name string) bool {
if name == "" || len(name) > 256 || strings.TrimSpace(name) != name {
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_windows_test.go b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_windows_test.go
new file mode 100644
index 00000000..50d5ab96
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/accountname/names_windows_test.go
@@ -0,0 +1,56 @@
+//go:build windows
+
+package accountname
+
+import (
+ "os/user"
+ "testing"
+
+ "golang.org/x/sys/windows"
+)
+
+func currentSID(t *testing.T) string {
+ t.Helper()
+ u, err := windows.GetCurrentProcessToken().GetTokenUser()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return u.User.Sid.String()
+}
+
+func TestResolveNameNamesTheCurrentAccount(t *testing.T) {
+ me, err := user.Current()
+ if err != nil {
+ t.Skip(err)
+ }
+ if got := Resolve(currentSID(t)); got != me.Username {
+ t.Fatalf("resolveName = %q, want %q", got, me.Username)
+ }
+ if got := Resolve("S-1-5-21-1-2-3-999999"); got != "" {
+ t.Fatalf("resolveName of an unknown SID = %q", got)
+ }
+}
+
+// Accounts that are not SidTypeUser are named too. os/user refused them, which would have left
+// events from SYSTEM, a service's virtual account or an Entra ID account without a name.
+func TestResolveNameNamesAccountsThatAreNotLocalUsers(t *testing.T) {
+ if got := Resolve("S-1-5-18"); got != `NT AUTHORITY\SYSTEM` {
+ t.Fatalf("Resolve(SYSTEM) = %q", got)
+ }
+ if got := Resolve("not a sid"); got != "" {
+ t.Fatalf("resolveName of a malformed SID = %q", got)
+ }
+}
+
+func TestValidWindowsName(t *testing.T) {
+ for _, ok := range []string{`CONTOSO\Jane Doe`, `DESKTOP-1\runneradmin`, `NT AUTHORITY\SYSTEM`} {
+ if !validWindowsName(ok) {
+ t.Errorf("validWindowsName(%q) = false", ok)
+ }
+ }
+ for _, bad := range []string{"", " lead", "trail ", "nl\nx", "esc\x1b[31m", "del\x7f", string(make([]byte, 257))} {
+ if validWindowsName(bad) {
+ t.Errorf("validWindowsName(%q) = true", bad)
+ }
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
index b2c6db7f..91cc7ade 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
@@ -95,8 +95,20 @@ type Options struct {
// CodexSurfaces remembers which Codex surface (CLI or desktop app) each conversation runs in,
// for records that don't say (see codex_surface.go). Nil places each record on its own.
CodexSurfaces *CodexSurfaces
+ // PeerUser takes each event's user from the PeerUIDAttribute and PeerUserAttribute resource
+ // attributes. Only a collector whose pipeline runs the beacon_peer processor sets it: that
+ // processor removes whatever a sender put under those names and writes the account the kernel
+ // says owns the sending socket, so without it the attributes are only what the sender claimed.
+ PeerUser bool
}
+const (
+ // PeerUIDAttribute and PeerUserAttribute are the resource attributes the beacon_peer processor
+ // writes: the account id that owns the client socket an export arrived on, and its name.
+ PeerUIDAttribute = "beacon.peer.uid"
+ PeerUserAttribute = "beacon.peer.user"
+)
+
type Converter struct {
opts Options
}
@@ -1179,6 +1191,7 @@ func ApplyTokenUsage(event *Event, tokenType string, value int64) {
func (c Converter) PopulateCommon(event *Event, attrs map[string]interface{}) {
populateRunContext(event, attrs)
+ c.applyPeerUser(event, attrs)
// A runtime that numbers its own telemetry gets that number preserved; the exporter
// stamps its own emission counter for everything else (see beaconExporter.
// stampSequence). Zero and negative values are ignored -- zero is the schema's
@@ -2339,3 +2352,25 @@ func EventCategory(action, explicit string) string {
return ""
}
}
+
+// applyPeerUser records the account that sent an export in place of the collector's own.
+//
+// Without it every OTLP event carries the collector process's account, which on a system install
+// is root for everyone: a prompt typed by one person on a shared machine reads as root's. The
+// beacon_peer processor resolves the sender from the kernel; this only copies what it found, and
+// changes nothing when it found nobody, so an unattributed event is the collector's account as it
+// always was rather than someone's guess. Runtime-specific identities (Claude Cowork's cloud user)
+// are applied after this and still win.
+func (c Converter) applyPeerUser(event *Event, attrs map[string]interface{}) {
+ if !c.opts.PeerUser {
+ return
+ }
+ uid := FirstString(attrs, PeerUIDAttribute)
+ if uid == "" {
+ return
+ }
+ event.User.UID = uid
+ // An account the system cannot name is still recorded by its id, rather than keeping the
+ // collector's name beside someone else's uid.
+ event.User.Name = FirstString(attrs, PeerUserAttribute)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go
new file mode 100644
index 00000000..395790a0
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/peer_user_test.go
@@ -0,0 +1,74 @@
+package beaconevent
+
+import (
+ "testing"
+
+ "go.opentelemetry.io/collector/pdata/plog"
+ "go.opentelemetry.io/collector/pdata/ptrace"
+)
+
+func peerLog(service string) (map[string]interface{}, plog.LogRecord) {
+ resource := map[string]interface{}{
+ "service.name": service,
+ PeerUIDAttribute: "1001",
+ PeerUserAttribute: "alice",
+ }
+ record := plog.NewLogRecord()
+ record.Body().SetStr("hello")
+ record.Attributes().PutStr("event.name", "user_prompt")
+ return resource, record
+}
+
+// With the processor in the pipeline, the account the kernel named replaces the collector's own.
+func TestPeerUserNamesTheSendingAccount(t *testing.T) {
+ t.Setenv("USER", "root")
+ t.Setenv("UID", "0")
+ resource, record := peerLog("chatgpt_web")
+ event := NewConverter(Options{PeerUser: true}).EventFromLog(resource, record)
+ if event.User.Name != "alice" || event.User.UID != "1001" {
+ t.Fatalf("user = %+v, want alice/1001", event.User)
+ }
+
+ span := ptrace.NewSpan()
+ span.SetName("tool")
+ if got := NewConverter(Options{PeerUser: true}).EventFromSpan(resource, span).User; got.Name != "alice" || got.UID != "1001" {
+ t.Fatalf("span user = %+v, want alice/1001", got)
+ }
+}
+
+// Without the processor the attributes are only what the sender wrote, so they are ignored.
+func TestPeerUserIsIgnoredUnlessConfigured(t *testing.T) {
+ t.Setenv("USER", "root")
+ t.Setenv("UID", "0")
+ resource, record := peerLog("chatgpt_web")
+ event := NewConverter(Options{}).EventFromLog(resource, record)
+ if event.User.Name != "root" || event.User.UID != "0" {
+ t.Fatalf("user = %+v, want the collector's own account", event.User)
+ }
+}
+
+// An account the system cannot name is recorded by id alone, never beside the collector's name.
+func TestPeerUserWithoutANameKeepsOnlyTheID(t *testing.T) {
+ t.Setenv("USER", "root")
+ resource, record := peerLog("chatgpt_web")
+ delete(resource, PeerUserAttribute)
+ event := NewConverter(Options{PeerUser: true}).EventFromLog(resource, record)
+ if event.User.Name != "" || event.User.UID != "1001" {
+ t.Fatalf("user = %+v, want uid 1001 and no name", event.User)
+ }
+}
+
+// A runtime that reports its own cloud identity (Claude Cowork) keeps it: the sender's local account
+// is the desktop app's, not the person's.
+func TestCoworkIdentityStillWinsOverThePeer(t *testing.T) {
+ resource, record := peerLog("claude-cowork")
+ resource["cowork.surface"] = "desktop"
+ record.Attributes().PutStr("user.email", "[email protected]")
+ event := NewConverter(Options{PeerUser: true}).EventFromLog(resource, record)
+ if event.Harness.Name != "claude_cowork" {
+ t.Skipf("fixture did not resolve to claude_cowork (%q)", event.Harness.Name)
+ }
+ if event.User.Name != "[email protected]" {
+ t.Fatalf("user = %+v, want the Cowork identity", event.User)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go
new file mode 100644
index 00000000..971ffb78
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred.go
@@ -0,0 +1,43 @@
+// Package peercred names the local account that owns the client end of a loopback TCP connection.
+//
+// The collector's OTLP receivers listen on 127.0.0.1, and every account on the machine exports to
+// them. OTLP itself carries no trustworthy identity: a resource attribute is whatever the sender
+// wrote. The kernel, though, records which account created each socket, so for a connection that
+// is still open the account on its client end is known without asking the client. This is the
+// same answer an ident server gives, read locally.
+//
+// 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.
+package peercred
+
+import (
+ "errors"
+ "net"
+)
+
+var (
+ // ErrUnsupported is returned where the platform offers no lookup this package implements.
+ ErrUnsupported = errors.New("peer account lookup is not supported on this platform")
+ // ErrNotFound is returned when no open socket matches the address, which includes a client
+ // that has already closed its end.
+ ErrNotFound = errors.New("no open local socket for this address")
+ // ErrAmbiguous is returned when more than one open socket matches with different owners, so no
+ // single account can be named.
+ ErrAmbiguous = errors.New("more than one local socket with different owners for this address")
+ // ErrNotLoopback is returned for an address that is not a loopback one: only a connection made
+ // on this machine has its client socket here to read.
+ ErrNotLoopback = errors.New("not a loopback address")
+)
+
+// UID returns the account id, as a decimal string, that owns the client socket bound to client: the
+// remote address of a connection the collector accepted.
+func UID(client *net.TCPAddr) (string, error) {
+ if client == nil || client.Port <= 0 || client.Port > 65535 {
+ return "", ErrNotFound
+ }
+ if !client.IP.IsLoopback() {
+ return "", ErrNotLoopback
+ }
+ return lookupUID(client)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go
new file mode 100644
index 00000000..6e752be0
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux.go
@@ -0,0 +1,127 @@
+//go:build linux
+
+package peercred
+
+import (
+ "bufio"
+ "encoding/binary"
+ "fmt"
+ "io"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+// procNet is where the socket tables are read. A var so tests can point it at fixtures.
+var procNet = "/proc/net"
+
+// lookupUID finds the client socket in the kernel's TCP tables.
+//
+// /proc/net/tcp and tcp6 list every socket in this network namespace, one per line:
+//
+// sl local_address rem_address st tx_queue:rx_queue tr:tm->when retrnsmt uid timeout inode
+// 0: 0100007F:B5D2 0100007F:10E6 01 00000000:00000000 00:00000000 00000000 1001 0 81234
+//
+// The client end of a loopback connection is the line whose local address is the address the
+// collector saw as remote, and its uid column is the account that created that socket (sk_uid,
+// fixed at creation). The table is world-readable, so this needs no privilege beyond the
+// collector's own, and it reads the namespace the collector listens in, which is the one a
+// loopback client must share.
+//
+// Three cases are refused rather than guessed. A line with inode 0 is a socket in TIME_WAIT or
+// otherwise orphaned: the kernel prints uid 0 for those, which would name root for a client that
+// has gone. Two matching lines with different uids cannot both be the client. And no match at all
+// means the client closed before the lookup, which a sender could do deliberately; the event is
+// then left unattributed, never attributed to whoever else is connected.
+func lookupUID(client *net.TCPAddr) (string, error) {
+ want := map[string]bool{}
+ if ip4 := client.IP.To4(); ip4 != nil {
+ want[procAddr4(ip4, client.Port)] = true
+ // A dual-stack listener sees an IPv4 client as ::ffff:a.b.c.d in tcp6.
+ want[procAddr6(net.IP(append(net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff}, ip4...)), client.Port)] = true
+ } else {
+ want[procAddr6(client.IP.To16(), client.Port)] = true
+ }
+ found := ""
+ for _, table := range []string{"tcp", "tcp6"} {
+ f, err := os.Open(filepath.Join(procNet, table))
+ if err != nil {
+ continue
+ }
+ uid, err := scanTable(f, want)
+ _ = f.Close()
+ switch {
+ case err == ErrNotFound:
+ continue
+ case err != nil:
+ return "", err
+ case found != "" && found != uid:
+ return "", ErrAmbiguous
+ }
+ found = uid
+ }
+ if found == "" {
+ return "", ErrNotFound
+ }
+ return found, nil
+}
+
+func scanTable(r io.Reader, want map[string]bool) (string, error) {
+ scanner := bufio.NewScanner(r)
+ found := ""
+ for scanner.Scan() {
+ fields := strings.Fields(scanner.Text())
+ // sl, local, remote, st, queues, timer, retransmits, uid, timeout, inode
+ if len(fields) < 10 || !want[strings.ToUpper(fields[1])] {
+ continue
+ }
+ if fields[9] == "0" {
+ // TIME_WAIT and orphans: the uid column is 0 for them whoever made the socket.
+ return "", ErrNotFound
+ }
+ uid := fields[7]
+ if !isDecimal(uid) {
+ continue
+ }
+ if found != "" && found != uid {
+ return "", ErrAmbiguous
+ }
+ found = uid
+ }
+ if err := scanner.Err(); err != nil {
+ return "", err
+ }
+ if found == "" {
+ return "", ErrNotFound
+ }
+ return found, nil
+}
+
+// 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 {
+ return fmt.Sprintf("%08X:%04X", binary.NativeEndian.Uint32(ip.To4()), port)
+}
+
+// procAddr6 is the IPv6 form: four 32-bit words, each in host byte order.
+func procAddr6(ip net.IP, port int) string {
+ ip = ip.To16()
+ var b strings.Builder
+ for i := 0; i < 16; i += 4 {
+ fmt.Fprintf(&b, "%08X", binary.NativeEndian.Uint32(ip[i:i+4]))
+ }
+ return fmt.Sprintf("%s:%04X", b.String(), port)
+}
+
+func isDecimal(s string) bool {
+ if s == "" {
+ return false
+ }
+ for _, r := range s {
+ if r < '0' || r > '9' {
+ return false
+ }
+ }
+ return true
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux_test.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux_test.go
new file mode 100644
index 00000000..498da146
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_linux_test.go
@@ -0,0 +1,174 @@
+//go:build linux
+
+package peercred
+
+import (
+ "errors"
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+)
+
+// The real thing: 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.
+func TestUIDNamesTheOwnerOfARealLoopbackConnection(t *testing.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()
+
+ uid, err := UID(server.RemoteAddr().(*net.TCPAddr))
+ if err != nil {
+ t.Fatalf("UID(%s) = %v", server.RemoteAddr(), err)
+ }
+ if want := strconv.Itoa(os.Geteuid()); uid != want {
+ t.Fatalf("UID = %s, want this process's %s", uid, want)
+ }
+ })
+ }
+}
+
+// Once the client has closed and the socket is gone or 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)
+ }
+ remote := server.RemoteAddr().(*net.TCPAddr)
+ // The server closes first, so the server's end takes TIME_WAIT; then the client's end closes
+ // with a reset so it leaves the table entirely.
+ _ = server.Close()
+ _ = client.(*net.TCPConn).SetLinger(0)
+ _ = client.Close()
+ if uid, err := UID(remote); err == nil {
+ t.Fatalf("UID of a closed client = %s, want unknown", uid)
+ }
+}
+
+func TestUIDRefusesWhatItCannotSee(t *testing.T) {
+ if _, err := UID(&net.TCPAddr{IP: net.ParseIP("10.1.2.3"), Port: 5000}); !errors.Is(err, ErrNotLoopback) {
+ t.Fatalf("remote address err = %v, want ErrNotLoopback", err)
+ }
+ for _, addr := range []*net.TCPAddr{nil, {IP: net.ParseIP("127.0.0.1")}, {IP: net.ParseIP("127.0.0.1"), Port: 70000}} {
+ if _, err := UID(addr); !errors.Is(err, ErrNotFound) {
+ t.Fatalf("UID(%v) err = %v, want ErrNotFound", addr, err)
+ }
+ }
+}
+
+// Fixtures in the kernel's own format: what systemd-era kernels print, with the address words in
+// host byte order (little-endian here, as on every platform Beacon packages).
+func TestScanTableFixtures(t *testing.T) {
+ dir := t.TempDir()
+ old := procNet
+ procNet = dir
+ t.Cleanup(func() { procNet = old })
+ header := " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n"
+ line := func(sl int, local, remote, st, uid, inode string) string {
+ return fmt.Sprintf("%4d: %s %s %s 00000000:00000000 00:00000000 00000000 %5s 0 %s 1 0000000000000000 20 4 30 10 -1\n", sl, local, remote, st, uid, inode)
+ }
+ client := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 0xB5D2}
+ write := func(tcp, tcp6 string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(dir, "tcp"), []byte(header+tcp), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "tcp6"), []byte(header+tcp6), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if procAddr4(client.IP, client.Port) != "0100007F:B5D2" {
+ t.Skipf("host byte order is not little-endian (%s); fixtures are written for it", procAddr4(client.IP, client.Port))
+ }
+
+ cases := []struct {
+ name, tcp, tcp6, want string
+ err error
+ }{
+ {
+ name: "client and server ends",
+ tcp: line(0, "0100007F:10E6", "00000000:0000", "0A", "0", "100") + // the collector listening
+ line(1, "0100007F:10E6", "0100007F:B5D2", "01", "0", "101") + // its end of the connection
+ line(2, "0100007F:B5D2", "0100007F:10E6", "01", "1001", "102"), // the client's end
+ want: "1001",
+ },
+ {
+ name: "lower-case hex still matches",
+ tcp: line(2, "0100007f:b5d2", "0100007f:10e6", "01", "1002", "102"),
+ want: "1002",
+ },
+ {
+ name: "time wait reads as gone, never as root",
+ tcp: line(2, "0100007F:B5D2", "0100007F:10E6", "06", "0", "0"),
+ err: ErrNotFound,
+ },
+ {
+ name: "two owners is ambiguous",
+ tcp: line(2, "0100007F:B5D2", "0100007F:10E6", "01", "1001", "102") +
+ line(3, "0100007F:B5D2", "0100007F:1F90", "01", "1002", "103"),
+ err: ErrAmbiguous,
+ },
+ {
+ name: "dual-stack listener sees the client in tcp6",
+ tcp6: line(0, "0000000000000000FFFF00000100007F:B5D2", "0000000000000000FFFF00000100007F:10E6", "01", "1003", "104"),
+ want: "1003",
+ },
+ {
+ name: "disagreeing tables are ambiguous",
+ tcp: line(2, "0100007F:B5D2", "0100007F:10E6", "01", "1001", "102"),
+ tcp6: line(0, "0000000000000000FFFF00000100007F:B5D2", "0000000000000000FFFF00000100007F:10E6", "01", "1003", "104"),
+ err: ErrAmbiguous,
+ },
+ {
+ name: "another port is not this client",
+ tcp: line(2, "0100007F:B5D3", "0100007F:10E6", "01", "1001", "102"),
+ err: ErrNotFound,
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ write(tc.tcp, tc.tcp6)
+ uid, err := UID(client)
+ if tc.err != nil {
+ if !errors.Is(err, tc.err) {
+ t.Fatalf("UID = %q, %v; want %v", uid, err, tc.err)
+ }
+ return
+ }
+ if err != nil || uid != tc.want {
+ t.Fatalf("UID = %q, %v; want %s", uid, err, tc.want)
+ }
+ })
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go
new file mode 100644
index 00000000..4a13906c
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/internal/peercred/peercred_other.go
@@ -0,0 +1,9 @@
+//go:build !linux
+
+package peercred
+
+import "net"
+
+func lookupUID(*net.TCPAddr) (string, error) {
+ return "", ErrUnsupported
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_linux_test.go b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_linux_test.go
new file mode 100644
index 00000000..cd9c2c59
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/peer_linux_test.go
@@ -0,0 +1,60 @@
+//go:build linux
+
+package otlphttpreceiver
+
+import (
+ "context"
+ "net/http"
+ "os"
+ "strconv"
+ "testing"
+
+ "go.opentelemetry.io/collector/component/componenttest"
+ "go.opentelemetry.io/collector/consumer/consumertest"
+ "go.opentelemetry.io/collector/processor/processortest"
+ "go.opentelemetry.io/collector/receiver/receivertest"
+
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/beaconevent"
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/peerprocessor"
+)
+
+// The whole chain on a real socket: an export over HTTP, through this receiver and beacon_peer,
+// comes out naming the account of the process that sent it, whatever it claimed.
+func TestAnHTTPExportIsAttributedToTheSendingAccount(t *testing.T) {
+ sink := new(consumertest.LogsSink)
+ pf := peerprocessor.NewFactory()
+ proc, err := pf.CreateLogs(context.Background(), processortest.NewNopSettings(pf.Type()), pf.CreateDefaultConfig(), sink)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f := NewFactory()
+ cfg := f.CreateDefaultConfig().(*Config)
+ cfg.Endpoint = "127.0.0.1:0"
+ r, err := f.CreateLogs(context.Background(), receivertest.NewNopSettings(componentType), cfg, proc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Start(context.Background(), componenttest.NewNopHost()); err != nil {
+ t.Fatal(err)
+ }
+ defer r.Shutdown(context.Background())
+
+ forged := `{"resourceLogs":[{"resource":{"attributes":[` +
+ `{"key":"service.name","value":{"stringValue":"chatgpt_web"}},` +
+ `{"key":"` + beaconevent.PeerUIDAttribute + `","value":{"stringValue":"4242"}}]},` +
+ `"scopeLogs":[{"logRecords":[{"body":{"stringValue":"hello"}}]}]}]}`
+ resp, _, _ := post(t, "http://"+r.(*otlpHTTP).addr.String()+"/v1/logs", "application/json", []byte(forged), nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d", resp.StatusCode)
+ }
+ if len(sink.AllLogs()) != 1 {
+ t.Fatalf("exports = %d", len(sink.AllLogs()))
+ }
+ uid, ok := sink.AllLogs()[0].ResourceLogs().At(0).Resource().Attributes().Get(beaconevent.PeerUIDAttribute)
+ if !ok {
+ t.Fatal("no peer uid recorded")
+ }
+ if want := strconv.Itoa(os.Geteuid()); 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
new file mode 100644
index 00000000..7f07c061
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver.go
@@ -0,0 +1,385 @@
+// Package otlphttpreceiver is the collector's OTLP/HTTP receiver, made to keep the sender's port.
+//
+// It serves exactly what the upstream otlp receiver's HTTP protocol serves (POST /v1/logs,
+// /v1/traces and /v1/metrics, protobuf or JSON, the same status codes and rpc.Status error bodies,
+// built on the same confighttp server with its decompression and size limits) with one difference.
+// The upstream receiver records the client's address in client.Info with the port dropped
+// (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.
+package otlphttpreceiver
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "mime"
+ "net"
+ "net/http"
+ "strconv"
+ "sync"
+
+ "go.opentelemetry.io/collector/client"
+ "go.opentelemetry.io/collector/component"
+ "go.opentelemetry.io/collector/component/componentstatus"
+ "go.opentelemetry.io/collector/config/confighttp"
+ "go.opentelemetry.io/collector/consumer"
+ "go.opentelemetry.io/collector/consumer/consumererror"
+ "go.opentelemetry.io/collector/pdata/plog/plogotlp"
+ "go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp"
+ "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
+ "go.opentelemetry.io/collector/receiver"
+ "go.uber.org/zap"
+ "google.golang.org/grpc/codes"
+ "google.golang.org/grpc/status"
+ "google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
+)
+
+var componentType = component.MustNewType("beacon_otlp_http")
+
+const (
+ pbContentType = "application/x-protobuf"
+ jsonContentType = "application/json"
+ defaultEndpoint = "127.0.0.1:4318"
+)
+
+// Config is confighttp's server config, as under the upstream receiver's `protocols.http`.
+type Config struct {
+ confighttp.ServerConfig `mapstructure:",squash"`
+}
+
+func createDefaultConfig() component.Config {
+ // The upstream receiver's HTTP defaults exactly, so swapping it in changes nothing but the
+ // address recorded: no TLS, and no server timeouts.
+ cfg := confighttp.NewDefaultServerConfig()
+ cfg.Endpoint = defaultEndpoint
+ cfg.TLSSetting = nil
+ cfg.WriteTimeout = 0
+ cfg.ReadHeaderTimeout = 0
+ cfg.IdleTimeout = 0
+ return &Config{ServerConfig: cfg}
+}
+
+func NewFactory() receiver.Factory {
+ return receiver.NewFactory(componentType, createDefaultConfig,
+ receiver.WithLogs(createLogs, component.StabilityLevelBeta),
+ receiver.WithTraces(createTraces, component.StabilityLevelBeta),
+ receiver.WithMetrics(createMetrics, component.StabilityLevelBeta))
+}
+
+// One server per configured receiver serves every signal, as the upstream receiver shares one, so
+// the logs, traces and metrics pipelines that name it all get the same instance.
+var (
+ sharedMu sync.Mutex
+ shared = map[*Config]*otlpHTTP{}
+)
+
+func instance(cfg component.Config, set receiver.Settings) *otlpHTTP {
+ c := cfg.(*Config)
+ sharedMu.Lock()
+ defer sharedMu.Unlock()
+ if r, ok := shared[c]; ok {
+ return r
+ }
+ r := &otlpHTTP{cfg: c, settings: set}
+ shared[c] = r
+ return r
+}
+
+func createLogs(_ context.Context, set receiver.Settings, cfg component.Config, next consumer.Logs) (receiver.Logs, error) {
+ r := instance(cfg, set)
+ r.logs = next
+ return r, nil
+}
+
+func createTraces(_ context.Context, set receiver.Settings, cfg component.Config, next consumer.Traces) (receiver.Traces, error) {
+ r := instance(cfg, set)
+ r.traces = next
+ return r, nil
+}
+
+func createMetrics(_ context.Context, set receiver.Settings, cfg component.Config, next consumer.Metrics) (receiver.Metrics, error) {
+ r := instance(cfg, set)
+ r.metrics = next
+ return r, nil
+}
+
+type otlpHTTP struct {
+ cfg *Config
+ settings receiver.Settings
+ logs consumer.Logs
+ traces consumer.Traces
+ metrics consumer.Metrics
+
+ mu sync.Mutex
+ addr net.Addr // where the server listens, once started
+ started bool
+ stopped bool
+ server *http.Server
+ serveErr chan struct{}
+}
+
+// Start is called once per pipeline that names the receiver; the server starts on the first.
+func (r *otlpHTTP) Start(ctx context.Context, host component.Host) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if r.started {
+ return nil
+ }
+ mux := http.NewServeMux()
+ if r.logs != nil {
+ mux.HandleFunc("/v1/logs", r.handle(func(ctx context.Context, enc encoder, body []byte) ([]byte, error) {
+ req := plogotlp.NewExportRequest()
+ if err := enc.unmarshal(body, req.UnmarshalProto, req.UnmarshalJSON); err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ if req.Logs().LogRecordCount() > 0 {
+ if err := r.logs.ConsumeLogs(ctx, req.Logs()); err != nil {
+ return nil, consumeStatus(err)
+ }
+ }
+ resp := plogotlp.NewExportResponse()
+ return enc.marshal(resp.MarshalProto, resp.MarshalJSON)
+ }))
+ }
+ if r.traces != nil {
+ mux.HandleFunc("/v1/traces", r.handle(func(ctx context.Context, enc encoder, body []byte) ([]byte, error) {
+ req := ptraceotlp.NewExportRequest()
+ if err := enc.unmarshal(body, req.UnmarshalProto, req.UnmarshalJSON); err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ if req.Traces().SpanCount() > 0 {
+ if err := r.traces.ConsumeTraces(ctx, req.Traces()); err != nil {
+ return nil, consumeStatus(err)
+ }
+ }
+ resp := ptraceotlp.NewExportResponse()
+ return enc.marshal(resp.MarshalProto, resp.MarshalJSON)
+ }))
+ }
+ if r.metrics != nil {
+ mux.HandleFunc("/v1/metrics", r.handle(func(ctx context.Context, enc encoder, body []byte) ([]byte, error) {
+ req := pmetricotlp.NewExportRequest()
+ if err := enc.unmarshal(body, req.UnmarshalProto, req.UnmarshalJSON); err != nil {
+ return nil, status.Error(codes.InvalidArgument, err.Error())
+ }
+ if req.Metrics().DataPointCount() > 0 {
+ if err := r.metrics.ConsumeMetrics(ctx, req.Metrics()); err != nil {
+ return nil, consumeStatus(err)
+ }
+ }
+ resp := pmetricotlp.NewExportResponse()
+ return enc.marshal(resp.MarshalProto, resp.MarshalJSON)
+ }))
+ }
+ var err error
+ r.server, err = r.cfg.ServerConfig.ToServer(ctx, host, r.settings.TelemetrySettings, mux,
+ confighttp.WithErrorHandler(errorHandler))
+ if err != nil {
+ return err
+ }
+ ln, err := r.cfg.ServerConfig.ToListener(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to bind to address %s: %w", r.cfg.Endpoint, err)
+ }
+ r.addr = ln.Addr()
+ r.settings.Logger.Info("Starting HTTP server", zap.String("endpoint", ln.Addr().String()))
+ r.started = true
+ r.serveErr = make(chan struct{})
+ go func() {
+ defer close(r.serveErr)
+ if err := r.server.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ componentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(err))
+ }
+ }()
+ return nil
+}
+
+// Shutdown is called once per pipeline too; the server stops on the first.
+func (r *otlpHTTP) Shutdown(ctx context.Context) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ if !r.started || r.stopped {
+ return nil
+ }
+ r.stopped = true
+ err := r.server.Shutdown(ctx)
+ <-r.serveErr
+ sharedMu.Lock()
+ delete(shared, r.cfg)
+ sharedMu.Unlock()
+ return err
+}
+
+// handle wraps one signal's export with the protocol around it: method, content type, body, and
+// the client's full address in client.Info.
+func (r *otlpHTTP) handle(export func(context.Context, encoder, []byte) ([]byte, error)) http.HandlerFunc {
+ return func(w http.ResponseWriter, req *http.Request) {
+ if req.Method != http.MethodPost {
+ writeResponse(w, "text/plain", http.StatusMethodNotAllowed,
+ []byte(fmt.Sprintf("%v method not allowed, supported: [POST]", http.StatusMethodNotAllowed)))
+ return
+ }
+ enc, ok := encoderFor(req.Header.Get("Content-Type"))
+ if !ok {
+ writeResponse(w, "text/plain", http.StatusUnsupportedMediaType,
+ []byte(fmt.Sprintf("%v unsupported media type, supported: [%s, %s]", http.StatusUnsupportedMediaType, jsonContentType, pbContentType)))
+ return
+ }
+ body, err := io.ReadAll(req.Body)
+ if err == nil {
+ err = req.Body.Close()
+ }
+ if err != nil {
+ writeStatus(w, enc, status.New(codes.InvalidArgument, err.Error()))
+ return
+ }
+ msg, err := export(withClientAddr(req), enc, body)
+ if err != nil {
+ s, _ := status.FromError(err)
+ writeStatus(w, enc, s)
+ return
+ }
+ writeResponse(w, enc.contentType, http.StatusOK, msg)
+ }
+}
+
+// withClientAddr is the one thing this receiver does differently: the request's context keeps
+// whatever client.Info confighttp put there (metadata, auth) with Addr replaced by the full
+// address, port included.
+func withClientAddr(req *http.Request) context.Context {
+ ctx := req.Context()
+ host, port, err := net.SplitHostPort(req.RemoteAddr)
+ if err != nil {
+ return ctx
+ }
+ ip := net.ParseIP(host)
+ p, err := strconv.Atoi(port)
+ if ip == nil || err != nil {
+ return ctx
+ }
+ info := client.FromContext(ctx)
+ info.Addr = &net.TCPAddr{IP: ip, Port: p}
+ return client.NewContext(ctx, info)
+}
+
+// consumeStatus maps a pipeline's error to the status the upstream receiver returns for it:
+// retryable unless the error says it is permanent.
+func consumeStatus(err error) error {
+ if _, ok := status.FromError(err); ok {
+ return err
+ }
+ code := codes.Unavailable
+ if consumererror.IsPermanent(err) {
+ code = codes.Internal
+ }
+ return status.Error(code, err.Error())
+}
+
+type encoder struct {
+ contentType string
+ json bool
+}
+
+func encoderFor(contentType string) (encoder, bool) {
+ media, _, err := mime.ParseMediaType(contentType)
+ if err != nil {
+ return encoder{}, false
+ }
+ switch media {
+ case pbContentType:
+ return encoder{contentType: pbContentType}, true
+ case jsonContentType:
+ return encoder{contentType: jsonContentType, json: true}, true
+ }
+ return encoder{}, false
+}
+
+func (e encoder) unmarshal(body []byte, pb, js func([]byte) error) error {
+ if e.json {
+ return js(body)
+ }
+ return pb(body)
+}
+
+func (e encoder) marshal(pb, js func() ([]byte, error)) ([]byte, error) {
+ if e.json {
+ return js()
+ }
+ return pb()
+}
+
+func (e encoder) marshalStatus(s *status.Status) ([]byte, error) {
+ if e.json {
+ return protojson.Marshal(s.Proto())
+ }
+ return proto.Marshal(s.Proto())
+}
+
+// httpStatus is the upstream receiver's mapping from a gRPC code to an HTTP status.
+func httpStatus(s *status.Status) int {
+ switch s.Code() {
+ case codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss:
+ return http.StatusServiceUnavailable
+ case codes.ResourceExhausted:
+ return http.StatusTooManyRequests
+ case codes.InvalidArgument:
+ return http.StatusBadRequest
+ case codes.Unauthenticated:
+ return http.StatusUnauthorized
+ case codes.PermissionDenied:
+ return http.StatusForbidden
+ case codes.Unimplemented:
+ return http.StatusNotFound
+ default:
+ return http.StatusInternalServerError
+ }
+}
+
+var fallbackMsg = []byte(`{"code": 13, "message": "failed to marshal error message"}`)
+
+func writeStatus(w http.ResponseWriter, enc encoder, s *status.Status) {
+ msg, err := enc.marshalStatus(s)
+ if err != nil {
+ writeResponse(w, jsonContentType, http.StatusInternalServerError, fallbackMsg)
+ return
+ }
+ writeResponse(w, enc.contentType, httpStatus(s), msg)
+}
+
+// errorHandler answers what confighttp refuses before a handler runs (a body over the size limit,
+// a compression it cannot decode), in the request's encoding.
+func errorHandler(w http.ResponseWriter, r *http.Request, msg string, code int) {
+ enc, ok := encoderFor(r.Header.Get("Content-Type"))
+ if !ok {
+ writeResponse(w, jsonContentType, http.StatusInternalServerError, fallbackMsg)
+ return
+ }
+ body, err := enc.marshalStatus(status.New(grpcCode(code), msg))
+ if err != nil {
+ writeResponse(w, jsonContentType, http.StatusInternalServerError, fallbackMsg)
+ return
+ }
+ writeResponse(w, enc.contentType, code, body)
+}
+
+func grpcCode(httpCode int) codes.Code {
+ switch httpCode {
+ case http.StatusBadRequest, http.StatusRequestEntityTooLarge:
+ return codes.InvalidArgument
+ case http.StatusTooManyRequests:
+ return codes.ResourceExhausted
+ case http.StatusServiceUnavailable:
+ return codes.Unavailable
+ }
+ return codes.Unknown
+}
+
+func writeResponse(w http.ResponseWriter, contentType string, code int, msg []byte) {
+ w.Header().Set("Content-Type", contentType)
+ w.WriteHeader(code)
+ _, _ = w.Write(msg)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver_test.go b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver_test.go
new file mode 100644
index 00000000..8bce7ef3
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/otlphttpreceiver/receiver_test.go
@@ -0,0 +1,245 @@
+package otlphttpreceiver
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "sync"
+ "testing"
+
+ "go.opentelemetry.io/collector/client"
+ "go.opentelemetry.io/collector/component/componenttest"
+ "go.opentelemetry.io/collector/consumer"
+ "go.opentelemetry.io/collector/consumer/consumererror"
+ "go.opentelemetry.io/collector/consumer/consumertest"
+ "go.opentelemetry.io/collector/pdata/plog"
+ "go.opentelemetry.io/collector/pdata/ptrace"
+ "go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp"
+ "go.opentelemetry.io/collector/receiver/receivertest"
+)
+
+// recordingLogs keeps every export and the client.Info it arrived with.
+type recordingLogs struct {
+ mu sync.Mutex
+ infos []client.Info
+ logs []plog.Logs
+ err error
+}
+
+func (r *recordingLogs) Capabilities() consumer.Capabilities { return consumer.Capabilities{} }
+func (r *recordingLogs) ConsumeLogs(ctx context.Context, ld plog.Logs) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.infos = append(r.infos, client.FromContext(ctx))
+ r.logs = append(r.logs, ld)
+ return r.err
+}
+
+type fixture struct {
+ url string
+ logs *recordingLogs
+ traces *consumertest.TracesSink
+ metrics *consumertest.MetricsSink
+}
+
+func start(t *testing.T) fixture {
+ t.Helper()
+ f := NewFactory()
+ cfg := f.CreateDefaultConfig().(*Config)
+ cfg.Endpoint = "127.0.0.1:0"
+ set := receivertest.NewNopSettings(componentType)
+ fx := fixture{logs: &recordingLogs{}, traces: new(consumertest.TracesSink), metrics: new(consumertest.MetricsSink)}
+ lr, err := f.CreateLogs(context.Background(), set, cfg, fx.logs)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tr, err := f.CreateTraces(context.Background(), set, cfg, fx.traces)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mr, err := f.CreateMetrics(context.Background(), set, cfg, fx.metrics)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if lr != tr || tr != mr {
+ t.Fatal("each signal got its own receiver; they must share one server")
+ }
+ host := componenttest.NewNopHost()
+ // Started once per pipeline, as the collector does.
+ if err := lr.Start(context.Background(), host); err != nil {
+ t.Fatal(err)
+ }
+ if err := tr.Start(context.Background(), host); err != nil {
+ t.Fatalf("a second Start failed: %v", err)
+ }
+ t.Cleanup(func() {
+ if err := lr.Shutdown(context.Background()); err != nil {
+ t.Error(err)
+ }
+ if err := mr.Shutdown(context.Background()); err != nil {
+ t.Errorf("a second Shutdown failed: %v", err)
+ }
+ })
+ fx.url = "http://" + lr.(*otlpHTTP).addr.String()
+ return fx
+}
+
+const jsonLog = `{"resourceLogs":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"chatgpt_web"}}]},"scopeLogs":[{"logRecords":[{"body":{"stringValue":"hello"}}]}]}]}`
+
+// post sends body from a connection whose local address the caller learns, so a test can compare
+// the port the receiver recorded with the one the client really used.
+func post(t *testing.T, url, contentType string, body []byte, header map[string]string) (*http.Response, []byte, *net.TCPAddr) {
+ t.Helper()
+ var local *net.TCPAddr
+ transport := &http.Transport{DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
+ c, err := (&net.Dialer{}).DialContext(ctx, network, addr)
+ if err == nil {
+ local = c.LocalAddr().(*net.TCPAddr)
+ }
+ return c, err
+ }}
+ defer transport.CloseIdleConnections()
+ req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", contentType)
+ for k, v := range header {
+ req.Header.Set(k, v)
+ }
+ resp, err := (&http.Client{Transport: transport}).Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ out, _ := io.ReadAll(resp.Body)
+ return resp, out, local
+}
+
+// The point of the receiver: the pipeline sees the client's address with its port.
+func TestTheClientPortReachesThePipeline(t *testing.T) {
+ fx := start(t)
+ resp, _, local := post(t, fx.url+"/v1/logs", "application/json", []byte(jsonLog), nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("status = %d", resp.StatusCode)
+ }
+ if len(fx.logs.infos) != 1 {
+ t.Fatalf("got %d exports, want 1", len(fx.logs.infos))
+ }
+ addr, ok := fx.logs.infos[0].Addr.(*net.TCPAddr)
+ if !ok {
+ t.Fatalf("client.Info.Addr = %T %v, want a *net.TCPAddr", fx.logs.infos[0].Addr, fx.logs.infos[0].Addr)
+ }
+ if addr.Port != local.Port || !addr.IP.Equal(local.IP) {
+ t.Fatalf("recorded %s, want the client's own %s", addr, local)
+ }
+ if got := fx.logs.logs[0].LogRecordCount(); got != 1 {
+ t.Fatalf("log records = %d", got)
+ }
+}
+
+func TestProtobufAndGzipAreServedLikeUpstream(t *testing.T) {
+ fx := start(t)
+ traces := ptrace.NewTraces()
+ traces.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().SetName("tool")
+ body, err := ptraceotlp.NewExportRequestFromTraces(traces).MarshalProto()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var zipped bytes.Buffer
+ zw := gzip.NewWriter(&zipped)
+ _, _ = zw.Write(body)
+ _ = zw.Close()
+ resp, out, _ := post(t, fx.url+"/v1/traces", "application/x-protobuf", zipped.Bytes(), map[string]string{"Content-Encoding": "gzip"})
+ if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "application/x-protobuf" {
+ t.Fatalf("status = %d, content type %q", resp.StatusCode, resp.Header.Get("Content-Type"))
+ }
+ if err := ptraceotlp.NewExportResponse().UnmarshalProto(out); err != nil {
+ t.Fatalf("response is not an ExportTraceServiceResponse: %v", err)
+ }
+ if fx.traces.SpanCount() != 1 {
+ t.Fatalf("spans = %d", fx.traces.SpanCount())
+ }
+
+ metrics := `{"resourceMetrics":[{"scopeMetrics":[{"metrics":[{"name":"m","gauge":{"dataPoints":[{"asInt":"1"}]}}]}]}]}`
+ resp, _, _ = post(t, fx.url+"/v1/metrics", "application/json; charset=utf-8", []byte(metrics), nil)
+ if resp.StatusCode != http.StatusOK || fx.metrics.DataPointCount() != 1 {
+ t.Fatalf("metrics status = %d, points = %d", resp.StatusCode, fx.metrics.DataPointCount())
+ }
+}
+
+func TestRefusalsMatchUpstream(t *testing.T) {
+ fx := start(t)
+
+ resp, err := http.Get(fx.url + "/v1/logs")
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusMethodNotAllowed {
+ t.Errorf("GET status = %d, want 405", resp.StatusCode)
+ }
+ if resp, _, _ := post(t, fx.url+"/v1/logs", "text/plain", []byte(jsonLog), nil); resp.StatusCode != http.StatusUnsupportedMediaType {
+ t.Errorf("text/plain status = %d, want 415", resp.StatusCode)
+ }
+ resp2, out, _ := post(t, fx.url+"/v1/logs", "application/json", []byte(`{"resourceLogs":`), nil)
+ if resp2.StatusCode != http.StatusBadRequest {
+ t.Errorf("malformed status = %d, want 400", resp2.StatusCode)
+ }
+ var st map[string]any
+ if err := json.Unmarshal(out, &st); err != nil || st["code"] != float64(3) {
+ t.Errorf("malformed body = %s, want an rpc.Status with InvalidArgument", out)
+ }
+ if resp, _, _ := post(t, fx.url+"/v1/profiles", "application/json", []byte(`{}`), nil); resp.StatusCode != http.StatusNotFound {
+ t.Errorf("unknown path status = %d, want 404", resp.StatusCode)
+ }
+
+ // A pipeline that refuses (memory_limiter) is retryable; a permanent error is not.
+ fx.logs.err = errors.New("memory limit")
+ if resp, _, _ := post(t, fx.url+"/v1/logs", "application/json", []byte(jsonLog), nil); resp.StatusCode != http.StatusServiceUnavailable {
+ t.Errorf("retryable status = %d, want 503", resp.StatusCode)
+ }
+ fx.logs.err = consumererror.NewPermanent(errors.New("bad data"))
+ if resp, _, _ := post(t, fx.url+"/v1/logs", "application/json", []byte(jsonLog), nil); resp.StatusCode != http.StatusInternalServerError {
+ t.Errorf("permanent status = %d, want 500", resp.StatusCode)
+ }
+
+ // An empty export is answered without reaching the pipeline.
+ fx.logs.err = nil
+ before := len(fx.logs.logs)
+ if resp, _, _ := post(t, fx.url+"/v1/logs", "application/json", []byte(`{}`), nil); resp.StatusCode != http.StatusOK {
+ t.Errorf("empty status = %d", resp.StatusCode)
+ }
+ if len(fx.logs.logs) != before {
+ t.Error("an empty export reached the pipeline")
+ }
+}
+
+func TestOnlyConfiguredSignalsAreServed(t *testing.T) {
+ f := NewFactory()
+ cfg := f.CreateDefaultConfig().(*Config)
+ cfg.Endpoint = "127.0.0.1:0"
+ r, err := f.CreateLogs(context.Background(), receivertest.NewNopSettings(componentType), cfg, new(consumertest.LogsSink))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := r.Start(context.Background(), componenttest.NewNopHost()); err != nil {
+ t.Fatal(err)
+ }
+ defer r.Shutdown(context.Background())
+ url := "http://" + r.(*otlpHTTP).addr.String()
+ if resp, _, _ := post(t, url+"/v1/traces", "application/json", []byte(`{}`), nil); resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("traces without a traces pipeline = %d, want 404", resp.StatusCode)
+ }
+}
+
+func TestDefaultsToTheLoopbackOTLPPort(t *testing.T) {
+ if got := createDefaultConfig().(*Config).Endpoint; got != "127.0.0.1:4318" {
+ t.Fatalf("default endpoint = %q", got)
+ }
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/peerprocessor/processor.go b/collector-builder/exporter/beaconjsonexporter/peerprocessor/processor.go
new file mode 100644
index 00000000..e9008d05
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/peerprocessor/processor.go
@@ -0,0 +1,133 @@
+// Package peerprocessor records which local account sent each OTLP export.
+//
+// Every account on a machine exports OTLP to the same loopback collector, and OTLP carries no
+// identity a collector can trust, so the exporter used to record every OTLP event under the
+// collector's own account: root on a system install, whoever actually typed the prompt. The kernel
+// knows better. For an export that arrived over a loopback TCP connection, the account that owns
+// the connection's client socket is the account of the process that sent it, and that is what
+// this processor writes on every resource, as beaconevent.PeerUIDAttribute and PeerUserAttribute.
+//
+// It must run before anything that loses the request's connection details (batch does), so it goes
+// first in a pipeline. It removes those attributes from every resource before writing them, so a
+// sender cannot name someone else by setting them itself, and it writes nothing when the sender
+// cannot be identified (another platform, a client that already closed, an address that is not
+// loopback). The client address comes from client.Info, which the gRPC receiver fills with the
+// peer's address and port; the beacon_otlp_http receiver does the same for HTTP, which the
+// upstream HTTP receiver cannot (it keeps only the IP).
+package peerprocessor
+
+import (
+ "context"
+ "net"
+
+ "go.opentelemetry.io/collector/client"
+ "go.opentelemetry.io/collector/component"
+ "go.opentelemetry.io/collector/consumer"
+ "go.opentelemetry.io/collector/pdata/pcommon"
+ "go.opentelemetry.io/collector/pdata/plog"
+ "go.opentelemetry.io/collector/pdata/pmetric"
+ "go.opentelemetry.io/collector/pdata/ptrace"
+ "go.opentelemetry.io/collector/processor"
+ "go.opentelemetry.io/collector/processor/processorhelper"
+ "go.uber.org/zap"
+
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/accountname"
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/beaconevent"
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/peercred"
+)
+
+var componentType = component.MustNewType("beacon_peer")
+
+// Config has no settings: the processor's whole behavior is fixed, so a config cannot weaken it.
+type Config struct{}
+
+func NewFactory() processor.Factory {
+ return processor.NewFactory(componentType, func() component.Config { return &Config{} },
+ processor.WithLogs(createLogs, component.StabilityLevelBeta),
+ processor.WithTraces(createTraces, component.StabilityLevelBeta),
+ processor.WithMetrics(createMetrics, component.StabilityLevelBeta))
+}
+
+// peer resolves a client address to an account.
+type peer struct {
+ uid func(*net.TCPAddr) (string, error)
+ name func(uid string) string
+ logger *zap.Logger
+}
+
+var (
+ // One name cache for the whole collector: the three signals' processors share it, as the
+ // ingest extension shares its own.
+ names = accountname.NewCache()
+ // lookupUID and lookupName are what newPeer uses; tests replace them.
+ lookupUID = peercred.UID
+ lookupName = names.Lookup
+)
+
+func newPeer(set processor.Settings) *peer {
+ return &peer{uid: lookupUID, name: lookupName, logger: set.Logger}
+}
+
+// identify returns the account that owns the client end of the connection the export in ctx came
+// in on, or empty strings when it cannot be named.
+func (p *peer) identify(ctx context.Context) (uid, name string) {
+ addr, ok := client.FromContext(ctx).Addr.(*net.TCPAddr)
+ if !ok || addr == nil {
+ return "", ""
+ }
+ uid, err := p.uid(addr)
+ if err != nil {
+ p.logger.Debug("could not identify the account that sent an export", zap.Stringer("client", addr), zap.Error(err))
+ return "", ""
+ }
+ return uid, p.name(uid)
+}
+
+// stamp makes a resource's peer attributes exactly what the kernel said: none of the sender's.
+func stamp(resource pcommon.Resource, uid, name string) {
+ attrs := resource.Attributes()
+ attrs.Remove(beaconevent.PeerUIDAttribute)
+ attrs.Remove(beaconevent.PeerUserAttribute)
+ if uid == "" {
+ return
+ }
+ attrs.PutStr(beaconevent.PeerUIDAttribute, uid)
+ if name != "" {
+ attrs.PutStr(beaconevent.PeerUserAttribute, name)
+ }
+}
+
+var mutates = processorhelper.WithCapabilities(consumer.Capabilities{MutatesData: true})
+
+func createLogs(ctx context.Context, set processor.Settings, cfg component.Config, next consumer.Logs) (processor.Logs, error) {
+ p := newPeer(set)
+ return processorhelper.NewLogs(ctx, set, cfg, next, func(ctx context.Context, logs plog.Logs) (plog.Logs, error) {
+ uid, name := p.identify(ctx)
+ for i := 0; i < logs.ResourceLogs().Len(); i++ {
+ stamp(logs.ResourceLogs().At(i).Resource(), uid, name)
+ }
+ return logs, nil
+ }, mutates)
+}
+
+func createTraces(ctx context.Context, set processor.Settings, cfg component.Config, next consumer.Traces) (processor.Traces, error) {
+ p := newPeer(set)
+ return processorhelper.NewTraces(ctx, set, cfg, next, func(ctx context.Context, traces ptrace.Traces) (ptrace.Traces, error) {
+ uid, name := p.identify(ctx)
+ for i := 0; i < traces.ResourceSpans().Len(); i++ {
+ stamp(traces.ResourceSpans().At(i).Resource(), uid, name)
+ }
+ return traces, nil
+ }, mutates)
+}
+
+func createMetrics(ctx context.Context, set processor.Settings, cfg component.Config, next consumer.Metrics) (processor.Metrics, error) {
+ p := newPeer(set)
+ return processorhelper.NewMetrics(ctx, set, cfg, next, func(ctx context.Context, metrics pmetric.Metrics) (pmetric.Metrics, error) {
+ uid, name := p.identify(ctx)
+ for i := 0; i < metrics.ResourceMetrics().Len(); i++ {
+ stamp(metrics.ResourceMetrics().At(i).Resource(), uid, name)
+ }
+ return metrics, nil
+ }, mutates)
+}
diff --git a/collector-builder/exporter/beaconjsonexporter/peerprocessor/processor_test.go b/collector-builder/exporter/beaconjsonexporter/peerprocessor/processor_test.go
new file mode 100644
index 00000000..42aef073
--- /dev/null
+++ b/collector-builder/exporter/beaconjsonexporter/peerprocessor/processor_test.go
@@ -0,0 +1,166 @@
+package peerprocessor
+
+import (
+ "context"
+ "errors"
+ "net"
+ "testing"
+
+ "go.opentelemetry.io/collector/client"
+ "go.opentelemetry.io/collector/consumer/consumertest"
+ "go.opentelemetry.io/collector/pdata/plog"
+ "go.opentelemetry.io/collector/pdata/pmetric"
+ "go.opentelemetry.io/collector/pdata/ptrace"
+ "go.opentelemetry.io/collector/processor/processortest"
+
+ "github.com/asymptote-labs/agent-beacon/collector-builder/exporter/beaconjsonexporter/internal/beaconevent"
+)
+
+// fakeKernel answers for one client address only, as the socket table does.
+func fakeKernel(t *testing.T, owner *net.TCPAddr, uid, name string) {
+ t.Helper()
+ oldUID, oldName := lookupUID, lookupName
+ t.Cleanup(func() { lookupUID, lookupName = oldUID, oldName })
+ lookupUID = func(addr *net.TCPAddr) (string, error) {
+ if owner != nil && addr.IP.Equal(owner.IP) && addr.Port == owner.Port {
+ return uid, nil
+ }
+ return "", errors.New("no socket")
+ }
+ lookupName = func(got string) string {
+ if got == uid {
+ return name
+ }
+ return ""
+ }
+}
+
+func from(addr net.Addr) context.Context {
+ return client.NewContext(context.Background(), client.Info{Addr: addr})
+}
+
+func forgedLogs() plog.Logs {
+ logs := plog.NewLogs()
+ for i := 0; i < 2; i++ {
+ rl := logs.ResourceLogs().AppendEmpty()
+ rl.Resource().Attributes().PutStr("service.name", "chatgpt_web")
+ // What a sender would write to pass itself off as someone else.
+ rl.Resource().Attributes().PutStr(beaconevent.PeerUIDAttribute, "0")
+ rl.Resource().Attributes().PutStr(beaconevent.PeerUserAttribute, "root")
+ rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Body().SetStr("hi")
+ }
+ return logs
+}
+
+func peerAttrs(t *testing.T, logs plog.Logs) []string {
+ t.Helper()
+ var out []string
+ for i := 0; i < logs.ResourceLogs().Len(); i++ {
+ attrs := logs.ResourceLogs().At(i).Resource().Attributes()
+ get := func(key string) string {
+ if v, ok := attrs.Get(key); ok {
+ return v.AsString()
+ }
+ return ""
+ }
+ out = append(out, get(beaconevent.PeerUIDAttribute)+"/"+get(beaconevent.PeerUserAttribute))
+ }
+ return out
+}
+
+func TestTheSendersAccountReplacesWhatItClaimed(t *testing.T) {
+ alice := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 50123}
+ fakeKernel(t, alice, "1001", "alice")
+ sink := new(consumertest.LogsSink)
+ p, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), &Config{}, sink)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := p.ConsumeLogs(from(alice), forgedLogs()); err != nil {
+ t.Fatal(err)
+ }
+ got := peerAttrs(t, sink.AllLogs()[0])
+ for _, v := range got {
+ if v != "1001/alice" {
+ t.Fatalf("peer attributes = %v, want alice's on every resource", got)
+ }
+ }
+}
+
+// An export whose sender cannot be named keeps nothing a sender wrote, so the exporter falls back to
+// the collector's own account rather than to the claim.
+func TestAnUnidentifiedSenderLeavesNoClaim(t *testing.T) {
+ fakeKernel(t, nil, "", "")
+ for name, ctx := range map[string]context.Context{
+ "no client info": context.Background(),
+ "socket gone": from(&net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 4000}),
+ "address without a port": from(&net.IPAddr{IP: net.IPv4(127, 0, 0, 1)}),
+ } {
+ t.Run(name, func(t *testing.T) {
+ sink := new(consumertest.LogsSink)
+ p, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), &Config{}, sink)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := p.ConsumeLogs(ctx, forgedLogs()); err != nil {
+ t.Fatal(err)
+ }
+ for _, v := range peerAttrs(t, sink.AllLogs()[0]) {
+ if v != "/" {
+ t.Fatalf("peer attributes = %q, want none", v)
+ }
+ }
+ })
+ }
+}
+
+// An account the system cannot name is still recorded by its id.
+func TestAnUnnamedAccountKeepsItsID(t *testing.T) {
+ bob := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 50124}
+ fakeKernel(t, bob, "1002", "")
+ sink := new(consumertest.LogsSink)
+ p, _ := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), &Config{}, sink)
+ if err := p.ConsumeLogs(from(bob), forgedLogs()); err != nil {
+ t.Fatal(err)
+ }
+ if got := peerAttrs(t, sink.AllLogs()[0]); got[0] != "1002/" {
+ t.Fatalf("peer attributes = %v, want uid 1002 and no name", got)
+ }
+}
+
+func TestTracesAndMetricsAreStampedToo(t *testing.T) {
+ alice := &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1), Port: 50125}
+ fakeKernel(t, alice, "1001", "alice")
+ set := processortest.NewNopSettings(componentType)
+
+ traces := ptrace.NewTraces()
+ traces.ResourceSpans().AppendEmpty().Resource().Attributes().PutStr(beaconevent.PeerUIDAttribute, "0")
+ tsink := new(consumertest.TracesSink)
+ tp, _ := NewFactory().CreateTraces(context.Background(), set, &Config{}, tsink)
+ if err := tp.ConsumeTraces(from(alice), traces); err != nil {
+ t.Fatal(err)
+ }
+ if v, _ := tsink.AllTraces()[0].ResourceSpans().At(0).Resource().Attributes().Get(beaconevent.PeerUIDAttribute); v.AsString() != "1001" {
+ t.Fatalf("trace peer uid = %q", v.AsString())
+ }
+
+ metrics := pmetric.NewMetrics()
+ metrics.ResourceMetrics().AppendEmpty().Resource().Attributes().PutStr(beaconevent.PeerUserAttribute, "root")
+ msink := new(consumertest.MetricsSink)
+ mp, _ := NewFactory().CreateMetrics(context.Background(), set, &Config{}, msink)
+ if err := mp.ConsumeMetrics(from(alice), metrics); err != nil {
+ t.Fatal(err)
+ }
+ if v, _ := msink.AllMetrics()[0].ResourceMetrics().At(0).Resource().Attributes().Get(beaconevent.PeerUserAttribute); v.AsString() != "alice" {
+ t.Fatalf("metric peer user = %q", v.AsString())
+ }
+}
+
+// The processor changes data, so the collector must hand it a copy when the receiver also feeds
+// another pipeline (the OTLP forward): that one must not carry Beacon's attribution to a backend.
+func TestDeclaresThatItMutates(t *testing.T) {
+ p, _ := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(componentType), &Config{}, new(consumertest.LogsSink))
+ if !p.Capabilities().MutatesData {
+ t.Fatal("MutatesData = false")
+ }
+}
diff --git a/docs/changelog/cli.mdx b/docs/changelog/cli.mdx
index 56f02768..4596ea02 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 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. A sender that cannot be identified (it has already disconnected) keeps the collector's account, as before. 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.
- **Microsoft Sentinel forwarding with one command, on macOS, Linux and Windows** · `beacon endpoint sentinel forwarder install --system` runs the Vector bundled with Beacon as a system service that sends the runtime log to Microsoft Sentinel through the Logs Ingestion API, with a Microsoft Entra app registration (certificate or client secret). The credential is stored where only root can read it, or SYSTEM and Administrators on Windows, and is never a command-line argument. Vector checks the config before anything changes. Repair and package upgrades keep the forwarder and restart it on the new Vector; uninstall removes the service. Throttling, server errors and `401`/`403` answers are retried without a limit, and a line counts as sent only once Azure has accepted it. `status` and `remove` complete the commands. The pack's Logs Ingestion DCR template no longer needs a Data Collection Endpoint. See [Vector and the Logs Ingestion API](/log-forwarding/microsoft-sentinel#vector-and-the-logs-ingestion-api).
- **The Windows MSI carries Vector** · The MSI now installs Vector 0.56.0 as `vector.exe` beside `beacon.exe` in `%ProgramFiles%\Beacon\bin`, as the macOS and Linux packages already carry it, checked against the same pinned checksums. Beacon finds it there. The package only installs it; nothing runs it until a forwarder is set up. Allow it alongside the other three programs if you run AppLocker or WDAC.
- **Scheduled session sync** · `beacon endpoint install|repair --session-sync` turns on a job that runs every 15 minutes and reads new records from the agent runtimes' local session stores into the runtime log. It runs the same bounded, confined sweep install already runs once, so session-store data keeps reaching the log, and any forwarder reading it, after install. Off by default; repair and upgrades keep the setting, and `--no-session-sync` removes the job. See [Scheduled session sync](/cli/endpoint-install#scheduled-session-sync).
diff --git a/docs/cli/endpoint-install.mdx b/docs/cli/endpoint-install.mdx
index 9d7527f2..a29888d2 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, use them. Events that arrive that way are not attributed by the operating system.
+- 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; on macOS and Windows they carry the collector's own account.
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/log-forwarding/microsoft-sentinel.mdx b/docs/log-forwarding/microsoft-sentinel.mdx
index a10f9ac4..fbd57aa8 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. Events from an agent's own OpenTelemetry export, such as Claude Code's token usage and cost, 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. Claude Cowork is the exception: its events name the cloud account it reports. 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. 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. 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. Claude Cowork is the exception: its events name the cloud account it reports. 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 4a770280..7cca181b 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 not attributed.** 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, use them. Events that arrive that way 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 identifies the sender. Claude Cowork's name the cloud account it reports instead, which no one checks either. 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 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 has already disconnected, or cannot be told apart, keeps the collector's own account. 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. Claude Cowork's name the cloud account it reports instead, which no one checks either. 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
diff --git a/packaging/linux/smoke-package.sh b/packaging/linux/smoke-package.sh
index 87470e4a..c6001541 100755
--- a/packaging/linux/smoke-package.sh
+++ b/packaging/linux/smoke-package.sh
@@ -249,6 +249,39 @@ if failed:
print(f"ok: doctor reports no failures across {len(checks)} checks")
PY
+# OTLP is attributed to the account that sent it, not to the root collector. Every account exports to
+# the same loopback collector, so before this every OTLP event on a system install read as root.
+# Each export below also claims to be root through the peer attributes, which must be ignored.
+otlp_from() {
+ # $1 = account, $2 = session id; a browser-extension-shaped log over OTLP/HTTP JSON.
+ body='{"resourceLogs":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"chatgpt_web"}},{"key":"beacon.peer.uid","value":{"stringValue":"0"}},{"key":"beacon.peer.user","value":{"stringValue":"root"}}]},"scopeLogs":[{"logRecords":[{"timeUnixNano":"1762430000000000000","body":{"stringValue":"smoke"},"attributes":[{"key":"event.name","value":{"stringValue":"user_prompt"}},{"key":"session.id","value":{"stringValue":"'"$2"'"}}]}]}]}]}'
+ docker exec "$CONTAINER" su -s /bin/sh "$1" -c "curl -fsS -o /dev/null -H 'Content-Type: application/json' --data-binary '$body' http://127.0.0.1:4318/v1/logs" || {
+ echo "OTLP export as $1 failed" >&2; exit 1; }
+}
+otlp_from "$SMOKE_USER" smoke-otlp-user
+otlp_from root smoke-otlp-root
+attributed=""
+i=0
+while [ "$i" -lt 20 ]; do
+ attributed="$(docker exec "$CONTAINER" cat /var/log/beacon-agent/runtime.jsonl | python3 -c '
+import json, sys
+seen = {}
+for line in sys.stdin:
+ e = json.loads(line)
+ sid = (e.get("session") or {}).get("id", "")
+ if sid.startswith("smoke-otlp-"):
+ seen[sid] = (e.get("user") or {}).get("name", "")
+print(" ".join("%s=%s" % kv for kv in sorted(seen.items())))')"
+ case "$attributed" in *smoke-otlp-root=*smoke-otlp-user=*|*smoke-otlp-user=*smoke-otlp-root=*) break ;; esac
+ i=$((i+1)); sleep 1
+done
+[ "$attributed" = "smoke-otlp-root=root smoke-otlp-user=$SMOKE_USER" ] || {
+ echo "OTLP events were attributed as '$attributed', want smoke-otlp-root=root smoke-otlp-user=$SMOKE_USER" >&2
+ docker exec "$CONTAINER" journalctl -u beacon-collector.service --no-pager -n 30 >&2 || true
+ exit 1
+}
+echo "ok: OTLP events are recorded under the account that sent them ($attributed)"
+
# Reinstalling the same package is an upgrade as far as both package managers are concerned, and it
# is the exact sequence `beacon endpoint update --apply` performs. It is worth its own assertion
# because the old package's pre-removal script runs during an upgrade -- and on rpm it runs *after*