The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu
Go agent-ai-cliagent-harnessesagent-securitybrowser-extensionciclaude-codecloudcodexcursordetection-engineeringjevknowledge-basememorymobile-device-managementobservabilitysecuritysecurity-information-and-event-managementsecurity-toolstelemetrytraces
Harden beacon rules pull and keep the baseline active beside the store
Claude8ed3b4044175
diff --git a/CLAUDE.md b/CLAUDE.mdindex 83eef3a9..b37f3fc8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -67,7 +67,7 @@ Supported runtime surfaces today:- Elasticsearch/Filebeat content pack generation for forwarding local Beacon JSONL into customer-managed Elastic deployments or the bundled loopback-only development stack.- A local-only dashboard served by `beacon endpoint dashboard`, bound to loopback by default and backed by the runtime JSONL log.- Token usage and runtime-reported cost capture across spans, logs, and metric datapoints, normalized into `gen_ai.usage`, with attribution rollups served by the dashboard token view (`/api/tokens`) and the `beacon token-usage` report command for local and CI logs. Every report row carries three costs (`cli/beacon/internal/tokens/cost.go`): `cost_usd` (runtime-reported, unchanged), `estimated_cost_usd` (list price of every priced token, from `internal/pricing`, computed after dedup and cumulative resolution) and `effective_cost_usd` with `cost_source` (per endpoint/harness/session scope, reported cost wins wholesale when the scope has any; otherwise the estimate; session-less events per event), plus `unpriced_events`/`unpriced_tokens` and a report-level `pricing` block (catalog provenance, per-model key, match, base rates, bands applied, fallbacks, unpriced models). Long-context bands apply only to events `requestScoped` classifies as one model request; it defaults to aggregate, so a new capture path is priced at base rates until it is added there with a test. Lens data (`LensDataV1`) carries no estimate.-- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network. A small frozen baseline is embedded so `scan` works before any rules are installed.+- Local threat detection via `beacon scan`, which runs the open Threat Rules format (`spec/threat-rules`; CEL match conditions over the endpoint event schema, with embedded conformance fixtures) over the runtime JSONL. The engine (`pkg/asymptoteobserve/threatrules`) ships in the binary; the rule corpus is external data loaded from a local store (`~/.beacon/endpoint/rules`) managed by `beacon rules`, so the corpus can grow without enlarging the binary. `scan` is read-only and offline; only the explicit, user-initiated `beacon rules pull <url>` reaches the network, over `https://` only (plain http just for loopback, no redirect off https), size-capped, and verified first when `--sha256` is given. A small frozen baseline is embedded so `scan` works before any rules are installed, and it stays active alongside the store: a store rule replaces a baseline rule only by id (`rulestore.LoadActiveSkipping`), so installing one rule never silently switches the baseline off; only `--rules <dir>` runs a directory alone.- Session handoff via `beacon handoff list|export|resume` (`cli/beacon/internal/handoff`, `cli/beacon/cmd/handoff*.go`; docs in `docs/cli/handoff.mdx` and `docs/concepts/session-handoff.mdx`). Every runtime is one entry in the registry in `cli/beacon/internal/handoff/runtimes.go`: its session source, the names it answers to, and the commands that reopen it or start it from a brief; `TestRegistryIsConsistent` checks the entries. Handoff reads the session stores of Claude Code, Codex CLI, OpenCode, Cline, Pi, Prime Agent, Factory Droid, GitHub Copilot CLI, Hermes Agent, DeepSeek Harness, fx, Grok Build, OpenClaw Gateway and Cursor read-only and never touches the network. Oh My Pi, Gemini CLI, Qwen Code, Kiro, Antigravity CLI, Devin CLI, Muse Code, OpenHands and goose have no store Beacon reads: their sessions come from the runtime log, and they take a brief as the target of `--agent`. `resume` reopens a session natively with its runtime's own command when it can, and otherwise writes a brief to `~/.beacon/endpoint/handoffs` (0700/0600) and starts a new session pointed at it. DeepSeek Harness cannot be started, and Hermes Agent and fx only reopen their own sessions, so their sessions continue in another runtime. fx, Grok Build and Cursor find a session by the directory they run in, so they are reopened natively only in the session's own directory. The brief is passed by absolute path, never inlined on a command line. Every launch keeps the runtime's approvals on: Beacon never passes a flag that turns them off, names the approval mode that asks where a CLI takes one (Cline always gets `--auto-approve false`, because Cline defaults to approving every tool call), and removes or overrides environment switches that would approve everything (`COPILOT_ALLOW_ALL`, `COPILOT_PLAN_THEN_AUTOPILOT`, `HERMES_YOLO_MODE`, `GOOSE_MODE`); `--print` shows them under `env`. Briefs run every event through `SanitizeEvent`, and quoted content goes in fences longer than any backtick run it contains, with inline fields reduced to one line, so quoted content cannot forge brief structure. A new session's first prompt ends with the `[beacon-handoff from=<harness> session=<id>]` marker (`pkg/asymptoteobserve/handoff.go`). The hook and plugin prompt paths and the session-store mappers record a `session.handoff` event with `handoff.{source_harness,source_session_id}` when they see it; that is an observed claim, not a verified identity.- Session sharing via `beacon share` and `beacon share refresh` (`cli/beacon/cmd/share.go`; docs in `docs/cli/share.mdx`, with the workflow guides in `docs/sharing/` kept in sync). It publishes one session the person names (or the most recent in a directory) to beacon.sh as a shared trace that is a `beacon.trace.v1` trace, the projection the dashboard uses: `BuildShareBundle` (sanitize, scrub, then `TraceEventFromEvent`/`TraceBuilder`), the wire types (`ShareTraceV1` summary body, `ShareEventsBatchV1` of `TraceEventV1`s, `ShareTraceStateV1` with `last_event_id`), `ShareExternalID` (`<harness>:<session-id>`, or a sha256 form), `ShareRelation` and `ShareEventsAfter` live in `pkg/asymptoteobserve/share.go`, and the client in `cli/beacon/internal/account/share.go` (`PUT /v1/traces/{external_id}`, `POST .../events/batch` capped at `ShareMaxEventsPerBatch`, `GET`). The chat view is derived on beacon.sh with `TraceMessages` (`pkg/asymptoteobserve/tracemessages.go`), which pairs a tool invocation and its completion by `tool_call_id` and writes a call reported twice once; messages are never uploaded. Sessions resolve through the handoff registry (store first, then the runtime log). Every event goes through `SanitizeEvent` and session-directory/home paths are rewritten in every projected field before projection, and the shared summary drops the working directory and repository path and names the project by `project.name`. `--print` shows the exact `{external_id, trace, events}` payload with no network, `public` needs confirmation (refused without a terminal unless `--yes`), a re-share upserts by stable event id, and a refresh sends only `ShareEventsAfter` the server's `last_event_id` (re-sending it and any tool call still open). After an upload it writes one `session.shared` event (`event.fidelity=inferred`, no collection method) carrying `shared_url`, `visibility`, `shared_at`/`last_refreshed_at` in raw, which the trace list reads as the sharing state; the projection skips that event. It never runs from hooks or in the background, except the opted-in pre-push sharing below. With no selector (or `--current`) it shares the session it runs inside: `BEACON_SESSION_ID`/`BEACON_HARNESS` (the Claude Code SessionStart hook appends both as `export` lines to `$CLAUDE_ENV_FILE`, plain identifiers only; a child runtime inherits them, so without `--harness` they are refused, naming both sessions, when the named session ran outside this directory and its parents or another runtime worked here more recently: `shareEnvContradiction`), then the active-session record (only when the entry was seen at least as recently as the directory's newest session, since OTLP-only and poll runtimes never write it), then the directory's most recent session. The record is `pkg/asymptoteobserve/activesession` (`~/.beacon/endpoint/active-sessions.json`, 0600 under 0700, atomic and locked, at most 256 entries, 14-day prune, an unchanged entry rewritten at most once a minute), written by the hook logger after every endpoint event with a session id, working directory and harness; it holds identifiers and paths only, never content, and hooks write it silently and never touch the network for it. Hook tests point `BEACON_ACTIVE_SESSIONS_FILE` at a temp file in `TestMain`. Auto-share (`beacon share auto enable|disable|status`, `cli/beacon/cmd/share_auto.go`, settings in `pkg/asymptoteobserve/shareauto`) is server-side publishing: when it applies to a session's working directory, the hook logger writes ONE local `session.share_requested` event per session (`event.fidelity=inferred`, `share.visibility`; deduplicated under the active-session record's lock) and Beacon Cloud forwarding ships it; beacon.sh builds and refreshes the trace with the same `BuildShareBundle` projection and `ShareExternalID`. Hooks never upload. The user file `~/.beacon/endpoint/share.json` (0600, CLI-written) holds the user-wide switch, three-state (unset, on, or off as a kill switch over every project; `auto.state`, with `auto.enabled` kept in step so older files read) and per-project choices by path, which a user-wide enable or disable never rewrites; a project marker `<repo>/.beacon/share.json` may disable on its own (and an off marker wins over the user's entry for the same directory; the closest directory with an entry or marker decides) but enables only when the user's file trusts that project, with the user's visibility, so a cloned repository can never publish someone's sessions. `ForHook` costs one failed read when nothing is enabled. Hook tests point `BEACON_SHARE_SETTINGS_FILE` at a temp file. The share projection and `handoff.LogSessions` recency skip `session.share_requested`.- Commit-to-session links via `beacon git setup|status|remove|link|notes` (`cli/beacon/internal/gitlink`, `cli/beacon/cmd/git*.go`; docs in `docs/cli/git.mdx`). A link is a `beacon:<harness>/<session-id>` line in a git note under `refs/notes/beacon`; it carries identifiers only, never content, because notes can be pushed. Which sessions to link is inferred from the local runtime log: a session is linked when, between the parent commit and the commit (at least two hours, at most 24), it wrote a file the commit changes (for a merge, only files that differ from every parent, so a clean merge or pull links nothing). Evidence is file write events, write-type `file.operation`s, plainly readable shell targets, and `apply_patch` envelopes; reads never count. Note updates are a compare-and-swap on the notes ref through a private `refs/notes/beacon-tx/` working ref, and every existing note line, a teammate's or a person's, is kept verbatim. `setup` installs post-commit (links HEAD in the foreground with a 3 s budget, silent, never fails the commit, skips rebase/cherry-pick/revert) and post-rewrite (normalizes the note git concatenates on amend) as standalone `beacon-<hook>` scripts called from a marked block inserted after the shebang of the repository's own hook; only shell hooks are edited, `core.hooksPath` is refused without `--hooks-path`, and `notes.rewriteRef` carries links through amend and rebase. `BEACON_GIT_HOOKS=0` disables the hooks for one command. Every link a run adds is also written to the runtime log as one `session.commit_linked` event in the linked session's timeline (`event.fidelity=inferred`, no collection method), with commit id, branch and credential-stripped remote in the OTel-shaped `vcs` block and overlap counts in `vcs.attribution`; the event deliberately carries no file, command or tool fields so it can never become attribution evidence. Sharing is opt-in (`setup --share-notes`, off by default): a non-destructive fetch refspec `+refs/notes/beacon:refs/notes/beacon-remotes/<remote>` so git's own fetch brings teammates' links into a read-only tracking ref that `beacon git notes` unions with the local one (never force-fetch into `refs/notes/beacon`: it would destroy unpushed links), and a pre-push hook that fetches, merges with `cat_sort_uniq` through the same CAS, and pushes only the notes ref with `--no-verify`, within a 10 s budget and never failing the push. That pre-push hook is the only Beacon git hook that touches the network, and only during a push the person started; `beacon git notes push|fetch` do the same by hand. A note line may carry the session's share URL as its first trailing field (`beacon:<harness>/<id> <url>`; an identifier, not content): `gitlink.ValidShareURL` admits only https URLs on beacon.sh or the configured Beacon host (`AllowShareHost`, fed by `gitAllowShareHosts`), on write and on read, and `MergeNote`/`ParseNote` prefer the line with the URL over the bare one. Post-commit and `link` take URLs only from local `session.shared` events (`localShareURLs`). `setup --share-sessions [--share-visibility]` (implies `--share-notes`; stored as `beacon.shareSessions`/`beacon.shareVisibility` in local git config; public needs confirmation or `--yes`) makes the pre-push hook, which now receives git's stdin, share sessions linked to pushed commits that have no URL (at most 100 commits/10 sessions, silent without credentials, never failing the push; the budget is enforced by the clock: the share phase runs in a goroutine delivering URLs to a collector, the hook takes what it holds after the 6 s upload budget and abandons the rest, then writes notes and pushes the notes ref with what remains of the hook's 10 s, never less than 1 s and 3 s, so only the main path ever writes notes) through `shareUpload` (`cmd/share_upload.go`: `alignShareSource` + `ShareEventsAfter`), then write the URLs into the notes before pushing them. `beacon share --follow [--interval]` (`cmd/share_follow.go`) polls the session locally, uploads through `shareUpload` only when the fingerprint of the projected trace events changed (the events only: the trace body carries its build time), stops at `session.ended` or Ctrl+C (`shareFollowWait`/`shareFollowSignals` are the test seams), and records `session.shared` after each upload, later ones as refreshes that keep the share date; `docs/cli/share.mdx` carries the API-key CI walkthrough with GitHub Actions and GitLab CI examples. Local views show sharing read-only: the trace summary (`traceFold`, which wraps `asymptoteobserve.TraceBuilder` with the local-only `traceStaleness`, and the history through `traceAggregateState`, derivation version 12) and the dashboard's `SessionRecord.Sharing` mark a shared session `stale` when an event `asymptoteobserve.ShareProjects` accepts (the one definition of what a share publishes) and that is not the share's own (`shareActivity`) is newer than what its last `session.shared` record covered (`shared_through`), and carry `asymptoteobserve.ShareRefreshCommand` for the reader to copy; the session list/page, `beacon traces` TUI and plain list display them, and nothing in them shares.@@ -235,7 +235,7 @@ Run local threat detection and manage rules during manual testing:```bashcd cli/beacongo run . scan # run active rules over the runtime log-go run . rules list # show active rules (baseline or store)+go run . rules list # show active rules (store plus baseline)go run . rules lint ../../rules # validate + run the repo rule pack's fixtures```diff --git a/cli/beacon/cmd/rules.go b/cli/beacon/cmd/rules.goindex 7aab4a89..a162ffdf 100644--- a/cli/beacon/cmd/rules.go+++ b/cli/beacon/cmd/rules.go@@ -2,9 +2,15 @@ package cmdimport ("archive/tar"+ "bytes""compress/gzip"+ "crypto/sha256"+ "crypto/subtle"+ "encoding/hex"+ "errors""fmt""io"+ "net""net/http"neturl "net/url""os"@@ -24,6 +30,7 @@ var rulesOpts struct {systemMode boolforce boolmarkdown bool+ sha256 string}func rulesUserMode() bool {@@ -40,8 +47,8 @@ var rulesCmd = &cobra.Command{runs, and author rules.The detection engine ships in the binary; rules are external data loaded from the store,-so a growing rule corpus never enlarges the binary. A small baseline is built in and used-until you install your own rules.`,+so a growing rule corpus never enlarges the binary. A small baseline is built in and+always active: a store rule replaces a baseline rule only when it has the same id.`,}var rulesListCmd = &cobra.Command{@@ -62,7 +69,14 @@ var rulesListCmd = &cobra.Command{for _, lr := range loaded {fmt.Fprintf(out, "%-32s %-8s %-12s %s\n", lr.Rule.ID, lr.Rule.Severity, lr.Rule.Status, lr.Source)}- fmt.Fprintf(out, "\n%d rule(s). Store: %s\n", len(loaded), detect.StoreDir(rulesUserMode()))+ fromStore := 0+ for _, lr := range loaded {+ if lr.Source == detect.SourceStore {+ fromStore+++ }+ }+ fmt.Fprintf(out, "\n%d rule(s): %d from the store, %d from the built-in baseline. Store: %s\n",+ len(loaded), fromStore, len(loaded)-fromStore, detect.StoreDir(rulesUserMode()))return nil},}@@ -98,6 +112,9 @@ var rulesRemoveCmd = &cobra.Command{return err}fmt.Fprintf(cmd.OutOrStdout(), "removed %s (%s)\n", args[0], path)+ if detect.IsBaselineID(args[0]) {+ fmt.Fprintf(cmd.OutOrStdout(), "%s is also a built-in baseline rule; the baseline copy is active again.\n", args[0])+ }return nil},}@@ -110,58 +127,167 @@ from an explicit URL and installs the valid rules into the store.This is the only Beacon command that reaches the network, and only when you run it. Theagent never fetches rules on its own. The URL is whatever you supply; there is no hosted-default.`,+default.++The URL must be https (plain http is accepted only for a loopback host, for local+testing), and a redirect that leaves https is refused. Pass --sha256 with the pack's+published checksum to verify the downloaded bytes before anything is installed. The+download is capped at 32 MiB, and a tarball at 10,000 entries and 64 MiB uncompressed.`,Args: cobra.ExactArgs(1),SilenceUsage: true,RunE: runRulesPull,}+// Limits on what `beacon rules pull` will download and unpack. The published corpus+// tarball is about 50 KB with under 100 entries and 300 KB uncompressed, so each limit+// leaves two orders of magnitude of headroom while keeping a hostile or broken source+// from filling the disk or $TMPDIR. They are variables only so tests can lower them.+var (+ rulesPullMaxDownloadBytes int64 = 32 << 20 // bytes read from the network+ rulesPullMaxTarEntries = 10000 // every tar header, rule file or not+ rulesPullMaxTarBytes int64 = 64 << 20 // the decompressed tar stream as a whole+ rulesPullMaxEntryBytes int64 = 1 << 20 // one .rule.yaml file+)++// rulesPullTransport is the HTTP transport `beacon rules pull` uses; nil means the+// default. Tests set it to trust an httptest TLS server.+var rulesPullTransport http.RoundTripper++// checkRulesPullURL accepts https URLs, and plain http only for a loopback host so a+// local test server still works. Everything else is refused before any request.+func checkRulesPullURL(u *neturl.URL) error {+ switch strings.ToLower(u.Scheme) {+ case "https":+ if u.Host == "" {+ return fmt.Errorf("url %q has no host", u.Redacted())+ }+ return nil+ case "http":+ if isLoopbackHost(u.Hostname()) {+ return nil+ }+ return fmt.Errorf("url must use https:// (plain http:// is accepted only for a loopback host such as 127.0.0.1)")+ default:+ return fmt.Errorf("url must start with https://")+ }+}++func isLoopbackHost(host string) bool {+ if strings.EqualFold(host, "localhost") {+ return true+ }+ ip := net.ParseIP(host)+ return ip != nil && ip.IsLoopback()+}++// rulesPullCheckRedirect refuses a redirect that leaves https, and any redirect to a+// URL the command would not have accepted in the first place.+func rulesPullCheckRedirect(req *http.Request, via []*http.Request) error {+ if len(via) >= 10 {+ return fmt.Errorf("stopped after 10 redirects")+ }+ if strings.EqualFold(via[0].URL.Scheme, "https") && !strings.EqualFold(req.URL.Scheme, "https") {+ return fmt.Errorf("refusing redirect from https to %s://%s", req.URL.Scheme, req.URL.Host)+ }+ if err := checkRulesPullURL(req.URL); err != nil {+ return fmt.Errorf("refusing redirect to %s: %w", req.URL.Redacted(), err)+ }+ return nil+}++// parseRulesPullSHA256 normalizes an optional --sha256 value: empty means no check,+// anything else must be 64 hex digits (an optional "sha256:" prefix is allowed).+func parseRulesPullSHA256(v string) (string, error) {+ v = strings.ToLower(strings.TrimSpace(v))+ v = strings.TrimPrefix(v, "sha256:")+ if v == "" {+ return "", nil+ }+ if len(v) != sha256.Size*2 {+ return "", fmt.Errorf("--sha256 must be %d hex digits", sha256.Size*2)+ }+ if _, err := hex.DecodeString(v); err != nil {+ return "", fmt.Errorf("--sha256 must be hex: %w", err)+ }+ return v, nil+}+func runRulesPull(cmd *cobra.Command, args []string) error {- url := args[0]- if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {- return fmt.Errorf("url must start with http:// or https://")+ rawURL := args[0]+ wantSum, err := parseRulesPullSHA256(rulesOpts.sha256)+ if err != nil {+ return err}// Detect the pack format from the URL path only; query/fragment must not// influence the suffix match or the downloaded filename.- parsed, err := neturl.Parse(url)+ parsed, err := neturl.Parse(rawURL)if err != nil {return fmt.Errorf("parse url: %w", err)}- urlPath := parsed.Path- out := cmd.OutOrStdout()- fmt.Fprintf(out, "Fetching %s (network)…\n", url)-- tmp, err := os.MkdirTemp("", "beacon-rules-pull-")- if err != nil {+ if err := checkRulesPullURL(parsed); err != nil {return err}- defer os.RemoveAll(tmp)+ urlPath := parsed.Path+ isTarball := strings.HasSuffix(urlPath, ".tar.gz") || strings.HasSuffix(urlPath, ".tgz")+ if !isTarball && !strings.HasSuffix(urlPath, ".rule.yaml") {+ return fmt.Errorf("unsupported url: expected a .rule.yaml or .tar.gz/.tgz pack")+ }+ out := cmd.OutOrStdout()+ fmt.Fprintf(out, "Fetching %s (network)…\n", rawURL)- client := &http.Client{Timeout: 60 * time.Second}- resp, err := client.Get(url)+ client := &http.Client{Timeout: 60 * time.Second, Transport: rulesPullTransport, CheckRedirect: rulesPullCheckRedirect}+ resp, err := client.Get(parsed.String())if err != nil {return fmt.Errorf("fetch: %w", err)}defer resp.Body.Close()if resp.StatusCode != http.StatusOK {- return fmt.Errorf("fetch %s: HTTP %d", url, resp.StatusCode)+ return fmt.Errorf("fetch %s: HTTP %d", rawURL, resp.StatusCode)+ }+ if resp.ContentLength > rulesPullMaxDownloadBytes {+ return fmt.Errorf("download is %d bytes, over the %d-byte limit for a rule pack", resp.ContentLength, rulesPullMaxDownloadBytes)+ }+ // Read the whole pack into memory (bounded) so it is verified before a single byte+ // is unpacked or installed.+ data, err := io.ReadAll(io.LimitReader(resp.Body, rulesPullMaxDownloadBytes+1))+ if err != nil {+ return fmt.Errorf("fetch: %w", err)+ }+ if int64(len(data)) > rulesPullMaxDownloadBytes {+ return fmt.Errorf("download exceeds the %d-byte limit for a rule pack", rulesPullMaxDownloadBytes)+ }+ sum := sha256.Sum256(data)+ gotSum := hex.EncodeToString(sum[:])+ if wantSum != "" {+ if subtle.ConstantTimeCompare([]byte(gotSum), []byte(wantSum)) != 1 {+ return fmt.Errorf("sha256 mismatch: downloaded %s, expected %s; nothing was installed", gotSum, wantSum)+ }+ fmt.Fprintf(out, "Verified sha256 %s\n", gotSum)+ } else {+ fmt.Fprintf(out, "Downloaded %d bytes, sha256 %s (pass --sha256 to verify)\n", len(data), gotSum)}+ tmp, err := os.MkdirTemp("", "beacon-rules-pull-")+ if err != nil {+ return err+ }+ defer os.RemoveAll(tmp)+var src string- switch {- case strings.HasSuffix(urlPath, ".tar.gz"), strings.HasSuffix(urlPath, ".tgz"):- if err := extractRuleTarball(resp.Body, tmp); err != nil {+ if isTarball {+ if err := extractRuleTarball(bytes.NewReader(data), tmp); err != nil {return err}src = tmp- case strings.HasSuffix(urlPath, ".rule.yaml"):+ } else {+ if int64(len(data)) > rulesPullMaxEntryBytes {+ return fmt.Errorf("rule file is %d bytes, over the %d-byte limit for one rule", len(data), rulesPullMaxEntryBytes)+ }dest := filepath.Join(tmp, path.Base(urlPath))- if err := writeReaderToFile(resp.Body, dest); err != nil {+ if err := os.WriteFile(dest, data, 0o600); err != nil {return err}src = dest- default:- return fmt.Errorf("unsupported url: expected a .rule.yaml or .tar.gz/.tgz pack")}installed, skipped, err := detect.InstallFilesSkipping(rulesUserMode(), src, rulesOpts.force)@@ -176,11 +302,47 @@ func runRulesPull(cmd *cobra.Command, args []string) error {return nil}+// errTarStreamTooLarge is returned by the bounded reader under the tar stream.+var errTarStreamTooLarge = errors.New("tarball exceeds the uncompressed size limit")++// boundedReader fails, rather than silently truncating, once more than n bytes are read.+type boundedReader struct {+ r io.Reader+ n int64+}++func (b *boundedReader) Read(p []byte) (int, error) {+ if b.n <= 0 {+ // Probe for one more byte so a stream of exactly the limit still ends cleanly.+ var one [1]byte+ k, err := b.r.Read(one[:])+ if k > 0 {+ return 0, errTarStreamTooLarge+ }+ return 0, err+ }+ if int64(len(p)) > b.n {+ p = p[:b.n]+ }+ k, err := b.r.Read(p)+ b.n -= int64(k)+ return k, err+}++func tarLimitError(err error) error {+ if errors.Is(err, errTarStreamTooLarge) {+ return fmt.Errorf("tarball exceeds the %d-byte uncompressed limit for a rule pack", rulesPullMaxTarBytes)+ }+ return nil+}+// extractRuleTarball extracts *.rule.yaml entries from a gzipped tarball into dir. Entry// paths keep their relative archive layout so two entries that share a base name (e.g.// network/exfil.rule.yaml and secrets/exfil.rule.yaml) do not overwrite each other;// path-traversal entries are rejected. InstallFiles walks dir recursively and keys the-// installed file on rule id, so preserving subdirectories here loses no rules.+// installed file on rule id, so preserving subdirectories here loses no rules. The+// number of entries, the size of each rule entry and the decompressed size of the whole+// stream are capped, so a gzip bomb fails with an error instead of filling the disk.func extractRuleTarball(r io.Reader, dir string) error {gz, err := gzip.NewReader(r)if err != nil {@@ -188,16 +350,23 @@ func extractRuleTarball(r io.Reader, dir string) error {}defer gz.Close()cleanDir := filepath.Clean(dir)- tr := tar.NewReader(gz)- count := 0+ tr := tar.NewReader(&boundedReader{r: gz, n: rulesPullMaxTarBytes})+ count, entries := 0, 0for {hdr, err := tr.Next()if err == io.EOF {break}+ if limitErr := tarLimitError(err); limitErr != nil {+ return limitErr+ }if err != nil {return fmt.Errorf("tar: %w", err)}+ entries+++ if entries > rulesPullMaxTarEntries {+ return fmt.Errorf("tarball has more than %d entries", rulesPullMaxTarEntries)+ }if hdr.Typeflag != tar.TypeReg || !strings.HasSuffix(hdr.Name, ".rule.yaml") || isAppleDoubleArchiveEntry(hdr.Name) {continue}@@ -207,6 +376,9 @@ func extractRuleTarball(r io.Reader, dir string) error {if strings.Contains(hdr.Name, "..") {return fmt.Errorf("archive entry %q contains a path traversal element", hdr.Name)}+ if hdr.Size > rulesPullMaxEntryBytes {+ return fmt.Errorf("archive entry %q is %d bytes, over the %d-byte limit for one rule", hdr.Name, hdr.Size, rulesPullMaxEntryBytes)+ }// Preserve the entry's relative directory structure (rejecting absolute paths),// then confirm the joined destination stays within cleanDir before any file// operation (defense in depth; the same `dest` value is both validated and@@ -223,7 +395,10 @@ func extractRuleTarball(r io.Reader, dir string) error {if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil {return err}- if err := writeReaderToFile(io.LimitReader(tr, 1<<20), dest); err != nil {+ if err := writeReaderToFile(io.LimitReader(tr, rulesPullMaxEntryBytes), dest); err != nil {+ if limitErr := tarLimitError(err); limitErr != nil {+ return limitErr+ }return err}count++@@ -370,6 +545,7 @@ func init() {for _, c := range []*cobra.Command{rulesAddCmd, rulesPullCmd} {c.Flags().BoolVar(&rulesOpts.force, "force", false, "Overwrite an existing rule with the same id")}+ rulesPullCmd.Flags().StringVar(&rulesOpts.sha256, "sha256", "", "Expected SHA-256 of the downloaded file (hex); nothing is installed on a mismatch")rulesCmd.AddCommand(rulesListCmd, rulesAddCmd, rulesRemoveCmd, rulesPullCmd, rulesLintCmd, rulesFieldsCmd)rootCmd.AddCommand(rulesCmd)}diff --git a/cli/beacon/cmd/rules_test.go b/cli/beacon/cmd/rules_test.goindex de762ad7..f673481c 100644--- a/cli/beacon/cmd/rules_test.go+++ b/cli/beacon/cmd/rules_test.go@@ -4,13 +4,20 @@ import ("archive/tar""bytes""compress/gzip"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "io""net/http""net/http/httptest"+ neturl "net/url""os""path/filepath""strings""testing"+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/detect""github.com/asymptote-labs/agent-beacon/cli/beacon/internal/testenv""github.com/spf13/cobra")@@ -286,3 +293,244 @@ func TestLoadRuleFilesSingleFile(t *testing.T) {t.Fatalf("unexpected: %+v", rules)}}++// pullTestSetup isolates the store and resets the pull options and limits for a test.+func pullTestSetup(t *testing.T) {+ t.Helper()+ testenv.SetHome(t, t.TempDir())+ prevOpts := rulesOpts+ prevTransport := rulesPullTransport+ prevDownload, prevEntries, prevTar, prevEntry := rulesPullMaxDownloadBytes, rulesPullMaxTarEntries, rulesPullMaxTarBytes, rulesPullMaxEntryBytes+ rulesOpts.userMode, rulesOpts.systemMode, rulesOpts.force, rulesOpts.sha256 = true, false, false, ""+ t.Cleanup(func() {+ rulesOpts = prevOpts+ rulesPullTransport = prevTransport+ rulesPullMaxDownloadBytes, rulesPullMaxTarEntries, rulesPullMaxTarBytes, rulesPullMaxEntryBytes = prevDownload, prevEntries, prevTar, prevEntry+ })+}++// storeIsEmpty reports whether nothing was installed into the user-mode rule store.+func storeIsEmpty(t *testing.T) bool {+ t.Helper()+ entries, err := os.ReadDir(detect.StoreDir(true))+ if os.IsNotExist(err) {+ return true+ }+ if err != nil {+ t.Fatal(err)+ }+ for _, e := range entries {+ if strings.HasSuffix(e.Name(), ".rule.yaml") {+ return false+ }+ }+ return true+}++func TestRulesPullRefusesNonLoopbackHTTP(t *testing.T) {+ pullTestSetup(t)+ for _, u := range []string{+ "http://example.com/pack.tar.gz",+ "http://10.0.0.1/x.rule.yaml",+ "ftp://example.com/pack.tar.gz",+ "file:///tmp/pack.tar.gz",+ } {+ cmd, _ := newCmd()+ err := runRulesPull(cmd, []string{u})+ if err == nil || !strings.Contains(err.Error(), "https://") {+ t.Errorf("%s: want an https-required error, got %v", u, err)+ }+ }+ for _, u := range []string{"http://127.0.0.1:1/x", "http://localhost/x", "http://[::1]/x", "https://example.com/x"} {+ parsed, _ := neturl.Parse(u)+ if err := checkRulesPullURL(parsed); err != nil {+ t.Errorf("%s should be accepted: %v", u, err)+ }+ }+}++func TestRulesPullOverHTTPS(t *testing.T) {+ pullTestSetup(t)+ pack := makeTarGz(t, map[string]string{"cli-test-rule.rule.yaml": validRuleYAML})+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(pack) }))+ t.Cleanup(srv.Close)+ rulesPullTransport = srv.Client().Transport++ sum := sha256.Sum256(pack)+ rulesOpts.sha256 = "SHA256:" + strings.ToUpper(hex.EncodeToString(sum[:]))+ cmd, buf := newCmd()+ if err := runRulesPull(cmd, []string{srv.URL + "/pack.tar.gz"}); err != nil {+ t.Fatalf("https pull: %v\n%s", err, buf.String())+ }+ if !strings.Contains(buf.String(), "Verified sha256") || !strings.Contains(buf.String(), "installed cli-test-rule") {+ t.Fatalf("want a verified install, got:\n%s", buf.String())+ }+}++func TestRulesPullRefusesHTTPSToHTTPRedirect(t *testing.T) {+ pullTestSetup(t)+ pack := makeTarGz(t, map[string]string{"cli-test-rule.rule.yaml": validRuleYAML})+ plain := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(pack) }))+ t.Cleanup(plain.Close)+ tlsSrv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, plain.URL+"/pack.tar.gz", http.StatusFound)+ }))+ t.Cleanup(tlsSrv.Close)+ rulesPullTransport = tlsSrv.Client().Transport++ cmd, buf := newCmd()+ err := runRulesPull(cmd, []string{tlsSrv.URL + "/pack.tar.gz"})+ if err == nil || !strings.Contains(err.Error(), "refusing redirect from https") {+ t.Fatalf("want the downgrade refused, got %v\n%s", err, buf.String())+ }+ if !storeIsEmpty(t) {+ t.Fatal("nothing may be installed after a refused redirect")+ }+}++func TestRulesPullRedirectChecks(t *testing.T) {+ req := &http.Request{URL: &neturl.URL{Scheme: "http", Host: "example.com", Path: "/x.tar.gz"}}+ via := []*http.Request{{URL: &neturl.URL{Scheme: "http", Host: "127.0.0.1", Path: "/x.tar.gz"}}}+ if err := rulesPullCheckRedirect(req, via); err == nil {+ t.Fatal("a redirect from loopback http to a remote http host must be refused")+ }+ same := &http.Request{URL: &neturl.URL{Scheme: "https", Host: "objects.example.com", Path: "/x.tar.gz"}}+ viaTLS := []*http.Request{{URL: &neturl.URL{Scheme: "https", Host: "github.com", Path: "/x.tar.gz"}}}+ if err := rulesPullCheckRedirect(same, viaTLS); err != nil {+ t.Fatalf("an https to https redirect must be followed: %v", err)+ }+}++func TestRulesPullSHA256MismatchInstallsNothing(t *testing.T) {+ pullTestSetup(t)+ pack := makeTarGz(t, map[string]string{"cli-test-rule.rule.yaml": validRuleYAML})+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(pack) }))+ t.Cleanup(srv.Close)++ rulesOpts.sha256 = strings.Repeat("0", 64)+ cmd, buf := newCmd()+ err := runRulesPull(cmd, []string{srv.URL + "/pack.tar.gz"})+ if err == nil || !strings.Contains(err.Error(), "sha256 mismatch") || !strings.Contains(err.Error(), "nothing was installed") {+ t.Fatalf("want a sha256 mismatch, got %v\n%s", err, buf.String())+ }+ if !storeIsEmpty(t) {+ t.Fatal("a checksum mismatch must install nothing")+ }++ rulesOpts.sha256 = "not-hex"+ if err := runRulesPull(cmd, []string{srv.URL + "/pack.tar.gz"}); err == nil || !strings.Contains(err.Error(), "--sha256") {+ t.Fatalf("want a malformed --sha256 refused, got %v", err)+ }+}++func TestRulesPullRefusesOversizedDownload(t *testing.T) {+ pullTestSetup(t)+ rulesPullMaxDownloadBytes = 1024+ big := strings.Repeat("#", 4096)+ for name, chunked := range map[string]bool{"content-length": false, "chunked": true} {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if chunked {+ w.(http.Flusher).Flush() // no Content-Length: the body cap must catch it+ }+ w.Write([]byte(big))+ }))+ cmd, _ := newCmd()+ err := runRulesPull(cmd, []string{srv.URL + "/x.rule.yaml"})+ srv.Close()+ if err == nil || !strings.Contains(err.Error(), "limit for a rule pack") {+ t.Errorf("%s: want the download limit refused, got %v", name, err)+ }+ }+ if !storeIsEmpty(t) {+ t.Fatal("an oversized download must install nothing")+ }+}++func TestExtractRuleTarballTooManyEntries(t *testing.T) {+ pullTestSetup(t)+ rulesPullMaxTarEntries = 5+ entries := map[string]string{}+ for i := 0; i < 6; i++ {+ entries[fmt.Sprintf("notes-%d.txt", i)] = "x"+ }+ err := extractRuleTarball(bytes.NewReader(makeTarGz(t, entries)), t.TempDir())+ if err == nil || !strings.Contains(err.Error(), "more than 5 entries") {+ t.Fatalf("want the entry cap enforced, got %v", err)+ }+}++func TestExtractRuleTarballTooManyBytes(t *testing.T) {+ pullTestSetup(t)+ rulesPullMaxTarBytes = 64 << 10+ // A highly compressible non-rule entry, as in a gzip bomb: small on the wire, large+ // once decompressed.+ data := makeTarGz(t, map[string]string{+ "a.rule.yaml": "id: a",+ "bomb.bin": strings.Repeat("\x00", 1<<20),+ })+ if int64(len(data)) >= rulesPullMaxTarBytes {+ t.Fatalf("fixture should compress below the limit, got %d bytes", len(data))+ }+ err := extractRuleTarball(bytes.NewReader(data), t.TempDir())+ if err == nil || !strings.Contains(err.Error(), "uncompressed limit") {+ t.Fatalf("want the decompressed-size cap enforced, got %v", err)+ }+}++func TestExtractRuleTarballOversizedEntry(t *testing.T) {+ pullTestSetup(t)+ rulesPullMaxEntryBytes = 16+ err := extractRuleTarball(bytes.NewReader(makeTarGz(t, map[string]string{"big.rule.yaml": strings.Repeat("a", 64)})), t.TempDir())+ if err == nil || !strings.Contains(err.Error(), "limit for one rule") {+ t.Fatalf("want an oversized rule entry refused rather than truncated, got %v", err)+ }+}++func TestBoundedReaderAllowsExactLimit(t *testing.T) {+ r := &boundedReader{r: strings.NewReader("abcd"), n: 4}+ got, err := io.ReadAll(r)+ if err != nil || string(got) != "abcd" {+ t.Fatalf("exact-limit read: %q, %v", got, err)+ }+ r = &boundedReader{r: strings.NewReader("abcde"), n: 4}+ if _, err := io.ReadAll(r); !errors.Is(err, errTarStreamTooLarge) {+ t.Fatalf("over-limit read: want errTarStreamTooLarge, got %v", err)+ }+}++func TestRulesListAndRemoveShowBaseline(t *testing.T) {+ pullTestSetup(t)+ src := t.TempDir()+ writeRuleFile(t, src, "ok.rule.yaml", validRuleYAML)+ cmd, buf := newCmd()+ if err := rulesAddCmd.RunE(cmd, []string{src}); err != nil {+ t.Fatalf("rules add: %v", err)+ }+ buf.Reset()+ if err := rulesListCmd.RunE(cmd, nil); err != nil {+ t.Fatalf("rules list: %v", err)+ }+ base, err := detect.Baseline()+ if err != nil {+ t.Fatal(err)+ }+ want := fmt.Sprintf("%d rule(s): 1 from the store, %d from the built-in baseline.", len(base)+1, len(base))+ if !strings.Contains(buf.String(), want) {+ t.Fatalf("want %q in:\n%s", want, buf.String())+ }++ // Installing and then removing a store copy of a baseline rule says the baseline+ // copy is active again.+ id := base[0].ID+ override := writeRuleFile(t, t.TempDir(), "override.rule.yaml", strings.Replace(validRuleYAML, "id: cli-test-rule", "id: "+id, 1))+ if err := rulesAddCmd.RunE(cmd, []string{override}); err != nil {+ t.Fatalf("rules add override: %v", err)+ }+ buf.Reset()+ if err := rulesRemoveCmd.RunE(cmd, []string{id}); err != nil {+ t.Fatalf("rules remove: %v", err)+ }+ if !strings.Contains(buf.String(), "baseline copy is active again") {+ t.Fatalf("want the baseline note, got:\n%s", buf.String())+ }+}diff --git a/cli/beacon/cmd/scan.go b/cli/beacon/cmd/scan.goindex a1a9c878..b0684942 100644--- a/cli/beacon/cmd/scan.go+++ b/cli/beacon/cmd/scan.go@@ -32,8 +32,9 @@ var scanCmd = &cobra.Command{Long: `Scans the local Beacon runtime telemetry log with the active threat-detectionrules and reports findings.-Rules come from the local store (~/.beacon/endpoint/rules) when present, otherwise from-the built-in baseline. Use --rules to scan with an explicit rule directory, and+Rules come from the local store (~/.beacon/endpoint/rules) plus every built-in baseline+rule the store does not replace by id. Use --rules to scan with only an explicit rule+directory, and'beacon rules add' / 'beacon rules pull' to manage the store.Scanning is read-only and never touches the network.`,@@ -209,7 +210,7 @@ func init() {scanCmd.Flags().BoolVar(&scanOpts.userMode, "user", true, "Use per-user endpoint paths")scanCmd.Flags().BoolVar(&scanOpts.systemMode, "system", false, "Use system endpoint paths")scanCmd.Flags().StringVar(&scanOpts.logPath, "log-path", "", "Runtime JSONL log path (default: resolved from config)")- scanCmd.Flags().StringVar(&scanOpts.rulesDir, "rules", "", "Rule directory to scan with (default: store, else baseline)")+ scanCmd.Flags().StringVar(&scanOpts.rulesDir, "rules", "", "Rule directory to scan with, instead of the store and baseline")scanCmd.Flags().BoolVar(&scanOpts.jsonOutput, "json", false, "Output findings as JSON")scanCmd.Flags().StringVar(&scanOpts.minSeverity, "min-severity", "", "Only report findings at or above this severity")scanCmd.Flags().StringVar(&scanOpts.session, "session", "", "Only scan events for this session id")diff --git a/cli/beacon/internal/endpoint/dashboard/detections.go b/cli/beacon/internal/endpoint/dashboard/detections.goindex 70528324..986c2186 100644--- a/cli/beacon/internal/endpoint/dashboard/detections.go+++ b/cli/beacon/internal/endpoint/dashboard/detections.go@@ -35,8 +35,9 @@ type DetectionsResponse struct {Skipped []string `json:"skipped,omitempty"`}-// BuildDetections lists the active rule set (store when present, else the-// embedded baseline — the same set `beacon scan` would run) as detection views.+// BuildDetections lists the active rule set (the store plus every embedded baseline+// rule it does not replace by id — the same set `beacon scan` would run) as detection+// views.func BuildDetections(userMode bool, rulesDir string) (DetectionsResponse, error) {loaded, skipped, err := detect.LoadActiveSkipping(userMode, strings.TrimSpace(rulesDir))if err != nil {diff --git a/cli/beacon/internal/endpoint/dashboard/findings_skipped_test.go b/cli/beacon/internal/endpoint/dashboard/findings_skipped_test.goindex 9fc91bcb..2a7d921f 100644--- a/cli/beacon/internal/endpoint/dashboard/findings_skipped_test.go+++ b/cli/beacon/internal/endpoint/dashboard/findings_skipped_test.go@@ -2,6 +2,7 @@ package dashboardimport ("encoding/json"+ "errors""net/http""net/http/httptest""os"@@ -64,23 +65,48 @@ func findingsFixture(t *testing.T, rules map[string]string) *httptest.ResponseRereturn rec}-func TestFindingsAllRulesSkippedNamesThem(t *testing.T) {+// TestFindingsAllStoreRulesSkippedStillRunsBaseline: the embedded baseline stays active+// alongside the store, so a store whose every rule needs a newer Beacon still scans with+// the baseline and names the skipped rules instead of failing.+func TestFindingsAllStoreRulesSkippedStillRunsBaseline(t *testing.T) {rec := findingsFixture(t, map[string]string{"future-a": storeRule("future-a", "threat-rules/v1.2"),"future-b": storeRule("future-b", "threat-rules/v2"),})- if rec.Code != http.StatusBadRequest {- t.Fatalf("status = %d, want 400; body %s", rec.Code, rec.Body.String())- }- var body struct {- Error string `json:"error"`- Skipped []string `json:"skipped"`+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body.String())}- if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {+ var resp FindingsResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {t.Fatalf("unmarshal: %v\n%s", err, rec.Body.String())}- if strings.Contains(body.Error, "store is empty") {- t.Fatalf("error must not claim the store is empty: %s", body.Error)+ if len(resp.Skipped) != 2 || !strings.Contains(strings.Join(resp.Skipped, "\n"), "future-a.rule.yaml") {+ t.Fatalf("want both rules in skipped, got %v", resp.Skipped)+ }+}++// TestRunScanAllRulesSkippedNamesThem: with an explicit rules directory (no baseline),+// every rule needing a newer Beacon is a NoRulesError that names them.+func TestRunScanAllRulesSkippedNamesThem(t *testing.T) {+ testenv.SetHome(t, t.TempDir())+ dir := t.TempDir()+ for id, spec := range map[string]string{"future-a": "threat-rules/v1.2", "future-b": "threat-rules/v2"} {+ if err := os.WriteFile(filepath.Join(dir, id+".rule.yaml"), []byte(storeRule(id, spec)), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ logPath := filepath.Join(t.TempDir(), "runtime.jsonl")+ if err := os.WriteFile(logPath, nil, 0o644); err != nil {+ t.Fatal(err)+ }+ _, err := RunScan(true, logPath, dir, "", "")+ var noRules *detect.NoRulesError+ if !errors.As(err, &noRules) || len(noRules.Skipped) != 2 {+ t.Fatalf("want a NoRulesError naming both rules, got %v", err)+ }+ msg := err.Error()+ if strings.Contains(msg, "store is empty") {+ t.Fatalf("error must not claim the store is empty: %s", msg)}for _, want := range []string{`rule "future-a" requires threat-rules/v1.2`,@@ -88,13 +114,10 @@ func TestFindingsAllRulesSkippedNamesThem(t *testing.T) {"supports up to " + threatrules.SupportedSpec,"upgrade Beacon",} {- if !strings.Contains(body.Error, want) {- t.Errorf("error %q missing %q", body.Error, want)+ if !strings.Contains(msg, want) {+ t.Errorf("error %q missing %q", msg, want)}}- if len(body.Skipped) != 2 || !strings.Contains(strings.Join(body.Skipped, "\n"), "future-a.rule.yaml") {- t.Fatalf("want both rules in skipped, got %v", body.Skipped)- }}func TestFindingsSomeRulesSkippedRunsTheRest(t *testing.T) {diff --git a/cli/beacon/internal/endpoint/detect/detect.go b/cli/beacon/internal/endpoint/detect/detect.goindex d9ab3428..fdc3df70 100644--- a/cli/beacon/internal/endpoint/detect/detect.go+++ b/cli/beacon/internal/endpoint/detect/detect.go@@ -48,6 +48,11 @@ func Baseline() ([]*threatrules.Rule, error) {return rulestore.Baseline()}+// IsBaselineID reports whether id names a rule in the embedded baseline.+func IsBaselineID(id string) bool {+ return rulestore.IsBaselineID(id)+}+// LoadActive resolves the active rule set for the given mode. See rulestore.LoadActive.func LoadActive(userMode bool, rulesDir string) ([]LoadedRule, error) {return rulestore.LoadActive(StoreDir(userMode), rulesDir)diff --git a/cli/beacon/internal/endpoint/detect/detect_test.go b/cli/beacon/internal/endpoint/detect/detect_test.goindex 9d02d32d..3be2c1bc 100644--- a/cli/beacon/internal/endpoint/detect/detect_test.go+++ b/cli/beacon/internal/endpoint/detect/detect_test.go@@ -85,8 +85,12 @@ func TestInstallRemoveRoundTripViaUserMode(t *testing.T) {if err != nil {t.Fatalf("load active: %v", err)}- if len(loaded) != 1 || loaded[0].Source != SourceStore || loaded[0].Rule.ID != "custom-rule" {- t.Fatalf("expected store rule, got %+v", loaded)+ base, err := Baseline()+ if err != nil {+ t.Fatal(err)+ }+ if len(loaded) != len(base)+1 || loaded[0].Source != SourceStore || loaded[0].Rule.ID != "custom-rule" {+ t.Fatalf("expected the store rule plus the baseline, got %+v", loaded)}if _, err := Remove(true, "custom-rule"); err != nil {diff --git a/docs/cli/dashboard.mdx b/docs/cli/dashboard.mdxindex b2b0f458..30997044 100644--- a/docs/cli/dashboard.mdx+++ b/docs/cli/dashboard.mdx@@ -49,8 +49,8 @@ poll, and OTLP collection paths.- **Token Usage:** review runtime-reported token usage and cost where sourcesprovide it.- **Detections:** browse the active [threat-rule](/detections) set that Beacon- would use for local scans, including rules installed in the local store or the- built-in baseline when no store is installed.+ would use for local scans: rules installed in the local store plus the+ built-in baseline rules the store does not replace by id.- **Findings:** run the active rules over the configured runtime log on demand andreview matching evidence with severity and session filters.- **Agent Inventory:** inspect [Inventory Local Agent Runtimes](/guides/inventory)diff --git a/docs/cli/rules-list.mdx b/docs/cli/rules-list.mdxindex 885586eb..d594fc89 100644--- a/docs/cli/rules-list.mdx+++ b/docs/cli/rules-list.mdx@@ -11,7 +11,9 @@ description: "List active Beacon threat-detection rules"beacon rules list [flags]```-The output includes each rule id, severity, maturity status, and source. The source shows whether Beacon loaded the rule from the local store or the built-in baseline.+The output includes each rule id, severity, maturity status, and source. The source shows whether Beacon loaded the rule from the local store or the built-in baseline, and the closing line counts the rules from each.++The built-in baseline stays active alongside the store. A store rule replaces a baseline rule only when it has the same id, so installing your own rules adds to the baseline rather than switching it off.## Examplesdiff --git a/docs/cli/rules-pull.mdx b/docs/cli/rules-pull.mdxindex 30e2aea9..de0a6936 100644--- a/docs/cli/rules-pull.mdx+++ b/docs/cli/rules-pull.mdx@@ -25,6 +25,27 @@ This is the only `beacon rules` command that reaches the network, and only whenDownloaded tarballs only install `.rule.yaml` entries. Archive entries containing path traversal elements are rejected before install.+## Transport and integrity++Rules decide what `beacon scan` can see, so a pull refuses sources that a network attacker could tamper with:++- The URL must use `https://`. Plain `http://` is accepted only for a loopback host (`localhost`, `127.0.0.1`, `::1`), for testing a pack served from your own machine.+- Redirects are followed only while they stay on `https://` (for example, a GitHub release download redirecting to its storage host). A redirect from `https://` to `http://`, or to a host the command would not have accepted directly, stops the pull.+- With `--sha256 <hex>`, Beacon hashes the downloaded bytes and installs nothing unless they match. Use the SHA-256 digest the publisher lists for the asset; GitHub shows one for every release asset. Without `--sha256`, Beacon prints the digest of what it downloaded so you can compare it yourself.++The whole download is read and checked before anything is unpacked or written to the store, and these limits apply:++| Limit | Value |+|-------|-------|+| Download size | 32 MiB |+| Tarball entries (every entry, rule or not) | 10,000 |+| Tarball size once decompressed | 64 MiB |+| One `.rule.yaml` file | 1 MiB |++The published rule pack is about 50 KB compressed, with under 100 entries and about 300 KB decompressed. A source over any limit fails with an error that names the limit, and nothing is installed.++Installing rules never switches off the [built-in baseline](/cli/rules-list): a pulled rule replaces a baseline rule only when it has the same id.+## ExamplesPull a rule pack:@@ -33,6 +54,13 @@ Pull a rule pack:beacon rules pull https://github.com/asymptote-labs/agent-beacon/releases/download/v0.0.95/threat-rules.tar.gz```+Pull a rule pack and verify it against the asset's published SHA-256 digest:++```bash title="Pull and verify a rule pack"+beacon rules pull https://github.com/asymptote-labs/agent-beacon/releases/download/v0.0.95/threat-rules.tar.gz \+ --sha256 <sha256-of-threat-rules.tar.gz>+```+Pull one rule file:```bash title="Pull one rule file"@@ -58,6 +86,7 @@ sudo beacon rules pull https://github.com/asymptote-labs/agent-beacon/releases/d| `--user` | Use per-user endpoint paths. Enabled by default || `--system` | Use system endpoint paths || `--force` | Overwrite an existing rule with the same id |+| `--sha256 <hex>` | Expected SHA-256 of the downloaded file, as 64 hex digits (a `sha256:` prefix is accepted). Nothing is installed on a mismatch |## Relateddiff --git a/docs/cli/rules-remove.mdx b/docs/cli/rules-remove.mdxindex fce1c5c6..b73f6e25 100644--- a/docs/cli/rules-remove.mdx+++ b/docs/cli/rules-remove.mdx@@ -13,6 +13,8 @@ beacon rules remove <id> [flags]Use [`beacon rules list`](/cli/rules-list) first when you need to confirm the active rule ids.+Built-in baseline rules are not in the store and cannot be removed. When the removed store rule shares its id with a baseline rule, the baseline copy becomes active again and the command says so.+## ExamplesRemove one rule from the user-mode store:diff --git a/docs/cli/rules.mdx b/docs/cli/rules.mdxindex 4b7e9840..dfcaf8ad 100644--- a/docs/cli/rules.mdx+++ b/docs/cli/rules.mdx@@ -11,7 +11,7 @@ description: "Manage and author Beacon threat-detection rules"beacon rules [command]```-The detection engine ships in the Beacon binary, but rules are external data loaded from the local store. A small baseline is built in and used until you install your own rules. Beacon publishes the full threat-rule pack as a versioned `threat-rules.tar.gz` asset on each GitHub release.+The detection engine ships in the Beacon binary, but rules are external data loaded from the local store. A small baseline is built in and stays active alongside the store: an installed rule replaces a baseline rule only when it has the same id, so installing rules never switches the baseline off. Beacon publishes the full threat-rule pack as a versioned `threat-rules.tar.gz` asset on each GitHub release.<Note>Beacon never fetches rules on its own. `beacon rules pull` is the only rules command that reaches the network, and only for the explicit URL you provide.@@ -73,7 +73,7 @@ tests:## beacon rules list-List the active rules and show whether each rule came from the store or the built-in baseline.+List the active rules and show whether each rule came from the store or the built-in baseline. The summary line counts both.```bash title="List active rules"beacon rules list@@ -103,6 +103,8 @@ Remove one rule from the store by id.beacon rules remove suspicious-egress-command```+Removing a store rule that shares its id with a baseline rule makes the baseline copy active again.+## beacon rules pullFetch a `.rule.yaml`, `.tar.gz`, or `.tgz` rule pack from an explicit URL and install valid rules into the store.@@ -111,7 +113,7 @@ Fetch a `.rule.yaml`, `.tar.gz`, or `.tgz` rule pack from an explicit URL and inbeacon rules pull https://github.com/asymptote-labs/agent-beacon/releases/download/v0.0.95/threat-rules.tar.gz```-Downloaded tarballs only install `.rule.yaml` entries. Archive entries containing path traversal elements are rejected before install.+The URL must be `https://` (plain `http://` only for a loopback host), and a redirect that leaves `https://` is refused. Pass `--sha256 <hex>` to verify the download before anything is installed. Downloads are capped at 32 MiB, and tarballs at 10,000 entries and 64 MiB decompressed. Downloaded tarballs only install `.rule.yaml` entries. Archive entries containing path traversal elements are rejected before install. See [`beacon rules pull`](/cli/rules-pull#transport-and-integrity).## beacon rules lint@@ -146,6 +148,7 @@ beacon rules fields --markdown| `--user` | Use per-user endpoint paths. Enabled by default || `--system` | Use system endpoint paths || `--force` | Overwrite an existing rule with the same id. Available on `add` and `pull` |+| `--sha256 <hex>` | Expected SHA-256 of the download. Available on `pull` |## Relateddiff --git a/docs/cli/scan-local.mdx b/docs/cli/scan-local.mdxindex c82191a4..c7c314e0 100644--- a/docs/cli/scan-local.mdx+++ b/docs/cli/scan-local.mdx@@ -18,8 +18,8 @@ Scanning is read-only. It loads local telemetry from the resolved runtime JSONLBeacon chooses rules in this order:1. Rules in the local rule store.-2. The built-in baseline rules when no store is installed.-3. The directory passed with `--rules`, when you want an explicit rule pack for one scan.+2. The built-in baseline rules, except any whose id a store rule already defines (the store copy wins). With no store installed, the baseline runs alone.+3. The directory passed with `--rules`, when you want an explicit rule pack for one scan. It replaces both of the above.```bash title="Scan with an explicit rule directory"beacon scan --rules ./rulesdiff --git a/docs/cli/scan.mdx b/docs/cli/scan.mdxindex 5d923698..a614c9e4 100644--- a/docs/cli/scan.mdx+++ b/docs/cli/scan.mdx@@ -15,7 +15,7 @@ Use this command after endpoint telemetry is flowing when you want a local risk## How scanning works-Beacon loads rules from the local rule store when present. If no store is installed, Beacon uses the built-in baseline rules. You can also point a scan at an explicit rule directory with `--rules`.+Beacon runs the rules in the local rule store plus every built-in baseline rule the store does not replace by id; with no store installed, that is the baseline alone. You can also point a scan at an explicit rule directory with `--rules`, which runs only that directory.Rules are YAML documents with CEL expressions over the Beacon [Endpoint Event Schema](/telemetry-schema/event-schema). Rules can match one event or correlate multiple ordered events within one session window.@@ -75,7 +75,7 @@ beacon scan --session claude-session-123| `--user` | Use per-user endpoint paths. Enabled by default || `--system` | Use system endpoint paths || `--log-path <path>` | Runtime JSONL log path. Defaults to the path resolved from endpoint config |-| `--rules <dir>` | Rule directory to scan with. Defaults to the local store, then the built-in baseline |+| `--rules <dir>` | Rule directory to scan with, instead of the local store and the built-in baseline || `--json` | Output findings as JSON || `--min-severity <level>` | Only report findings at or above `info`, `low`, `medium`, `high`, or `critical` || `--session <id>` | Only scan events whose session id contains this value |diff --git a/docs/detections/engine.mdx b/docs/detections/engine.mdxindex 5868713e..57cc0d9a 100644--- a/docs/detections/engine.mdx+++ b/docs/detections/engine.mdx@@ -15,7 +15,7 @@ When `beacon scan` runs, Beacon resolves the active rules in this order:1. If `--rules <dir>` is provided, load `.rule.yaml` files from that directory.2. Otherwise, load installed rules from the endpoint rule store.-3. If the store is absent or empty, load the built-in baseline rules embedded in the binary.+3. Add every built-in baseline rule embedded in the binary whose id the store does not define. A store rule with a baseline rule's id replaces that one baseline rule; installing rules never switches the rest of the baseline off. With the store absent or empty, the baseline runs alone.The per-user store is under the endpoint base directory, commonly `~/.beacon/endpoint/rules`. System-mode installs use the system endpoint base directory.diff --git a/docs/detections/index.mdx b/docs/detections/index.mdxindex 9e34e2a9..a0bda76c 100644--- a/docs/detections/index.mdx+++ b/docs/detections/index.mdx@@ -66,7 +66,7 @@ Because rules run over the shared Beacon event model, the same rule vocabulary c## Detection coverage-Beacon ships with a small built-in baseline so `beacon scan` works before any rule store is installed. The broader rule pack is distributed as a release asset and includes categories like these:+Beacon ships with a small built-in baseline so `beacon scan` works before any rule store is installed, and it stays active once you install rules. The broader rule pack is distributed as a release asset and includes categories like these:| Category | Example behaviors || --- | --- |@@ -86,7 +86,7 @@ Rules only evaluate events that exist in the runtime log. For example, an MCP de1. A supported agent harness emits runtime telemetry.2. Beacon normalizes that telemetry into endpoint events and writes `runtime.jsonl`.-3. `beacon scan` loads the active rule set from an explicit rules directory, the local rule store, or the built-in baseline.+3. `beacon scan` loads the active rule set from an explicit rules directory, or from the local rule store plus the built-in baseline.4. Each rule is decoded, validated, and compiled before it runs.5. The scan evaluates rules against the ordered event stream.6. Matching rules produce findings with rule metadata, severity, reason, session context, and evidence events.@@ -151,9 +151,9 @@ tests:Beacon can run detections from three sources, resolved in this order:-1. An explicit directory passed to `beacon scan --rules`.+1. An explicit directory passed to `beacon scan --rules`, which runs alone.2. The local endpoint rule store managed by `beacon rules`.-3. The built-in baseline when no local store is installed or the store is empty.+3. The built-in baseline, alongside the store. A store rule with a baseline rule's id replaces that baseline rule; every other baseline rule stays active.Use an explicit rule directory when you are developing or testing a rule pack without installing it:@@ -193,7 +193,7 @@ Use the [Detection YAML Schema](/detections/yaml-schema) page for the rule docum- `beacon scan --fail-on <level>` exits non-zero when any finding at or above the threshold exists.- `beacon scan --session <id>` narrows evaluation to events whose session ID contains the supplied value.- `beacon scan --log-path <path>` scans a copied or archived `runtime.jsonl` file.-- `beacon rules pull` is the only rules workflow that reaches the network, and only for the explicit URL you provide.+- `beacon rules pull` is the only rules workflow that reaches the network, and only for the explicit `https://` URL you provide. It refuses redirects that leave `https://`, caps the download size, and with `--sha256` installs nothing unless the download matches the expected digest.- The local dashboard mirrors `beacon scan` rule resolution and finding behavior, but stays loopback-only and read-only.## Beacon Cloud detectionsdiff --git a/docs/guides/local-testing/dashboard.mdx b/docs/guides/local-testing/dashboard.mdxindex 3428c9b5..19c14ea5 100644--- a/docs/guides/local-testing/dashboard.mdx+++ b/docs/guides/local-testing/dashboard.mdx@@ -92,8 +92,8 @@ Use the remaining local views to check adjacent state:- **Memory:** read-only evaluation, candidate, and approved-memory counts from`memory.db`.-- **Detections:** the active threat-rule set from the local rules store or built-in- baseline.+- **Detections:** the active threat-rule set from the local rules store plus the+ built-in baseline.- **Findings:** on-demand rule matches over the configured runtime log.- **Agent Inventory:** detected runtimes, MCP servers, Agent Skills, hooks, andtelemetry status.diff --git a/pkg/asymptoteobserve/rulestore/rulestore.go b/pkg/asymptoteobserve/rulestore/rulestore.goindex 9602e989..6e7b9e16 100644--- a/pkg/asymptoteobserve/rulestore/rulestore.go+++ b/pkg/asymptoteobserve/rulestore/rulestore.go@@ -103,8 +103,12 @@ func baselineRulePath(name string) string {// LoadActive resolves the active rule set://// - if rulesDir is non-empty, load only from that directory (explicit override);-// - else load from storeDir; if the store is empty (or absent), fall back to the-// embedded baseline.+// - else load the store rules from storeDir plus every embedded baseline rule whose+// id the store does not define (a store rule replaces the baseline rule with the+// same id). An empty or absent store therefore yields exactly the baseline.+//+// The baseline stays active alongside the store so that installing one rule can never+// silently switch the baseline off; a store rule overrides a baseline rule only by id.//// Every returned rule has passed validation (via threatrules.LoadDir / Baseline). A rule// that needs a newer spec than this engine supports fails the load; LoadActiveSkipping is@@ -125,12 +129,8 @@ func LoadActive(storeDir, rulesDir string) ([]LoadedRule, error) {// of the corpus still runs. Callers surface skipped as warnings. The embedded baseline is// never skipped: it ships with the engine that evaluates it.func LoadActiveSkipping(storeDir, rulesDir string) ([]LoadedRule, []threatrules.SkippedRule, error) {- dir := rulesDir- if dir == "" && HasRuleFiles(storeDir) {- dir = storeDir- }- if dir != "" {- rules, skipped, err := threatrules.LoadDirSkipping(dir)+ if rulesDir != "" {+ rules, skipped, err := threatrules.LoadDirSkipping(rulesDir)if err != nil {return nil, nil, err}@@ -141,7 +141,38 @@ func LoadActiveSkipping(storeDir, rulesDir string) ([]LoadedRule, []threatrules.if err != nil {return nil, nil, err}- return tag(base, SourceBaseline), nil, nil+ if !HasRuleFiles(storeDir) {+ return tag(base, SourceBaseline), nil, nil+ }+ stored, skipped, err := threatrules.LoadDirSkipping(storeDir)+ if err != nil {+ return nil, nil, err+ }+ active := tag(stored, SourceStore)+ defined := make(map[string]bool, len(stored))+ for _, r := range stored {+ defined[r.ID] = true+ }+ for _, r := range base {+ if !defined[r.ID] {+ active = append(active, LoadedRule{Rule: r, Source: SourceBaseline})+ }+ }+ return active, skipped, nil+}++// IsBaselineID reports whether id names a rule in the embedded baseline.+func IsBaselineID(id string) bool {+ base, err := Baseline()+ if err != nil {+ return false+ }+ for _, r := range base {+ if r.ID == id {+ return true+ }+ }+ return false}func tag(rules []*threatrules.Rule, src Source) []LoadedRule {diff --git a/pkg/asymptoteobserve/rulestore/rulestore_test.go b/pkg/asymptoteobserve/rulestore/rulestore_test.goindex 5d769acd..693e9eee 100644--- a/pkg/asymptoteobserve/rulestore/rulestore_test.go+++ b/pkg/asymptoteobserve/rulestore/rulestore_test.go@@ -95,11 +95,89 @@ func TestInstallThenLoadActiveUsesStore(t *testing.T) {if err != nil {t.Fatalf("load active: %v", err)}- if len(loaded) != 1 || loaded[0].Source != SourceStore || loaded[0].Rule.ID != "custom-rule" {- t.Fatalf("expected store rule, got %+v", loaded)+ fromStore := bySource(loaded, SourceStore)+ if len(fromStore) != 1 || fromStore[0].ID != "custom-rule" {+ t.Fatalf("expected the store rule, got %+v", srcOf(loaded))}}+// TestLoadActiveKeepsBaselineAlongsideStore guards against one installed rule silently+// switching off the whole embedded baseline: every baseline rule the store does not+// define stays active.+func TestLoadActiveKeepsBaselineAlongsideStore(t *testing.T) {+ base, err := Baseline()+ if err != nil {+ t.Fatal(err)+ }+ store := t.TempDir()+ if err := os.WriteFile(filepath.Join(store, "custom-rule.rule.yaml"), []byte(ruleWithID("custom-rule")), 0o644); err != nil {+ t.Fatal(err)+ }+ loaded, err := LoadActive(store, "")+ if err != nil {+ t.Fatalf("load active: %v", err)+ }+ if len(loaded) != len(base)+1 {+ t.Fatalf("want %d rules (store + full baseline), got %d", len(base)+1, len(loaded))+ }+ baseIDs := map[string]bool{}+ for _, r := range bySource(loaded, SourceBaseline) {+ baseIDs[r.ID] = true+ }+ for _, r := range base {+ if !baseIDs[r.ID] {+ t.Errorf("baseline rule %q is missing from the active set", r.ID)+ }+ }+}++// TestLoadActiveStoreOverridesBaselineByID: a store rule with a baseline rule's id+// replaces that one baseline rule (store wins), and only that one.+func TestLoadActiveStoreOverridesBaselineByID(t *testing.T) {+ base, err := Baseline()+ if err != nil {+ t.Fatal(err)+ }+ id := base[0].ID+ if !IsBaselineID(id) || IsBaselineID("custom-rule") {+ t.Fatalf("IsBaselineID disagrees with Baseline()")+ }+ store := t.TempDir()+ if err := os.WriteFile(filepath.Join(store, id+RuleFileSuffix), []byte(ruleWithID(id)), 0o644); err != nil {+ t.Fatal(err)+ }+ loaded, err := LoadActive(store, "")+ if err != nil {+ t.Fatalf("load active: %v", err)+ }+ if len(loaded) != len(base) {+ t.Fatalf("want %d rules, got %d", len(base), len(loaded))+ }+ seen := 0+ for _, lr := range loaded {+ if lr.Rule.ID != id {+ continue+ }+ seen+++ if lr.Source != SourceStore || lr.Rule.Title != "T" {+ t.Errorf("rule %q should come from the store, got source %s title %q", id, lr.Source, lr.Rule.Title)+ }+ }+ if seen != 1 {+ t.Fatalf("rule %q active %d times, want once", id, seen)+ }+}++func bySource(l []LoadedRule, src Source) []*threatrules.Rule {+ var out []*threatrules.Rule+ for _, lr := range l {+ if lr.Source == src {+ out = append(out, lr.Rule)+ }+ }+ return out+}+func TestInstallFilesIgnoresAppleDoubleRuleFiles(t *testing.T) {store := t.TempDir()srcDir := t.TempDir()@@ -349,8 +427,9 @@ func TestLoadActiveSkippingRunsTheRestOfTheStore(t *testing.T) {if err != nil {t.Fatalf("load: %v", err)}- if len(loaded) != 1 || loaded[0].Rule.ID != "current-rule" || loaded[0].Source != SourceStore {- t.Fatalf("want only current-rule from the store, got %d rules", len(loaded))+ fromStore := bySource(loaded, SourceStore)+ if len(fromStore) != 1 || fromStore[0].ID != "current-rule" {+ t.Fatalf("want only current-rule from the store, got %d store rules", len(fromStore))}if len(skipped) != 1 || !strings.Contains(skipped[0].String(), `rule "future-rule" requires threat-rules/v1.9, but this Beacon supports up to `+threatrules.SupportedSpec+`; upgrade Beacon to load it`) {t.Fatalf("want future-rule skipped with the upgrade message, got %+v", skipped)