efficacy

package
v3.153.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 1, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

SAST rule efficacy

A rule is effective when it reports the defect it was written for, in the shapes that defect really takes, and stays quiet on code that only resembles it. This directory holds the harness that measures both, and internal/sast/testdata/efficacy/ holds the cases.

Cases

internal/sast/testdata/efficacy/<rule-stem>/<case-name>/<any files...>
  • <rule-stem> is the rule file name without .rego (vnx-go-014, vnx-89).
  • A case is a directory of real files at real relative paths. Paths matter: Dockerfile, .github/workflows/ci.yml, src/app_test.go and templates/index.html are what the rule sees.
  • A line that begins with ~> is a line the rule must report. The marker is removed before scanning, so ~> db.Query(q) scans as db.Query(q).
  • Every other line must not be reported. A case with no marker is a pure false-positive trap.
  • Name cases for what they prove: tp-concat-in-exec, tp-two-line-taint, fp-parameterised-query, fp-in-comment, fp-test-file. tp- cases have at least one marker, fp- cases have none.

Cases run through the production engine (sast.NewEngine(...).Evaluate), so the input builder, gitignore handling, the language filter and the per-finding file scope (internal/sast/file_scope.go) all apply as in a scan.

Never copy code from a third-party rule repository's tests into a case. Write the code yourself.

What a rule's case set must cover
  1. Every shape of the defect the rule claims. The common one, a two-line form (source assigned on one line, sink on the next), every API the description names, every language in metadata.languages, and the formatting variants real code uses (extra spaces, line breaks inside a call, single and double quotes, aliases such as import subprocess as sp).
  2. The lookalikes. The safe API next to the unsafe one (parameterised query, yaml.safe_load, html/template), the sanitised flow, the constant argument, the pattern inside a string literal or a comment, the pattern in a test file when the rule is about production hardening, documentation.
  3. The boundaries. What the rule deliberately does not do (deep dataflow, cross-file flows) gets an fp- or a documented gap, not silence.

Commands

Build once, then run from the repository root. Rules are read from disk, so an edited rule is measured immediately without rebuilding.

go build -o /tmp/sasteff ./tools/sasteff

sasteff cases vnx-go-014 vnx-89          # run cases; prints FN/FP lines and recall/precision
sasteff cases -q                          # every case, failures only
sasteff coverage                          # rules missing a tp- or an fp- case
sasteff secrets                           # generated secret rules vs their own token shapes
sasteff snapshot -out c.json DIR...       # freeze a corpus
sasteff hits -snapshot c.json vnx-89      # what the rule reports on real code
sasteff perf -snapshot c.json [stem...]   # per-rule eval and compile cost
sasteff total -kind sast DIR...           # full-ruleset wall time through the engine

hits on a corpus of ordinary, well-maintained projects is the precision check that cases cannot be: most of what a rule reports there is noise. On a corpus of deliberately vulnerable applications it is the recall check.

Writing a rule that works

  • Match a call, not a word. Anchor on the API (hashlib.md5(, \.Query\( with a receiver), on a declaration, or on an assignment to a name that says what it is.
  • Take the sink, then ask whether the source reaches it. Reading a request parameter is not a finding; passing it to a command, a query or a file path is. helpers.tainted_names(lines, i, before, source_re) returns variables assigned from source_re in the lines above i; helpers.assigned_first takes the first name on the left of an assignment (n, err := ... is n). Check the lines between for a guard or sanitiser.
  • Code, not prose. helpers.is_comment_line, helpers.code_window and helpers.next_code_index skip comments. The engine already drops a sast finding whose line is only a comment, and any finding in Markdown or Rego, unless the rule is tagged comments or documentation.
  • Stay in your language. Gate on file extension. A rule that declares languages never reports a file of a different known language.
  • A mitigation elsewhere counts. Middleware, a project-wide limiter or a framework default protects every handler; hardening rules judge the project and skip helpers.is_test_path.
  • Describe exactly what is matched. metadata.description says what the rule reports and what it deliberately does not. "Detects source patterns associated with CWE-N" is not a description.

Performance

Every rule is evaluated against every file. A rule that splits every file into lines and tests every line pays for the whole repository, so gate on the whole file first:

findings contains finding if {
	some path, content in input.file_contents
	endswith(path, ".py")
	contains(content, "subprocess")          # one check per file
	lines := split(content, "\n")             # only files that can match
	some i, line in lines
	...
}

A regular expression can gate a whole file in multi-line mode (regex.match(concat("", ["(?m)", pattern]), content)) whenever it would match a line of it. Prefer some path, content in input.file_contents to some path in object.keys(...) followed by a lookup. sasteff perf shows outliers.

Credentials in cases

Never write a token in a live provider format into a case: it trips push protection and is a leak-shaped artefact. Write the shape instead, and the loader fills it at test time with a random string the expression matches:

~>aws_secret_access_key = "@@sample:[A-Za-z0-9/+=]{40}@@"
~>token: @@sample:ghp_[A-Za-z0-9]{36}@@

Placeholder values ("your-key-here", "xxxxxxxx…") are fine to write literally in fp- cases.

Known limits

These are the gaps that were measured and left open, each with its cause. A rule that meets one is not broken; the shape is outside what a rule reading one project's files line by line can decide. Anything a rule cannot resolve stays reported, so a limit costs a false positive, not a missed finding, unless stated otherwise.

Measured against the OWASP Benchmark (Java 1.2 and Python 0.1) and Juice Shop's own vuln-code-snippet labels (sasteff bench for the Benchmark; for Juice Shop, compare each vuln-code-snippet vuln-line comment with the lines sasteff hits reports, same line or adjacent):

Area Limit Why
Python XPath, command injection (VNX-643, VNX-PY-007) 7 false positives, all request.path.split("/")[1] or a request wrapper whose method is only named "safe" A path segment is constant only because of the route definition, and a method name proves nothing about its body
Java XPath (VNX-643) its 15 request-traced Java findings are reported by VNX-JAVA-013 one defect, one finding: the pair was deduplicated on purpose
Weak hash (VNX-CRYPTO-001, VNX-CRYPTO-002) an algorithm named only in a gitignored properties file is not seen the scan skips files the project ignores; with the file visible the Benchmark scores 129 of 129
Cross-file Java calls one level deep, methods over 60 lines, varargs, lambdas, a receiver held in a field the summary is a bounded line-level reading; anything it cannot resolve stays tainted
A field assigned from outside its class new Cls().getter() is read as constant the inert-call fallback cannot see the assignment; a real flow through such a class can be missed
Language pre-filter a rule is dropped when none of its declared languages is in the project an XML-only, YAML-only or properties-only tree reports nothing for rules that declare only code languages; the docs of VNX-431, VNX-936, VNX-1395 and VNX-ANDROID-005 say so
Juice Shop labelled lines 11 of 36 reported the rest are data (security-question answers, allowlist entries), an absent guard (a route with no canActivate), a hidden-feature route, a runtime-computed matcher, Solidity, or a route that is unauthenticated only by deployment
Juice Shop "correct" fixes 5 of 25 still flagged each still contains the weakness the rule names (a bypassable includes allowlist, multi: true with a request-chosen id); they are findings in code the project calls fixed

The independent ind-* cases are the check that does not depend on the agents that fixed a rule: a writer who saw only the rule's doc page wrote them. Before repair 219 of 3,968 documented positives were missed and 123 of 3,646 documented negatives were reported; after repair none is. When a doc and a rule disagree, change the rule or narrow the doc, then keep a case for the claim that remains.

Documentation

Overview

Package efficacy measures whether a SAST rule does what it says: it reports the defect it was written for, in the shapes that defect takes, and stays quiet on the code that merely resembles it.

A case is a directory of real files under testdata/efficacy/<rule>/<case>/. A line that begins with the marker "~>" is a line the rule must report; the marker is removed before the files are scanned, so the scanner sees exactly the code a developer would have written. Every other line in the case must not be reported. A case with no marker is a pure false-positive trap.

Cases are evaluated through the production engine (sast.NewEngine and Evaluate), so the input builder, the language filter, content loading and the per-finding file scope all apply exactly as they do in a scan.

Index

Constants

View Source
const (
	VerdictOK         = "ok"
	VerdictFail       = "fail"       // realistic tokens of the rule's own shape are missed, or a gate is ineffective
	VerdictUnmeasured = "unmeasured" // no pattern-valid sample carries a keyword: needs a realistic example
)

Verdicts for a catalog entry.

View Source
const Marker = "~>"

Marker is the line prefix that marks a line the rule must report.

Variables

This section is empty.

Functions

func Describe

func Describe(r Result) string

Describe renders one result for a human.

func Entropy

func Entropy(s string) float64

Entropy is the Shannon entropy in bits per byte, as vulnetix.shannon_entropy.

func EvalSharded

func EvalSharded(rules *Rules, stems []string, in *sast.ScanInput) (map[string][]Hit, error)

EvalSharded evaluates many rules against one input, compiling them in parallel shards as the engine does, and returns each rule's hits.

func ExpandSamples

func ExpandSamples(src, file string) (string, error)

ExpandSamples replaces every @@sample:REGEX@@ in src.

func RandomTokenEntropy

func RandomTokenEntropy(pattern string, q float64, n int) (float64, error)

RandomTokenEntropy returns the q-quantile of the entropy of n random tokens of the pattern's capture group: the threshold below which a real credential of this shape almost always falls.

func RuleID

func RuleID(src string) string

RuleID returns the metadata id declared by a rule module.

func Sample

func Sample(pattern string, variant int) (full, group string, err error)

Sample produces a string that matches pattern, built from the pattern's own syntax tree. It exists so a secret-detection rule can be proven to fire on the token shape it describes without a realistic credential ever being committed (provider push protection would rightly block that, and a test corpus of live-looking keys is its own leak).

variant selects among alternatives and repetition lengths, so successive variants exercise different branches. Character runs are drawn without replacement from the class, which maximises entropy: an entropy-gated rule should accept a sample, and when it does not, the threshold is unreachable for that alphabet.

The result is checked against the compiled pattern; an error means no variant up to the limit could satisfy the pattern's assertions (\b, ^, $).

func SampleMode

func SampleMode(pattern string, variant int, mode genMode) (full, group string, err error)

SampleMode is Sample with a fill mode for character runs.

func SaveSnapshot

func SaveSnapshot(path string, ps []Project) error

SaveSnapshot and LoadSnapshot persist a corpus so repeated measurements do not walk and read thousands of files each time.

func StripMarkers

func StripMarkers(src string) (string, []int)

StripMarkers removes "~>" markers and returns the cleaned text with the 1-based lines that carried one.

Types

type Case

type Case struct {
	Rule  string            `json:"rule"` // rule file stem, e.g. "vnx-go-014"
	Name  string            `json:"name"` // case directory name
	Dir   string            `json:"dir"`
	Files map[string]string `json:"-"` // relative path → content, markers removed
	Want  []Loc             `json:"want"`
}

Case is one fixture directory for one rule.

func LoadCases

func LoadCases(root string, rules ...string) ([]Case, error)

LoadCases reads every case under root (root/<rule>/<case>/...). When rules is non-empty only those rule stems are loaded.

func (Case) Positive

func (c Case) Positive() bool

Positive reports whether the case expects at least one finding.

type CatalogEntry

type CatalogEntry struct {
	ID         int      `json:"id"`
	Category   string   `json:"category"`
	Name       string   `json:"name"`
	Strategy   string   `json:"strategy"`
	Pattern    string   `json:"token_pattern"`
	Keywords   []string `json:"keywords"`
	EntropyMin float64  `json:"entropy_min"`
	Deprecated bool     `json:"deprecated"`
}

CatalogEntry is the part of a secretsgen catalog entry the checks need.

func LoadCatalog

func LoadCatalog(path string) ([]CatalogEntry, error)

LoadCatalog reads secretsgen/catalog.json.

func (CatalogEntry) Stem

func (e CatalogEntry) Stem() string

Stem is the generated rule's file stem.

type Hit

type Hit struct {
	Project string `json:"project"`
	File    string `json:"file"`
	Line    int    `json:"line"`
	Snippet string `json:"snippet"`
}

Hit is one finding on a corpus project.

type Loc

type Loc struct {
	File string `json:"file"`
	Line int    `json:"line"`
}

Loc is a reported or expected position.

func (Loc) String

func (l Loc) String() string

type Profile

type Profile struct {
	Rule      string         `json:"rule"`
	ID        string         `json:"id"`
	Compile   time.Duration  `json:"compile_ns"`
	Eval      time.Duration  `json:"eval_ns"` // sum over projects of the fastest repetition
	Findings  int            `json:"findings"`
	Files     int            `json:"files"` // distinct files with a finding
	ByProject map[string]int `json:"by_project,omitempty"`
	Hits      []Hit          `json:"hits,omitempty"`
	Err       string         `json:"error,omitempty"`
}

Profile is the measurement of one rule over a corpus.

func ProfileRules

func ProfileRules(rules *Rules, stems []string, projects []Project, opts ProfileOptions) ([]Profile, error)

ProfileRules compiles and evaluates each rule on its own against every project and reports its cost and its findings.

type ProfileOptions

type ProfileOptions struct {
	Reps     int // repetitions per project; the fastest is kept (default 1)
	Workers  int // concurrent rules (default GOMAXPROCS/2)
	KeepHits int // hits to keep per rule (0 keeps none)
}

ProfileOptions controls Profile.

type Project

type Project struct {
	Name  string          `json:"name"`
	Root  string          `json:"root"`
	Input *sast.ScanInput `json:"input"`
}

Project is one scanned tree in a corpus snapshot. Projects are kept apart rather than merged under a prefix so that root-anchored rules (a path that starts with ".github/", a Dockerfile at the top) see the layout they would see in a real scan.

func LoadSnapshot

func LoadSnapshot(path string) ([]Project, error)

func Snapshot

func Snapshot(dirs []string, secrets bool) ([]Project, error)

Snapshot builds the scan input for each corpus directory the way the sast command does: gitignore respected, text up to 1 MiB, binaries skipped. With secrets it is built the way the secrets command does instead: binaries read for their strings and the git history merged in, up to the command's default limits, which is most of what a secrets rule evaluates.

type Result

type Result struct {
	Rule    string        `json:"rule"`
	Case    string        `json:"case"`
	Want    []Loc         `json:"want"`
	Got     []Loc         `json:"got"`
	Missing []Loc         `json:"missing,omitempty"` // expected, not reported: a false negative
	Extra   []Loc         `json:"extra,omitempty"`   // reported, not expected: a false positive
	Err     string        `json:"error,omitempty"`
	Elapsed time.Duration `json:"elapsed_ns"`
}

Result is the outcome of one case.

func RunCase

func RunCase(rules *Rules, c Case) Result

RunCase writes the case to a temporary directory and scans it with the rule through the production engine.

func (Result) Pass

func (r Result) Pass() bool

Pass reports whether the rule reported exactly the expected lines.

type Rules

type Rules struct {
	Dir    string
	Shared map[string]string // module name → source (helpers, libraries)
	ByStem map[string]string // rule file stem → source
}

Rules is a rule directory read from disk: the shared library modules every rule may import, and the rule modules by file stem.

func LoadRules

func LoadRules(dir string) (*Rules, error)

LoadRules reads a rule directory. Reading from disk (not the embedded FS) means an edited rule is measured without rebuilding anything.

func (*Rules) Modules

func (r *Rules) Modules(stems ...string) map[string]string

Modules returns the shared modules plus the named rules, keyed the way the engine keys embedded modules.

func (*Rules) Stems

func (r *Rules) Stems() []string

Stems returns the rule stems in order.

type SecretCheck

type SecretCheck struct {
	ID            int      `json:"id"`
	Rule          string   `json:"rule"`
	Name          string   `json:"name"`
	Verdict       string   `json:"verdict"`
	Eligible      int      `json:"eligible"` // random samples that carry a keyword and are not placeholders
	Detected      int      `json:"detected"`
	Rate          float64  `json:"rate"`
	KeywordGap    int      `json:"keyword_gap"` // pattern-valid samples the keyword prefilter skips
	MedianEntropy float64  `json:"median_entropy,omitempty"`
	Problems      []string `json:"problems,omitempty"`
	Warnings      []string `json:"warnings,omitempty"`
	FiredOnBy     []string `json:"fired_on_by,omitempty"` // other rules that report this entry's tokens
	FiresOnOthers int      `json:"fires_on_others"`       // other entries' tokens this rule reports
	Skipped       string   `json:"skipped,omitempty"`     // the generator could not produce a sample
}

SecretCheck is the verdict for one catalog entry.

func CheckSecretsCatalog

func CheckSecretsCatalog(rules *Rules, entries []CatalogEntry) ([]SecretCheck, error)

CheckSecretsCatalog proves each generated secret rule reports realistic random tokens of its own shape, that its placeholder and entropy gates reject what they are meant to, and records which other rules report the same token.

type Summary

type Summary struct {
	Rule          string `json:"rule"`
	Cases         int    `json:"cases"`
	PositiveCases int    `json:"positive_cases"`
	NegativeCases int    `json:"negative_cases"`
	Expected      int    `json:"expected"` // lines the cases mark
	TruePos       int    `json:"tp"`
	FalseNeg      int    `json:"fn"`
	FalsePos      int    `json:"fp"`
	Failed        int    `json:"failed_cases"`
}

Summary aggregates results per rule.

func Summarise

func Summarise(cases []Case, results []Result) []Summary

Summarise folds case results into per-rule summaries.

func (Summary) Precision

func (s Summary) Precision() float64

Precision is TP / (TP + FP); 1 when nothing is reported.

func (Summary) Recall

func (s Summary) Recall() float64

Recall is TP / (TP + FN); 1 when nothing is expected.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL