Skip to content

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

9.9 KB
Raw Blame
package threatrules

import (
	"os"
	"path/filepath"
	"regexp"
	"runtime"
	"strings"
	"testing"

	"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)

// repoRoot locates the repository root by walking up from this test file until it finds
// the spec sentinel (spec/threat-rules/VERSION). This keeps tests hermetic without
// hardcoded absolute paths.
func repoRoot(t testing.TB) string {
	t.Helper()
	_, thisFile, _, ok := runtime.Caller(0)
	if !ok {
		t.Fatal("runtime.Caller failed")
	}
	dir := filepath.Dir(thisFile)
	for {
		if _, err := os.Stat(filepath.Join(dir, "spec", "threat-rules", "VERSION")); err == nil {
			return dir
		}
		parent := filepath.Dir(dir)
		if parent == dir {
			t.Fatal("could not locate repo root (spec/threat-rules/VERSION sentinel)")
		}
		dir = parent
	}
}

func rulesDir(t testing.TB) string { return filepath.Join(repoRoot(t), "rules") }

func specDir(t *testing.T) string { return filepath.Join(repoRoot(t), "spec", "threat-rules") }

// TestPackConformance is the keystone: it loads the real rule pack and, for every rule,
// validates it, enforces its maturity gate, and runs every embedded fixture against the
// reference evaluator. Adding a rule file automatically extends coverage.
func TestPackConformance(t *testing.T) {
	dir := rulesDir(t)
	rules, err := LoadDir(dir) // also asserts no duplicate ids and that every rule validates
	if err != nil {
		t.Fatalf("load rule pack: %v", err)
	}
	if len(rules) == 0 {
		t.Fatal("rule pack is empty")
	}

	for _, rule := range rules {
		rule := rule
		t.Run(rule.ID, func(t *testing.T) {
			results, err := CheckRule(rule)
			if err != nil {
				t.Fatalf("rule-level failure: %v", err)
			}
			for _, res := range results {
				res := res
				t.Run(res.Fixture, func(t *testing.T) {
					if !res.OK() {
						t.Fatalf("%s", res.String())
					}
				})
			}
		})
	}
}

// TestPackMatchesWhatTheLogHolds runs every fixture again after the sanitizer every log writer
// applies, and requires the same verdict. `beacon scan` and the dashboard only ever see the
// sanitized line, so a rule that matches a raw value redaction removes (a token, a key) is dead on
// real logs even though its plain fixtures pass.
func TestPackMatchesWhatTheLogHolds(t *testing.T) {
	rules, err := LoadDir(rulesDir(t))
	if err != nil {
		t.Fatalf("load rule pack: %v", err)
	}
	for _, rule := range rules {
		compiled, err := Compile(rule)
		if err != nil {
			t.Fatalf("rule %q: compile: %v", rule.ID, err)
		}
		for _, fixture := range rule.Tests {
			events := fixture.EventList()
			for i := range events {
				events[i] = asymptoteobserve.SanitizeEvent(events[i], 64*1024)
			}
			got, err := compiled.Evaluate(events)
			if err != nil {
				t.Errorf("%s/%s: evaluate sanitized events: %v", rule.ID, fixture.Name, err)
				continue
			}
			if got != fixture.Verdict {
				t.Errorf("%s/%s: verdict %q on the sanitized events the log holds, want %q", rule.ID, fixture.Name, got, fixture.Verdict)
			}
		}
	}
}

// TestPackSharedCredentialRead pins correlation read steps that are meant to reuse
// credential-file-read's definition of a secret. The format has no include mechanism, so
// the expression is copied; this fails when one copy changes without the other.
func TestPackSharedCredentialRead(t *testing.T) {
	rules, err := LoadDir(rulesDir(t))
	if err != nil {
		t.Fatalf("load rule pack: %v", err)
	}
	byID := make(map[string]*Rule, len(rules))
	for _, r := range rules {
		byID[r.ID] = r
	}
	base := byID["credential-file-read"]
	if base == nil {
		t.Fatal("credential-file-read missing from the pack")
	}
	for _, ref := range []struct{ rule, step string }{
		{"secret-read-then-destructive", "read_secret"},
	} {
		r := byID[ref.rule]
		if r == nil || r.Correlation == nil {
			t.Fatalf("%s missing or not a correlation rule", ref.rule)
		}
		var got string
		for _, s := range r.Correlation.Steps {
			if s.ID == ref.step {
				got = s.Match
			}
		}
		if normalizeCEL(got) != normalizeCEL(base.Match) {
			t.Errorf("%s step %s drifted from credential-file-read's match:\n  got:  %s\n  want: %s",
				ref.rule, ref.step, normalizeCEL(got), normalizeCEL(base.Match))
		}
	}
}

// The egress rules' shared definition of "this command sends data over the network", in the
// normalized form TestPackSharedEgressSender compares. The format has no include mechanism,
// so each rule carries a copy.
const (
	// egressSender: a parsed command (s) that is a network client by base name, or runs one
	// under a wrapper the parser does not unwrap.
	egressSenderNames = `"(?i)(^|/)(curl|wget|http|https|httpie|xh|xhs|nc|ncat|netcat|socat)$"`
	egressSender      = `(s.name.matches(` + egressSenderNames + `) || s.name.matches("(?i)^(timeout|nice|ionice|stdbuf|doas|torsocks|proxychains4?)$") && s.argv.exists(a, a.matches(` + egressSenderNames + `)))`
	// egressReadsStdin: the sender (s) reads what is piped or redirected into it; curl and
	// wget only with a stdin body.
	egressReadsStdin = `(!s.argv.exists(a, a.matches("(?i)(^|/)(curl|wget)$")) || s.argv.exists(a, a.matches("^.*[=@<](-|/dev/stdin)$")) || s.argv.exists(a, a.matches("^(-[a-zA-Z]*T|--upload-file|--post-file|--body-file)$")) && s.argv.exists(a, a in ["-", "/dev/stdin"]))`
	// egressDevTCP: a bash /dev/tcp or /dev/udp redirect, not a word of a non-shell command
	// (a commit message or an echo argument).
	egressDevTCP = `(e.command.command.matches("[<>][&|]?\\s*/dev/(tcp|udp)/") && !e.command.parsed_commands.exists(w, !w.name.matches("(?i)^(ba|z|da|k)?sh$") && w.argv_raw.exists(a, a.matches("/dev/(tcp|udp)/"))))`
	// egressRemoteCopy: scp/sftp/rsync with a host: operand.
	egressRemoteCopy = `(s.name.matches("(?i)^(scp|sftp|rsync)$") && s.argv_raw.exists(a, a.matches("^[\\x27\"]?[\\w.@-]+:")))`
)

// TestPackSharedEgressSender pins every egress rule to the one shared sender definition, so
// adding a sender (or a wrapper) to one rule and not the others fails here. It also fails when
// any rule's parsed-command check names a netcat with a list other than the shared one, or
// carries the shared list without being in this table.
func TestPackSharedEgressSender(t *testing.T) {
	rules, err := LoadDir(rulesDir(t))
	if err != nil {
		t.Fatalf("load rule pack: %v", err)
	}
	const sender, stdin, devTCP, remoteCopy = 1, 2, 4, 8
	uses := map[string]int{
		"upload-to-paste-transfer-site":    sender | devTCP,
		"secret-read-then-egress":          sender | devTCP | remoteCopy,
		"browser-session-read-then-egress": sender | devTCP | remoteCopy,
		"git-bundle-then-egress":           sender | devTCP | remoteCopy,
		"env-dump-piped-to-network":        sender | stdin | devTCP,
		"secret-read-and-egress":           sender | stdin | devTCP,
		"archive-then-upload":              sender | stdin | devTCP,
		"credentials-in-curl-data":         sender,
	}
	snippets := []struct {
		bit  int
		name string
		expr string
	}{
		{sender, "sender", egressSender},
		{stdin, "reads-stdin", egressReadsStdin},
		{devTCP, "/dev/tcp", egressDevTCP},
		{remoteCopy, "remote-copy", egressRemoteCopy},
	}
	literal := regexp.MustCompile(`([\w.]+)\.matches\(("(?:[^"\\]|\\.)*")\)`)
	seen := map[string]bool{}
	for _, r := range rules {
		expr := normalizeCEL(strings.Join(ruleExpressions(r), " "))
		want, listed := uses[r.ID]
		if listed {
			seen[r.ID] = true
			for _, s := range snippets {
				if want&s.bit != 0 && !strings.Contains(expr, s.expr) {
					t.Errorf("%s: the shared %s check is missing or drifted; want it verbatim:\n  %s", r.ID, s.name, s.expr)
				}
			}
		}
		for _, m := range literal.FindAllStringSubmatch(expr, -1) {
			receiver, lit := m[1], m[2]
			if receiver == "e.command.command" || !strings.Contains(lit, "ncat") && !strings.Contains(lit, "netcat") {
				continue // a text fallback, or not a sender list
			}
			if lit != egressSenderNames {
				t.Errorf("%s: %s.matches(%s) is a sender list other than the shared one %s", r.ID, receiver, lit, egressSenderNames)
			} else if !listed {
				t.Errorf("%s: uses the shared sender list; add it to TestPackSharedEgressSender so its copy is checked", r.ID)
			}
		}
	}
	for id := range uses {
		if !seen[id] {
			t.Errorf("egress rule %s missing from the pack", id)
		}
	}
}

// normalizeCEL collapses whitespace so YAML indentation differences do not count.
func normalizeCEL(expr string) string { return strings.Join(strings.Fields(expr), " ") }

// TestPackCategoriesMatchDirectories pins taxonomy.beacon_category to the directory each rule
// lives in. The rule store keeps rules flat, so the category travels inside the rule: it is what
// groups findings by kind of risk (the Security Review lens, for one) once a rule is installed.
func TestPackCategoriesMatchDirectories(t *testing.T) {
	paths, err := filepath.Glob(filepath.Join(rulesDir(t), "*", "*.rule.yaml"))
	if err != nil || len(paths) == 0 {
		t.Fatalf("rule files: %v, %v", paths, err)
	}
	for _, path := range paths {
		rule, err := LoadRule(path)
		if err != nil {
			t.Fatalf("%s: %v", path, err)
		}
		want := filepath.Base(filepath.Dir(path))
		if got := rule.Taxonomy["beacon_category"]; got != want {
			t.Errorf("%s: taxonomy.beacon_category = %q, want its directory %q", path, got, want)
		}
	}
}

// TestBaselineRulesAreCorpusCopies keeps the embedded baseline byte-identical to the rules it was
// taken from, so a fix to a corpus rule cannot leave a stale copy in every binary.
func TestBaselineRulesAreCorpusCopies(t *testing.T) {
	baseline, err := filepath.Glob(filepath.Join(repoRoot(t), "pkg", "asymptoteobserve", "rulestore", "baseline", "*.rule.yaml"))
	if err != nil || len(baseline) == 0 {
		t.Fatalf("baseline rules: %v, %v", baseline, err)
	}
	for _, path := range baseline {
		matches, _ := filepath.Glob(filepath.Join(rulesDir(t), "*", filepath.Base(path)))
		if len(matches) != 1 {
			t.Errorf("%s: want exactly one corpus copy, found %v", filepath.Base(path), matches)
			continue
		}
		got, _ := os.ReadFile(path)
		want, _ := os.ReadFile(matches[0])
		if string(got) != string(want) {
			t.Errorf("%s differs from %s; copy the corpus rule over", path, matches[0])
		}
	}
}